resolv: Remove BSD compatibility conditionals and header
[glibc.git] / malloc / malloc.c
blobea97df2cb4b18017bcd0c7278b85b227d6c9f720
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2016 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 changes made 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
30 based on:
31 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
33 * Quickstart
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
69 versions.
71 * Contents, described in more detail in "description of public routines" below.
73 Standard (ANSI/SVID/...) functions:
74 malloc(size_t n);
75 calloc(size_t n_elements, size_t element_size);
76 free(void* p);
77 realloc(void* p, size_t n);
78 memalign(size_t alignment, size_t n);
79 valloc(size_t n);
80 mallinfo()
81 mallopt(int parameter_number, int parameter_value)
83 Additional functions:
84 independent_calloc(size_t n_elements, size_t size, void* chunks[]);
85 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
86 pvalloc(size_t n);
87 cfree(void* p);
88 malloc_trim(size_t pad);
89 malloc_usable_size(void* p);
90 malloc_stats();
92 * Vital statistics:
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
115 16/24/32 bytes.
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
141 limitation.
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.)
167 OPTION DEFAULT VALUE
169 Compilation Environment options:
171 HAVE_MREMAP 0
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
185 TRIM_FASTBINS 0
187 Options for customizing MORECORE:
189 MORECORE sbrk
190 MORECORE_FAILURE -1
191 MORECORE_CONTIGUOUS 1
192 MORECORE_CANNOT_TRIM NOT defined
193 MORECORE_CLEARS 1
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
200 DEFAULT_TOP_PAD 0
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
211 #ifndef void
212 #define void void
213 #endif /*void*/
215 #include <stddef.h> /* for size_t */
216 #include <stdlib.h> /* for getenv(), abort() */
217 #include <unistd.h> /* for __libc_enable_secure */
219 #include <malloc-machine.h>
220 #include <malloc-sysdep.h>
222 #include <atomic.h>
223 #include <_itoa.h>
224 #include <bits/wordsize.h>
225 #include <sys/sysinfo.h>
227 #include <ldsodefs.h>
229 #include <unistd.h>
230 #include <stdio.h> /* needed for malloc_stats */
231 #include <errno.h>
233 #include <shlib-compat.h>
235 /* For uintptr_t. */
236 #include <stdint.h>
238 /* For va_arg, va_start, va_end. */
239 #include <stdarg.h>
241 /* For MIN, MAX, powerof2. */
242 #include <sys/param.h>
244 /* For ALIGN_UP et. al. */
245 #include <libc-internal.h>
247 #include <malloc/malloc-internal.h>
250 Debugging:
252 Because freed chunks may be overwritten with bookkeeping fields, this
253 malloc will often die when freed memory is overwritten by user
254 programs. This can be very effective (albeit in an annoying way)
255 in helping track down dangling pointers.
257 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
258 enabled that will catch more memory errors. You probably won't be
259 able to make much sense of the actual assertion errors, but they
260 should help you locate incorrectly overwritten memory. The checking
261 is fairly extensive, and will slow down execution
262 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
263 will attempt to check every non-mmapped allocated and free chunk in
264 the course of computing the summmaries. (By nature, mmapped regions
265 cannot be checked very much automatically.)
267 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
268 this code. The assertions in the check routines spell out in more
269 detail the assumptions and invariants underlying the algorithms.
271 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
272 checking that all accesses to malloced memory stay within their
273 bounds. However, there are several add-ons and adaptations of this
274 or other mallocs available that do this.
277 #ifndef MALLOC_DEBUG
278 #define MALLOC_DEBUG 0
279 #endif
281 #ifdef NDEBUG
282 # define assert(expr) ((void) 0)
283 #else
284 # define assert(expr) \
285 ((expr) \
286 ? ((void) 0) \
287 : __malloc_assert (#expr, __FILE__, __LINE__, __func__))
289 extern const char *__progname;
291 static void
292 __malloc_assert (const char *assertion, const char *file, unsigned int line,
293 const char *function)
295 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
296 __progname, __progname[0] ? ": " : "",
297 file, line,
298 function ? function : "", function ? ": " : "",
299 assertion);
300 fflush (stderr);
301 abort ();
303 #endif
307 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
308 of chunk sizes.
310 The default version is the same as size_t.
312 While not strictly necessary, it is best to define this as an
313 unsigned type, even if size_t is a signed type. This may avoid some
314 artificial size limitations on some systems.
316 On a 64-bit machine, you may be able to reduce malloc overhead by
317 defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
318 expense of not being able to handle more than 2^32 of malloced
319 space. If this limitation is acceptable, you are encouraged to set
320 this unless you are on a platform requiring 16byte alignments. In
321 this case the alignment requirements turn out to negate any
322 potential advantages of decreasing size_t word size.
324 Implementors: Beware of the possible combinations of:
325 - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
326 and might be the same width as int or as long
327 - size_t might have different width and signedness as INTERNAL_SIZE_T
328 - int and long might be 32 or 64 bits, and might be the same width
329 To deal with this, most comparisons and difference computations
330 among INTERNAL_SIZE_Ts should cast them to unsigned long, being
331 aware of the fact that casting an unsigned int to a wider long does
332 not sign-extend. (This also makes checking for negative numbers
333 awkward.) Some of these casts result in harmless compiler warnings
334 on some systems.
337 #ifndef INTERNAL_SIZE_T
338 #define INTERNAL_SIZE_T size_t
339 #endif
341 /* The corresponding word size */
342 #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
346 MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
347 It must be a power of two at least 2 * SIZE_SZ, even on machines
348 for which smaller alignments would suffice. It may be defined as
349 larger than this though. Note however that code and data structures
350 are optimized for the case of 8-byte alignment.
354 #ifndef MALLOC_ALIGNMENT
355 # if !SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_16)
356 /* This is the correct definition when there is no past ABI to constrain it.
358 Among configurations with a past ABI constraint, it differs from
359 2*SIZE_SZ only on powerpc32. For the time being, changing this is
360 causing more compatibility problems due to malloc_get_state and
361 malloc_set_state than will returning blocks not adequately aligned for
362 long double objects under -mlong-double-128. */
364 # define MALLOC_ALIGNMENT (2 *SIZE_SZ < __alignof__ (long double) \
365 ? __alignof__ (long double) : 2 *SIZE_SZ)
366 # else
367 # define MALLOC_ALIGNMENT (2 *SIZE_SZ)
368 # endif
369 #endif
371 /* The corresponding bit mask value */
372 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
377 REALLOC_ZERO_BYTES_FREES should be set if a call to
378 realloc with zero bytes should be the same as a call to free.
379 This is required by the C standard. Otherwise, since this malloc
380 returns a unique pointer for malloc(0), so does realloc(p, 0).
383 #ifndef REALLOC_ZERO_BYTES_FREES
384 #define REALLOC_ZERO_BYTES_FREES 1
385 #endif
388 TRIM_FASTBINS controls whether free() of a very small chunk can
389 immediately lead to trimming. Setting to true (1) can reduce memory
390 footprint, but will almost always slow down programs that use a lot
391 of small chunks.
393 Define this only if you are willing to give up some speed to more
394 aggressively reduce system-level memory footprint when releasing
395 memory in programs that use many small chunks. You can get
396 essentially the same effect by setting MXFAST to 0, but this can
397 lead to even greater slowdowns in programs using many small chunks.
398 TRIM_FASTBINS is an in-between compile-time option, that disables
399 only those chunks bordering topmost memory from being placed in
400 fastbins.
403 #ifndef TRIM_FASTBINS
404 #define TRIM_FASTBINS 0
405 #endif
408 /* Definition for getting more memory from the OS. */
409 #define MORECORE (*__morecore)
410 #define MORECORE_FAILURE 0
411 void * __default_morecore (ptrdiff_t);
412 void *(*__morecore)(ptrdiff_t) = __default_morecore;
415 #include <string.h>
418 MORECORE-related declarations. By default, rely on sbrk
423 MORECORE is the name of the routine to call to obtain more memory
424 from the system. See below for general guidance on writing
425 alternative MORECORE functions, as well as a version for WIN32 and a
426 sample version for pre-OSX macos.
429 #ifndef MORECORE
430 #define MORECORE sbrk
431 #endif
434 MORECORE_FAILURE is the value returned upon failure of MORECORE
435 as well as mmap. Since it cannot be an otherwise valid memory address,
436 and must reflect values of standard sys calls, you probably ought not
437 try to redefine it.
440 #ifndef MORECORE_FAILURE
441 #define MORECORE_FAILURE (-1)
442 #endif
445 If MORECORE_CONTIGUOUS is true, take advantage of fact that
446 consecutive calls to MORECORE with positive arguments always return
447 contiguous increasing addresses. This is true of unix sbrk. Even
448 if not defined, when regions happen to be contiguous, malloc will
449 permit allocations spanning regions obtained from different
450 calls. But defining this when applicable enables some stronger
451 consistency checks and space efficiencies.
454 #ifndef MORECORE_CONTIGUOUS
455 #define MORECORE_CONTIGUOUS 1
456 #endif
459 Define MORECORE_CANNOT_TRIM if your version of MORECORE
460 cannot release space back to the system when given negative
461 arguments. This is generally necessary only if you are using
462 a hand-crafted MORECORE function that cannot handle negative arguments.
465 /* #define MORECORE_CANNOT_TRIM */
467 /* MORECORE_CLEARS (default 1)
468 The degree to which the routine mapped to MORECORE zeroes out
469 memory: never (0), only for newly allocated space (1) or always
470 (2). The distinction between (1) and (2) is necessary because on
471 some systems, if the application first decrements and then
472 increments the break value, the contents of the reallocated space
473 are unspecified.
476 #ifndef MORECORE_CLEARS
477 # define MORECORE_CLEARS 1
478 #endif
482 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
483 sbrk fails, and mmap is used as a backup. The value must be a
484 multiple of page size. This backup strategy generally applies only
485 when systems have "holes" in address space, so sbrk cannot perform
486 contiguous expansion, but there is still space available on system.
487 On systems for which this is known to be useful (i.e. most linux
488 kernels), this occurs only when programs allocate huge amounts of
489 memory. Between this, and the fact that mmap regions tend to be
490 limited, the size should be large, to avoid too many mmap calls and
491 thus avoid running out of kernel resources. */
493 #ifndef MMAP_AS_MORECORE_SIZE
494 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
495 #endif
498 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
499 large blocks.
502 #ifndef HAVE_MREMAP
503 #define HAVE_MREMAP 0
504 #endif
508 This version of malloc supports the standard SVID/XPG mallinfo
509 routine that returns a struct containing usage properties and
510 statistics. It should work on any SVID/XPG compliant system that has
511 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
512 install such a thing yourself, cut out the preliminary declarations
513 as described above and below and save them in a malloc.h file. But
514 there's no compelling reason to bother to do this.)
516 The main declaration needed is the mallinfo struct that is returned
517 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
518 bunch of fields that are not even meaningful in this version of
519 malloc. These fields are are instead filled by mallinfo() with
520 other numbers that might be of interest.
524 /* ---------- description of public routines ------------ */
527 malloc(size_t n)
528 Returns a pointer to a newly allocated chunk of at least n bytes, or null
529 if no space is available. Additionally, on failure, errno is
530 set to ENOMEM on ANSI C systems.
532 If n is zero, malloc returns a minumum-sized chunk. (The minimum
533 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
534 systems.) On most systems, size_t is an unsigned type, so calls
535 with negative arguments are interpreted as requests for huge amounts
536 of space, which will often fail. The maximum supported value of n
537 differs across systems, but is in all cases less than the maximum
538 representable value of a size_t.
540 void* __libc_malloc(size_t);
541 libc_hidden_proto (__libc_malloc)
544 free(void* p)
545 Releases the chunk of memory pointed to by p, that had been previously
546 allocated using malloc or a related routine such as realloc.
547 It has no effect if p is null. It can have arbitrary (i.e., bad!)
548 effects if p has already been freed.
550 Unless disabled (using mallopt), freeing very large spaces will
551 when possible, automatically trigger operations that give
552 back unused memory to the system, thus reducing program footprint.
554 void __libc_free(void*);
555 libc_hidden_proto (__libc_free)
558 calloc(size_t n_elements, size_t element_size);
559 Returns a pointer to n_elements * element_size bytes, with all locations
560 set to zero.
562 void* __libc_calloc(size_t, size_t);
565 realloc(void* p, size_t n)
566 Returns a pointer to a chunk of size n that contains the same data
567 as does chunk p up to the minimum of (n, p's size) bytes, or null
568 if no space is available.
570 The returned pointer may or may not be the same as p. The algorithm
571 prefers extending p when possible, otherwise it employs the
572 equivalent of a malloc-copy-free sequence.
574 If p is null, realloc is equivalent to malloc.
576 If space is not available, realloc returns null, errno is set (if on
577 ANSI) and p is NOT freed.
579 if n is for fewer bytes than already held by p, the newly unused
580 space is lopped off and freed if possible. Unless the #define
581 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
582 zero (re)allocates a minimum-sized chunk.
584 Large chunks that were internally obtained via mmap will always
585 be reallocated using malloc-copy-free sequences unless
586 the system supports MREMAP (currently only linux).
588 The old unix realloc convention of allowing the last-free'd chunk
589 to be used as an argument to realloc is not supported.
591 void* __libc_realloc(void*, size_t);
592 libc_hidden_proto (__libc_realloc)
595 memalign(size_t alignment, size_t n);
596 Returns a pointer to a newly allocated chunk of n bytes, aligned
597 in accord with the alignment argument.
599 The alignment argument should be a power of two. If the argument is
600 not a power of two, the nearest greater power is used.
601 8-byte alignment is guaranteed by normal malloc calls, so don't
602 bother calling memalign with an argument of 8 or less.
604 Overreliance on memalign is a sure way to fragment space.
606 void* __libc_memalign(size_t, size_t);
607 libc_hidden_proto (__libc_memalign)
610 valloc(size_t n);
611 Equivalent to memalign(pagesize, n), where pagesize is the page
612 size of the system. If the pagesize is unknown, 4096 is used.
614 void* __libc_valloc(size_t);
619 mallopt(int parameter_number, int parameter_value)
620 Sets tunable parameters The format is to provide a
621 (parameter-number, parameter-value) pair. mallopt then sets the
622 corresponding parameter to the argument value if it can (i.e., so
623 long as the value is meaningful), and returns 1 if successful else
624 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
625 normally defined in malloc.h. Only one of these (M_MXFAST) is used
626 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
627 so setting them has no effect. But this malloc also supports four
628 other options in mallopt. See below for details. Briefly, supported
629 parameters are as follows (listed defaults are for "typical"
630 configurations).
632 Symbol param # default allowed param values
633 M_MXFAST 1 64 0-80 (0 disables fastbins)
634 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
635 M_TOP_PAD -2 0 any
636 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
637 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
639 int __libc_mallopt(int, int);
640 libc_hidden_proto (__libc_mallopt)
644 mallinfo()
645 Returns (by copy) a struct containing various summary statistics:
647 arena: current total non-mmapped bytes allocated from system
648 ordblks: the number of free chunks
649 smblks: the number of fastbin blocks (i.e., small chunks that
650 have been freed but not use resused or consolidated)
651 hblks: current number of mmapped regions
652 hblkhd: total bytes held in mmapped regions
653 usmblks: always 0
654 fsmblks: total bytes held in fastbin blocks
655 uordblks: current total allocated space (normal or mmapped)
656 fordblks: total free space
657 keepcost: the maximum number of bytes that could ideally be released
658 back to system via malloc_trim. ("ideally" means that
659 it ignores page restrictions etc.)
661 Because these fields are ints, but internal bookkeeping may
662 be kept as longs, the reported values may wrap around zero and
663 thus be inaccurate.
665 struct mallinfo __libc_mallinfo(void);
669 pvalloc(size_t n);
670 Equivalent to valloc(minimum-page-that-holds(n)), that is,
671 round up n to nearest pagesize.
673 void* __libc_pvalloc(size_t);
676 malloc_trim(size_t pad);
678 If possible, gives memory back to the system (via negative
679 arguments to sbrk) if there is unused memory at the `high' end of
680 the malloc pool. You can call this after freeing large blocks of
681 memory to potentially reduce the system-level memory requirements
682 of a program. However, it cannot guarantee to reduce memory. Under
683 some allocation patterns, some large free blocks of memory will be
684 locked between two used chunks, so they cannot be given back to
685 the system.
687 The `pad' argument to malloc_trim represents the amount of free
688 trailing space to leave untrimmed. If this argument is zero,
689 only the minimum amount of memory to maintain internal data
690 structures will be left (one page or less). Non-zero arguments
691 can be supplied to maintain enough trailing space to service
692 future expected allocations without having to re-obtain memory
693 from the system.
695 Malloc_trim returns 1 if it actually released any memory, else 0.
696 On systems that do not support "negative sbrks", it will always
697 return 0.
699 int __malloc_trim(size_t);
702 malloc_usable_size(void* p);
704 Returns the number of bytes you can actually use in
705 an allocated chunk, which may be more than you requested (although
706 often not) due to alignment and minimum size constraints.
707 You can use this many bytes without worrying about
708 overwriting other allocated objects. This is not a particularly great
709 programming practice. malloc_usable_size can be more useful in
710 debugging and assertions, for example:
712 p = malloc(n);
713 assert(malloc_usable_size(p) >= 256);
716 size_t __malloc_usable_size(void*);
719 malloc_stats();
720 Prints on stderr the amount of space obtained from the system (both
721 via sbrk and mmap), the maximum amount (which may be more than
722 current if malloc_trim and/or munmap got called), and the current
723 number of bytes allocated via malloc (or realloc, etc) but not yet
724 freed. Note that this is the number of bytes allocated, not the
725 number requested. It will be larger than the number requested
726 because of alignment and bookkeeping overhead. Because it includes
727 alignment wastage as being in use, this figure may be greater than
728 zero even when no user-level chunks are allocated.
730 The reported current and maximum system memory can be inaccurate if
731 a program makes other calls to system memory allocation functions
732 (normally sbrk) outside of malloc.
734 malloc_stats prints only the most commonly interesting statistics.
735 More information can be obtained by calling mallinfo.
738 void __malloc_stats(void);
741 malloc_get_state(void);
743 Returns the state of all malloc variables in an opaque data
744 structure.
746 void* __malloc_get_state(void);
749 malloc_set_state(void* state);
751 Restore the state of all malloc variables from data obtained with
752 malloc_get_state().
754 int __malloc_set_state(void*);
757 posix_memalign(void **memptr, size_t alignment, size_t size);
759 POSIX wrapper like memalign(), checking for validity of size.
761 int __posix_memalign(void **, size_t, size_t);
763 /* mallopt tuning options */
766 M_MXFAST is the maximum request size used for "fastbins", special bins
767 that hold returned chunks without consolidating their spaces. This
768 enables future requests for chunks of the same size to be handled
769 very quickly, but can increase fragmentation, and thus increase the
770 overall memory footprint of a program.
772 This malloc manages fastbins very conservatively yet still
773 efficiently, so fragmentation is rarely a problem for values less
774 than or equal to the default. The maximum supported value of MXFAST
775 is 80. You wouldn't want it any higher than this anyway. Fastbins
776 are designed especially for use with many small structs, objects or
777 strings -- the default handles structs/objects/arrays with sizes up
778 to 8 4byte fields, or small strings representing words, tokens,
779 etc. Using fastbins for larger objects normally worsens
780 fragmentation without improving speed.
782 M_MXFAST is set in REQUEST size units. It is internally used in
783 chunksize units, which adds padding and alignment. You can reduce
784 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
785 algorithm to be a closer approximation of fifo-best-fit in all cases,
786 not just for larger requests, but will generally cause it to be
787 slower.
791 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
792 #ifndef M_MXFAST
793 #define M_MXFAST 1
794 #endif
796 #ifndef DEFAULT_MXFAST
797 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
798 #endif
802 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
803 to keep before releasing via malloc_trim in free().
805 Automatic trimming is mainly useful in long-lived programs.
806 Because trimming via sbrk can be slow on some systems, and can
807 sometimes be wasteful (in cases where programs immediately
808 afterward allocate more large chunks) the value should be high
809 enough so that your overall system performance would improve by
810 releasing this much memory.
812 The trim threshold and the mmap control parameters (see below)
813 can be traded off with one another. Trimming and mmapping are
814 two different ways of releasing unused memory back to the
815 system. Between these two, it is often possible to keep
816 system-level demands of a long-lived program down to a bare
817 minimum. For example, in one test suite of sessions measuring
818 the XF86 X server on Linux, using a trim threshold of 128K and a
819 mmap threshold of 192K led to near-minimal long term resource
820 consumption.
822 If you are using this malloc in a long-lived program, it should
823 pay to experiment with these values. As a rough guide, you
824 might set to a value close to the average size of a process
825 (program) running on your system. Releasing this much memory
826 would allow such a process to run in memory. Generally, it's
827 worth it to tune for trimming rather tham memory mapping when a
828 program undergoes phases where several large chunks are
829 allocated and released in ways that can reuse each other's
830 storage, perhaps mixed with phases where there are no such
831 chunks at all. And in well-behaved long-lived programs,
832 controlling release of large blocks via trimming versus mapping
833 is usually faster.
835 However, in most programs, these parameters serve mainly as
836 protection against the system-level effects of carrying around
837 massive amounts of unneeded memory. Since frequent calls to
838 sbrk, mmap, and munmap otherwise degrade performance, the default
839 parameters are set to relatively high values that serve only as
840 safeguards.
842 The trim value It must be greater than page size to have any useful
843 effect. To disable trimming completely, you can set to
844 (unsigned long)(-1)
846 Trim settings interact with fastbin (MXFAST) settings: Unless
847 TRIM_FASTBINS is defined, automatic trimming never takes place upon
848 freeing a chunk with size less than or equal to MXFAST. Trimming is
849 instead delayed until subsequent freeing of larger chunks. However,
850 you can still force an attempted trim by calling malloc_trim.
852 Also, trimming is not generally possible in cases where
853 the main arena is obtained via mmap.
855 Note that the trick some people use of mallocing a huge space and
856 then freeing it at program startup, in an attempt to reserve system
857 memory, doesn't have the intended effect under automatic trimming,
858 since that memory will immediately be returned to the system.
861 #define M_TRIM_THRESHOLD -1
863 #ifndef DEFAULT_TRIM_THRESHOLD
864 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
865 #endif
868 M_TOP_PAD is the amount of extra `padding' space to allocate or
869 retain whenever sbrk is called. It is used in two ways internally:
871 * When sbrk is called to extend the top of the arena to satisfy
872 a new malloc request, this much padding is added to the sbrk
873 request.
875 * When malloc_trim is called automatically from free(),
876 it is used as the `pad' argument.
878 In both cases, the actual amount of padding is rounded
879 so that the end of the arena is always a system page boundary.
881 The main reason for using padding is to avoid calling sbrk so
882 often. Having even a small pad greatly reduces the likelihood
883 that nearly every malloc request during program start-up (or
884 after trimming) will invoke sbrk, which needlessly wastes
885 time.
887 Automatic rounding-up to page-size units is normally sufficient
888 to avoid measurable overhead, so the default is 0. However, in
889 systems where sbrk is relatively slow, it can pay to increase
890 this value, at the expense of carrying around more memory than
891 the program needs.
894 #define M_TOP_PAD -2
896 #ifndef DEFAULT_TOP_PAD
897 #define DEFAULT_TOP_PAD (0)
898 #endif
901 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
902 adjusted MMAP_THRESHOLD.
905 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
906 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
907 #endif
909 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
910 /* For 32-bit platforms we cannot increase the maximum mmap
911 threshold much because it is also the minimum value for the
912 maximum heap size and its alignment. Going above 512k (i.e., 1M
913 for new heaps) wastes too much address space. */
914 # if __WORDSIZE == 32
915 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
916 # else
917 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
918 # endif
919 #endif
922 M_MMAP_THRESHOLD is the request size threshold for using mmap()
923 to service a request. Requests of at least this size that cannot
924 be allocated using already-existing space will be serviced via mmap.
925 (If enough normal freed space already exists it is used instead.)
927 Using mmap segregates relatively large chunks of memory so that
928 they can be individually obtained and released from the host
929 system. A request serviced through mmap is never reused by any
930 other request (at least not directly; the system may just so
931 happen to remap successive requests to the same locations).
933 Segregating space in this way has the benefits that:
935 1. Mmapped space can ALWAYS be individually released back
936 to the system, which helps keep the system level memory
937 demands of a long-lived program low.
938 2. Mapped memory can never become `locked' between
939 other chunks, as can happen with normally allocated chunks, which
940 means that even trimming via malloc_trim would not release them.
941 3. On some systems with "holes" in address spaces, mmap can obtain
942 memory that sbrk cannot.
944 However, it has the disadvantages that:
946 1. The space cannot be reclaimed, consolidated, and then
947 used to service later requests, as happens with normal chunks.
948 2. It can lead to more wastage because of mmap page alignment
949 requirements
950 3. It causes malloc performance to be more dependent on host
951 system memory management support routines which may vary in
952 implementation quality and may impose arbitrary
953 limitations. Generally, servicing a request via normal
954 malloc steps is faster than going through a system's mmap.
956 The advantages of mmap nearly always outweigh disadvantages for
957 "large" chunks, but the value of "large" varies across systems. The
958 default is an empirically derived value that works well in most
959 systems.
962 Update in 2006:
963 The above was written in 2001. Since then the world has changed a lot.
964 Memory got bigger. Applications got bigger. The virtual address space
965 layout in 32 bit linux changed.
967 In the new situation, brk() and mmap space is shared and there are no
968 artificial limits on brk size imposed by the kernel. What is more,
969 applications have started using transient allocations larger than the
970 128Kb as was imagined in 2001.
972 The price for mmap is also high now; each time glibc mmaps from the
973 kernel, the kernel is forced to zero out the memory it gives to the
974 application. Zeroing memory is expensive and eats a lot of cache and
975 memory bandwidth. This has nothing to do with the efficiency of the
976 virtual memory system, by doing mmap the kernel just has no choice but
977 to zero.
979 In 2001, the kernel had a maximum size for brk() which was about 800
980 megabytes on 32 bit x86, at that point brk() would hit the first
981 mmaped shared libaries and couldn't expand anymore. With current 2.6
982 kernels, the VA space layout is different and brk() and mmap
983 both can span the entire heap at will.
985 Rather than using a static threshold for the brk/mmap tradeoff,
986 we are now using a simple dynamic one. The goal is still to avoid
987 fragmentation. The old goals we kept are
988 1) try to get the long lived large allocations to use mmap()
989 2) really large allocations should always use mmap()
990 and we're adding now:
991 3) transient allocations should use brk() to avoid forcing the kernel
992 having to zero memory over and over again
994 The implementation works with a sliding threshold, which is by default
995 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
996 out at 128Kb as per the 2001 default.
998 This allows us to satisfy requirement 1) under the assumption that long
999 lived allocations are made early in the process' lifespan, before it has
1000 started doing dynamic allocations of the same size (which will
1001 increase the threshold).
1003 The upperbound on the threshold satisfies requirement 2)
1005 The threshold goes up in value when the application frees memory that was
1006 allocated with the mmap allocator. The idea is that once the application
1007 starts freeing memory of a certain size, it's highly probable that this is
1008 a size the application uses for transient allocations. This estimator
1009 is there to satisfy the new third requirement.
1013 #define M_MMAP_THRESHOLD -3
1015 #ifndef DEFAULT_MMAP_THRESHOLD
1016 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1017 #endif
1020 M_MMAP_MAX is the maximum number of requests to simultaneously
1021 service using mmap. This parameter exists because
1022 some systems have a limited number of internal tables for
1023 use by mmap, and using more than a few of them may degrade
1024 performance.
1026 The default is set to a value that serves only as a safeguard.
1027 Setting to 0 disables use of mmap for servicing large requests.
1030 #define M_MMAP_MAX -4
1032 #ifndef DEFAULT_MMAP_MAX
1033 #define DEFAULT_MMAP_MAX (65536)
1034 #endif
1036 #include <malloc.h>
1038 #ifndef RETURN_ADDRESS
1039 #define RETURN_ADDRESS(X_) (NULL)
1040 #endif
1042 /* On some platforms we can compile internal, not exported functions better.
1043 Let the environment provide a macro and define it to be empty if it
1044 is not available. */
1045 #ifndef internal_function
1046 # define internal_function
1047 #endif
1049 /* Forward declarations. */
1050 struct malloc_chunk;
1051 typedef struct malloc_chunk* mchunkptr;
1053 /* Internal routines. */
1055 static void* _int_malloc(mstate, size_t);
1056 static void _int_free(mstate, mchunkptr, int);
1057 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1058 INTERNAL_SIZE_T);
1059 static void* _int_memalign(mstate, size_t, size_t);
1060 static void* _mid_memalign(size_t, size_t, void *);
1062 static void malloc_printerr(int action, const char *str, void *ptr, mstate av);
1064 static void* internal_function mem2mem_check(void *p, size_t sz);
1065 static int internal_function top_check(void);
1066 static void internal_function munmap_chunk(mchunkptr p);
1067 #if HAVE_MREMAP
1068 static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
1069 #endif
1071 static void* malloc_check(size_t sz, const void *caller);
1072 static void free_check(void* mem, const void *caller);
1073 static void* realloc_check(void* oldmem, size_t bytes,
1074 const void *caller);
1075 static void* memalign_check(size_t alignment, size_t bytes,
1076 const void *caller);
1078 /* ------------------ MMAP support ------------------ */
1081 #include <fcntl.h>
1082 #include <sys/mman.h>
1084 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1085 # define MAP_ANONYMOUS MAP_ANON
1086 #endif
1088 #ifndef MAP_NORESERVE
1089 # define MAP_NORESERVE 0
1090 #endif
1092 #define MMAP(addr, size, prot, flags) \
1093 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1097 ----------------------- Chunk representations -----------------------
1102 This struct declaration is misleading (but accurate and necessary).
1103 It declares a "view" into memory allowing access to necessary
1104 fields at known offsets from a given base. See explanation below.
1107 struct malloc_chunk {
1109 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
1110 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
1112 struct malloc_chunk* fd; /* double links -- used only if free. */
1113 struct malloc_chunk* bk;
1115 /* Only used for large blocks: pointer to next larger size. */
1116 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1117 struct malloc_chunk* bk_nextsize;
1122 malloc_chunk details:
1124 (The following includes lightly edited explanations by Colin Plumb.)
1126 Chunks of memory are maintained using a `boundary tag' method as
1127 described in e.g., Knuth or Standish. (See the paper by Paul
1128 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1129 survey of such techniques.) Sizes of free chunks are stored both
1130 in the front of each chunk and at the end. This makes
1131 consolidating fragmented chunks into bigger chunks very fast. The
1132 size fields also hold bits representing whether chunks are free or
1133 in use.
1135 An allocated chunk looks like this:
1138 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1139 | Size of previous chunk, if allocated | |
1140 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1141 | Size of chunk, in bytes |M|P|
1142 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1143 | User data starts here... .
1145 . (malloc_usable_size() bytes) .
1147 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1148 | Size of chunk |
1149 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1152 Where "chunk" is the front of the chunk for the purpose of most of
1153 the malloc code, but "mem" is the pointer that is returned to the
1154 user. "Nextchunk" is the beginning of the next contiguous chunk.
1156 Chunks always begin on even word boundaries, so the mem portion
1157 (which is returned to the user) is also on an even word boundary, and
1158 thus at least double-word aligned.
1160 Free chunks are stored in circular doubly-linked lists, and look like this:
1162 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1163 | Size of previous chunk |
1164 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1165 `head:' | Size of chunk, in bytes |P|
1166 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1167 | Forward pointer to next chunk in list |
1168 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1169 | Back pointer to previous chunk in list |
1170 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1171 | Unused space (may be 0 bytes long) .
1174 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1175 `foot:' | Size of chunk, in bytes |
1176 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1178 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1179 chunk size (which is always a multiple of two words), is an in-use
1180 bit for the *previous* chunk. If that bit is *clear*, then the
1181 word before the current chunk size contains the previous chunk
1182 size, and can be used to find the front of the previous chunk.
1183 The very first chunk allocated always has this bit set,
1184 preventing access to non-existent (or non-owned) memory. If
1185 prev_inuse is set for any given chunk, then you CANNOT determine
1186 the size of the previous chunk, and might even get a memory
1187 addressing fault when trying to do so.
1189 Note that the `foot' of the current chunk is actually represented
1190 as the prev_size of the NEXT chunk. This makes it easier to
1191 deal with alignments etc but can be very confusing when trying
1192 to extend or adapt this code.
1194 The two exceptions to all this are
1196 1. The special chunk `top' doesn't bother using the
1197 trailing size field since there is no next contiguous chunk
1198 that would have to index off it. After initialization, `top'
1199 is forced to always exist. If it would become less than
1200 MINSIZE bytes long, it is replenished.
1202 2. Chunks allocated via mmap, which have the second-lowest-order
1203 bit M (IS_MMAPPED) set in their size fields. Because they are
1204 allocated one-by-one, each must contain its own trailing size field.
1209 ---------- Size and alignment checks and conversions ----------
1212 /* conversion from malloc headers to user pointers, and back */
1214 #define chunk2mem(p) ((void*)((char*)(p) + 2*SIZE_SZ))
1215 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1217 /* The smallest possible chunk */
1218 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1220 /* The smallest size we can malloc is an aligned minimal chunk */
1222 #define MINSIZE \
1223 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1225 /* Check if m has acceptable alignment */
1227 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1229 #define misaligned_chunk(p) \
1230 ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
1231 & MALLOC_ALIGN_MASK)
1235 Check if a request is so large that it would wrap around zero when
1236 padded and aligned. To simplify some other code, the bound is made
1237 low enough so that adding MINSIZE will also not wrap around zero.
1240 #define REQUEST_OUT_OF_RANGE(req) \
1241 ((unsigned long) (req) >= \
1242 (unsigned long) (INTERNAL_SIZE_T) (-2 * MINSIZE))
1244 /* pad request bytes into a usable size -- internal version */
1246 #define request2size(req) \
1247 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1248 MINSIZE : \
1249 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1251 /* Same, except also perform argument check */
1253 #define checked_request2size(req, sz) \
1254 if (REQUEST_OUT_OF_RANGE (req)) { \
1255 __set_errno (ENOMEM); \
1256 return 0; \
1258 (sz) = request2size (req);
1261 --------------- Physical chunk operations ---------------
1265 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1266 #define PREV_INUSE 0x1
1268 /* extract inuse bit of previous chunk */
1269 #define prev_inuse(p) ((p)->size & PREV_INUSE)
1272 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1273 #define IS_MMAPPED 0x2
1275 /* check for mmap()'ed chunk */
1276 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1279 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1280 from a non-main arena. This is only set immediately before handing
1281 the chunk to the user, if necessary. */
1282 #define NON_MAIN_ARENA 0x4
1284 /* check for chunk from non-main arena */
1285 #define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)
1289 Bits to mask off when extracting size
1291 Note: IS_MMAPPED is intentionally not masked off from size field in
1292 macros for which mmapped chunks should never be seen. This should
1293 cause helpful core dumps to occur if it is tried by accident by
1294 people extending or adapting this malloc.
1296 #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1298 /* Get size, ignoring use bits */
1299 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
1302 /* Ptr to next physical malloc_chunk. */
1303 #define next_chunk(p) ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))
1305 /* Ptr to previous physical malloc_chunk */
1306 #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - ((p)->prev_size)))
1308 /* Treat space at ptr + offset as a chunk */
1309 #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1311 /* extract p's inuse bit */
1312 #define inuse(p) \
1313 ((((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)
1315 /* set/clear chunk as being inuse without otherwise disturbing */
1316 #define set_inuse(p) \
1317 ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE
1319 #define clear_inuse(p) \
1320 ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)
1323 /* check/set/clear inuse bits in known places */
1324 #define inuse_bit_at_offset(p, s) \
1325 (((mchunkptr) (((char *) (p)) + (s)))->size & PREV_INUSE)
1327 #define set_inuse_bit_at_offset(p, s) \
1328 (((mchunkptr) (((char *) (p)) + (s)))->size |= PREV_INUSE)
1330 #define clear_inuse_bit_at_offset(p, s) \
1331 (((mchunkptr) (((char *) (p)) + (s)))->size &= ~(PREV_INUSE))
1334 /* Set size at head, without disturbing its use bit */
1335 #define set_head_size(p, s) ((p)->size = (((p)->size & SIZE_BITS) | (s)))
1337 /* Set size/use field */
1338 #define set_head(p, s) ((p)->size = (s))
1340 /* Set size at footer (only when chunk is not in use) */
1341 #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->prev_size = (s))
1345 -------------------- Internal data structures --------------------
1347 All internal state is held in an instance of malloc_state defined
1348 below. There are no other static variables, except in two optional
1349 cases:
1350 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1351 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1352 for mmap.
1354 Beware of lots of tricks that minimize the total bookkeeping space
1355 requirements. The result is a little over 1K bytes (for 4byte
1356 pointers and size_t.)
1360 Bins
1362 An array of bin headers for free chunks. Each bin is doubly
1363 linked. The bins are approximately proportionally (log) spaced.
1364 There are a lot of these bins (128). This may look excessive, but
1365 works very well in practice. Most bins hold sizes that are
1366 unusual as malloc request sizes, but are more usual for fragments
1367 and consolidated sets of chunks, which is what these bins hold, so
1368 they can be found quickly. All procedures maintain the invariant
1369 that no consolidated chunk physically borders another one, so each
1370 chunk in a list is known to be preceeded and followed by either
1371 inuse chunks or the ends of memory.
1373 Chunks in bins are kept in size order, with ties going to the
1374 approximately least recently used chunk. Ordering isn't needed
1375 for the small bins, which all contain the same-sized chunks, but
1376 facilitates best-fit allocation for larger chunks. These lists
1377 are just sequential. Keeping them in order almost never requires
1378 enough traversal to warrant using fancier ordered data
1379 structures.
1381 Chunks of the same size are linked with the most
1382 recently freed at the front, and allocations are taken from the
1383 back. This results in LRU (FIFO) allocation order, which tends
1384 to give each chunk an equal opportunity to be consolidated with
1385 adjacent freed chunks, resulting in larger free chunks and less
1386 fragmentation.
1388 To simplify use in double-linked lists, each bin header acts
1389 as a malloc_chunk. This avoids special-casing for headers.
1390 But to conserve space and improve locality, we allocate
1391 only the fd/bk pointers of bins, and then use repositioning tricks
1392 to treat these as the fields of a malloc_chunk*.
1395 typedef struct malloc_chunk *mbinptr;
1397 /* addressing -- note that bin_at(0) does not exist */
1398 #define bin_at(m, i) \
1399 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1400 - offsetof (struct malloc_chunk, fd))
1402 /* analog of ++bin */
1403 #define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
1405 /* Reminders about list directionality within bins */
1406 #define first(b) ((b)->fd)
1407 #define last(b) ((b)->bk)
1409 /* Take a chunk off a bin list */
1410 #define unlink(AV, P, BK, FD) { \
1411 FD = P->fd; \
1412 BK = P->bk; \
1413 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
1414 malloc_printerr (check_action, "corrupted double-linked list", P, AV); \
1415 else { \
1416 FD->bk = BK; \
1417 BK->fd = FD; \
1418 if (!in_smallbin_range (P->size) \
1419 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \
1420 if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \
1421 || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \
1422 malloc_printerr (check_action, \
1423 "corrupted double-linked list (not small)", \
1424 P, AV); \
1425 if (FD->fd_nextsize == NULL) { \
1426 if (P->fd_nextsize == P) \
1427 FD->fd_nextsize = FD->bk_nextsize = FD; \
1428 else { \
1429 FD->fd_nextsize = P->fd_nextsize; \
1430 FD->bk_nextsize = P->bk_nextsize; \
1431 P->fd_nextsize->bk_nextsize = FD; \
1432 P->bk_nextsize->fd_nextsize = FD; \
1434 } else { \
1435 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \
1436 P->bk_nextsize->fd_nextsize = P->fd_nextsize; \
1443 Indexing
1445 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1446 8 bytes apart. Larger bins are approximately logarithmically spaced:
1448 64 bins of size 8
1449 32 bins of size 64
1450 16 bins of size 512
1451 8 bins of size 4096
1452 4 bins of size 32768
1453 2 bins of size 262144
1454 1 bin of size what's left
1456 There is actually a little bit of slop in the numbers in bin_index
1457 for the sake of speed. This makes no difference elsewhere.
1459 The bins top out around 1MB because we expect to service large
1460 requests via mmap.
1462 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1463 a valid chunk size the small bins are bumped up one.
1466 #define NBINS 128
1467 #define NSMALLBINS 64
1468 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1469 #define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > 2 * SIZE_SZ)
1470 #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
1472 #define in_smallbin_range(sz) \
1473 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
1475 #define smallbin_index(sz) \
1476 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
1477 + SMALLBIN_CORRECTION)
1479 #define largebin_index_32(sz) \
1480 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1481 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1482 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1483 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1484 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1485 126)
1487 #define largebin_index_32_big(sz) \
1488 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1489 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1490 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1491 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1492 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1493 126)
1495 // XXX It remains to be seen whether it is good to keep the widths of
1496 // XXX the buckets the same or whether it should be scaled by a factor
1497 // XXX of two as well.
1498 #define largebin_index_64(sz) \
1499 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1500 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1501 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1502 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1503 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1504 126)
1506 #define largebin_index(sz) \
1507 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1508 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1509 : largebin_index_32 (sz))
1511 #define bin_index(sz) \
1512 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
1516 Unsorted chunks
1518 All remainders from chunk splits, as well as all returned chunks,
1519 are first placed in the "unsorted" bin. They are then placed
1520 in regular bins after malloc gives them ONE chance to be used before
1521 binning. So, basically, the unsorted_chunks list acts as a queue,
1522 with chunks being placed on it in free (and malloc_consolidate),
1523 and taken off (to be either used or placed in bins) in malloc.
1525 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1526 does not have to be taken into account in size comparisons.
1529 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1530 #define unsorted_chunks(M) (bin_at (M, 1))
1535 The top-most available chunk (i.e., the one bordering the end of
1536 available memory) is treated specially. It is never included in
1537 any bin, is used only if no other chunk is available, and is
1538 released back to the system if it is very large (see
1539 M_TRIM_THRESHOLD). Because top initially
1540 points to its own bin with initial zero size, thus forcing
1541 extension on the first malloc request, we avoid having any special
1542 code in malloc to check whether it even exists yet. But we still
1543 need to do so when getting memory from system, so we make
1544 initial_top treat the bin as a legal but unusable chunk during the
1545 interval between initialization and the first call to
1546 sysmalloc. (This is somewhat delicate, since it relies on
1547 the 2 preceding words to be zero during this interval as well.)
1550 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1551 #define initial_top(M) (unsorted_chunks (M))
1554 Binmap
1556 To help compensate for the large number of bins, a one-level index
1557 structure is used for bin-by-bin searching. `binmap' is a
1558 bitvector recording whether bins are definitely empty so they can
1559 be skipped over during during traversals. The bits are NOT always
1560 cleared as soon as bins are empty, but instead only
1561 when they are noticed to be empty during traversal in malloc.
1564 /* Conservatively use 32 bits per map word, even if on 64bit system */
1565 #define BINMAPSHIFT 5
1566 #define BITSPERMAP (1U << BINMAPSHIFT)
1567 #define BINMAPSIZE (NBINS / BITSPERMAP)
1569 #define idx2block(i) ((i) >> BINMAPSHIFT)
1570 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
1572 #define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1573 #define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1574 #define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
1577 Fastbins
1579 An array of lists holding recently freed small chunks. Fastbins
1580 are not doubly linked. It is faster to single-link them, and
1581 since chunks are never removed from the middles of these lists,
1582 double linking is not necessary. Also, unlike regular bins, they
1583 are not even processed in FIFO order (they use faster LIFO) since
1584 ordering doesn't much matter in the transient contexts in which
1585 fastbins are normally used.
1587 Chunks in fastbins keep their inuse bit set, so they cannot
1588 be consolidated with other free chunks. malloc_consolidate
1589 releases all chunks in fastbins and consolidates them with
1590 other free chunks.
1593 typedef struct malloc_chunk *mfastbinptr;
1594 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1596 /* offset 2 to use otherwise unindexable first 2 bins */
1597 #define fastbin_index(sz) \
1598 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1601 /* The maximum fastbin request size we support */
1602 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1604 #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
1607 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1608 that triggers automatic consolidation of possibly-surrounding
1609 fastbin chunks. This is a heuristic, so the exact value should not
1610 matter too much. It is defined at half the default trim threshold as a
1611 compromise heuristic to only attempt consolidation if it is likely
1612 to lead to trimming. However, it is not dynamically tunable, since
1613 consolidation reduces fragmentation surrounding large chunks even
1614 if trimming is not used.
1617 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1620 Since the lowest 2 bits in max_fast don't matter in size comparisons,
1621 they are used as flags.
1625 FASTCHUNKS_BIT held in max_fast indicates that there are probably
1626 some fastbin chunks. It is set true on entering a chunk into any
1627 fastbin, and cleared only in malloc_consolidate.
1629 The truth value is inverted so that have_fastchunks will be true
1630 upon startup (since statics are zero-filled), simplifying
1631 initialization checks.
1634 #define FASTCHUNKS_BIT (1U)
1636 #define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
1637 #define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT)
1638 #define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT)
1641 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1642 regions. Otherwise, contiguity is exploited in merging together,
1643 when possible, results from consecutive MORECORE calls.
1645 The initial value comes from MORECORE_CONTIGUOUS, but is
1646 changed dynamically if mmap is ever used as an sbrk substitute.
1649 #define NONCONTIGUOUS_BIT (2U)
1651 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1652 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1653 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1654 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1656 /* ARENA_CORRUPTION_BIT is set if a memory corruption was detected on the
1657 arena. Such an arena is no longer used to allocate chunks. Chunks
1658 allocated in that arena before detecting corruption are not freed. */
1660 #define ARENA_CORRUPTION_BIT (4U)
1662 #define arena_is_corrupt(A) (((A)->flags & ARENA_CORRUPTION_BIT))
1663 #define set_arena_corrupt(A) ((A)->flags |= ARENA_CORRUPTION_BIT)
1666 Set value of max_fast.
1667 Use impossibly small value if 0.
1668 Precondition: there are no existing fastbin chunks.
1669 Setting the value clears fastchunk bit but preserves noncontiguous bit.
1672 #define set_max_fast(s) \
1673 global_max_fast = (((s) == 0) \
1674 ? SMALLBIN_WIDTH : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1675 #define get_max_fast() global_max_fast
1679 ----------- Internal state representation and initialization -----------
1682 struct malloc_state
1684 /* Serialize access. */
1685 mutex_t mutex;
1687 /* Flags (formerly in max_fast). */
1688 int flags;
1690 /* Fastbins */
1691 mfastbinptr fastbinsY[NFASTBINS];
1693 /* Base of the topmost chunk -- not otherwise kept in a bin */
1694 mchunkptr top;
1696 /* The remainder from the most recent split of a small request */
1697 mchunkptr last_remainder;
1699 /* Normal bins packed as described above */
1700 mchunkptr bins[NBINS * 2 - 2];
1702 /* Bitmap of bins */
1703 unsigned int binmap[BINMAPSIZE];
1705 /* Linked list */
1706 struct malloc_state *next;
1708 /* Linked list for free arenas. Access to this field is serialized
1709 by free_list_lock in arena.c. */
1710 struct malloc_state *next_free;
1712 /* Number of threads attached to this arena. 0 if the arena is on
1713 the free list. Access to this field is serialized by
1714 free_list_lock in arena.c. */
1715 INTERNAL_SIZE_T attached_threads;
1717 /* Memory allocated from the system in this arena. */
1718 INTERNAL_SIZE_T system_mem;
1719 INTERNAL_SIZE_T max_system_mem;
1722 struct malloc_par
1724 /* Tunable parameters */
1725 unsigned long trim_threshold;
1726 INTERNAL_SIZE_T top_pad;
1727 INTERNAL_SIZE_T mmap_threshold;
1728 INTERNAL_SIZE_T arena_test;
1729 INTERNAL_SIZE_T arena_max;
1731 /* Memory map support */
1732 int n_mmaps;
1733 int n_mmaps_max;
1734 int max_n_mmaps;
1735 /* the mmap_threshold is dynamic, until the user sets
1736 it manually, at which point we need to disable any
1737 dynamic behavior. */
1738 int no_dyn_threshold;
1740 /* Statistics */
1741 INTERNAL_SIZE_T mmapped_mem;
1742 INTERNAL_SIZE_T max_mmapped_mem;
1744 /* First address handed out by MORECORE/sbrk. */
1745 char *sbrk_base;
1748 /* There are several instances of this struct ("arenas") in this
1749 malloc. If you are adapting this malloc in a way that does NOT use
1750 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1751 before using. This malloc relies on the property that malloc_state
1752 is initialized to all zeroes (as is true of C statics). */
1754 static struct malloc_state main_arena =
1756 .mutex = _LIBC_LOCK_INITIALIZER,
1757 .next = &main_arena,
1758 .attached_threads = 1
1761 /* There is only one instance of the malloc parameters. */
1763 static struct malloc_par mp_ =
1765 .top_pad = DEFAULT_TOP_PAD,
1766 .n_mmaps_max = DEFAULT_MMAP_MAX,
1767 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1768 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1769 #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1770 .arena_test = NARENAS_FROM_NCORES (1)
1774 /* Non public mallopt parameters. */
1775 #define M_ARENA_TEST -7
1776 #define M_ARENA_MAX -8
1779 /* Maximum size of memory handled in fastbins. */
1780 static INTERNAL_SIZE_T global_max_fast;
1783 Initialize a malloc_state struct.
1785 This is called only from within malloc_consolidate, which needs
1786 be called in the same contexts anyway. It is never called directly
1787 outside of malloc_consolidate because some optimizing compilers try
1788 to inline it at all call points, which turns out not to be an
1789 optimization at all. (Inlining it in malloc_consolidate is fine though.)
1792 static void
1793 malloc_init_state (mstate av)
1795 int i;
1796 mbinptr bin;
1798 /* Establish circular links for normal bins */
1799 for (i = 1; i < NBINS; ++i)
1801 bin = bin_at (av, i);
1802 bin->fd = bin->bk = bin;
1805 #if MORECORE_CONTIGUOUS
1806 if (av != &main_arena)
1807 #endif
1808 set_noncontiguous (av);
1809 if (av == &main_arena)
1810 set_max_fast (DEFAULT_MXFAST);
1811 av->flags |= FASTCHUNKS_BIT;
1813 av->top = initial_top (av);
1817 Other internal utilities operating on mstates
1820 static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1821 static int systrim (size_t, mstate);
1822 static void malloc_consolidate (mstate);
1825 /* -------------- Early definitions for debugging hooks ---------------- */
1827 /* Define and initialize the hook variables. These weak definitions must
1828 appear before any use of the variables in a function (arena.c uses one). */
1829 #ifndef weak_variable
1830 /* In GNU libc we want the hook variables to be weak definitions to
1831 avoid a problem with Emacs. */
1832 # define weak_variable weak_function
1833 #endif
1835 /* Forward declarations. */
1836 static void *malloc_hook_ini (size_t sz,
1837 const void *caller) __THROW;
1838 static void *realloc_hook_ini (void *ptr, size_t sz,
1839 const void *caller) __THROW;
1840 static void *memalign_hook_ini (size_t alignment, size_t sz,
1841 const void *caller) __THROW;
1843 void weak_variable (*__malloc_initialize_hook) (void) = NULL;
1844 void weak_variable (*__free_hook) (void *__ptr,
1845 const void *) = NULL;
1846 void *weak_variable (*__malloc_hook)
1847 (size_t __size, const void *) = malloc_hook_ini;
1848 void *weak_variable (*__realloc_hook)
1849 (void *__ptr, size_t __size, const void *)
1850 = realloc_hook_ini;
1851 void *weak_variable (*__memalign_hook)
1852 (size_t __alignment, size_t __size, const void *)
1853 = memalign_hook_ini;
1854 void weak_variable (*__after_morecore_hook) (void) = NULL;
1857 /* ---------------- Error behavior ------------------------------------ */
1859 #ifndef DEFAULT_CHECK_ACTION
1860 # define DEFAULT_CHECK_ACTION 3
1861 #endif
1863 static int check_action = DEFAULT_CHECK_ACTION;
1866 /* ------------------ Testing support ----------------------------------*/
1868 static int perturb_byte;
1870 static void
1871 alloc_perturb (char *p, size_t n)
1873 if (__glibc_unlikely (perturb_byte))
1874 memset (p, perturb_byte ^ 0xff, n);
1877 static void
1878 free_perturb (char *p, size_t n)
1880 if (__glibc_unlikely (perturb_byte))
1881 memset (p, perturb_byte, n);
1886 #include <stap-probe.h>
1888 /* ------------------- Support for multiple arenas -------------------- */
1889 #include "arena.c"
1892 Debugging support
1894 These routines make a number of assertions about the states
1895 of data structures that should be true at all times. If any
1896 are not true, it's very likely that a user program has somehow
1897 trashed memory. (It's also possible that there is a coding error
1898 in malloc. In which case, please report it!)
1901 #if !MALLOC_DEBUG
1903 # define check_chunk(A, P)
1904 # define check_free_chunk(A, P)
1905 # define check_inuse_chunk(A, P)
1906 # define check_remalloced_chunk(A, P, N)
1907 # define check_malloced_chunk(A, P, N)
1908 # define check_malloc_state(A)
1910 #else
1912 # define check_chunk(A, P) do_check_chunk (A, P)
1913 # define check_free_chunk(A, P) do_check_free_chunk (A, P)
1914 # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
1915 # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
1916 # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
1917 # define check_malloc_state(A) do_check_malloc_state (A)
1920 Properties of all chunks
1923 static void
1924 do_check_chunk (mstate av, mchunkptr p)
1926 unsigned long sz = chunksize (p);
1927 /* min and max possible addresses assuming contiguous allocation */
1928 char *max_address = (char *) (av->top) + chunksize (av->top);
1929 char *min_address = max_address - av->system_mem;
1931 if (!chunk_is_mmapped (p))
1933 /* Has legal address ... */
1934 if (p != av->top)
1936 if (contiguous (av))
1938 assert (((char *) p) >= min_address);
1939 assert (((char *) p + sz) <= ((char *) (av->top)));
1942 else
1944 /* top size is always at least MINSIZE */
1945 assert ((unsigned long) (sz) >= MINSIZE);
1946 /* top predecessor always marked inuse */
1947 assert (prev_inuse (p));
1950 else
1952 /* address is outside main heap */
1953 if (contiguous (av) && av->top != initial_top (av))
1955 assert (((char *) p) < min_address || ((char *) p) >= max_address);
1957 /* chunk is page-aligned */
1958 assert (((p->prev_size + sz) & (GLRO (dl_pagesize) - 1)) == 0);
1959 /* mem is aligned */
1960 assert (aligned_OK (chunk2mem (p)));
1965 Properties of free chunks
1968 static void
1969 do_check_free_chunk (mstate av, mchunkptr p)
1971 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
1972 mchunkptr next = chunk_at_offset (p, sz);
1974 do_check_chunk (av, p);
1976 /* Chunk must claim to be free ... */
1977 assert (!inuse (p));
1978 assert (!chunk_is_mmapped (p));
1980 /* Unless a special marker, must have OK fields */
1981 if ((unsigned long) (sz) >= MINSIZE)
1983 assert ((sz & MALLOC_ALIGN_MASK) == 0);
1984 assert (aligned_OK (chunk2mem (p)));
1985 /* ... matching footer field */
1986 assert (next->prev_size == sz);
1987 /* ... and is fully consolidated */
1988 assert (prev_inuse (p));
1989 assert (next == av->top || inuse (next));
1991 /* ... and has minimally sane links */
1992 assert (p->fd->bk == p);
1993 assert (p->bk->fd == p);
1995 else /* markers are always of size SIZE_SZ */
1996 assert (sz == SIZE_SZ);
2000 Properties of inuse chunks
2003 static void
2004 do_check_inuse_chunk (mstate av, mchunkptr p)
2006 mchunkptr next;
2008 do_check_chunk (av, p);
2010 if (chunk_is_mmapped (p))
2011 return; /* mmapped chunks have no next/prev */
2013 /* Check whether it claims to be in use ... */
2014 assert (inuse (p));
2016 next = next_chunk (p);
2018 /* ... and is surrounded by OK chunks.
2019 Since more things can be checked with free chunks than inuse ones,
2020 if an inuse chunk borders them and debug is on, it's worth doing them.
2022 if (!prev_inuse (p))
2024 /* Note that we cannot even look at prev unless it is not inuse */
2025 mchunkptr prv = prev_chunk (p);
2026 assert (next_chunk (prv) == p);
2027 do_check_free_chunk (av, prv);
2030 if (next == av->top)
2032 assert (prev_inuse (next));
2033 assert (chunksize (next) >= MINSIZE);
2035 else if (!inuse (next))
2036 do_check_free_chunk (av, next);
2040 Properties of chunks recycled from fastbins
2043 static void
2044 do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2046 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
2048 if (!chunk_is_mmapped (p))
2050 assert (av == arena_for_chunk (p));
2051 if (chunk_non_main_arena (p))
2052 assert (av != &main_arena);
2053 else
2054 assert (av == &main_arena);
2057 do_check_inuse_chunk (av, p);
2059 /* Legal size ... */
2060 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2061 assert ((unsigned long) (sz) >= MINSIZE);
2062 /* ... and alignment */
2063 assert (aligned_OK (chunk2mem (p)));
2064 /* chunk is less than MINSIZE more than request */
2065 assert ((long) (sz) - (long) (s) >= 0);
2066 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2070 Properties of nonrecycled chunks at the point they are malloced
2073 static void
2074 do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2076 /* same as recycled case ... */
2077 do_check_remalloced_chunk (av, p, s);
2080 ... plus, must obey implementation invariant that prev_inuse is
2081 always true of any allocated chunk; i.e., that each allocated
2082 chunk borders either a previously allocated and still in-use
2083 chunk, or the base of its memory arena. This is ensured
2084 by making all allocations from the `lowest' part of any found
2085 chunk. This does not necessarily hold however for chunks
2086 recycled via fastbins.
2089 assert (prev_inuse (p));
2094 Properties of malloc_state.
2096 This may be useful for debugging malloc, as well as detecting user
2097 programmer errors that somehow write into malloc_state.
2099 If you are extending or experimenting with this malloc, you can
2100 probably figure out how to hack this routine to print out or
2101 display chunk addresses, sizes, bins, and other instrumentation.
2104 static void
2105 do_check_malloc_state (mstate av)
2107 int i;
2108 mchunkptr p;
2109 mchunkptr q;
2110 mbinptr b;
2111 unsigned int idx;
2112 INTERNAL_SIZE_T size;
2113 unsigned long total = 0;
2114 int max_fast_bin;
2116 /* internal size_t must be no wider than pointer type */
2117 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2119 /* alignment is a power of 2 */
2120 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2122 /* cannot run remaining checks until fully initialized */
2123 if (av->top == 0 || av->top == initial_top (av))
2124 return;
2126 /* pagesize is a power of 2 */
2127 assert (powerof2(GLRO (dl_pagesize)));
2129 /* A contiguous main_arena is consistent with sbrk_base. */
2130 if (av == &main_arena && contiguous (av))
2131 assert ((char *) mp_.sbrk_base + av->system_mem ==
2132 (char *) av->top + chunksize (av->top));
2134 /* properties of fastbins */
2136 /* max_fast is in allowed range */
2137 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2139 max_fast_bin = fastbin_index (get_max_fast ());
2141 for (i = 0; i < NFASTBINS; ++i)
2143 p = fastbin (av, i);
2145 /* The following test can only be performed for the main arena.
2146 While mallopt calls malloc_consolidate to get rid of all fast
2147 bins (especially those larger than the new maximum) this does
2148 only happen for the main arena. Trying to do this for any
2149 other arena would mean those arenas have to be locked and
2150 malloc_consolidate be called for them. This is excessive. And
2151 even if this is acceptable to somebody it still cannot solve
2152 the problem completely since if the arena is locked a
2153 concurrent malloc call might create a new arena which then
2154 could use the newly invalid fast bins. */
2156 /* all bins past max_fast are empty */
2157 if (av == &main_arena && i > max_fast_bin)
2158 assert (p == 0);
2160 while (p != 0)
2162 /* each chunk claims to be inuse */
2163 do_check_inuse_chunk (av, p);
2164 total += chunksize (p);
2165 /* chunk belongs in this bin */
2166 assert (fastbin_index (chunksize (p)) == i);
2167 p = p->fd;
2171 if (total != 0)
2172 assert (have_fastchunks (av));
2173 else if (!have_fastchunks (av))
2174 assert (total == 0);
2176 /* check normal bins */
2177 for (i = 1; i < NBINS; ++i)
2179 b = bin_at (av, i);
2181 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2182 if (i >= 2)
2184 unsigned int binbit = get_binmap (av, i);
2185 int empty = last (b) == b;
2186 if (!binbit)
2187 assert (empty);
2188 else if (!empty)
2189 assert (binbit);
2192 for (p = last (b); p != b; p = p->bk)
2194 /* each chunk claims to be free */
2195 do_check_free_chunk (av, p);
2196 size = chunksize (p);
2197 total += size;
2198 if (i >= 2)
2200 /* chunk belongs in bin */
2201 idx = bin_index (size);
2202 assert (idx == i);
2203 /* lists are sorted */
2204 assert (p->bk == b ||
2205 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2207 if (!in_smallbin_range (size))
2209 if (p->fd_nextsize != NULL)
2211 if (p->fd_nextsize == p)
2212 assert (p->bk_nextsize == p);
2213 else
2215 if (p->fd_nextsize == first (b))
2216 assert (chunksize (p) < chunksize (p->fd_nextsize));
2217 else
2218 assert (chunksize (p) > chunksize (p->fd_nextsize));
2220 if (p == first (b))
2221 assert (chunksize (p) > chunksize (p->bk_nextsize));
2222 else
2223 assert (chunksize (p) < chunksize (p->bk_nextsize));
2226 else
2227 assert (p->bk_nextsize == NULL);
2230 else if (!in_smallbin_range (size))
2231 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2232 /* chunk is followed by a legal chain of inuse chunks */
2233 for (q = next_chunk (p);
2234 (q != av->top && inuse (q) &&
2235 (unsigned long) (chunksize (q)) >= MINSIZE);
2236 q = next_chunk (q))
2237 do_check_inuse_chunk (av, q);
2241 /* top chunk is OK */
2242 check_chunk (av, av->top);
2244 #endif
2247 /* ----------------- Support for debugging hooks -------------------- */
2248 #include "hooks.c"
2251 /* ----------- Routines dealing with system allocation -------------- */
2254 sysmalloc handles malloc cases requiring more memory from the system.
2255 On entry, it is assumed that av->top does not have enough
2256 space to service request for nb bytes, thus requiring that av->top
2257 be extended or replaced.
2260 static void *
2261 sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2263 mchunkptr old_top; /* incoming value of av->top */
2264 INTERNAL_SIZE_T old_size; /* its size */
2265 char *old_end; /* its end address */
2267 long size; /* arg to first MORECORE or mmap call */
2268 char *brk; /* return value from MORECORE */
2270 long correction; /* arg to 2nd MORECORE call */
2271 char *snd_brk; /* 2nd return val */
2273 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2274 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2275 char *aligned_brk; /* aligned offset into brk */
2277 mchunkptr p; /* the allocated/returned chunk */
2278 mchunkptr remainder; /* remainder from allocation */
2279 unsigned long remainder_size; /* its size */
2282 size_t pagesize = GLRO (dl_pagesize);
2283 bool tried_mmap = false;
2287 If have mmap, and the request size meets the mmap threshold, and
2288 the system supports mmap, and there are few enough currently
2289 allocated mmapped regions, try to directly map this request
2290 rather than expanding top.
2293 if (av == NULL
2294 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2295 && (mp_.n_mmaps < mp_.n_mmaps_max)))
2297 char *mm; /* return value from mmap call*/
2299 try_mmap:
2301 Round up size to nearest page. For mmapped chunks, the overhead
2302 is one SIZE_SZ unit larger than for normal chunks, because there
2303 is no following chunk whose prev_size field could be used.
2305 See the front_misalign handling below, for glibc there is no
2306 need for further alignments unless we have have high alignment.
2308 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2309 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2310 else
2311 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2312 tried_mmap = true;
2314 /* Don't try if size wraps around 0 */
2315 if ((unsigned long) (size) > (unsigned long) (nb))
2317 mm = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2319 if (mm != MAP_FAILED)
2322 The offset to the start of the mmapped region is stored
2323 in the prev_size field of the chunk. This allows us to adjust
2324 returned start address to meet alignment requirements here
2325 and in memalign(), and still be able to compute proper
2326 address argument for later munmap in free() and realloc().
2329 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2331 /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and
2332 MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
2333 aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
2334 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2335 front_misalign = 0;
2337 else
2338 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2339 if (front_misalign > 0)
2341 correction = MALLOC_ALIGNMENT - front_misalign;
2342 p = (mchunkptr) (mm + correction);
2343 p->prev_size = correction;
2344 set_head (p, (size - correction) | IS_MMAPPED);
2346 else
2348 p = (mchunkptr) mm;
2349 set_head (p, size | IS_MMAPPED);
2352 /* update statistics */
2354 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2355 atomic_max (&mp_.max_n_mmaps, new);
2357 unsigned long sum;
2358 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2359 atomic_max (&mp_.max_mmapped_mem, sum);
2361 check_chunk (av, p);
2363 return chunk2mem (p);
2368 /* There are no usable arenas and mmap also failed. */
2369 if (av == NULL)
2370 return 0;
2372 /* Record incoming configuration of top */
2374 old_top = av->top;
2375 old_size = chunksize (old_top);
2376 old_end = (char *) (chunk_at_offset (old_top, old_size));
2378 brk = snd_brk = (char *) (MORECORE_FAILURE);
2381 If not the first time through, we require old_size to be
2382 at least MINSIZE and to have prev_inuse set.
2385 assert ((old_top == initial_top (av) && old_size == 0) ||
2386 ((unsigned long) (old_size) >= MINSIZE &&
2387 prev_inuse (old_top) &&
2388 ((unsigned long) old_end & (pagesize - 1)) == 0));
2390 /* Precondition: not enough current space to satisfy nb request */
2391 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2394 if (av != &main_arena)
2396 heap_info *old_heap, *heap;
2397 size_t old_heap_size;
2399 /* First try to extend the current heap. */
2400 old_heap = heap_for_ptr (old_top);
2401 old_heap_size = old_heap->size;
2402 if ((long) (MINSIZE + nb - old_size) > 0
2403 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2405 av->system_mem += old_heap->size - old_heap_size;
2406 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2407 | PREV_INUSE);
2409 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2411 /* Use a newly allocated heap. */
2412 heap->ar_ptr = av;
2413 heap->prev = old_heap;
2414 av->system_mem += heap->size;
2415 /* Set up the new top. */
2416 top (av) = chunk_at_offset (heap, sizeof (*heap));
2417 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2419 /* Setup fencepost and free the old top chunk with a multiple of
2420 MALLOC_ALIGNMENT in size. */
2421 /* The fencepost takes at least MINSIZE bytes, because it might
2422 become the top chunk again later. Note that a footer is set
2423 up, too, although the chunk is marked in use. */
2424 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2425 set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ), 0 | PREV_INUSE);
2426 if (old_size >= MINSIZE)
2428 set_head (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE);
2429 set_foot (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ));
2430 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2431 _int_free (av, old_top, 1);
2433 else
2435 set_head (old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE);
2436 set_foot (old_top, (old_size + 2 * SIZE_SZ));
2439 else if (!tried_mmap)
2440 /* We can at least try to use to mmap memory. */
2441 goto try_mmap;
2443 else /* av == main_arena */
2446 { /* Request enough space for nb + pad + overhead */
2447 size = nb + mp_.top_pad + MINSIZE;
2450 If contiguous, we can subtract out existing space that we hope to
2451 combine with new space. We add it back later only if
2452 we don't actually get contiguous space.
2455 if (contiguous (av))
2456 size -= old_size;
2459 Round to a multiple of page size.
2460 If MORECORE is not contiguous, this ensures that we only call it
2461 with whole-page arguments. And if MORECORE is contiguous and
2462 this is not first time through, this preserves page-alignment of
2463 previous calls. Otherwise, we correct to page-align below.
2466 size = ALIGN_UP (size, pagesize);
2469 Don't try to call MORECORE if argument is so big as to appear
2470 negative. Note that since mmap takes size_t arg, it may succeed
2471 below even if we cannot call MORECORE.
2474 if (size > 0)
2476 brk = (char *) (MORECORE (size));
2477 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2480 if (brk != (char *) (MORECORE_FAILURE))
2482 /* Call the `morecore' hook if necessary. */
2483 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2484 if (__builtin_expect (hook != NULL, 0))
2485 (*hook)();
2487 else
2490 If have mmap, try using it as a backup when MORECORE fails or
2491 cannot be used. This is worth doing on systems that have "holes" in
2492 address space, so sbrk cannot extend to give contiguous space, but
2493 space is available elsewhere. Note that we ignore mmap max count
2494 and threshold limits, since the space will not be used as a
2495 segregated mmap region.
2498 /* Cannot merge with old top, so add its size back in */
2499 if (contiguous (av))
2500 size = ALIGN_UP (size + old_size, pagesize);
2502 /* If we are relying on mmap as backup, then use larger units */
2503 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2504 size = MMAP_AS_MORECORE_SIZE;
2506 /* Don't try if size wraps around 0 */
2507 if ((unsigned long) (size) > (unsigned long) (nb))
2509 char *mbrk = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2511 if (mbrk != MAP_FAILED)
2513 /* We do not need, and cannot use, another sbrk call to find end */
2514 brk = mbrk;
2515 snd_brk = brk + size;
2518 Record that we no longer have a contiguous sbrk region.
2519 After the first time mmap is used as backup, we do not
2520 ever rely on contiguous space since this could incorrectly
2521 bridge regions.
2523 set_noncontiguous (av);
2528 if (brk != (char *) (MORECORE_FAILURE))
2530 if (mp_.sbrk_base == 0)
2531 mp_.sbrk_base = brk;
2532 av->system_mem += size;
2535 If MORECORE extends previous space, we can likewise extend top size.
2538 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2539 set_head (old_top, (size + old_size) | PREV_INUSE);
2541 else if (contiguous (av) && old_size && brk < old_end)
2543 /* Oops! Someone else killed our space.. Can't touch anything. */
2544 malloc_printerr (3, "break adjusted to free malloc space", brk,
2545 av);
2549 Otherwise, make adjustments:
2551 * If the first time through or noncontiguous, we need to call sbrk
2552 just to find out where the end of memory lies.
2554 * We need to ensure that all returned chunks from malloc will meet
2555 MALLOC_ALIGNMENT
2557 * If there was an intervening foreign sbrk, we need to adjust sbrk
2558 request size to account for fact that we will not be able to
2559 combine new space with existing space in old_top.
2561 * Almost all systems internally allocate whole pages at a time, in
2562 which case we might as well use the whole last page of request.
2563 So we allocate enough more memory to hit a page boundary now,
2564 which in turn causes future contiguous calls to page-align.
2567 else
2569 front_misalign = 0;
2570 end_misalign = 0;
2571 correction = 0;
2572 aligned_brk = brk;
2574 /* handle contiguous cases */
2575 if (contiguous (av))
2577 /* Count foreign sbrk as system_mem. */
2578 if (old_size)
2579 av->system_mem += brk - old_end;
2581 /* Guarantee alignment of first new chunk made from this space */
2583 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2584 if (front_misalign > 0)
2587 Skip over some bytes to arrive at an aligned position.
2588 We don't need to specially mark these wasted front bytes.
2589 They will never be accessed anyway because
2590 prev_inuse of av->top (and any chunk created from its start)
2591 is always true after initialization.
2594 correction = MALLOC_ALIGNMENT - front_misalign;
2595 aligned_brk += correction;
2599 If this isn't adjacent to existing space, then we will not
2600 be able to merge with old_top space, so must add to 2nd request.
2603 correction += old_size;
2605 /* Extend the end address to hit a page boundary */
2606 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2607 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2609 assert (correction >= 0);
2610 snd_brk = (char *) (MORECORE (correction));
2613 If can't allocate correction, try to at least find out current
2614 brk. It might be enough to proceed without failing.
2616 Note that if second sbrk did NOT fail, we assume that space
2617 is contiguous with first sbrk. This is a safe assumption unless
2618 program is multithreaded but doesn't use locks and a foreign sbrk
2619 occurred between our first and second calls.
2622 if (snd_brk == (char *) (MORECORE_FAILURE))
2624 correction = 0;
2625 snd_brk = (char *) (MORECORE (0));
2627 else
2629 /* Call the `morecore' hook if necessary. */
2630 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2631 if (__builtin_expect (hook != NULL, 0))
2632 (*hook)();
2636 /* handle non-contiguous cases */
2637 else
2639 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2640 /* MORECORE/mmap must correctly align */
2641 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2642 else
2644 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2645 if (front_misalign > 0)
2648 Skip over some bytes to arrive at an aligned position.
2649 We don't need to specially mark these wasted front bytes.
2650 They will never be accessed anyway because
2651 prev_inuse of av->top (and any chunk created from its start)
2652 is always true after initialization.
2655 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2659 /* Find out current end of memory */
2660 if (snd_brk == (char *) (MORECORE_FAILURE))
2662 snd_brk = (char *) (MORECORE (0));
2666 /* Adjust top based on results of second sbrk */
2667 if (snd_brk != (char *) (MORECORE_FAILURE))
2669 av->top = (mchunkptr) aligned_brk;
2670 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2671 av->system_mem += correction;
2674 If not the first time through, we either have a
2675 gap due to foreign sbrk or a non-contiguous region. Insert a
2676 double fencepost at old_top to prevent consolidation with space
2677 we don't own. These fenceposts are artificial chunks that are
2678 marked as inuse and are in any case too small to use. We need
2679 two to make sizes and alignments work out.
2682 if (old_size != 0)
2685 Shrink old_top to insert fenceposts, keeping size a
2686 multiple of MALLOC_ALIGNMENT. We know there is at least
2687 enough space in old_top to do this.
2689 old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK;
2690 set_head (old_top, old_size | PREV_INUSE);
2693 Note that the following assignments completely overwrite
2694 old_top when old_size was previously MINSIZE. This is
2695 intentional. We need the fencepost, even if old_top otherwise gets
2696 lost.
2698 chunk_at_offset (old_top, old_size)->size =
2699 (2 * SIZE_SZ) | PREV_INUSE;
2701 chunk_at_offset (old_top, old_size + 2 * SIZE_SZ)->size =
2702 (2 * SIZE_SZ) | PREV_INUSE;
2704 /* If possible, release the rest. */
2705 if (old_size >= MINSIZE)
2707 _int_free (av, old_top, 1);
2713 } /* if (av != &main_arena) */
2715 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2716 av->max_system_mem = av->system_mem;
2717 check_malloc_state (av);
2719 /* finally, do the allocation */
2720 p = av->top;
2721 size = chunksize (p);
2723 /* check that one of the above allocation paths succeeded */
2724 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2726 remainder_size = size - nb;
2727 remainder = chunk_at_offset (p, nb);
2728 av->top = remainder;
2729 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2730 set_head (remainder, remainder_size | PREV_INUSE);
2731 check_malloced_chunk (av, p, nb);
2732 return chunk2mem (p);
2735 /* catch all failure paths */
2736 __set_errno (ENOMEM);
2737 return 0;
2742 systrim is an inverse of sorts to sysmalloc. It gives memory back
2743 to the system (via negative arguments to sbrk) if there is unused
2744 memory at the `high' end of the malloc pool. It is called
2745 automatically by free() when top space exceeds the trim
2746 threshold. It is also called by the public malloc_trim routine. It
2747 returns 1 if it actually released any memory, else 0.
2750 static int
2751 systrim (size_t pad, mstate av)
2753 long top_size; /* Amount of top-most memory */
2754 long extra; /* Amount to release */
2755 long released; /* Amount actually released */
2756 char *current_brk; /* address returned by pre-check sbrk call */
2757 char *new_brk; /* address returned by post-check sbrk call */
2758 size_t pagesize;
2759 long top_area;
2761 pagesize = GLRO (dl_pagesize);
2762 top_size = chunksize (av->top);
2764 top_area = top_size - MINSIZE - 1;
2765 if (top_area <= pad)
2766 return 0;
2768 /* Release in pagesize units and round down to the nearest page. */
2769 extra = ALIGN_DOWN(top_area - pad, pagesize);
2771 if (extra == 0)
2772 return 0;
2775 Only proceed if end of memory is where we last set it.
2776 This avoids problems if there were foreign sbrk calls.
2778 current_brk = (char *) (MORECORE (0));
2779 if (current_brk == (char *) (av->top) + top_size)
2782 Attempt to release memory. We ignore MORECORE return value,
2783 and instead call again to find out where new end of memory is.
2784 This avoids problems if first call releases less than we asked,
2785 of if failure somehow altered brk value. (We could still
2786 encounter problems if it altered brk in some very bad way,
2787 but the only thing we can do is adjust anyway, which will cause
2788 some downstream failure.)
2791 MORECORE (-extra);
2792 /* Call the `morecore' hook if necessary. */
2793 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2794 if (__builtin_expect (hook != NULL, 0))
2795 (*hook)();
2796 new_brk = (char *) (MORECORE (0));
2798 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2800 if (new_brk != (char *) MORECORE_FAILURE)
2802 released = (long) (current_brk - new_brk);
2804 if (released != 0)
2806 /* Success. Adjust top. */
2807 av->system_mem -= released;
2808 set_head (av->top, (top_size - released) | PREV_INUSE);
2809 check_malloc_state (av);
2810 return 1;
2814 return 0;
2817 static void
2818 internal_function
2819 munmap_chunk (mchunkptr p)
2821 INTERNAL_SIZE_T size = chunksize (p);
2823 assert (chunk_is_mmapped (p));
2825 uintptr_t block = (uintptr_t) p - p->prev_size;
2826 size_t total_size = p->prev_size + size;
2827 /* Unfortunately we have to do the compilers job by hand here. Normally
2828 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2829 page size. But gcc does not recognize the optimization possibility
2830 (in the moment at least) so we combine the two values into one before
2831 the bit test. */
2832 if (__builtin_expect (((block | total_size) & (GLRO (dl_pagesize) - 1)) != 0, 0))
2834 malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
2835 chunk2mem (p), NULL);
2836 return;
2839 atomic_decrement (&mp_.n_mmaps);
2840 atomic_add (&mp_.mmapped_mem, -total_size);
2842 /* If munmap failed the process virtual memory address space is in a
2843 bad shape. Just leave the block hanging around, the process will
2844 terminate shortly anyway since not much can be done. */
2845 __munmap ((char *) block, total_size);
2848 #if HAVE_MREMAP
2850 static mchunkptr
2851 internal_function
2852 mremap_chunk (mchunkptr p, size_t new_size)
2854 size_t pagesize = GLRO (dl_pagesize);
2855 INTERNAL_SIZE_T offset = p->prev_size;
2856 INTERNAL_SIZE_T size = chunksize (p);
2857 char *cp;
2859 assert (chunk_is_mmapped (p));
2860 assert (((size + offset) & (GLRO (dl_pagesize) - 1)) == 0);
2862 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2863 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
2865 /* No need to remap if the number of pages does not change. */
2866 if (size + offset == new_size)
2867 return p;
2869 cp = (char *) __mremap ((char *) p - offset, size + offset, new_size,
2870 MREMAP_MAYMOVE);
2872 if (cp == MAP_FAILED)
2873 return 0;
2875 p = (mchunkptr) (cp + offset);
2877 assert (aligned_OK (chunk2mem (p)));
2879 assert ((p->prev_size == offset));
2880 set_head (p, (new_size - offset) | IS_MMAPPED);
2882 INTERNAL_SIZE_T new;
2883 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
2884 + new_size - size - offset;
2885 atomic_max (&mp_.max_mmapped_mem, new);
2886 return p;
2888 #endif /* HAVE_MREMAP */
2890 /*------------------------ Public wrappers. --------------------------------*/
2892 void *
2893 __libc_malloc (size_t bytes)
2895 mstate ar_ptr;
2896 void *victim;
2898 void *(*hook) (size_t, const void *)
2899 = atomic_forced_read (__malloc_hook);
2900 if (__builtin_expect (hook != NULL, 0))
2901 return (*hook)(bytes, RETURN_ADDRESS (0));
2903 arena_get (ar_ptr, bytes);
2905 victim = _int_malloc (ar_ptr, bytes);
2906 /* Retry with another arena only if we were able to find a usable arena
2907 before. */
2908 if (!victim && ar_ptr != NULL)
2910 LIBC_PROBE (memory_malloc_retry, 1, bytes);
2911 ar_ptr = arena_get_retry (ar_ptr, bytes);
2912 victim = _int_malloc (ar_ptr, bytes);
2915 if (ar_ptr != NULL)
2916 (void) mutex_unlock (&ar_ptr->mutex);
2918 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
2919 ar_ptr == arena_for_chunk (mem2chunk (victim)));
2920 return victim;
2922 libc_hidden_def (__libc_malloc)
2924 void
2925 __libc_free (void *mem)
2927 mstate ar_ptr;
2928 mchunkptr p; /* chunk corresponding to mem */
2930 void (*hook) (void *, const void *)
2931 = atomic_forced_read (__free_hook);
2932 if (__builtin_expect (hook != NULL, 0))
2934 (*hook)(mem, RETURN_ADDRESS (0));
2935 return;
2938 if (mem == 0) /* free(0) has no effect */
2939 return;
2941 p = mem2chunk (mem);
2943 if (chunk_is_mmapped (p)) /* release mmapped memory. */
2945 /* see if the dynamic brk/mmap threshold needs adjusting */
2946 if (!mp_.no_dyn_threshold
2947 && p->size > mp_.mmap_threshold
2948 && p->size <= DEFAULT_MMAP_THRESHOLD_MAX)
2950 mp_.mmap_threshold = chunksize (p);
2951 mp_.trim_threshold = 2 * mp_.mmap_threshold;
2952 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
2953 mp_.mmap_threshold, mp_.trim_threshold);
2955 munmap_chunk (p);
2956 return;
2959 ar_ptr = arena_for_chunk (p);
2960 _int_free (ar_ptr, p, 0);
2962 libc_hidden_def (__libc_free)
2964 void *
2965 __libc_realloc (void *oldmem, size_t bytes)
2967 mstate ar_ptr;
2968 INTERNAL_SIZE_T nb; /* padded request size */
2970 void *newp; /* chunk to return */
2972 void *(*hook) (void *, size_t, const void *) =
2973 atomic_forced_read (__realloc_hook);
2974 if (__builtin_expect (hook != NULL, 0))
2975 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
2977 #if REALLOC_ZERO_BYTES_FREES
2978 if (bytes == 0 && oldmem != NULL)
2980 __libc_free (oldmem); return 0;
2982 #endif
2984 /* realloc of null is supposed to be same as malloc */
2985 if (oldmem == 0)
2986 return __libc_malloc (bytes);
2988 /* chunk corresponding to oldmem */
2989 const mchunkptr oldp = mem2chunk (oldmem);
2990 /* its size */
2991 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
2993 if (chunk_is_mmapped (oldp))
2994 ar_ptr = NULL;
2995 else
2996 ar_ptr = arena_for_chunk (oldp);
2998 /* Little security check which won't hurt performance: the
2999 allocator never wrapps around at the end of the address space.
3000 Therefore we can exclude some size values which might appear
3001 here by accident or by "design" from some intruder. */
3002 if (__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
3003 || __builtin_expect (misaligned_chunk (oldp), 0))
3005 malloc_printerr (check_action, "realloc(): invalid pointer", oldmem,
3006 ar_ptr);
3007 return NULL;
3010 checked_request2size (bytes, nb);
3012 if (chunk_is_mmapped (oldp))
3014 void *newmem;
3016 #if HAVE_MREMAP
3017 newp = mremap_chunk (oldp, nb);
3018 if (newp)
3019 return chunk2mem (newp);
3020 #endif
3021 /* Note the extra SIZE_SZ overhead. */
3022 if (oldsize - SIZE_SZ >= nb)
3023 return oldmem; /* do nothing */
3025 /* Must alloc, copy, free. */
3026 newmem = __libc_malloc (bytes);
3027 if (newmem == 0)
3028 return 0; /* propagate failure */
3030 memcpy (newmem, oldmem, oldsize - 2 * SIZE_SZ);
3031 munmap_chunk (oldp);
3032 return newmem;
3035 (void) mutex_lock (&ar_ptr->mutex);
3037 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3039 (void) mutex_unlock (&ar_ptr->mutex);
3040 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3041 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3043 if (newp == NULL)
3045 /* Try harder to allocate memory in other arenas. */
3046 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3047 newp = __libc_malloc (bytes);
3048 if (newp != NULL)
3050 memcpy (newp, oldmem, oldsize - SIZE_SZ);
3051 _int_free (ar_ptr, oldp, 0);
3055 return newp;
3057 libc_hidden_def (__libc_realloc)
3059 void *
3060 __libc_memalign (size_t alignment, size_t bytes)
3062 void *address = RETURN_ADDRESS (0);
3063 return _mid_memalign (alignment, bytes, address);
3066 static void *
3067 _mid_memalign (size_t alignment, size_t bytes, void *address)
3069 mstate ar_ptr;
3070 void *p;
3072 void *(*hook) (size_t, size_t, const void *) =
3073 atomic_forced_read (__memalign_hook);
3074 if (__builtin_expect (hook != NULL, 0))
3075 return (*hook)(alignment, bytes, address);
3077 /* If we need less alignment than we give anyway, just relay to malloc. */
3078 if (alignment <= MALLOC_ALIGNMENT)
3079 return __libc_malloc (bytes);
3081 /* Otherwise, ensure that it is at least a minimum chunk size */
3082 if (alignment < MINSIZE)
3083 alignment = MINSIZE;
3085 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3086 power of 2 and will cause overflow in the check below. */
3087 if (alignment > SIZE_MAX / 2 + 1)
3089 __set_errno (EINVAL);
3090 return 0;
3093 /* Check for overflow. */
3094 if (bytes > SIZE_MAX - alignment - MINSIZE)
3096 __set_errno (ENOMEM);
3097 return 0;
3101 /* Make sure alignment is power of 2. */
3102 if (!powerof2 (alignment))
3104 size_t a = MALLOC_ALIGNMENT * 2;
3105 while (a < alignment)
3106 a <<= 1;
3107 alignment = a;
3110 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3112 p = _int_memalign (ar_ptr, alignment, bytes);
3113 if (!p && ar_ptr != NULL)
3115 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3116 ar_ptr = arena_get_retry (ar_ptr, bytes);
3117 p = _int_memalign (ar_ptr, alignment, bytes);
3120 if (ar_ptr != NULL)
3121 (void) mutex_unlock (&ar_ptr->mutex);
3123 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3124 ar_ptr == arena_for_chunk (mem2chunk (p)));
3125 return p;
3127 /* For ISO C11. */
3128 weak_alias (__libc_memalign, aligned_alloc)
3129 libc_hidden_def (__libc_memalign)
3131 void *
3132 __libc_valloc (size_t bytes)
3134 if (__malloc_initialized < 0)
3135 ptmalloc_init ();
3137 void *address = RETURN_ADDRESS (0);
3138 size_t pagesize = GLRO (dl_pagesize);
3139 return _mid_memalign (pagesize, bytes, address);
3142 void *
3143 __libc_pvalloc (size_t bytes)
3145 if (__malloc_initialized < 0)
3146 ptmalloc_init ();
3148 void *address = RETURN_ADDRESS (0);
3149 size_t pagesize = GLRO (dl_pagesize);
3150 size_t rounded_bytes = ALIGN_UP (bytes, pagesize);
3152 /* Check for overflow. */
3153 if (bytes > SIZE_MAX - 2 * pagesize - MINSIZE)
3155 __set_errno (ENOMEM);
3156 return 0;
3159 return _mid_memalign (pagesize, rounded_bytes, address);
3162 void *
3163 __libc_calloc (size_t n, size_t elem_size)
3165 mstate av;
3166 mchunkptr oldtop, p;
3167 INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
3168 void *mem;
3169 unsigned long clearsize;
3170 unsigned long nclears;
3171 INTERNAL_SIZE_T *d;
3173 /* size_t is unsigned so the behavior on overflow is defined. */
3174 bytes = n * elem_size;
3175 #define HALF_INTERNAL_SIZE_T \
3176 (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
3177 if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0))
3179 if (elem_size != 0 && bytes / elem_size != n)
3181 __set_errno (ENOMEM);
3182 return 0;
3186 void *(*hook) (size_t, const void *) =
3187 atomic_forced_read (__malloc_hook);
3188 if (__builtin_expect (hook != NULL, 0))
3190 sz = bytes;
3191 mem = (*hook)(sz, RETURN_ADDRESS (0));
3192 if (mem == 0)
3193 return 0;
3195 return memset (mem, 0, sz);
3198 sz = bytes;
3200 arena_get (av, sz);
3201 if (av)
3203 /* Check if we hand out the top chunk, in which case there may be no
3204 need to clear. */
3205 #if MORECORE_CLEARS
3206 oldtop = top (av);
3207 oldtopsize = chunksize (top (av));
3208 # if MORECORE_CLEARS < 2
3209 /* Only newly allocated memory is guaranteed to be cleared. */
3210 if (av == &main_arena &&
3211 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3212 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3213 # endif
3214 if (av != &main_arena)
3216 heap_info *heap = heap_for_ptr (oldtop);
3217 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3218 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3220 #endif
3222 else
3224 /* No usable arenas. */
3225 oldtop = 0;
3226 oldtopsize = 0;
3228 mem = _int_malloc (av, sz);
3231 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3232 av == arena_for_chunk (mem2chunk (mem)));
3234 if (mem == 0 && av != NULL)
3236 LIBC_PROBE (memory_calloc_retry, 1, sz);
3237 av = arena_get_retry (av, sz);
3238 mem = _int_malloc (av, sz);
3241 if (av != NULL)
3242 (void) mutex_unlock (&av->mutex);
3244 /* Allocation failed even after a retry. */
3245 if (mem == 0)
3246 return 0;
3248 p = mem2chunk (mem);
3250 /* Two optional cases in which clearing not necessary */
3251 if (chunk_is_mmapped (p))
3253 if (__builtin_expect (perturb_byte, 0))
3254 return memset (mem, 0, sz);
3256 return mem;
3259 csz = chunksize (p);
3261 #if MORECORE_CLEARS
3262 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3264 /* clear only the bytes from non-freshly-sbrked memory */
3265 csz = oldtopsize;
3267 #endif
3269 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3270 contents have an odd number of INTERNAL_SIZE_T-sized words;
3271 minimally 3. */
3272 d = (INTERNAL_SIZE_T *) mem;
3273 clearsize = csz - SIZE_SZ;
3274 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3275 assert (nclears >= 3);
3277 if (nclears > 9)
3278 return memset (d, 0, clearsize);
3280 else
3282 *(d + 0) = 0;
3283 *(d + 1) = 0;
3284 *(d + 2) = 0;
3285 if (nclears > 4)
3287 *(d + 3) = 0;
3288 *(d + 4) = 0;
3289 if (nclears > 6)
3291 *(d + 5) = 0;
3292 *(d + 6) = 0;
3293 if (nclears > 8)
3295 *(d + 7) = 0;
3296 *(d + 8) = 0;
3302 return mem;
3306 ------------------------------ malloc ------------------------------
3309 static void *
3310 _int_malloc (mstate av, size_t bytes)
3312 INTERNAL_SIZE_T nb; /* normalized request size */
3313 unsigned int idx; /* associated bin index */
3314 mbinptr bin; /* associated bin */
3316 mchunkptr victim; /* inspected/selected chunk */
3317 INTERNAL_SIZE_T size; /* its size */
3318 int victim_index; /* its bin index */
3320 mchunkptr remainder; /* remainder from a split */
3321 unsigned long remainder_size; /* its size */
3323 unsigned int block; /* bit map traverser */
3324 unsigned int bit; /* bit map traverser */
3325 unsigned int map; /* current word of binmap */
3327 mchunkptr fwd; /* misc temp for linking */
3328 mchunkptr bck; /* misc temp for linking */
3330 const char *errstr = NULL;
3333 Convert request size to internal form by adding SIZE_SZ bytes
3334 overhead plus possibly more to obtain necessary alignment and/or
3335 to obtain a size of at least MINSIZE, the smallest allocatable
3336 size. Also, checked_request2size traps (returning 0) request sizes
3337 that are so large that they wrap around zero when padded and
3338 aligned.
3341 checked_request2size (bytes, nb);
3343 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3344 mmap. */
3345 if (__glibc_unlikely (av == NULL))
3347 void *p = sysmalloc (nb, av);
3348 if (p != NULL)
3349 alloc_perturb (p, bytes);
3350 return p;
3354 If the size qualifies as a fastbin, first check corresponding bin.
3355 This code is safe to execute even if av is not yet initialized, so we
3356 can try it without checking, which saves some time on this fast path.
3359 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3361 idx = fastbin_index (nb);
3362 mfastbinptr *fb = &fastbin (av, idx);
3363 mchunkptr pp = *fb;
3366 victim = pp;
3367 if (victim == NULL)
3368 break;
3370 while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim))
3371 != victim);
3372 if (victim != 0)
3374 if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
3376 errstr = "malloc(): memory corruption (fast)";
3377 errout:
3378 malloc_printerr (check_action, errstr, chunk2mem (victim), av);
3379 return NULL;
3381 check_remalloced_chunk (av, victim, nb);
3382 void *p = chunk2mem (victim);
3383 alloc_perturb (p, bytes);
3384 return p;
3389 If a small request, check regular bin. Since these "smallbins"
3390 hold one size each, no searching within bins is necessary.
3391 (For a large request, we need to wait until unsorted chunks are
3392 processed to find best fit. But for small ones, fits are exact
3393 anyway, so we can check now, which is faster.)
3396 if (in_smallbin_range (nb))
3398 idx = smallbin_index (nb);
3399 bin = bin_at (av, idx);
3401 if ((victim = last (bin)) != bin)
3403 if (victim == 0) /* initialization check */
3404 malloc_consolidate (av);
3405 else
3407 bck = victim->bk;
3408 if (__glibc_unlikely (bck->fd != victim))
3410 errstr = "malloc(): smallbin double linked list corrupted";
3411 goto errout;
3413 set_inuse_bit_at_offset (victim, nb);
3414 bin->bk = bck;
3415 bck->fd = bin;
3417 if (av != &main_arena)
3418 victim->size |= NON_MAIN_ARENA;
3419 check_malloced_chunk (av, victim, nb);
3420 void *p = chunk2mem (victim);
3421 alloc_perturb (p, bytes);
3422 return p;
3428 If this is a large request, consolidate fastbins before continuing.
3429 While it might look excessive to kill all fastbins before
3430 even seeing if there is space available, this avoids
3431 fragmentation problems normally associated with fastbins.
3432 Also, in practice, programs tend to have runs of either small or
3433 large requests, but less often mixtures, so consolidation is not
3434 invoked all that often in most programs. And the programs that
3435 it is called frequently in otherwise tend to fragment.
3438 else
3440 idx = largebin_index (nb);
3441 if (have_fastchunks (av))
3442 malloc_consolidate (av);
3446 Process recently freed or remaindered chunks, taking one only if
3447 it is exact fit, or, if this a small request, the chunk is remainder from
3448 the most recent non-exact fit. Place other traversed chunks in
3449 bins. Note that this step is the only place in any routine where
3450 chunks are placed in bins.
3452 The outer loop here is needed because we might not realize until
3453 near the end of malloc that we should have consolidated, so must
3454 do so and retry. This happens at most once, and only when we would
3455 otherwise need to expand memory to service a "small" request.
3458 for (;; )
3460 int iters = 0;
3461 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3463 bck = victim->bk;
3464 if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0)
3465 || __builtin_expect (victim->size > av->system_mem, 0))
3466 malloc_printerr (check_action, "malloc(): memory corruption",
3467 chunk2mem (victim), av);
3468 size = chunksize (victim);
3471 If a small request, try to use last remainder if it is the
3472 only chunk in unsorted bin. This helps promote locality for
3473 runs of consecutive small requests. This is the only
3474 exception to best-fit, and applies only when there is
3475 no exact fit for a small chunk.
3478 if (in_smallbin_range (nb) &&
3479 bck == unsorted_chunks (av) &&
3480 victim == av->last_remainder &&
3481 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
3483 /* split and reattach remainder */
3484 remainder_size = size - nb;
3485 remainder = chunk_at_offset (victim, nb);
3486 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
3487 av->last_remainder = remainder;
3488 remainder->bk = remainder->fd = unsorted_chunks (av);
3489 if (!in_smallbin_range (remainder_size))
3491 remainder->fd_nextsize = NULL;
3492 remainder->bk_nextsize = NULL;
3495 set_head (victim, nb | PREV_INUSE |
3496 (av != &main_arena ? NON_MAIN_ARENA : 0));
3497 set_head (remainder, remainder_size | PREV_INUSE);
3498 set_foot (remainder, remainder_size);
3500 check_malloced_chunk (av, victim, nb);
3501 void *p = chunk2mem (victim);
3502 alloc_perturb (p, bytes);
3503 return p;
3506 /* remove from unsorted list */
3507 unsorted_chunks (av)->bk = bck;
3508 bck->fd = unsorted_chunks (av);
3510 /* Take now instead of binning if exact fit */
3512 if (size == nb)
3514 set_inuse_bit_at_offset (victim, size);
3515 if (av != &main_arena)
3516 victim->size |= NON_MAIN_ARENA;
3517 check_malloced_chunk (av, victim, nb);
3518 void *p = chunk2mem (victim);
3519 alloc_perturb (p, bytes);
3520 return p;
3523 /* place chunk in bin */
3525 if (in_smallbin_range (size))
3527 victim_index = smallbin_index (size);
3528 bck = bin_at (av, victim_index);
3529 fwd = bck->fd;
3531 else
3533 victim_index = largebin_index (size);
3534 bck = bin_at (av, victim_index);
3535 fwd = bck->fd;
3537 /* maintain large bins in sorted order */
3538 if (fwd != bck)
3540 /* Or with inuse bit to speed comparisons */
3541 size |= PREV_INUSE;
3542 /* if smaller than smallest, bypass loop below */
3543 assert ((bck->bk->size & NON_MAIN_ARENA) == 0);
3544 if ((unsigned long) (size) < (unsigned long) (bck->bk->size))
3546 fwd = bck;
3547 bck = bck->bk;
3549 victim->fd_nextsize = fwd->fd;
3550 victim->bk_nextsize = fwd->fd->bk_nextsize;
3551 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
3553 else
3555 assert ((fwd->size & NON_MAIN_ARENA) == 0);
3556 while ((unsigned long) size < fwd->size)
3558 fwd = fwd->fd_nextsize;
3559 assert ((fwd->size & NON_MAIN_ARENA) == 0);
3562 if ((unsigned long) size == (unsigned long) fwd->size)
3563 /* Always insert in the second position. */
3564 fwd = fwd->fd;
3565 else
3567 victim->fd_nextsize = fwd;
3568 victim->bk_nextsize = fwd->bk_nextsize;
3569 fwd->bk_nextsize = victim;
3570 victim->bk_nextsize->fd_nextsize = victim;
3572 bck = fwd->bk;
3575 else
3576 victim->fd_nextsize = victim->bk_nextsize = victim;
3579 mark_bin (av, victim_index);
3580 victim->bk = bck;
3581 victim->fd = fwd;
3582 fwd->bk = victim;
3583 bck->fd = victim;
3585 #define MAX_ITERS 10000
3586 if (++iters >= MAX_ITERS)
3587 break;
3591 If a large request, scan through the chunks of current bin in
3592 sorted order to find smallest that fits. Use the skip list for this.
3595 if (!in_smallbin_range (nb))
3597 bin = bin_at (av, idx);
3599 /* skip scan if empty or largest chunk is too small */
3600 if ((victim = first (bin)) != bin &&
3601 (unsigned long) (victim->size) >= (unsigned long) (nb))
3603 victim = victim->bk_nextsize;
3604 while (((unsigned long) (size = chunksize (victim)) <
3605 (unsigned long) (nb)))
3606 victim = victim->bk_nextsize;
3608 /* Avoid removing the first entry for a size so that the skip
3609 list does not have to be rerouted. */
3610 if (victim != last (bin) && victim->size == victim->fd->size)
3611 victim = victim->fd;
3613 remainder_size = size - nb;
3614 unlink (av, victim, bck, fwd);
3616 /* Exhaust */
3617 if (remainder_size < MINSIZE)
3619 set_inuse_bit_at_offset (victim, size);
3620 if (av != &main_arena)
3621 victim->size |= NON_MAIN_ARENA;
3623 /* Split */
3624 else
3626 remainder = chunk_at_offset (victim, nb);
3627 /* We cannot assume the unsorted list is empty and therefore
3628 have to perform a complete insert here. */
3629 bck = unsorted_chunks (av);
3630 fwd = bck->fd;
3631 if (__glibc_unlikely (fwd->bk != bck))
3633 errstr = "malloc(): corrupted unsorted chunks";
3634 goto errout;
3636 remainder->bk = bck;
3637 remainder->fd = fwd;
3638 bck->fd = remainder;
3639 fwd->bk = remainder;
3640 if (!in_smallbin_range (remainder_size))
3642 remainder->fd_nextsize = NULL;
3643 remainder->bk_nextsize = NULL;
3645 set_head (victim, nb | PREV_INUSE |
3646 (av != &main_arena ? NON_MAIN_ARENA : 0));
3647 set_head (remainder, remainder_size | PREV_INUSE);
3648 set_foot (remainder, remainder_size);
3650 check_malloced_chunk (av, victim, nb);
3651 void *p = chunk2mem (victim);
3652 alloc_perturb (p, bytes);
3653 return p;
3658 Search for a chunk by scanning bins, starting with next largest
3659 bin. This search is strictly by best-fit; i.e., the smallest
3660 (with ties going to approximately the least recently used) chunk
3661 that fits is selected.
3663 The bitmap avoids needing to check that most blocks are nonempty.
3664 The particular case of skipping all bins during warm-up phases
3665 when no chunks have been returned yet is faster than it might look.
3668 ++idx;
3669 bin = bin_at (av, idx);
3670 block = idx2block (idx);
3671 map = av->binmap[block];
3672 bit = idx2bit (idx);
3674 for (;; )
3676 /* Skip rest of block if there are no more set bits in this block. */
3677 if (bit > map || bit == 0)
3681 if (++block >= BINMAPSIZE) /* out of bins */
3682 goto use_top;
3684 while ((map = av->binmap[block]) == 0);
3686 bin = bin_at (av, (block << BINMAPSHIFT));
3687 bit = 1;
3690 /* Advance to bin with set bit. There must be one. */
3691 while ((bit & map) == 0)
3693 bin = next_bin (bin);
3694 bit <<= 1;
3695 assert (bit != 0);
3698 /* Inspect the bin. It is likely to be non-empty */
3699 victim = last (bin);
3701 /* If a false alarm (empty bin), clear the bit. */
3702 if (victim == bin)
3704 av->binmap[block] = map &= ~bit; /* Write through */
3705 bin = next_bin (bin);
3706 bit <<= 1;
3709 else
3711 size = chunksize (victim);
3713 /* We know the first chunk in this bin is big enough to use. */
3714 assert ((unsigned long) (size) >= (unsigned long) (nb));
3716 remainder_size = size - nb;
3718 /* unlink */
3719 unlink (av, victim, bck, fwd);
3721 /* Exhaust */
3722 if (remainder_size < MINSIZE)
3724 set_inuse_bit_at_offset (victim, size);
3725 if (av != &main_arena)
3726 victim->size |= NON_MAIN_ARENA;
3729 /* Split */
3730 else
3732 remainder = chunk_at_offset (victim, nb);
3734 /* We cannot assume the unsorted list is empty and therefore
3735 have to perform a complete insert here. */
3736 bck = unsorted_chunks (av);
3737 fwd = bck->fd;
3738 if (__glibc_unlikely (fwd->bk != bck))
3740 errstr = "malloc(): corrupted unsorted chunks 2";
3741 goto errout;
3743 remainder->bk = bck;
3744 remainder->fd = fwd;
3745 bck->fd = remainder;
3746 fwd->bk = remainder;
3748 /* advertise as last remainder */
3749 if (in_smallbin_range (nb))
3750 av->last_remainder = remainder;
3751 if (!in_smallbin_range (remainder_size))
3753 remainder->fd_nextsize = NULL;
3754 remainder->bk_nextsize = NULL;
3756 set_head (victim, nb | PREV_INUSE |
3757 (av != &main_arena ? NON_MAIN_ARENA : 0));
3758 set_head (remainder, remainder_size | PREV_INUSE);
3759 set_foot (remainder, remainder_size);
3761 check_malloced_chunk (av, victim, nb);
3762 void *p = chunk2mem (victim);
3763 alloc_perturb (p, bytes);
3764 return p;
3768 use_top:
3770 If large enough, split off the chunk bordering the end of memory
3771 (held in av->top). Note that this is in accord with the best-fit
3772 search rule. In effect, av->top is treated as larger (and thus
3773 less well fitting) than any other available chunk since it can
3774 be extended to be as large as necessary (up to system
3775 limitations).
3777 We require that av->top always exists (i.e., has size >=
3778 MINSIZE) after initialization, so if it would otherwise be
3779 exhausted by current request, it is replenished. (The main
3780 reason for ensuring it exists is that we may need MINSIZE space
3781 to put in fenceposts in sysmalloc.)
3784 victim = av->top;
3785 size = chunksize (victim);
3787 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
3789 remainder_size = size - nb;
3790 remainder = chunk_at_offset (victim, nb);
3791 av->top = remainder;
3792 set_head (victim, nb | PREV_INUSE |
3793 (av != &main_arena ? NON_MAIN_ARENA : 0));
3794 set_head (remainder, remainder_size | PREV_INUSE);
3796 check_malloced_chunk (av, victim, nb);
3797 void *p = chunk2mem (victim);
3798 alloc_perturb (p, bytes);
3799 return p;
3802 /* When we are using atomic ops to free fast chunks we can get
3803 here for all block sizes. */
3804 else if (have_fastchunks (av))
3806 malloc_consolidate (av);
3807 /* restore original bin index */
3808 if (in_smallbin_range (nb))
3809 idx = smallbin_index (nb);
3810 else
3811 idx = largebin_index (nb);
3815 Otherwise, relay to handle system-dependent cases
3817 else
3819 void *p = sysmalloc (nb, av);
3820 if (p != NULL)
3821 alloc_perturb (p, bytes);
3822 return p;
3828 ------------------------------ free ------------------------------
3831 static void
3832 _int_free (mstate av, mchunkptr p, int have_lock)
3834 INTERNAL_SIZE_T size; /* its size */
3835 mfastbinptr *fb; /* associated fastbin */
3836 mchunkptr nextchunk; /* next contiguous chunk */
3837 INTERNAL_SIZE_T nextsize; /* its size */
3838 int nextinuse; /* true if nextchunk is used */
3839 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
3840 mchunkptr bck; /* misc temp for linking */
3841 mchunkptr fwd; /* misc temp for linking */
3843 const char *errstr = NULL;
3844 int locked = 0;
3846 size = chunksize (p);
3848 /* Little security check which won't hurt performance: the
3849 allocator never wrapps around at the end of the address space.
3850 Therefore we can exclude some size values which might appear
3851 here by accident or by "design" from some intruder. */
3852 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
3853 || __builtin_expect (misaligned_chunk (p), 0))
3855 errstr = "free(): invalid pointer";
3856 errout:
3857 if (!have_lock && locked)
3858 (void) mutex_unlock (&av->mutex);
3859 malloc_printerr (check_action, errstr, chunk2mem (p), av);
3860 return;
3862 /* We know that each chunk is at least MINSIZE bytes in size or a
3863 multiple of MALLOC_ALIGNMENT. */
3864 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
3866 errstr = "free(): invalid size";
3867 goto errout;
3870 check_inuse_chunk(av, p);
3873 If eligible, place chunk on a fastbin so it can be found
3874 and used quickly in malloc.
3877 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
3879 #if TRIM_FASTBINS
3881 If TRIM_FASTBINS set, don't place chunks
3882 bordering top into fastbins
3884 && (chunk_at_offset(p, size) != av->top)
3885 #endif
3888 if (__builtin_expect (chunk_at_offset (p, size)->size <= 2 * SIZE_SZ, 0)
3889 || __builtin_expect (chunksize (chunk_at_offset (p, size))
3890 >= av->system_mem, 0))
3892 /* We might not have a lock at this point and concurrent modifications
3893 of system_mem might have let to a false positive. Redo the test
3894 after getting the lock. */
3895 if (have_lock
3896 || ({ assert (locked == 0);
3897 mutex_lock(&av->mutex);
3898 locked = 1;
3899 chunk_at_offset (p, size)->size <= 2 * SIZE_SZ
3900 || chunksize (chunk_at_offset (p, size)) >= av->system_mem;
3903 errstr = "free(): invalid next size (fast)";
3904 goto errout;
3906 if (! have_lock)
3908 (void)mutex_unlock(&av->mutex);
3909 locked = 0;
3913 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3915 set_fastchunks(av);
3916 unsigned int idx = fastbin_index(size);
3917 fb = &fastbin (av, idx);
3919 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
3920 mchunkptr old = *fb, old2;
3921 unsigned int old_idx = ~0u;
3924 /* Check that the top of the bin is not the record we are going to add
3925 (i.e., double free). */
3926 if (__builtin_expect (old == p, 0))
3928 errstr = "double free or corruption (fasttop)";
3929 goto errout;
3931 /* Check that size of fastbin chunk at the top is the same as
3932 size of the chunk that we are adding. We can dereference OLD
3933 only if we have the lock, otherwise it might have already been
3934 deallocated. See use of OLD_IDX below for the actual check. */
3935 if (have_lock && old != NULL)
3936 old_idx = fastbin_index(chunksize(old));
3937 p->fd = old2 = old;
3939 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2)) != old2);
3941 if (have_lock && old != NULL && __builtin_expect (old_idx != idx, 0))
3943 errstr = "invalid fastbin entry (free)";
3944 goto errout;
3949 Consolidate other non-mmapped chunks as they arrive.
3952 else if (!chunk_is_mmapped(p)) {
3953 if (! have_lock) {
3954 (void)mutex_lock(&av->mutex);
3955 locked = 1;
3958 nextchunk = chunk_at_offset(p, size);
3960 /* Lightweight tests: check whether the block is already the
3961 top block. */
3962 if (__glibc_unlikely (p == av->top))
3964 errstr = "double free or corruption (top)";
3965 goto errout;
3967 /* Or whether the next chunk is beyond the boundaries of the arena. */
3968 if (__builtin_expect (contiguous (av)
3969 && (char *) nextchunk
3970 >= ((char *) av->top + chunksize(av->top)), 0))
3972 errstr = "double free or corruption (out)";
3973 goto errout;
3975 /* Or whether the block is actually not marked used. */
3976 if (__glibc_unlikely (!prev_inuse(nextchunk)))
3978 errstr = "double free or corruption (!prev)";
3979 goto errout;
3982 nextsize = chunksize(nextchunk);
3983 if (__builtin_expect (nextchunk->size <= 2 * SIZE_SZ, 0)
3984 || __builtin_expect (nextsize >= av->system_mem, 0))
3986 errstr = "free(): invalid next size (normal)";
3987 goto errout;
3990 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3992 /* consolidate backward */
3993 if (!prev_inuse(p)) {
3994 prevsize = p->prev_size;
3995 size += prevsize;
3996 p = chunk_at_offset(p, -((long) prevsize));
3997 unlink(av, p, bck, fwd);
4000 if (nextchunk != av->top) {
4001 /* get and clear inuse bit */
4002 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4004 /* consolidate forward */
4005 if (!nextinuse) {
4006 unlink(av, nextchunk, bck, fwd);
4007 size += nextsize;
4008 } else
4009 clear_inuse_bit_at_offset(nextchunk, 0);
4012 Place the chunk in unsorted chunk list. Chunks are
4013 not placed into regular bins until after they have
4014 been given one chance to be used in malloc.
4017 bck = unsorted_chunks(av);
4018 fwd = bck->fd;
4019 if (__glibc_unlikely (fwd->bk != bck))
4021 errstr = "free(): corrupted unsorted chunks";
4022 goto errout;
4024 p->fd = fwd;
4025 p->bk = bck;
4026 if (!in_smallbin_range(size))
4028 p->fd_nextsize = NULL;
4029 p->bk_nextsize = NULL;
4031 bck->fd = p;
4032 fwd->bk = p;
4034 set_head(p, size | PREV_INUSE);
4035 set_foot(p, size);
4037 check_free_chunk(av, p);
4041 If the chunk borders the current high end of memory,
4042 consolidate into top
4045 else {
4046 size += nextsize;
4047 set_head(p, size | PREV_INUSE);
4048 av->top = p;
4049 check_chunk(av, p);
4053 If freeing a large space, consolidate possibly-surrounding
4054 chunks. Then, if the total unused topmost memory exceeds trim
4055 threshold, ask malloc_trim to reduce top.
4057 Unless max_fast is 0, we don't know if there are fastbins
4058 bordering top, so we cannot tell for sure whether threshold
4059 has been reached unless fastbins are consolidated. But we
4060 don't want to consolidate on each free. As a compromise,
4061 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4062 is reached.
4065 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4066 if (have_fastchunks(av))
4067 malloc_consolidate(av);
4069 if (av == &main_arena) {
4070 #ifndef MORECORE_CANNOT_TRIM
4071 if ((unsigned long)(chunksize(av->top)) >=
4072 (unsigned long)(mp_.trim_threshold))
4073 systrim(mp_.top_pad, av);
4074 #endif
4075 } else {
4076 /* Always try heap_trim(), even if the top chunk is not
4077 large, because the corresponding heap might go away. */
4078 heap_info *heap = heap_for_ptr(top(av));
4080 assert(heap->ar_ptr == av);
4081 heap_trim(heap, mp_.top_pad);
4085 if (! have_lock) {
4086 assert (locked);
4087 (void)mutex_unlock(&av->mutex);
4091 If the chunk was allocated via mmap, release via munmap().
4094 else {
4095 munmap_chunk (p);
4100 ------------------------- malloc_consolidate -------------------------
4102 malloc_consolidate is a specialized version of free() that tears
4103 down chunks held in fastbins. Free itself cannot be used for this
4104 purpose since, among other things, it might place chunks back onto
4105 fastbins. So, instead, we need to use a minor variant of the same
4106 code.
4108 Also, because this routine needs to be called the first time through
4109 malloc anyway, it turns out to be the perfect place to trigger
4110 initialization code.
4113 static void malloc_consolidate(mstate av)
4115 mfastbinptr* fb; /* current fastbin being consolidated */
4116 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4117 mchunkptr p; /* current chunk being consolidated */
4118 mchunkptr nextp; /* next chunk to consolidate */
4119 mchunkptr unsorted_bin; /* bin header */
4120 mchunkptr first_unsorted; /* chunk to link to */
4122 /* These have same use as in free() */
4123 mchunkptr nextchunk;
4124 INTERNAL_SIZE_T size;
4125 INTERNAL_SIZE_T nextsize;
4126 INTERNAL_SIZE_T prevsize;
4127 int nextinuse;
4128 mchunkptr bck;
4129 mchunkptr fwd;
4132 If max_fast is 0, we know that av hasn't
4133 yet been initialized, in which case do so below
4136 if (get_max_fast () != 0) {
4137 clear_fastchunks(av);
4139 unsorted_bin = unsorted_chunks(av);
4142 Remove each chunk from fast bin and consolidate it, placing it
4143 then in unsorted bin. Among other reasons for doing this,
4144 placing in unsorted bin avoids needing to calculate actual bins
4145 until malloc is sure that chunks aren't immediately going to be
4146 reused anyway.
4149 maxfb = &fastbin (av, NFASTBINS - 1);
4150 fb = &fastbin (av, 0);
4151 do {
4152 p = atomic_exchange_acq (fb, NULL);
4153 if (p != 0) {
4154 do {
4155 check_inuse_chunk(av, p);
4156 nextp = p->fd;
4158 /* Slightly streamlined version of consolidation code in free() */
4159 size = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
4160 nextchunk = chunk_at_offset(p, size);
4161 nextsize = chunksize(nextchunk);
4163 if (!prev_inuse(p)) {
4164 prevsize = p->prev_size;
4165 size += prevsize;
4166 p = chunk_at_offset(p, -((long) prevsize));
4167 unlink(av, p, bck, fwd);
4170 if (nextchunk != av->top) {
4171 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4173 if (!nextinuse) {
4174 size += nextsize;
4175 unlink(av, nextchunk, bck, fwd);
4176 } else
4177 clear_inuse_bit_at_offset(nextchunk, 0);
4179 first_unsorted = unsorted_bin->fd;
4180 unsorted_bin->fd = p;
4181 first_unsorted->bk = p;
4183 if (!in_smallbin_range (size)) {
4184 p->fd_nextsize = NULL;
4185 p->bk_nextsize = NULL;
4188 set_head(p, size | PREV_INUSE);
4189 p->bk = unsorted_bin;
4190 p->fd = first_unsorted;
4191 set_foot(p, size);
4194 else {
4195 size += nextsize;
4196 set_head(p, size | PREV_INUSE);
4197 av->top = p;
4200 } while ( (p = nextp) != 0);
4203 } while (fb++ != maxfb);
4205 else {
4206 malloc_init_state(av);
4207 check_malloc_state(av);
4212 ------------------------------ realloc ------------------------------
4215 void*
4216 _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4217 INTERNAL_SIZE_T nb)
4219 mchunkptr newp; /* chunk to return */
4220 INTERNAL_SIZE_T newsize; /* its size */
4221 void* newmem; /* corresponding user mem */
4223 mchunkptr next; /* next contiguous chunk after oldp */
4225 mchunkptr remainder; /* extra space at end of newp */
4226 unsigned long remainder_size; /* its size */
4228 mchunkptr bck; /* misc temp for linking */
4229 mchunkptr fwd; /* misc temp for linking */
4231 unsigned long copysize; /* bytes to copy */
4232 unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
4233 INTERNAL_SIZE_T* s; /* copy source */
4234 INTERNAL_SIZE_T* d; /* copy destination */
4236 const char *errstr = NULL;
4238 /* oldmem size */
4239 if (__builtin_expect (oldp->size <= 2 * SIZE_SZ, 0)
4240 || __builtin_expect (oldsize >= av->system_mem, 0))
4242 errstr = "realloc(): invalid old size";
4243 errout:
4244 malloc_printerr (check_action, errstr, chunk2mem (oldp), av);
4245 return NULL;
4248 check_inuse_chunk (av, oldp);
4250 /* All callers already filter out mmap'ed chunks. */
4251 assert (!chunk_is_mmapped (oldp));
4253 next = chunk_at_offset (oldp, oldsize);
4254 INTERNAL_SIZE_T nextsize = chunksize (next);
4255 if (__builtin_expect (next->size <= 2 * SIZE_SZ, 0)
4256 || __builtin_expect (nextsize >= av->system_mem, 0))
4258 errstr = "realloc(): invalid next size";
4259 goto errout;
4262 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4264 /* already big enough; split below */
4265 newp = oldp;
4266 newsize = oldsize;
4269 else
4271 /* Try to expand forward into top */
4272 if (next == av->top &&
4273 (unsigned long) (newsize = oldsize + nextsize) >=
4274 (unsigned long) (nb + MINSIZE))
4276 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4277 av->top = chunk_at_offset (oldp, nb);
4278 set_head (av->top, (newsize - nb) | PREV_INUSE);
4279 check_inuse_chunk (av, oldp);
4280 return chunk2mem (oldp);
4283 /* Try to expand forward into next chunk; split off remainder below */
4284 else if (next != av->top &&
4285 !inuse (next) &&
4286 (unsigned long) (newsize = oldsize + nextsize) >=
4287 (unsigned long) (nb))
4289 newp = oldp;
4290 unlink (av, next, bck, fwd);
4293 /* allocate, copy, free */
4294 else
4296 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4297 if (newmem == 0)
4298 return 0; /* propagate failure */
4300 newp = mem2chunk (newmem);
4301 newsize = chunksize (newp);
4304 Avoid copy if newp is next chunk after oldp.
4306 if (newp == next)
4308 newsize += oldsize;
4309 newp = oldp;
4311 else
4314 Unroll copy of <= 36 bytes (72 if 8byte sizes)
4315 We know that contents have an odd number of
4316 INTERNAL_SIZE_T-sized words; minimally 3.
4319 copysize = oldsize - SIZE_SZ;
4320 s = (INTERNAL_SIZE_T *) (chunk2mem (oldp));
4321 d = (INTERNAL_SIZE_T *) (newmem);
4322 ncopies = copysize / sizeof (INTERNAL_SIZE_T);
4323 assert (ncopies >= 3);
4325 if (ncopies > 9)
4326 memcpy (d, s, copysize);
4328 else
4330 *(d + 0) = *(s + 0);
4331 *(d + 1) = *(s + 1);
4332 *(d + 2) = *(s + 2);
4333 if (ncopies > 4)
4335 *(d + 3) = *(s + 3);
4336 *(d + 4) = *(s + 4);
4337 if (ncopies > 6)
4339 *(d + 5) = *(s + 5);
4340 *(d + 6) = *(s + 6);
4341 if (ncopies > 8)
4343 *(d + 7) = *(s + 7);
4344 *(d + 8) = *(s + 8);
4350 _int_free (av, oldp, 1);
4351 check_inuse_chunk (av, newp);
4352 return chunk2mem (newp);
4357 /* If possible, free extra space in old or extended chunk */
4359 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
4361 remainder_size = newsize - nb;
4363 if (remainder_size < MINSIZE) /* not enough extra to split off */
4365 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4366 set_inuse_bit_at_offset (newp, newsize);
4368 else /* split remainder */
4370 remainder = chunk_at_offset (newp, nb);
4371 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4372 set_head (remainder, remainder_size | PREV_INUSE |
4373 (av != &main_arena ? NON_MAIN_ARENA : 0));
4374 /* Mark remainder as inuse so free() won't complain */
4375 set_inuse_bit_at_offset (remainder, remainder_size);
4376 _int_free (av, remainder, 1);
4379 check_inuse_chunk (av, newp);
4380 return chunk2mem (newp);
4384 ------------------------------ memalign ------------------------------
4387 static void *
4388 _int_memalign (mstate av, size_t alignment, size_t bytes)
4390 INTERNAL_SIZE_T nb; /* padded request size */
4391 char *m; /* memory returned by malloc call */
4392 mchunkptr p; /* corresponding chunk */
4393 char *brk; /* alignment point within p */
4394 mchunkptr newp; /* chunk to return */
4395 INTERNAL_SIZE_T newsize; /* its size */
4396 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4397 mchunkptr remainder; /* spare room at end to split off */
4398 unsigned long remainder_size; /* its size */
4399 INTERNAL_SIZE_T size;
4403 checked_request2size (bytes, nb);
4406 Strategy: find a spot within that chunk that meets the alignment
4407 request, and then possibly free the leading and trailing space.
4411 /* Call malloc with worst case padding to hit alignment. */
4413 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4415 if (m == 0)
4416 return 0; /* propagate failure */
4418 p = mem2chunk (m);
4420 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4422 { /*
4423 Find an aligned spot inside chunk. Since we need to give back
4424 leading space in a chunk of at least MINSIZE, if the first
4425 calculation places us at a spot with less than MINSIZE leader,
4426 we can move to the next aligned spot -- we've allocated enough
4427 total room so that this is always possible.
4429 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4430 - ((signed long) alignment));
4431 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4432 brk += alignment;
4434 newp = (mchunkptr) brk;
4435 leadsize = brk - (char *) (p);
4436 newsize = chunksize (p) - leadsize;
4438 /* For mmapped chunks, just adjust offset */
4439 if (chunk_is_mmapped (p))
4441 newp->prev_size = p->prev_size + leadsize;
4442 set_head (newp, newsize | IS_MMAPPED);
4443 return chunk2mem (newp);
4446 /* Otherwise, give back leader, use the rest */
4447 set_head (newp, newsize | PREV_INUSE |
4448 (av != &main_arena ? NON_MAIN_ARENA : 0));
4449 set_inuse_bit_at_offset (newp, newsize);
4450 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4451 _int_free (av, p, 1);
4452 p = newp;
4454 assert (newsize >= nb &&
4455 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
4458 /* Also give back spare room at the end */
4459 if (!chunk_is_mmapped (p))
4461 size = chunksize (p);
4462 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4464 remainder_size = size - nb;
4465 remainder = chunk_at_offset (p, nb);
4466 set_head (remainder, remainder_size | PREV_INUSE |
4467 (av != &main_arena ? NON_MAIN_ARENA : 0));
4468 set_head_size (p, nb);
4469 _int_free (av, remainder, 1);
4473 check_inuse_chunk (av, p);
4474 return chunk2mem (p);
4479 ------------------------------ malloc_trim ------------------------------
4482 static int
4483 mtrim (mstate av, size_t pad)
4485 /* Don't touch corrupt arenas. */
4486 if (arena_is_corrupt (av))
4487 return 0;
4489 /* Ensure initialization/consolidation */
4490 malloc_consolidate (av);
4492 const size_t ps = GLRO (dl_pagesize);
4493 int psindex = bin_index (ps);
4494 const size_t psm1 = ps - 1;
4496 int result = 0;
4497 for (int i = 1; i < NBINS; ++i)
4498 if (i == 1 || i >= psindex)
4500 mbinptr bin = bin_at (av, i);
4502 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4504 INTERNAL_SIZE_T size = chunksize (p);
4506 if (size > psm1 + sizeof (struct malloc_chunk))
4508 /* See whether the chunk contains at least one unused page. */
4509 char *paligned_mem = (char *) (((uintptr_t) p
4510 + sizeof (struct malloc_chunk)
4511 + psm1) & ~psm1);
4513 assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
4514 assert ((char *) p + size > paligned_mem);
4516 /* This is the size we could potentially free. */
4517 size -= paligned_mem - (char *) p;
4519 if (size > psm1)
4521 #if MALLOC_DEBUG
4522 /* When debugging we simulate destroying the memory
4523 content. */
4524 memset (paligned_mem, 0x89, size & ~psm1);
4525 #endif
4526 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
4528 result = 1;
4534 #ifndef MORECORE_CANNOT_TRIM
4535 return result | (av == &main_arena ? systrim (pad, av) : 0);
4537 #else
4538 return result;
4539 #endif
4544 __malloc_trim (size_t s)
4546 int result = 0;
4548 if (__malloc_initialized < 0)
4549 ptmalloc_init ();
4551 mstate ar_ptr = &main_arena;
4554 (void) mutex_lock (&ar_ptr->mutex);
4555 result |= mtrim (ar_ptr, s);
4556 (void) mutex_unlock (&ar_ptr->mutex);
4558 ar_ptr = ar_ptr->next;
4560 while (ar_ptr != &main_arena);
4562 return result;
4567 ------------------------- malloc_usable_size -------------------------
4570 static size_t
4571 musable (void *mem)
4573 mchunkptr p;
4574 if (mem != 0)
4576 p = mem2chunk (mem);
4578 if (__builtin_expect (using_malloc_checking == 1, 0))
4579 return malloc_check_get_size (p);
4581 if (chunk_is_mmapped (p))
4582 return chunksize (p) - 2 * SIZE_SZ;
4583 else if (inuse (p))
4584 return chunksize (p) - SIZE_SZ;
4586 return 0;
4590 size_t
4591 __malloc_usable_size (void *m)
4593 size_t result;
4595 result = musable (m);
4596 return result;
4600 ------------------------------ mallinfo ------------------------------
4601 Accumulate malloc statistics for arena AV into M.
4604 static void
4605 int_mallinfo (mstate av, struct mallinfo *m)
4607 size_t i;
4608 mbinptr b;
4609 mchunkptr p;
4610 INTERNAL_SIZE_T avail;
4611 INTERNAL_SIZE_T fastavail;
4612 int nblocks;
4613 int nfastblocks;
4615 /* Ensure initialization */
4616 if (av->top == 0)
4617 malloc_consolidate (av);
4619 check_malloc_state (av);
4621 /* Account for top */
4622 avail = chunksize (av->top);
4623 nblocks = 1; /* top always exists */
4625 /* traverse fastbins */
4626 nfastblocks = 0;
4627 fastavail = 0;
4629 for (i = 0; i < NFASTBINS; ++i)
4631 for (p = fastbin (av, i); p != 0; p = p->fd)
4633 ++nfastblocks;
4634 fastavail += chunksize (p);
4638 avail += fastavail;
4640 /* traverse regular bins */
4641 for (i = 1; i < NBINS; ++i)
4643 b = bin_at (av, i);
4644 for (p = last (b); p != b; p = p->bk)
4646 ++nblocks;
4647 avail += chunksize (p);
4651 m->smblks += nfastblocks;
4652 m->ordblks += nblocks;
4653 m->fordblks += avail;
4654 m->uordblks += av->system_mem - avail;
4655 m->arena += av->system_mem;
4656 m->fsmblks += fastavail;
4657 if (av == &main_arena)
4659 m->hblks = mp_.n_mmaps;
4660 m->hblkhd = mp_.mmapped_mem;
4661 m->usmblks = 0;
4662 m->keepcost = chunksize (av->top);
4667 struct mallinfo
4668 __libc_mallinfo (void)
4670 struct mallinfo m;
4671 mstate ar_ptr;
4673 if (__malloc_initialized < 0)
4674 ptmalloc_init ();
4676 memset (&m, 0, sizeof (m));
4677 ar_ptr = &main_arena;
4680 (void) mutex_lock (&ar_ptr->mutex);
4681 int_mallinfo (ar_ptr, &m);
4682 (void) mutex_unlock (&ar_ptr->mutex);
4684 ar_ptr = ar_ptr->next;
4686 while (ar_ptr != &main_arena);
4688 return m;
4692 ------------------------------ malloc_stats ------------------------------
4695 void
4696 __malloc_stats (void)
4698 int i;
4699 mstate ar_ptr;
4700 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
4702 if (__malloc_initialized < 0)
4703 ptmalloc_init ();
4704 _IO_flockfile (stderr);
4705 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
4706 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
4707 for (i = 0, ar_ptr = &main_arena;; i++)
4709 struct mallinfo mi;
4711 memset (&mi, 0, sizeof (mi));
4712 (void) mutex_lock (&ar_ptr->mutex);
4713 int_mallinfo (ar_ptr, &mi);
4714 fprintf (stderr, "Arena %d:\n", i);
4715 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
4716 fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
4717 #if MALLOC_DEBUG > 1
4718 if (i > 0)
4719 dump_heap (heap_for_ptr (top (ar_ptr)));
4720 #endif
4721 system_b += mi.arena;
4722 in_use_b += mi.uordblks;
4723 (void) mutex_unlock (&ar_ptr->mutex);
4724 ar_ptr = ar_ptr->next;
4725 if (ar_ptr == &main_arena)
4726 break;
4728 fprintf (stderr, "Total (incl. mmap):\n");
4729 fprintf (stderr, "system bytes = %10u\n", system_b);
4730 fprintf (stderr, "in use bytes = %10u\n", in_use_b);
4731 fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
4732 fprintf (stderr, "max mmap bytes = %10lu\n",
4733 (unsigned long) mp_.max_mmapped_mem);
4734 ((_IO_FILE *) stderr)->_flags2 |= old_flags2;
4735 _IO_funlockfile (stderr);
4740 ------------------------------ mallopt ------------------------------
4744 __libc_mallopt (int param_number, int value)
4746 mstate av = &main_arena;
4747 int res = 1;
4749 if (__malloc_initialized < 0)
4750 ptmalloc_init ();
4751 (void) mutex_lock (&av->mutex);
4752 /* Ensure initialization/consolidation */
4753 malloc_consolidate (av);
4755 LIBC_PROBE (memory_mallopt, 2, param_number, value);
4757 switch (param_number)
4759 case M_MXFAST:
4760 if (value >= 0 && value <= MAX_FAST_SIZE)
4762 LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
4763 set_max_fast (value);
4765 else
4766 res = 0;
4767 break;
4769 case M_TRIM_THRESHOLD:
4770 LIBC_PROBE (memory_mallopt_trim_threshold, 3, value,
4771 mp_.trim_threshold, mp_.no_dyn_threshold);
4772 mp_.trim_threshold = value;
4773 mp_.no_dyn_threshold = 1;
4774 break;
4776 case M_TOP_PAD:
4777 LIBC_PROBE (memory_mallopt_top_pad, 3, value,
4778 mp_.top_pad, mp_.no_dyn_threshold);
4779 mp_.top_pad = value;
4780 mp_.no_dyn_threshold = 1;
4781 break;
4783 case M_MMAP_THRESHOLD:
4784 /* Forbid setting the threshold too high. */
4785 if ((unsigned long) value > HEAP_MAX_SIZE / 2)
4786 res = 0;
4787 else
4789 LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value,
4790 mp_.mmap_threshold, mp_.no_dyn_threshold);
4791 mp_.mmap_threshold = value;
4792 mp_.no_dyn_threshold = 1;
4794 break;
4796 case M_MMAP_MAX:
4797 LIBC_PROBE (memory_mallopt_mmap_max, 3, value,
4798 mp_.n_mmaps_max, mp_.no_dyn_threshold);
4799 mp_.n_mmaps_max = value;
4800 mp_.no_dyn_threshold = 1;
4801 break;
4803 case M_CHECK_ACTION:
4804 LIBC_PROBE (memory_mallopt_check_action, 2, value, check_action);
4805 check_action = value;
4806 break;
4808 case M_PERTURB:
4809 LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
4810 perturb_byte = value;
4811 break;
4813 case M_ARENA_TEST:
4814 if (value > 0)
4816 LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
4817 mp_.arena_test = value;
4819 break;
4821 case M_ARENA_MAX:
4822 if (value > 0)
4824 LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
4825 mp_.arena_max = value;
4827 break;
4829 (void) mutex_unlock (&av->mutex);
4830 return res;
4832 libc_hidden_def (__libc_mallopt)
4836 -------------------- Alternative MORECORE functions --------------------
4841 General Requirements for MORECORE.
4843 The MORECORE function must have the following properties:
4845 If MORECORE_CONTIGUOUS is false:
4847 * MORECORE must allocate in multiples of pagesize. It will
4848 only be called with arguments that are multiples of pagesize.
4850 * MORECORE(0) must return an address that is at least
4851 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
4853 else (i.e. If MORECORE_CONTIGUOUS is true):
4855 * Consecutive calls to MORECORE with positive arguments
4856 return increasing addresses, indicating that space has been
4857 contiguously extended.
4859 * MORECORE need not allocate in multiples of pagesize.
4860 Calls to MORECORE need not have args of multiples of pagesize.
4862 * MORECORE need not page-align.
4864 In either case:
4866 * MORECORE may allocate more memory than requested. (Or even less,
4867 but this will generally result in a malloc failure.)
4869 * MORECORE must not allocate memory when given argument zero, but
4870 instead return one past the end address of memory from previous
4871 nonzero call. This malloc does NOT call MORECORE(0)
4872 until at least one call with positive arguments is made, so
4873 the initial value returned is not important.
4875 * Even though consecutive calls to MORECORE need not return contiguous
4876 addresses, it must be OK for malloc'ed chunks to span multiple
4877 regions in those cases where they do happen to be contiguous.
4879 * MORECORE need not handle negative arguments -- it may instead
4880 just return MORECORE_FAILURE when given negative arguments.
4881 Negative arguments are always multiples of pagesize. MORECORE
4882 must not misinterpret negative args as large positive unsigned
4883 args. You can suppress all such calls from even occurring by defining
4884 MORECORE_CANNOT_TRIM,
4886 There is some variation across systems about the type of the
4887 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
4888 actually be size_t, because sbrk supports negative args, so it is
4889 normally the signed type of the same width as size_t (sometimes
4890 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
4891 matter though. Internally, we use "long" as arguments, which should
4892 work across all reasonable possibilities.
4894 Additionally, if MORECORE ever returns failure for a positive
4895 request, then mmap is used as a noncontiguous system allocator. This
4896 is a useful backup strategy for systems with holes in address spaces
4897 -- in this case sbrk cannot contiguously expand the heap, but mmap
4898 may be able to map noncontiguous space.
4900 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
4901 a function that always returns MORECORE_FAILURE.
4903 If you are using this malloc with something other than sbrk (or its
4904 emulation) to supply memory regions, you probably want to set
4905 MORECORE_CONTIGUOUS as false. As an example, here is a custom
4906 allocator kindly contributed for pre-OSX macOS. It uses virtually
4907 but not necessarily physically contiguous non-paged memory (locked
4908 in, present and won't get swapped out). You can use it by
4909 uncommenting this section, adding some #includes, and setting up the
4910 appropriate defines above:
4912 *#define MORECORE osMoreCore
4913 *#define MORECORE_CONTIGUOUS 0
4915 There is also a shutdown routine that should somehow be called for
4916 cleanup upon program exit.
4918 *#define MAX_POOL_ENTRIES 100
4919 *#define MINIMUM_MORECORE_SIZE (64 * 1024)
4920 static int next_os_pool;
4921 void *our_os_pools[MAX_POOL_ENTRIES];
4923 void *osMoreCore(int size)
4925 void *ptr = 0;
4926 static void *sbrk_top = 0;
4928 if (size > 0)
4930 if (size < MINIMUM_MORECORE_SIZE)
4931 size = MINIMUM_MORECORE_SIZE;
4932 if (CurrentExecutionLevel() == kTaskLevel)
4933 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
4934 if (ptr == 0)
4936 return (void *) MORECORE_FAILURE;
4938 // save ptrs so they can be freed during cleanup
4939 our_os_pools[next_os_pool] = ptr;
4940 next_os_pool++;
4941 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
4942 sbrk_top = (char *) ptr + size;
4943 return ptr;
4945 else if (size < 0)
4947 // we don't currently support shrink behavior
4948 return (void *) MORECORE_FAILURE;
4950 else
4952 return sbrk_top;
4956 // cleanup any allocated memory pools
4957 // called as last thing before shutting down driver
4959 void osCleanupMem(void)
4961 void **ptr;
4963 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
4964 if (*ptr)
4966 PoolDeallocate(*ptr);
4967 * ptr = 0;
4974 /* Helper code. */
4976 extern char **__libc_argv attribute_hidden;
4978 static void
4979 malloc_printerr (int action, const char *str, void *ptr, mstate ar_ptr)
4981 /* Avoid using this arena in future. We do not attempt to synchronize this
4982 with anything else because we minimally want to ensure that __libc_message
4983 gets its resources safely without stumbling on the current corruption. */
4984 if (ar_ptr)
4985 set_arena_corrupt (ar_ptr);
4987 if ((action & 5) == 5)
4988 __libc_message (action & 2, "%s\n", str);
4989 else if (action & 1)
4991 char buf[2 * sizeof (uintptr_t) + 1];
4993 buf[sizeof (buf) - 1] = '\0';
4994 char *cp = _itoa_word ((uintptr_t) ptr, &buf[sizeof (buf) - 1], 16, 0);
4995 while (cp > buf)
4996 *--cp = '0';
4998 __libc_message (action & 2, "*** Error in `%s': %s: 0x%s ***\n",
4999 __libc_argv[0] ? : "<unknown>", str, cp);
5001 else if (action & 2)
5002 abort ();
5005 /* We need a wrapper function for one of the additions of POSIX. */
5007 __posix_memalign (void **memptr, size_t alignment, size_t size)
5009 void *mem;
5011 /* Test whether the SIZE argument is valid. It must be a power of
5012 two multiple of sizeof (void *). */
5013 if (alignment % sizeof (void *) != 0
5014 || !powerof2 (alignment / sizeof (void *))
5015 || alignment == 0)
5016 return EINVAL;
5019 void *address = RETURN_ADDRESS (0);
5020 mem = _mid_memalign (alignment, size, address);
5022 if (mem != NULL)
5024 *memptr = mem;
5025 return 0;
5028 return ENOMEM;
5030 weak_alias (__posix_memalign, posix_memalign)
5034 __malloc_info (int options, FILE *fp)
5036 /* For now, at least. */
5037 if (options != 0)
5038 return EINVAL;
5040 int n = 0;
5041 size_t total_nblocks = 0;
5042 size_t total_nfastblocks = 0;
5043 size_t total_avail = 0;
5044 size_t total_fastavail = 0;
5045 size_t total_system = 0;
5046 size_t total_max_system = 0;
5047 size_t total_aspace = 0;
5048 size_t total_aspace_mprotect = 0;
5052 if (__malloc_initialized < 0)
5053 ptmalloc_init ();
5055 fputs ("<malloc version=\"1\">\n", fp);
5057 /* Iterate over all arenas currently in use. */
5058 mstate ar_ptr = &main_arena;
5061 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
5063 size_t nblocks = 0;
5064 size_t nfastblocks = 0;
5065 size_t avail = 0;
5066 size_t fastavail = 0;
5067 struct
5069 size_t from;
5070 size_t to;
5071 size_t total;
5072 size_t count;
5073 } sizes[NFASTBINS + NBINS - 1];
5074 #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
5076 mutex_lock (&ar_ptr->mutex);
5078 for (size_t i = 0; i < NFASTBINS; ++i)
5080 mchunkptr p = fastbin (ar_ptr, i);
5081 if (p != NULL)
5083 size_t nthissize = 0;
5084 size_t thissize = chunksize (p);
5086 while (p != NULL)
5088 ++nthissize;
5089 p = p->fd;
5092 fastavail += nthissize * thissize;
5093 nfastblocks += nthissize;
5094 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
5095 sizes[i].to = thissize;
5096 sizes[i].count = nthissize;
5098 else
5099 sizes[i].from = sizes[i].to = sizes[i].count = 0;
5101 sizes[i].total = sizes[i].count * sizes[i].to;
5105 mbinptr bin;
5106 struct malloc_chunk *r;
5108 for (size_t i = 1; i < NBINS; ++i)
5110 bin = bin_at (ar_ptr, i);
5111 r = bin->fd;
5112 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5113 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5114 = sizes[NFASTBINS - 1 + i].count = 0;
5116 if (r != NULL)
5117 while (r != bin)
5119 ++sizes[NFASTBINS - 1 + i].count;
5120 sizes[NFASTBINS - 1 + i].total += r->size;
5121 sizes[NFASTBINS - 1 + i].from
5122 = MIN (sizes[NFASTBINS - 1 + i].from, r->size);
5123 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5124 r->size);
5126 r = r->fd;
5129 if (sizes[NFASTBINS - 1 + i].count == 0)
5130 sizes[NFASTBINS - 1 + i].from = 0;
5131 nblocks += sizes[NFASTBINS - 1 + i].count;
5132 avail += sizes[NFASTBINS - 1 + i].total;
5135 mutex_unlock (&ar_ptr->mutex);
5137 total_nfastblocks += nfastblocks;
5138 total_fastavail += fastavail;
5140 total_nblocks += nblocks;
5141 total_avail += avail;
5143 for (size_t i = 0; i < nsizes; ++i)
5144 if (sizes[i].count != 0 && i != NFASTBINS)
5145 fprintf (fp, " \
5146 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5147 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
5149 if (sizes[NFASTBINS].count != 0)
5150 fprintf (fp, "\
5151 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5152 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5153 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
5155 total_system += ar_ptr->system_mem;
5156 total_max_system += ar_ptr->max_system_mem;
5158 fprintf (fp,
5159 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5160 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5161 "<system type=\"current\" size=\"%zu\"/>\n"
5162 "<system type=\"max\" size=\"%zu\"/>\n",
5163 nfastblocks, fastavail, nblocks, avail,
5164 ar_ptr->system_mem, ar_ptr->max_system_mem);
5166 if (ar_ptr != &main_arena)
5168 heap_info *heap = heap_for_ptr (top (ar_ptr));
5169 fprintf (fp,
5170 "<aspace type=\"total\" size=\"%zu\"/>\n"
5171 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5172 heap->size, heap->mprotect_size);
5173 total_aspace += heap->size;
5174 total_aspace_mprotect += heap->mprotect_size;
5176 else
5178 fprintf (fp,
5179 "<aspace type=\"total\" size=\"%zu\"/>\n"
5180 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5181 ar_ptr->system_mem, ar_ptr->system_mem);
5182 total_aspace += ar_ptr->system_mem;
5183 total_aspace_mprotect += ar_ptr->system_mem;
5186 fputs ("</heap>\n", fp);
5187 ar_ptr = ar_ptr->next;
5189 while (ar_ptr != &main_arena);
5191 fprintf (fp,
5192 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5193 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5194 "<total type=\"mmap\" count=\"%d\" size=\"%zu\"/>\n"
5195 "<system type=\"current\" size=\"%zu\"/>\n"
5196 "<system type=\"max\" size=\"%zu\"/>\n"
5197 "<aspace type=\"total\" size=\"%zu\"/>\n"
5198 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5199 "</malloc>\n",
5200 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
5201 mp_.n_mmaps, mp_.mmapped_mem,
5202 total_system, total_max_system,
5203 total_aspace, total_aspace_mprotect);
5205 return 0;
5207 weak_alias (__malloc_info, malloc_info)
5210 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5211 strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5212 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5213 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5214 strong_alias (__libc_memalign, __memalign)
5215 weak_alias (__libc_memalign, memalign)
5216 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5217 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5218 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5219 strong_alias (__libc_mallinfo, __mallinfo)
5220 weak_alias (__libc_mallinfo, mallinfo)
5221 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5223 weak_alias (__malloc_stats, malloc_stats)
5224 weak_alias (__malloc_usable_size, malloc_usable_size)
5225 weak_alias (__malloc_trim, malloc_trim)
5226 weak_alias (__malloc_get_state, malloc_get_state)
5227 weak_alias (__malloc_set_state, malloc_set_state)
5230 /* ------------------------------------------------------------
5231 History:
5233 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
5237 * Local variables:
5238 * c-basic-offset: 2
5239 * End: