Replace M_PI_4l with lit_pi_4_d in libm-test.inc
[glibc.git] / malloc / malloc.c
blobead9a21d81fb1442551b30ddc9e00deeead47922
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 # define MALLOC_ALIGNMENT (2 * SIZE_SZ < __alignof__ (long double) \
356 ? __alignof__ (long double) : 2 * SIZE_SZ)
357 #endif
359 /* The corresponding bit mask value */
360 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
365 REALLOC_ZERO_BYTES_FREES should be set if a call to
366 realloc with zero bytes should be the same as a call to free.
367 This is required by the C standard. Otherwise, since this malloc
368 returns a unique pointer for malloc(0), so does realloc(p, 0).
371 #ifndef REALLOC_ZERO_BYTES_FREES
372 #define REALLOC_ZERO_BYTES_FREES 1
373 #endif
376 TRIM_FASTBINS controls whether free() of a very small chunk can
377 immediately lead to trimming. Setting to true (1) can reduce memory
378 footprint, but will almost always slow down programs that use a lot
379 of small chunks.
381 Define this only if you are willing to give up some speed to more
382 aggressively reduce system-level memory footprint when releasing
383 memory in programs that use many small chunks. You can get
384 essentially the same effect by setting MXFAST to 0, but this can
385 lead to even greater slowdowns in programs using many small chunks.
386 TRIM_FASTBINS is an in-between compile-time option, that disables
387 only those chunks bordering topmost memory from being placed in
388 fastbins.
391 #ifndef TRIM_FASTBINS
392 #define TRIM_FASTBINS 0
393 #endif
396 /* Definition for getting more memory from the OS. */
397 #define MORECORE (*__morecore)
398 #define MORECORE_FAILURE 0
399 void * __default_morecore (ptrdiff_t);
400 void *(*__morecore)(ptrdiff_t) = __default_morecore;
403 #include <string.h>
406 MORECORE-related declarations. By default, rely on sbrk
411 MORECORE is the name of the routine to call to obtain more memory
412 from the system. See below for general guidance on writing
413 alternative MORECORE functions, as well as a version for WIN32 and a
414 sample version for pre-OSX macos.
417 #ifndef MORECORE
418 #define MORECORE sbrk
419 #endif
422 MORECORE_FAILURE is the value returned upon failure of MORECORE
423 as well as mmap. Since it cannot be an otherwise valid memory address,
424 and must reflect values of standard sys calls, you probably ought not
425 try to redefine it.
428 #ifndef MORECORE_FAILURE
429 #define MORECORE_FAILURE (-1)
430 #endif
433 If MORECORE_CONTIGUOUS is true, take advantage of fact that
434 consecutive calls to MORECORE with positive arguments always return
435 contiguous increasing addresses. This is true of unix sbrk. Even
436 if not defined, when regions happen to be contiguous, malloc will
437 permit allocations spanning regions obtained from different
438 calls. But defining this when applicable enables some stronger
439 consistency checks and space efficiencies.
442 #ifndef MORECORE_CONTIGUOUS
443 #define MORECORE_CONTIGUOUS 1
444 #endif
447 Define MORECORE_CANNOT_TRIM if your version of MORECORE
448 cannot release space back to the system when given negative
449 arguments. This is generally necessary only if you are using
450 a hand-crafted MORECORE function that cannot handle negative arguments.
453 /* #define MORECORE_CANNOT_TRIM */
455 /* MORECORE_CLEARS (default 1)
456 The degree to which the routine mapped to MORECORE zeroes out
457 memory: never (0), only for newly allocated space (1) or always
458 (2). The distinction between (1) and (2) is necessary because on
459 some systems, if the application first decrements and then
460 increments the break value, the contents of the reallocated space
461 are unspecified.
464 #ifndef MORECORE_CLEARS
465 # define MORECORE_CLEARS 1
466 #endif
470 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
471 sbrk fails, and mmap is used as a backup. The value must be a
472 multiple of page size. This backup strategy generally applies only
473 when systems have "holes" in address space, so sbrk cannot perform
474 contiguous expansion, but there is still space available on system.
475 On systems for which this is known to be useful (i.e. most linux
476 kernels), this occurs only when programs allocate huge amounts of
477 memory. Between this, and the fact that mmap regions tend to be
478 limited, the size should be large, to avoid too many mmap calls and
479 thus avoid running out of kernel resources. */
481 #ifndef MMAP_AS_MORECORE_SIZE
482 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
483 #endif
486 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
487 large blocks.
490 #ifndef HAVE_MREMAP
491 #define HAVE_MREMAP 0
492 #endif
496 This version of malloc supports the standard SVID/XPG mallinfo
497 routine that returns a struct containing usage properties and
498 statistics. It should work on any SVID/XPG compliant system that has
499 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
500 install such a thing yourself, cut out the preliminary declarations
501 as described above and below and save them in a malloc.h file. But
502 there's no compelling reason to bother to do this.)
504 The main declaration needed is the mallinfo struct that is returned
505 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
506 bunch of fields that are not even meaningful in this version of
507 malloc. These fields are are instead filled by mallinfo() with
508 other numbers that might be of interest.
512 /* ---------- description of public routines ------------ */
515 malloc(size_t n)
516 Returns a pointer to a newly allocated chunk of at least n bytes, or null
517 if no space is available. Additionally, on failure, errno is
518 set to ENOMEM on ANSI C systems.
520 If n is zero, malloc returns a minumum-sized chunk. (The minimum
521 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
522 systems.) On most systems, size_t is an unsigned type, so calls
523 with negative arguments are interpreted as requests for huge amounts
524 of space, which will often fail. The maximum supported value of n
525 differs across systems, but is in all cases less than the maximum
526 representable value of a size_t.
528 void* __libc_malloc(size_t);
529 libc_hidden_proto (__libc_malloc)
532 free(void* p)
533 Releases the chunk of memory pointed to by p, that had been previously
534 allocated using malloc or a related routine such as realloc.
535 It has no effect if p is null. It can have arbitrary (i.e., bad!)
536 effects if p has already been freed.
538 Unless disabled (using mallopt), freeing very large spaces will
539 when possible, automatically trigger operations that give
540 back unused memory to the system, thus reducing program footprint.
542 void __libc_free(void*);
543 libc_hidden_proto (__libc_free)
546 calloc(size_t n_elements, size_t element_size);
547 Returns a pointer to n_elements * element_size bytes, with all locations
548 set to zero.
550 void* __libc_calloc(size_t, size_t);
553 realloc(void* p, size_t n)
554 Returns a pointer to a chunk of size n that contains the same data
555 as does chunk p up to the minimum of (n, p's size) bytes, or null
556 if no space is available.
558 The returned pointer may or may not be the same as p. The algorithm
559 prefers extending p when possible, otherwise it employs the
560 equivalent of a malloc-copy-free sequence.
562 If p is null, realloc is equivalent to malloc.
564 If space is not available, realloc returns null, errno is set (if on
565 ANSI) and p is NOT freed.
567 if n is for fewer bytes than already held by p, the newly unused
568 space is lopped off and freed if possible. Unless the #define
569 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
570 zero (re)allocates a minimum-sized chunk.
572 Large chunks that were internally obtained via mmap will always
573 be reallocated using malloc-copy-free sequences unless
574 the system supports MREMAP (currently only linux).
576 The old unix realloc convention of allowing the last-free'd chunk
577 to be used as an argument to realloc is not supported.
579 void* __libc_realloc(void*, size_t);
580 libc_hidden_proto (__libc_realloc)
583 memalign(size_t alignment, size_t n);
584 Returns a pointer to a newly allocated chunk of n bytes, aligned
585 in accord with the alignment argument.
587 The alignment argument should be a power of two. If the argument is
588 not a power of two, the nearest greater power is used.
589 8-byte alignment is guaranteed by normal malloc calls, so don't
590 bother calling memalign with an argument of 8 or less.
592 Overreliance on memalign is a sure way to fragment space.
594 void* __libc_memalign(size_t, size_t);
595 libc_hidden_proto (__libc_memalign)
598 valloc(size_t n);
599 Equivalent to memalign(pagesize, n), where pagesize is the page
600 size of the system. If the pagesize is unknown, 4096 is used.
602 void* __libc_valloc(size_t);
607 mallopt(int parameter_number, int parameter_value)
608 Sets tunable parameters The format is to provide a
609 (parameter-number, parameter-value) pair. mallopt then sets the
610 corresponding parameter to the argument value if it can (i.e., so
611 long as the value is meaningful), and returns 1 if successful else
612 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
613 normally defined in malloc.h. Only one of these (M_MXFAST) is used
614 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
615 so setting them has no effect. But this malloc also supports four
616 other options in mallopt. See below for details. Briefly, supported
617 parameters are as follows (listed defaults are for "typical"
618 configurations).
620 Symbol param # default allowed param values
621 M_MXFAST 1 64 0-80 (0 disables fastbins)
622 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
623 M_TOP_PAD -2 0 any
624 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
625 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
627 int __libc_mallopt(int, int);
628 libc_hidden_proto (__libc_mallopt)
632 mallinfo()
633 Returns (by copy) a struct containing various summary statistics:
635 arena: current total non-mmapped bytes allocated from system
636 ordblks: the number of free chunks
637 smblks: the number of fastbin blocks (i.e., small chunks that
638 have been freed but not use resused or consolidated)
639 hblks: current number of mmapped regions
640 hblkhd: total bytes held in mmapped regions
641 usmblks: always 0
642 fsmblks: total bytes held in fastbin blocks
643 uordblks: current total allocated space (normal or mmapped)
644 fordblks: total free space
645 keepcost: the maximum number of bytes that could ideally be released
646 back to system via malloc_trim. ("ideally" means that
647 it ignores page restrictions etc.)
649 Because these fields are ints, but internal bookkeeping may
650 be kept as longs, the reported values may wrap around zero and
651 thus be inaccurate.
653 struct mallinfo __libc_mallinfo(void);
657 pvalloc(size_t n);
658 Equivalent to valloc(minimum-page-that-holds(n)), that is,
659 round up n to nearest pagesize.
661 void* __libc_pvalloc(size_t);
664 malloc_trim(size_t pad);
666 If possible, gives memory back to the system (via negative
667 arguments to sbrk) if there is unused memory at the `high' end of
668 the malloc pool. You can call this after freeing large blocks of
669 memory to potentially reduce the system-level memory requirements
670 of a program. However, it cannot guarantee to reduce memory. Under
671 some allocation patterns, some large free blocks of memory will be
672 locked between two used chunks, so they cannot be given back to
673 the system.
675 The `pad' argument to malloc_trim represents the amount of free
676 trailing space to leave untrimmed. If this argument is zero,
677 only the minimum amount of memory to maintain internal data
678 structures will be left (one page or less). Non-zero arguments
679 can be supplied to maintain enough trailing space to service
680 future expected allocations without having to re-obtain memory
681 from the system.
683 Malloc_trim returns 1 if it actually released any memory, else 0.
684 On systems that do not support "negative sbrks", it will always
685 return 0.
687 int __malloc_trim(size_t);
690 malloc_usable_size(void* p);
692 Returns the number of bytes you can actually use in
693 an allocated chunk, which may be more than you requested (although
694 often not) due to alignment and minimum size constraints.
695 You can use this many bytes without worrying about
696 overwriting other allocated objects. This is not a particularly great
697 programming practice. malloc_usable_size can be more useful in
698 debugging and assertions, for example:
700 p = malloc(n);
701 assert(malloc_usable_size(p) >= 256);
704 size_t __malloc_usable_size(void*);
707 malloc_stats();
708 Prints on stderr the amount of space obtained from the system (both
709 via sbrk and mmap), the maximum amount (which may be more than
710 current if malloc_trim and/or munmap got called), and the current
711 number of bytes allocated via malloc (or realloc, etc) but not yet
712 freed. Note that this is the number of bytes allocated, not the
713 number requested. It will be larger than the number requested
714 because of alignment and bookkeeping overhead. Because it includes
715 alignment wastage as being in use, this figure may be greater than
716 zero even when no user-level chunks are allocated.
718 The reported current and maximum system memory can be inaccurate if
719 a program makes other calls to system memory allocation functions
720 (normally sbrk) outside of malloc.
722 malloc_stats prints only the most commonly interesting statistics.
723 More information can be obtained by calling mallinfo.
726 void __malloc_stats(void);
729 malloc_get_state(void);
731 Returns the state of all malloc variables in an opaque data
732 structure.
734 void* __malloc_get_state(void);
737 malloc_set_state(void* state);
739 Restore the state of all malloc variables from data obtained with
740 malloc_get_state().
742 int __malloc_set_state(void*);
745 posix_memalign(void **memptr, size_t alignment, size_t size);
747 POSIX wrapper like memalign(), checking for validity of size.
749 int __posix_memalign(void **, size_t, size_t);
751 /* mallopt tuning options */
754 M_MXFAST is the maximum request size used for "fastbins", special bins
755 that hold returned chunks without consolidating their spaces. This
756 enables future requests for chunks of the same size to be handled
757 very quickly, but can increase fragmentation, and thus increase the
758 overall memory footprint of a program.
760 This malloc manages fastbins very conservatively yet still
761 efficiently, so fragmentation is rarely a problem for values less
762 than or equal to the default. The maximum supported value of MXFAST
763 is 80. You wouldn't want it any higher than this anyway. Fastbins
764 are designed especially for use with many small structs, objects or
765 strings -- the default handles structs/objects/arrays with sizes up
766 to 8 4byte fields, or small strings representing words, tokens,
767 etc. Using fastbins for larger objects normally worsens
768 fragmentation without improving speed.
770 M_MXFAST is set in REQUEST size units. It is internally used in
771 chunksize units, which adds padding and alignment. You can reduce
772 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
773 algorithm to be a closer approximation of fifo-best-fit in all cases,
774 not just for larger requests, but will generally cause it to be
775 slower.
779 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
780 #ifndef M_MXFAST
781 #define M_MXFAST 1
782 #endif
784 #ifndef DEFAULT_MXFAST
785 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
786 #endif
790 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
791 to keep before releasing via malloc_trim in free().
793 Automatic trimming is mainly useful in long-lived programs.
794 Because trimming via sbrk can be slow on some systems, and can
795 sometimes be wasteful (in cases where programs immediately
796 afterward allocate more large chunks) the value should be high
797 enough so that your overall system performance would improve by
798 releasing this much memory.
800 The trim threshold and the mmap control parameters (see below)
801 can be traded off with one another. Trimming and mmapping are
802 two different ways of releasing unused memory back to the
803 system. Between these two, it is often possible to keep
804 system-level demands of a long-lived program down to a bare
805 minimum. For example, in one test suite of sessions measuring
806 the XF86 X server on Linux, using a trim threshold of 128K and a
807 mmap threshold of 192K led to near-minimal long term resource
808 consumption.
810 If you are using this malloc in a long-lived program, it should
811 pay to experiment with these values. As a rough guide, you
812 might set to a value close to the average size of a process
813 (program) running on your system. Releasing this much memory
814 would allow such a process to run in memory. Generally, it's
815 worth it to tune for trimming rather tham memory mapping when a
816 program undergoes phases where several large chunks are
817 allocated and released in ways that can reuse each other's
818 storage, perhaps mixed with phases where there are no such
819 chunks at all. And in well-behaved long-lived programs,
820 controlling release of large blocks via trimming versus mapping
821 is usually faster.
823 However, in most programs, these parameters serve mainly as
824 protection against the system-level effects of carrying around
825 massive amounts of unneeded memory. Since frequent calls to
826 sbrk, mmap, and munmap otherwise degrade performance, the default
827 parameters are set to relatively high values that serve only as
828 safeguards.
830 The trim value It must be greater than page size to have any useful
831 effect. To disable trimming completely, you can set to
832 (unsigned long)(-1)
834 Trim settings interact with fastbin (MXFAST) settings: Unless
835 TRIM_FASTBINS is defined, automatic trimming never takes place upon
836 freeing a chunk with size less than or equal to MXFAST. Trimming is
837 instead delayed until subsequent freeing of larger chunks. However,
838 you can still force an attempted trim by calling malloc_trim.
840 Also, trimming is not generally possible in cases where
841 the main arena is obtained via mmap.
843 Note that the trick some people use of mallocing a huge space and
844 then freeing it at program startup, in an attempt to reserve system
845 memory, doesn't have the intended effect under automatic trimming,
846 since that memory will immediately be returned to the system.
849 #define M_TRIM_THRESHOLD -1
851 #ifndef DEFAULT_TRIM_THRESHOLD
852 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
853 #endif
856 M_TOP_PAD is the amount of extra `padding' space to allocate or
857 retain whenever sbrk is called. It is used in two ways internally:
859 * When sbrk is called to extend the top of the arena to satisfy
860 a new malloc request, this much padding is added to the sbrk
861 request.
863 * When malloc_trim is called automatically from free(),
864 it is used as the `pad' argument.
866 In both cases, the actual amount of padding is rounded
867 so that the end of the arena is always a system page boundary.
869 The main reason for using padding is to avoid calling sbrk so
870 often. Having even a small pad greatly reduces the likelihood
871 that nearly every malloc request during program start-up (or
872 after trimming) will invoke sbrk, which needlessly wastes
873 time.
875 Automatic rounding-up to page-size units is normally sufficient
876 to avoid measurable overhead, so the default is 0. However, in
877 systems where sbrk is relatively slow, it can pay to increase
878 this value, at the expense of carrying around more memory than
879 the program needs.
882 #define M_TOP_PAD -2
884 #ifndef DEFAULT_TOP_PAD
885 #define DEFAULT_TOP_PAD (0)
886 #endif
889 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
890 adjusted MMAP_THRESHOLD.
893 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
894 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
895 #endif
897 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
898 /* For 32-bit platforms we cannot increase the maximum mmap
899 threshold much because it is also the minimum value for the
900 maximum heap size and its alignment. Going above 512k (i.e., 1M
901 for new heaps) wastes too much address space. */
902 # if __WORDSIZE == 32
903 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
904 # else
905 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
906 # endif
907 #endif
910 M_MMAP_THRESHOLD is the request size threshold for using mmap()
911 to service a request. Requests of at least this size that cannot
912 be allocated using already-existing space will be serviced via mmap.
913 (If enough normal freed space already exists it is used instead.)
915 Using mmap segregates relatively large chunks of memory so that
916 they can be individually obtained and released from the host
917 system. A request serviced through mmap is never reused by any
918 other request (at least not directly; the system may just so
919 happen to remap successive requests to the same locations).
921 Segregating space in this way has the benefits that:
923 1. Mmapped space can ALWAYS be individually released back
924 to the system, which helps keep the system level memory
925 demands of a long-lived program low.
926 2. Mapped memory can never become `locked' between
927 other chunks, as can happen with normally allocated chunks, which
928 means that even trimming via malloc_trim would not release them.
929 3. On some systems with "holes" in address spaces, mmap can obtain
930 memory that sbrk cannot.
932 However, it has the disadvantages that:
934 1. The space cannot be reclaimed, consolidated, and then
935 used to service later requests, as happens with normal chunks.
936 2. It can lead to more wastage because of mmap page alignment
937 requirements
938 3. It causes malloc performance to be more dependent on host
939 system memory management support routines which may vary in
940 implementation quality and may impose arbitrary
941 limitations. Generally, servicing a request via normal
942 malloc steps is faster than going through a system's mmap.
944 The advantages of mmap nearly always outweigh disadvantages for
945 "large" chunks, but the value of "large" varies across systems. The
946 default is an empirically derived value that works well in most
947 systems.
950 Update in 2006:
951 The above was written in 2001. Since then the world has changed a lot.
952 Memory got bigger. Applications got bigger. The virtual address space
953 layout in 32 bit linux changed.
955 In the new situation, brk() and mmap space is shared and there are no
956 artificial limits on brk size imposed by the kernel. What is more,
957 applications have started using transient allocations larger than the
958 128Kb as was imagined in 2001.
960 The price for mmap is also high now; each time glibc mmaps from the
961 kernel, the kernel is forced to zero out the memory it gives to the
962 application. Zeroing memory is expensive and eats a lot of cache and
963 memory bandwidth. This has nothing to do with the efficiency of the
964 virtual memory system, by doing mmap the kernel just has no choice but
965 to zero.
967 In 2001, the kernel had a maximum size for brk() which was about 800
968 megabytes on 32 bit x86, at that point brk() would hit the first
969 mmaped shared libaries and couldn't expand anymore. With current 2.6
970 kernels, the VA space layout is different and brk() and mmap
971 both can span the entire heap at will.
973 Rather than using a static threshold for the brk/mmap tradeoff,
974 we are now using a simple dynamic one. The goal is still to avoid
975 fragmentation. The old goals we kept are
976 1) try to get the long lived large allocations to use mmap()
977 2) really large allocations should always use mmap()
978 and we're adding now:
979 3) transient allocations should use brk() to avoid forcing the kernel
980 having to zero memory over and over again
982 The implementation works with a sliding threshold, which is by default
983 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
984 out at 128Kb as per the 2001 default.
986 This allows us to satisfy requirement 1) under the assumption that long
987 lived allocations are made early in the process' lifespan, before it has
988 started doing dynamic allocations of the same size (which will
989 increase the threshold).
991 The upperbound on the threshold satisfies requirement 2)
993 The threshold goes up in value when the application frees memory that was
994 allocated with the mmap allocator. The idea is that once the application
995 starts freeing memory of a certain size, it's highly probable that this is
996 a size the application uses for transient allocations. This estimator
997 is there to satisfy the new third requirement.
1001 #define M_MMAP_THRESHOLD -3
1003 #ifndef DEFAULT_MMAP_THRESHOLD
1004 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1005 #endif
1008 M_MMAP_MAX is the maximum number of requests to simultaneously
1009 service using mmap. This parameter exists because
1010 some systems have a limited number of internal tables for
1011 use by mmap, and using more than a few of them may degrade
1012 performance.
1014 The default is set to a value that serves only as a safeguard.
1015 Setting to 0 disables use of mmap for servicing large requests.
1018 #define M_MMAP_MAX -4
1020 #ifndef DEFAULT_MMAP_MAX
1021 #define DEFAULT_MMAP_MAX (65536)
1022 #endif
1024 #include <malloc.h>
1026 #ifndef RETURN_ADDRESS
1027 #define RETURN_ADDRESS(X_) (NULL)
1028 #endif
1030 /* On some platforms we can compile internal, not exported functions better.
1031 Let the environment provide a macro and define it to be empty if it
1032 is not available. */
1033 #ifndef internal_function
1034 # define internal_function
1035 #endif
1037 /* Forward declarations. */
1038 struct malloc_chunk;
1039 typedef struct malloc_chunk* mchunkptr;
1041 /* Internal routines. */
1043 static void* _int_malloc(mstate, size_t);
1044 static void _int_free(mstate, mchunkptr, int);
1045 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1046 INTERNAL_SIZE_T);
1047 static void* _int_memalign(mstate, size_t, size_t);
1048 static void* _mid_memalign(size_t, size_t, void *);
1050 static void malloc_printerr(int action, const char *str, void *ptr, mstate av);
1052 static void* internal_function mem2mem_check(void *p, size_t sz);
1053 static int internal_function top_check(void);
1054 static void internal_function munmap_chunk(mchunkptr p);
1055 #if HAVE_MREMAP
1056 static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
1057 #endif
1059 static void* malloc_check(size_t sz, const void *caller);
1060 static void free_check(void* mem, const void *caller);
1061 static void* realloc_check(void* oldmem, size_t bytes,
1062 const void *caller);
1063 static void* memalign_check(size_t alignment, size_t bytes,
1064 const void *caller);
1066 /* ------------------ MMAP support ------------------ */
1069 #include <fcntl.h>
1070 #include <sys/mman.h>
1072 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1073 # define MAP_ANONYMOUS MAP_ANON
1074 #endif
1076 #ifndef MAP_NORESERVE
1077 # define MAP_NORESERVE 0
1078 #endif
1080 #define MMAP(addr, size, prot, flags) \
1081 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1085 ----------------------- Chunk representations -----------------------
1090 This struct declaration is misleading (but accurate and necessary).
1091 It declares a "view" into memory allowing access to necessary
1092 fields at known offsets from a given base. See explanation below.
1095 struct malloc_chunk {
1097 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
1098 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
1100 struct malloc_chunk* fd; /* double links -- used only if free. */
1101 struct malloc_chunk* bk;
1103 /* Only used for large blocks: pointer to next larger size. */
1104 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1105 struct malloc_chunk* bk_nextsize;
1110 malloc_chunk details:
1112 (The following includes lightly edited explanations by Colin Plumb.)
1114 Chunks of memory are maintained using a `boundary tag' method as
1115 described in e.g., Knuth or Standish. (See the paper by Paul
1116 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1117 survey of such techniques.) Sizes of free chunks are stored both
1118 in the front of each chunk and at the end. This makes
1119 consolidating fragmented chunks into bigger chunks very fast. The
1120 size fields also hold bits representing whether chunks are free or
1121 in use.
1123 An allocated chunk looks like this:
1126 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1127 | Size of previous chunk, if allocated | |
1128 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1129 | Size of chunk, in bytes |M|P|
1130 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1131 | User data starts here... .
1133 . (malloc_usable_size() bytes) .
1135 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1136 | Size of chunk |
1137 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1140 Where "chunk" is the front of the chunk for the purpose of most of
1141 the malloc code, but "mem" is the pointer that is returned to the
1142 user. "Nextchunk" is the beginning of the next contiguous chunk.
1144 Chunks always begin on even word boundaries, so the mem portion
1145 (which is returned to the user) is also on an even word boundary, and
1146 thus at least double-word aligned.
1148 Free chunks are stored in circular doubly-linked lists, and look like this:
1150 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1151 | Size of previous chunk |
1152 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1153 `head:' | Size of chunk, in bytes |P|
1154 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1155 | Forward pointer to next chunk in list |
1156 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1157 | Back pointer to previous chunk in list |
1158 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1159 | Unused space (may be 0 bytes long) .
1162 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1163 `foot:' | Size of chunk, in bytes |
1164 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1166 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1167 chunk size (which is always a multiple of two words), is an in-use
1168 bit for the *previous* chunk. If that bit is *clear*, then the
1169 word before the current chunk size contains the previous chunk
1170 size, and can be used to find the front of the previous chunk.
1171 The very first chunk allocated always has this bit set,
1172 preventing access to non-existent (or non-owned) memory. If
1173 prev_inuse is set for any given chunk, then you CANNOT determine
1174 the size of the previous chunk, and might even get a memory
1175 addressing fault when trying to do so.
1177 Note that the `foot' of the current chunk is actually represented
1178 as the prev_size of the NEXT chunk. This makes it easier to
1179 deal with alignments etc but can be very confusing when trying
1180 to extend or adapt this code.
1182 The two exceptions to all this are
1184 1. The special chunk `top' doesn't bother using the
1185 trailing size field since there is no next contiguous chunk
1186 that would have to index off it. After initialization, `top'
1187 is forced to always exist. If it would become less than
1188 MINSIZE bytes long, it is replenished.
1190 2. Chunks allocated via mmap, which have the second-lowest-order
1191 bit M (IS_MMAPPED) set in their size fields. Because they are
1192 allocated one-by-one, each must contain its own trailing size field.
1197 ---------- Size and alignment checks and conversions ----------
1200 /* conversion from malloc headers to user pointers, and back */
1202 #define chunk2mem(p) ((void*)((char*)(p) + 2*SIZE_SZ))
1203 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1205 /* The smallest possible chunk */
1206 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1208 /* The smallest size we can malloc is an aligned minimal chunk */
1210 #define MINSIZE \
1211 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1213 /* Check if m has acceptable alignment */
1215 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1217 #define misaligned_chunk(p) \
1218 ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
1219 & MALLOC_ALIGN_MASK)
1223 Check if a request is so large that it would wrap around zero when
1224 padded and aligned. To simplify some other code, the bound is made
1225 low enough so that adding MINSIZE will also not wrap around zero.
1228 #define REQUEST_OUT_OF_RANGE(req) \
1229 ((unsigned long) (req) >= \
1230 (unsigned long) (INTERNAL_SIZE_T) (-2 * MINSIZE))
1232 /* pad request bytes into a usable size -- internal version */
1234 #define request2size(req) \
1235 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1236 MINSIZE : \
1237 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1239 /* Same, except also perform argument check */
1241 #define checked_request2size(req, sz) \
1242 if (REQUEST_OUT_OF_RANGE (req)) { \
1243 __set_errno (ENOMEM); \
1244 return 0; \
1246 (sz) = request2size (req);
1249 --------------- Physical chunk operations ---------------
1253 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1254 #define PREV_INUSE 0x1
1256 /* extract inuse bit of previous chunk */
1257 #define prev_inuse(p) ((p)->size & PREV_INUSE)
1260 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1261 #define IS_MMAPPED 0x2
1263 /* check for mmap()'ed chunk */
1264 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1267 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1268 from a non-main arena. This is only set immediately before handing
1269 the chunk to the user, if necessary. */
1270 #define NON_MAIN_ARENA 0x4
1272 /* check for chunk from non-main arena */
1273 #define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)
1277 Bits to mask off when extracting size
1279 Note: IS_MMAPPED is intentionally not masked off from size field in
1280 macros for which mmapped chunks should never be seen. This should
1281 cause helpful core dumps to occur if it is tried by accident by
1282 people extending or adapting this malloc.
1284 #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1286 /* Get size, ignoring use bits */
1287 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
1290 /* Ptr to next physical malloc_chunk. */
1291 #define next_chunk(p) ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))
1293 /* Ptr to previous physical malloc_chunk */
1294 #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - ((p)->prev_size)))
1296 /* Treat space at ptr + offset as a chunk */
1297 #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1299 /* extract p's inuse bit */
1300 #define inuse(p) \
1301 ((((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)
1303 /* set/clear chunk as being inuse without otherwise disturbing */
1304 #define set_inuse(p) \
1305 ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE
1307 #define clear_inuse(p) \
1308 ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)
1311 /* check/set/clear inuse bits in known places */
1312 #define inuse_bit_at_offset(p, s) \
1313 (((mchunkptr) (((char *) (p)) + (s)))->size & PREV_INUSE)
1315 #define set_inuse_bit_at_offset(p, s) \
1316 (((mchunkptr) (((char *) (p)) + (s)))->size |= PREV_INUSE)
1318 #define clear_inuse_bit_at_offset(p, s) \
1319 (((mchunkptr) (((char *) (p)) + (s)))->size &= ~(PREV_INUSE))
1322 /* Set size at head, without disturbing its use bit */
1323 #define set_head_size(p, s) ((p)->size = (((p)->size & SIZE_BITS) | (s)))
1325 /* Set size/use field */
1326 #define set_head(p, s) ((p)->size = (s))
1328 /* Set size at footer (only when chunk is not in use) */
1329 #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->prev_size = (s))
1333 -------------------- Internal data structures --------------------
1335 All internal state is held in an instance of malloc_state defined
1336 below. There are no other static variables, except in two optional
1337 cases:
1338 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1339 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1340 for mmap.
1342 Beware of lots of tricks that minimize the total bookkeeping space
1343 requirements. The result is a little over 1K bytes (for 4byte
1344 pointers and size_t.)
1348 Bins
1350 An array of bin headers for free chunks. Each bin is doubly
1351 linked. The bins are approximately proportionally (log) spaced.
1352 There are a lot of these bins (128). This may look excessive, but
1353 works very well in practice. Most bins hold sizes that are
1354 unusual as malloc request sizes, but are more usual for fragments
1355 and consolidated sets of chunks, which is what these bins hold, so
1356 they can be found quickly. All procedures maintain the invariant
1357 that no consolidated chunk physically borders another one, so each
1358 chunk in a list is known to be preceeded and followed by either
1359 inuse chunks or the ends of memory.
1361 Chunks in bins are kept in size order, with ties going to the
1362 approximately least recently used chunk. Ordering isn't needed
1363 for the small bins, which all contain the same-sized chunks, but
1364 facilitates best-fit allocation for larger chunks. These lists
1365 are just sequential. Keeping them in order almost never requires
1366 enough traversal to warrant using fancier ordered data
1367 structures.
1369 Chunks of the same size are linked with the most
1370 recently freed at the front, and allocations are taken from the
1371 back. This results in LRU (FIFO) allocation order, which tends
1372 to give each chunk an equal opportunity to be consolidated with
1373 adjacent freed chunks, resulting in larger free chunks and less
1374 fragmentation.
1376 To simplify use in double-linked lists, each bin header acts
1377 as a malloc_chunk. This avoids special-casing for headers.
1378 But to conserve space and improve locality, we allocate
1379 only the fd/bk pointers of bins, and then use repositioning tricks
1380 to treat these as the fields of a malloc_chunk*.
1383 typedef struct malloc_chunk *mbinptr;
1385 /* addressing -- note that bin_at(0) does not exist */
1386 #define bin_at(m, i) \
1387 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1388 - offsetof (struct malloc_chunk, fd))
1390 /* analog of ++bin */
1391 #define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
1393 /* Reminders about list directionality within bins */
1394 #define first(b) ((b)->fd)
1395 #define last(b) ((b)->bk)
1397 /* Take a chunk off a bin list */
1398 #define unlink(AV, P, BK, FD) { \
1399 FD = P->fd; \
1400 BK = P->bk; \
1401 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
1402 malloc_printerr (check_action, "corrupted double-linked list", P, AV); \
1403 else { \
1404 FD->bk = BK; \
1405 BK->fd = FD; \
1406 if (!in_smallbin_range (P->size) \
1407 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \
1408 if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \
1409 || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \
1410 malloc_printerr (check_action, \
1411 "corrupted double-linked list (not small)", \
1412 P, AV); \
1413 if (FD->fd_nextsize == NULL) { \
1414 if (P->fd_nextsize == P) \
1415 FD->fd_nextsize = FD->bk_nextsize = FD; \
1416 else { \
1417 FD->fd_nextsize = P->fd_nextsize; \
1418 FD->bk_nextsize = P->bk_nextsize; \
1419 P->fd_nextsize->bk_nextsize = FD; \
1420 P->bk_nextsize->fd_nextsize = FD; \
1422 } else { \
1423 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \
1424 P->bk_nextsize->fd_nextsize = P->fd_nextsize; \
1431 Indexing
1433 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1434 8 bytes apart. Larger bins are approximately logarithmically spaced:
1436 64 bins of size 8
1437 32 bins of size 64
1438 16 bins of size 512
1439 8 bins of size 4096
1440 4 bins of size 32768
1441 2 bins of size 262144
1442 1 bin of size what's left
1444 There is actually a little bit of slop in the numbers in bin_index
1445 for the sake of speed. This makes no difference elsewhere.
1447 The bins top out around 1MB because we expect to service large
1448 requests via mmap.
1450 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1451 a valid chunk size the small bins are bumped up one.
1454 #define NBINS 128
1455 #define NSMALLBINS 64
1456 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1457 #define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > 2 * SIZE_SZ)
1458 #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
1460 #define in_smallbin_range(sz) \
1461 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
1463 #define smallbin_index(sz) \
1464 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
1465 + SMALLBIN_CORRECTION)
1467 #define largebin_index_32(sz) \
1468 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1469 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1470 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1471 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1472 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1473 126)
1475 #define largebin_index_32_big(sz) \
1476 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1477 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1478 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1479 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1480 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1481 126)
1483 // XXX It remains to be seen whether it is good to keep the widths of
1484 // XXX the buckets the same or whether it should be scaled by a factor
1485 // XXX of two as well.
1486 #define largebin_index_64(sz) \
1487 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1488 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1489 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1490 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1491 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1492 126)
1494 #define largebin_index(sz) \
1495 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1496 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1497 : largebin_index_32 (sz))
1499 #define bin_index(sz) \
1500 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
1504 Unsorted chunks
1506 All remainders from chunk splits, as well as all returned chunks,
1507 are first placed in the "unsorted" bin. They are then placed
1508 in regular bins after malloc gives them ONE chance to be used before
1509 binning. So, basically, the unsorted_chunks list acts as a queue,
1510 with chunks being placed on it in free (and malloc_consolidate),
1511 and taken off (to be either used or placed in bins) in malloc.
1513 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1514 does not have to be taken into account in size comparisons.
1517 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1518 #define unsorted_chunks(M) (bin_at (M, 1))
1523 The top-most available chunk (i.e., the one bordering the end of
1524 available memory) is treated specially. It is never included in
1525 any bin, is used only if no other chunk is available, and is
1526 released back to the system if it is very large (see
1527 M_TRIM_THRESHOLD). Because top initially
1528 points to its own bin with initial zero size, thus forcing
1529 extension on the first malloc request, we avoid having any special
1530 code in malloc to check whether it even exists yet. But we still
1531 need to do so when getting memory from system, so we make
1532 initial_top treat the bin as a legal but unusable chunk during the
1533 interval between initialization and the first call to
1534 sysmalloc. (This is somewhat delicate, since it relies on
1535 the 2 preceding words to be zero during this interval as well.)
1538 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1539 #define initial_top(M) (unsorted_chunks (M))
1542 Binmap
1544 To help compensate for the large number of bins, a one-level index
1545 structure is used for bin-by-bin searching. `binmap' is a
1546 bitvector recording whether bins are definitely empty so they can
1547 be skipped over during during traversals. The bits are NOT always
1548 cleared as soon as bins are empty, but instead only
1549 when they are noticed to be empty during traversal in malloc.
1552 /* Conservatively use 32 bits per map word, even if on 64bit system */
1553 #define BINMAPSHIFT 5
1554 #define BITSPERMAP (1U << BINMAPSHIFT)
1555 #define BINMAPSIZE (NBINS / BITSPERMAP)
1557 #define idx2block(i) ((i) >> BINMAPSHIFT)
1558 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
1560 #define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1561 #define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1562 #define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
1565 Fastbins
1567 An array of lists holding recently freed small chunks. Fastbins
1568 are not doubly linked. It is faster to single-link them, and
1569 since chunks are never removed from the middles of these lists,
1570 double linking is not necessary. Also, unlike regular bins, they
1571 are not even processed in FIFO order (they use faster LIFO) since
1572 ordering doesn't much matter in the transient contexts in which
1573 fastbins are normally used.
1575 Chunks in fastbins keep their inuse bit set, so they cannot
1576 be consolidated with other free chunks. malloc_consolidate
1577 releases all chunks in fastbins and consolidates them with
1578 other free chunks.
1581 typedef struct malloc_chunk *mfastbinptr;
1582 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1584 /* offset 2 to use otherwise unindexable first 2 bins */
1585 #define fastbin_index(sz) \
1586 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1589 /* The maximum fastbin request size we support */
1590 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1592 #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
1595 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1596 that triggers automatic consolidation of possibly-surrounding
1597 fastbin chunks. This is a heuristic, so the exact value should not
1598 matter too much. It is defined at half the default trim threshold as a
1599 compromise heuristic to only attempt consolidation if it is likely
1600 to lead to trimming. However, it is not dynamically tunable, since
1601 consolidation reduces fragmentation surrounding large chunks even
1602 if trimming is not used.
1605 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1608 Since the lowest 2 bits in max_fast don't matter in size comparisons,
1609 they are used as flags.
1613 FASTCHUNKS_BIT held in max_fast indicates that there are probably
1614 some fastbin chunks. It is set true on entering a chunk into any
1615 fastbin, and cleared only in malloc_consolidate.
1617 The truth value is inverted so that have_fastchunks will be true
1618 upon startup (since statics are zero-filled), simplifying
1619 initialization checks.
1622 #define FASTCHUNKS_BIT (1U)
1624 #define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
1625 #define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT)
1626 #define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT)
1629 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1630 regions. Otherwise, contiguity is exploited in merging together,
1631 when possible, results from consecutive MORECORE calls.
1633 The initial value comes from MORECORE_CONTIGUOUS, but is
1634 changed dynamically if mmap is ever used as an sbrk substitute.
1637 #define NONCONTIGUOUS_BIT (2U)
1639 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1640 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1641 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1642 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1644 /* ARENA_CORRUPTION_BIT is set if a memory corruption was detected on the
1645 arena. Such an arena is no longer used to allocate chunks. Chunks
1646 allocated in that arena before detecting corruption are not freed. */
1648 #define ARENA_CORRUPTION_BIT (4U)
1650 #define arena_is_corrupt(A) (((A)->flags & ARENA_CORRUPTION_BIT))
1651 #define set_arena_corrupt(A) ((A)->flags |= ARENA_CORRUPTION_BIT)
1654 Set value of max_fast.
1655 Use impossibly small value if 0.
1656 Precondition: there are no existing fastbin chunks.
1657 Setting the value clears fastchunk bit but preserves noncontiguous bit.
1660 #define set_max_fast(s) \
1661 global_max_fast = (((s) == 0) \
1662 ? SMALLBIN_WIDTH : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1663 #define get_max_fast() global_max_fast
1667 ----------- Internal state representation and initialization -----------
1670 struct malloc_state
1672 /* Serialize access. */
1673 mutex_t mutex;
1675 /* Flags (formerly in max_fast). */
1676 int flags;
1678 /* Fastbins */
1679 mfastbinptr fastbinsY[NFASTBINS];
1681 /* Base of the topmost chunk -- not otherwise kept in a bin */
1682 mchunkptr top;
1684 /* The remainder from the most recent split of a small request */
1685 mchunkptr last_remainder;
1687 /* Normal bins packed as described above */
1688 mchunkptr bins[NBINS * 2 - 2];
1690 /* Bitmap of bins */
1691 unsigned int binmap[BINMAPSIZE];
1693 /* Linked list */
1694 struct malloc_state *next;
1696 /* Linked list for free arenas. Access to this field is serialized
1697 by free_list_lock in arena.c. */
1698 struct malloc_state *next_free;
1700 /* Number of threads attached to this arena. 0 if the arena is on
1701 the free list. Access to this field is serialized by
1702 free_list_lock in arena.c. */
1703 INTERNAL_SIZE_T attached_threads;
1705 /* Memory allocated from the system in this arena. */
1706 INTERNAL_SIZE_T system_mem;
1707 INTERNAL_SIZE_T max_system_mem;
1710 struct malloc_par
1712 /* Tunable parameters */
1713 unsigned long trim_threshold;
1714 INTERNAL_SIZE_T top_pad;
1715 INTERNAL_SIZE_T mmap_threshold;
1716 INTERNAL_SIZE_T arena_test;
1717 INTERNAL_SIZE_T arena_max;
1719 /* Memory map support */
1720 int n_mmaps;
1721 int n_mmaps_max;
1722 int max_n_mmaps;
1723 /* the mmap_threshold is dynamic, until the user sets
1724 it manually, at which point we need to disable any
1725 dynamic behavior. */
1726 int no_dyn_threshold;
1728 /* Statistics */
1729 INTERNAL_SIZE_T mmapped_mem;
1730 INTERNAL_SIZE_T max_mmapped_mem;
1732 /* First address handed out by MORECORE/sbrk. */
1733 char *sbrk_base;
1736 /* There are several instances of this struct ("arenas") in this
1737 malloc. If you are adapting this malloc in a way that does NOT use
1738 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1739 before using. This malloc relies on the property that malloc_state
1740 is initialized to all zeroes (as is true of C statics). */
1742 static struct malloc_state main_arena =
1744 .mutex = _LIBC_LOCK_INITIALIZER,
1745 .next = &main_arena,
1746 .attached_threads = 1
1749 /* These variables are used for undumping support. Chunked are marked
1750 as using mmap, but we leave them alone if they fall into this
1751 range. */
1752 static mchunkptr dumped_main_arena_start; /* Inclusive. */
1753 static mchunkptr dumped_main_arena_end; /* Exclusive. */
1755 /* True if the pointer falls into the dumped arena. Use this after
1756 chunk_is_mmapped indicates a chunk is mmapped. */
1757 #define DUMPED_MAIN_ARENA_CHUNK(p) \
1758 ((p) >= dumped_main_arena_start && (p) < dumped_main_arena_end)
1760 /* There is only one instance of the malloc parameters. */
1762 static struct malloc_par mp_ =
1764 .top_pad = DEFAULT_TOP_PAD,
1765 .n_mmaps_max = DEFAULT_MMAP_MAX,
1766 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1767 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1768 #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1769 .arena_test = NARENAS_FROM_NCORES (1)
1773 /* Non public mallopt parameters. */
1774 #define M_ARENA_TEST -7
1775 #define M_ARENA_MAX -8
1778 /* Maximum size of memory handled in fastbins. */
1779 static INTERNAL_SIZE_T global_max_fast;
1782 Initialize a malloc_state struct.
1784 This is called only from within malloc_consolidate, which needs
1785 be called in the same contexts anyway. It is never called directly
1786 outside of malloc_consolidate because some optimizing compilers try
1787 to inline it at all call points, which turns out not to be an
1788 optimization at all. (Inlining it in malloc_consolidate is fine though.)
1791 static void
1792 malloc_init_state (mstate av)
1794 int i;
1795 mbinptr bin;
1797 /* Establish circular links for normal bins */
1798 for (i = 1; i < NBINS; ++i)
1800 bin = bin_at (av, i);
1801 bin->fd = bin->bk = bin;
1804 #if MORECORE_CONTIGUOUS
1805 if (av != &main_arena)
1806 #endif
1807 set_noncontiguous (av);
1808 if (av == &main_arena)
1809 set_max_fast (DEFAULT_MXFAST);
1810 av->flags |= FASTCHUNKS_BIT;
1812 av->top = initial_top (av);
1816 Other internal utilities operating on mstates
1819 static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1820 static int systrim (size_t, mstate);
1821 static void malloc_consolidate (mstate);
1824 /* -------------- Early definitions for debugging hooks ---------------- */
1826 /* Define and initialize the hook variables. These weak definitions must
1827 appear before any use of the variables in a function (arena.c uses one). */
1828 #ifndef weak_variable
1829 /* In GNU libc we want the hook variables to be weak definitions to
1830 avoid a problem with Emacs. */
1831 # define weak_variable weak_function
1832 #endif
1834 /* Forward declarations. */
1835 static void *malloc_hook_ini (size_t sz,
1836 const void *caller) __THROW;
1837 static void *realloc_hook_ini (void *ptr, size_t sz,
1838 const void *caller) __THROW;
1839 static void *memalign_hook_ini (size_t alignment, size_t sz,
1840 const void *caller) __THROW;
1842 void weak_variable (*__malloc_initialize_hook) (void) = NULL;
1843 void weak_variable (*__free_hook) (void *__ptr,
1844 const void *) = NULL;
1845 void *weak_variable (*__malloc_hook)
1846 (size_t __size, const void *) = malloc_hook_ini;
1847 void *weak_variable (*__realloc_hook)
1848 (void *__ptr, size_t __size, const void *)
1849 = realloc_hook_ini;
1850 void *weak_variable (*__memalign_hook)
1851 (size_t __alignment, size_t __size, const void *)
1852 = memalign_hook_ini;
1853 void weak_variable (*__after_morecore_hook) (void) = NULL;
1856 /* ---------------- Error behavior ------------------------------------ */
1858 #ifndef DEFAULT_CHECK_ACTION
1859 # define DEFAULT_CHECK_ACTION 3
1860 #endif
1862 static int check_action = DEFAULT_CHECK_ACTION;
1865 /* ------------------ Testing support ----------------------------------*/
1867 static int perturb_byte;
1869 static void
1870 alloc_perturb (char *p, size_t n)
1872 if (__glibc_unlikely (perturb_byte))
1873 memset (p, perturb_byte ^ 0xff, n);
1876 static void
1877 free_perturb (char *p, size_t n)
1879 if (__glibc_unlikely (perturb_byte))
1880 memset (p, perturb_byte, n);
1885 #include <stap-probe.h>
1887 /* ------------------- Support for multiple arenas -------------------- */
1888 #include "arena.c"
1891 Debugging support
1893 These routines make a number of assertions about the states
1894 of data structures that should be true at all times. If any
1895 are not true, it's very likely that a user program has somehow
1896 trashed memory. (It's also possible that there is a coding error
1897 in malloc. In which case, please report it!)
1900 #if !MALLOC_DEBUG
1902 # define check_chunk(A, P)
1903 # define check_free_chunk(A, P)
1904 # define check_inuse_chunk(A, P)
1905 # define check_remalloced_chunk(A, P, N)
1906 # define check_malloced_chunk(A, P, N)
1907 # define check_malloc_state(A)
1909 #else
1911 # define check_chunk(A, P) do_check_chunk (A, P)
1912 # define check_free_chunk(A, P) do_check_free_chunk (A, P)
1913 # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
1914 # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
1915 # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
1916 # define check_malloc_state(A) do_check_malloc_state (A)
1919 Properties of all chunks
1922 static void
1923 do_check_chunk (mstate av, mchunkptr p)
1925 unsigned long sz = chunksize (p);
1926 /* min and max possible addresses assuming contiguous allocation */
1927 char *max_address = (char *) (av->top) + chunksize (av->top);
1928 char *min_address = max_address - av->system_mem;
1930 if (!chunk_is_mmapped (p))
1932 /* Has legal address ... */
1933 if (p != av->top)
1935 if (contiguous (av))
1937 assert (((char *) p) >= min_address);
1938 assert (((char *) p + sz) <= ((char *) (av->top)));
1941 else
1943 /* top size is always at least MINSIZE */
1944 assert ((unsigned long) (sz) >= MINSIZE);
1945 /* top predecessor always marked inuse */
1946 assert (prev_inuse (p));
1949 else if (!DUMPED_MAIN_ARENA_CHUNK (p))
1951 /* address is outside main heap */
1952 if (contiguous (av) && av->top != initial_top (av))
1954 assert (((char *) p) < min_address || ((char *) p) >= max_address);
1956 /* chunk is page-aligned */
1957 assert (((p->prev_size + sz) & (GLRO (dl_pagesize) - 1)) == 0);
1958 /* mem is aligned */
1959 assert (aligned_OK (chunk2mem (p)));
1964 Properties of free chunks
1967 static void
1968 do_check_free_chunk (mstate av, mchunkptr p)
1970 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
1971 mchunkptr next = chunk_at_offset (p, sz);
1973 do_check_chunk (av, p);
1975 /* Chunk must claim to be free ... */
1976 assert (!inuse (p));
1977 assert (!chunk_is_mmapped (p));
1979 /* Unless a special marker, must have OK fields */
1980 if ((unsigned long) (sz) >= MINSIZE)
1982 assert ((sz & MALLOC_ALIGN_MASK) == 0);
1983 assert (aligned_OK (chunk2mem (p)));
1984 /* ... matching footer field */
1985 assert (next->prev_size == sz);
1986 /* ... and is fully consolidated */
1987 assert (prev_inuse (p));
1988 assert (next == av->top || inuse (next));
1990 /* ... and has minimally sane links */
1991 assert (p->fd->bk == p);
1992 assert (p->bk->fd == p);
1994 else /* markers are always of size SIZE_SZ */
1995 assert (sz == SIZE_SZ);
1999 Properties of inuse chunks
2002 static void
2003 do_check_inuse_chunk (mstate av, mchunkptr p)
2005 mchunkptr next;
2007 do_check_chunk (av, p);
2009 if (chunk_is_mmapped (p))
2010 return; /* mmapped chunks have no next/prev */
2012 /* Check whether it claims to be in use ... */
2013 assert (inuse (p));
2015 next = next_chunk (p);
2017 /* ... and is surrounded by OK chunks.
2018 Since more things can be checked with free chunks than inuse ones,
2019 if an inuse chunk borders them and debug is on, it's worth doing them.
2021 if (!prev_inuse (p))
2023 /* Note that we cannot even look at prev unless it is not inuse */
2024 mchunkptr prv = prev_chunk (p);
2025 assert (next_chunk (prv) == p);
2026 do_check_free_chunk (av, prv);
2029 if (next == av->top)
2031 assert (prev_inuse (next));
2032 assert (chunksize (next) >= MINSIZE);
2034 else if (!inuse (next))
2035 do_check_free_chunk (av, next);
2039 Properties of chunks recycled from fastbins
2042 static void
2043 do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2045 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
2047 if (!chunk_is_mmapped (p))
2049 assert (av == arena_for_chunk (p));
2050 if (chunk_non_main_arena (p))
2051 assert (av != &main_arena);
2052 else
2053 assert (av == &main_arena);
2056 do_check_inuse_chunk (av, p);
2058 /* Legal size ... */
2059 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2060 assert ((unsigned long) (sz) >= MINSIZE);
2061 /* ... and alignment */
2062 assert (aligned_OK (chunk2mem (p)));
2063 /* chunk is less than MINSIZE more than request */
2064 assert ((long) (sz) - (long) (s) >= 0);
2065 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2069 Properties of nonrecycled chunks at the point they are malloced
2072 static void
2073 do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2075 /* same as recycled case ... */
2076 do_check_remalloced_chunk (av, p, s);
2079 ... plus, must obey implementation invariant that prev_inuse is
2080 always true of any allocated chunk; i.e., that each allocated
2081 chunk borders either a previously allocated and still in-use
2082 chunk, or the base of its memory arena. This is ensured
2083 by making all allocations from the `lowest' part of any found
2084 chunk. This does not necessarily hold however for chunks
2085 recycled via fastbins.
2088 assert (prev_inuse (p));
2093 Properties of malloc_state.
2095 This may be useful for debugging malloc, as well as detecting user
2096 programmer errors that somehow write into malloc_state.
2098 If you are extending or experimenting with this malloc, you can
2099 probably figure out how to hack this routine to print out or
2100 display chunk addresses, sizes, bins, and other instrumentation.
2103 static void
2104 do_check_malloc_state (mstate av)
2106 int i;
2107 mchunkptr p;
2108 mchunkptr q;
2109 mbinptr b;
2110 unsigned int idx;
2111 INTERNAL_SIZE_T size;
2112 unsigned long total = 0;
2113 int max_fast_bin;
2115 /* internal size_t must be no wider than pointer type */
2116 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2118 /* alignment is a power of 2 */
2119 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2121 /* cannot run remaining checks until fully initialized */
2122 if (av->top == 0 || av->top == initial_top (av))
2123 return;
2125 /* pagesize is a power of 2 */
2126 assert (powerof2(GLRO (dl_pagesize)));
2128 /* A contiguous main_arena is consistent with sbrk_base. */
2129 if (av == &main_arena && contiguous (av))
2130 assert ((char *) mp_.sbrk_base + av->system_mem ==
2131 (char *) av->top + chunksize (av->top));
2133 /* properties of fastbins */
2135 /* max_fast is in allowed range */
2136 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2138 max_fast_bin = fastbin_index (get_max_fast ());
2140 for (i = 0; i < NFASTBINS; ++i)
2142 p = fastbin (av, i);
2144 /* The following test can only be performed for the main arena.
2145 While mallopt calls malloc_consolidate to get rid of all fast
2146 bins (especially those larger than the new maximum) this does
2147 only happen for the main arena. Trying to do this for any
2148 other arena would mean those arenas have to be locked and
2149 malloc_consolidate be called for them. This is excessive. And
2150 even if this is acceptable to somebody it still cannot solve
2151 the problem completely since if the arena is locked a
2152 concurrent malloc call might create a new arena which then
2153 could use the newly invalid fast bins. */
2155 /* all bins past max_fast are empty */
2156 if (av == &main_arena && i > max_fast_bin)
2157 assert (p == 0);
2159 while (p != 0)
2161 /* each chunk claims to be inuse */
2162 do_check_inuse_chunk (av, p);
2163 total += chunksize (p);
2164 /* chunk belongs in this bin */
2165 assert (fastbin_index (chunksize (p)) == i);
2166 p = p->fd;
2170 if (total != 0)
2171 assert (have_fastchunks (av));
2172 else if (!have_fastchunks (av))
2173 assert (total == 0);
2175 /* check normal bins */
2176 for (i = 1; i < NBINS; ++i)
2178 b = bin_at (av, i);
2180 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2181 if (i >= 2)
2183 unsigned int binbit = get_binmap (av, i);
2184 int empty = last (b) == b;
2185 if (!binbit)
2186 assert (empty);
2187 else if (!empty)
2188 assert (binbit);
2191 for (p = last (b); p != b; p = p->bk)
2193 /* each chunk claims to be free */
2194 do_check_free_chunk (av, p);
2195 size = chunksize (p);
2196 total += size;
2197 if (i >= 2)
2199 /* chunk belongs in bin */
2200 idx = bin_index (size);
2201 assert (idx == i);
2202 /* lists are sorted */
2203 assert (p->bk == b ||
2204 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2206 if (!in_smallbin_range (size))
2208 if (p->fd_nextsize != NULL)
2210 if (p->fd_nextsize == p)
2211 assert (p->bk_nextsize == p);
2212 else
2214 if (p->fd_nextsize == first (b))
2215 assert (chunksize (p) < chunksize (p->fd_nextsize));
2216 else
2217 assert (chunksize (p) > chunksize (p->fd_nextsize));
2219 if (p == first (b))
2220 assert (chunksize (p) > chunksize (p->bk_nextsize));
2221 else
2222 assert (chunksize (p) < chunksize (p->bk_nextsize));
2225 else
2226 assert (p->bk_nextsize == NULL);
2229 else if (!in_smallbin_range (size))
2230 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2231 /* chunk is followed by a legal chain of inuse chunks */
2232 for (q = next_chunk (p);
2233 (q != av->top && inuse (q) &&
2234 (unsigned long) (chunksize (q)) >= MINSIZE);
2235 q = next_chunk (q))
2236 do_check_inuse_chunk (av, q);
2240 /* top chunk is OK */
2241 check_chunk (av, av->top);
2243 #endif
2246 /* ----------------- Support for debugging hooks -------------------- */
2247 #include "hooks.c"
2250 /* ----------- Routines dealing with system allocation -------------- */
2253 sysmalloc handles malloc cases requiring more memory from the system.
2254 On entry, it is assumed that av->top does not have enough
2255 space to service request for nb bytes, thus requiring that av->top
2256 be extended or replaced.
2259 static void *
2260 sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2262 mchunkptr old_top; /* incoming value of av->top */
2263 INTERNAL_SIZE_T old_size; /* its size */
2264 char *old_end; /* its end address */
2266 long size; /* arg to first MORECORE or mmap call */
2267 char *brk; /* return value from MORECORE */
2269 long correction; /* arg to 2nd MORECORE call */
2270 char *snd_brk; /* 2nd return val */
2272 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2273 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2274 char *aligned_brk; /* aligned offset into brk */
2276 mchunkptr p; /* the allocated/returned chunk */
2277 mchunkptr remainder; /* remainder from allocation */
2278 unsigned long remainder_size; /* its size */
2281 size_t pagesize = GLRO (dl_pagesize);
2282 bool tried_mmap = false;
2286 If have mmap, and the request size meets the mmap threshold, and
2287 the system supports mmap, and there are few enough currently
2288 allocated mmapped regions, try to directly map this request
2289 rather than expanding top.
2292 if (av == NULL
2293 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2294 && (mp_.n_mmaps < mp_.n_mmaps_max)))
2296 char *mm; /* return value from mmap call*/
2298 try_mmap:
2300 Round up size to nearest page. For mmapped chunks, the overhead
2301 is one SIZE_SZ unit larger than for normal chunks, because there
2302 is no following chunk whose prev_size field could be used.
2304 See the front_misalign handling below, for glibc there is no
2305 need for further alignments unless we have have high alignment.
2307 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2308 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2309 else
2310 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2311 tried_mmap = true;
2313 /* Don't try if size wraps around 0 */
2314 if ((unsigned long) (size) > (unsigned long) (nb))
2316 mm = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2318 if (mm != MAP_FAILED)
2321 The offset to the start of the mmapped region is stored
2322 in the prev_size field of the chunk. This allows us to adjust
2323 returned start address to meet alignment requirements here
2324 and in memalign(), and still be able to compute proper
2325 address argument for later munmap in free() and realloc().
2328 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2330 /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and
2331 MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
2332 aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
2333 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2334 front_misalign = 0;
2336 else
2337 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2338 if (front_misalign > 0)
2340 correction = MALLOC_ALIGNMENT - front_misalign;
2341 p = (mchunkptr) (mm + correction);
2342 p->prev_size = correction;
2343 set_head (p, (size - correction) | IS_MMAPPED);
2345 else
2347 p = (mchunkptr) mm;
2348 set_head (p, size | IS_MMAPPED);
2351 /* update statistics */
2353 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2354 atomic_max (&mp_.max_n_mmaps, new);
2356 unsigned long sum;
2357 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2358 atomic_max (&mp_.max_mmapped_mem, sum);
2360 check_chunk (av, p);
2362 return chunk2mem (p);
2367 /* There are no usable arenas and mmap also failed. */
2368 if (av == NULL)
2369 return 0;
2371 /* Record incoming configuration of top */
2373 old_top = av->top;
2374 old_size = chunksize (old_top);
2375 old_end = (char *) (chunk_at_offset (old_top, old_size));
2377 brk = snd_brk = (char *) (MORECORE_FAILURE);
2380 If not the first time through, we require old_size to be
2381 at least MINSIZE and to have prev_inuse set.
2384 assert ((old_top == initial_top (av) && old_size == 0) ||
2385 ((unsigned long) (old_size) >= MINSIZE &&
2386 prev_inuse (old_top) &&
2387 ((unsigned long) old_end & (pagesize - 1)) == 0));
2389 /* Precondition: not enough current space to satisfy nb request */
2390 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2393 if (av != &main_arena)
2395 heap_info *old_heap, *heap;
2396 size_t old_heap_size;
2398 /* First try to extend the current heap. */
2399 old_heap = heap_for_ptr (old_top);
2400 old_heap_size = old_heap->size;
2401 if ((long) (MINSIZE + nb - old_size) > 0
2402 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2404 av->system_mem += old_heap->size - old_heap_size;
2405 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2406 | PREV_INUSE);
2408 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2410 /* Use a newly allocated heap. */
2411 heap->ar_ptr = av;
2412 heap->prev = old_heap;
2413 av->system_mem += heap->size;
2414 /* Set up the new top. */
2415 top (av) = chunk_at_offset (heap, sizeof (*heap));
2416 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2418 /* Setup fencepost and free the old top chunk with a multiple of
2419 MALLOC_ALIGNMENT in size. */
2420 /* The fencepost takes at least MINSIZE bytes, because it might
2421 become the top chunk again later. Note that a footer is set
2422 up, too, although the chunk is marked in use. */
2423 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2424 set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ), 0 | PREV_INUSE);
2425 if (old_size >= MINSIZE)
2427 set_head (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE);
2428 set_foot (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ));
2429 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2430 _int_free (av, old_top, 1);
2432 else
2434 set_head (old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE);
2435 set_foot (old_top, (old_size + 2 * SIZE_SZ));
2438 else if (!tried_mmap)
2439 /* We can at least try to use to mmap memory. */
2440 goto try_mmap;
2442 else /* av == main_arena */
2445 { /* Request enough space for nb + pad + overhead */
2446 size = nb + mp_.top_pad + MINSIZE;
2449 If contiguous, we can subtract out existing space that we hope to
2450 combine with new space. We add it back later only if
2451 we don't actually get contiguous space.
2454 if (contiguous (av))
2455 size -= old_size;
2458 Round to a multiple of page size.
2459 If MORECORE is not contiguous, this ensures that we only call it
2460 with whole-page arguments. And if MORECORE is contiguous and
2461 this is not first time through, this preserves page-alignment of
2462 previous calls. Otherwise, we correct to page-align below.
2465 size = ALIGN_UP (size, pagesize);
2468 Don't try to call MORECORE if argument is so big as to appear
2469 negative. Note that since mmap takes size_t arg, it may succeed
2470 below even if we cannot call MORECORE.
2473 if (size > 0)
2475 brk = (char *) (MORECORE (size));
2476 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2479 if (brk != (char *) (MORECORE_FAILURE))
2481 /* Call the `morecore' hook if necessary. */
2482 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2483 if (__builtin_expect (hook != NULL, 0))
2484 (*hook)();
2486 else
2489 If have mmap, try using it as a backup when MORECORE fails or
2490 cannot be used. This is worth doing on systems that have "holes" in
2491 address space, so sbrk cannot extend to give contiguous space, but
2492 space is available elsewhere. Note that we ignore mmap max count
2493 and threshold limits, since the space will not be used as a
2494 segregated mmap region.
2497 /* Cannot merge with old top, so add its size back in */
2498 if (contiguous (av))
2499 size = ALIGN_UP (size + old_size, pagesize);
2501 /* If we are relying on mmap as backup, then use larger units */
2502 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2503 size = MMAP_AS_MORECORE_SIZE;
2505 /* Don't try if size wraps around 0 */
2506 if ((unsigned long) (size) > (unsigned long) (nb))
2508 char *mbrk = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2510 if (mbrk != MAP_FAILED)
2512 /* We do not need, and cannot use, another sbrk call to find end */
2513 brk = mbrk;
2514 snd_brk = brk + size;
2517 Record that we no longer have a contiguous sbrk region.
2518 After the first time mmap is used as backup, we do not
2519 ever rely on contiguous space since this could incorrectly
2520 bridge regions.
2522 set_noncontiguous (av);
2527 if (brk != (char *) (MORECORE_FAILURE))
2529 if (mp_.sbrk_base == 0)
2530 mp_.sbrk_base = brk;
2531 av->system_mem += size;
2534 If MORECORE extends previous space, we can likewise extend top size.
2537 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2538 set_head (old_top, (size + old_size) | PREV_INUSE);
2540 else if (contiguous (av) && old_size && brk < old_end)
2542 /* Oops! Someone else killed our space.. Can't touch anything. */
2543 malloc_printerr (3, "break adjusted to free malloc space", brk,
2544 av);
2548 Otherwise, make adjustments:
2550 * If the first time through or noncontiguous, we need to call sbrk
2551 just to find out where the end of memory lies.
2553 * We need to ensure that all returned chunks from malloc will meet
2554 MALLOC_ALIGNMENT
2556 * If there was an intervening foreign sbrk, we need to adjust sbrk
2557 request size to account for fact that we will not be able to
2558 combine new space with existing space in old_top.
2560 * Almost all systems internally allocate whole pages at a time, in
2561 which case we might as well use the whole last page of request.
2562 So we allocate enough more memory to hit a page boundary now,
2563 which in turn causes future contiguous calls to page-align.
2566 else
2568 front_misalign = 0;
2569 end_misalign = 0;
2570 correction = 0;
2571 aligned_brk = brk;
2573 /* handle contiguous cases */
2574 if (contiguous (av))
2576 /* Count foreign sbrk as system_mem. */
2577 if (old_size)
2578 av->system_mem += brk - old_end;
2580 /* Guarantee alignment of first new chunk made from this space */
2582 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2583 if (front_misalign > 0)
2586 Skip over some bytes to arrive at an aligned position.
2587 We don't need to specially mark these wasted front bytes.
2588 They will never be accessed anyway because
2589 prev_inuse of av->top (and any chunk created from its start)
2590 is always true after initialization.
2593 correction = MALLOC_ALIGNMENT - front_misalign;
2594 aligned_brk += correction;
2598 If this isn't adjacent to existing space, then we will not
2599 be able to merge with old_top space, so must add to 2nd request.
2602 correction += old_size;
2604 /* Extend the end address to hit a page boundary */
2605 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2606 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2608 assert (correction >= 0);
2609 snd_brk = (char *) (MORECORE (correction));
2612 If can't allocate correction, try to at least find out current
2613 brk. It might be enough to proceed without failing.
2615 Note that if second sbrk did NOT fail, we assume that space
2616 is contiguous with first sbrk. This is a safe assumption unless
2617 program is multithreaded but doesn't use locks and a foreign sbrk
2618 occurred between our first and second calls.
2621 if (snd_brk == (char *) (MORECORE_FAILURE))
2623 correction = 0;
2624 snd_brk = (char *) (MORECORE (0));
2626 else
2628 /* Call the `morecore' hook if necessary. */
2629 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2630 if (__builtin_expect (hook != NULL, 0))
2631 (*hook)();
2635 /* handle non-contiguous cases */
2636 else
2638 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2639 /* MORECORE/mmap must correctly align */
2640 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2641 else
2643 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2644 if (front_misalign > 0)
2647 Skip over some bytes to arrive at an aligned position.
2648 We don't need to specially mark these wasted front bytes.
2649 They will never be accessed anyway because
2650 prev_inuse of av->top (and any chunk created from its start)
2651 is always true after initialization.
2654 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2658 /* Find out current end of memory */
2659 if (snd_brk == (char *) (MORECORE_FAILURE))
2661 snd_brk = (char *) (MORECORE (0));
2665 /* Adjust top based on results of second sbrk */
2666 if (snd_brk != (char *) (MORECORE_FAILURE))
2668 av->top = (mchunkptr) aligned_brk;
2669 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2670 av->system_mem += correction;
2673 If not the first time through, we either have a
2674 gap due to foreign sbrk or a non-contiguous region. Insert a
2675 double fencepost at old_top to prevent consolidation with space
2676 we don't own. These fenceposts are artificial chunks that are
2677 marked as inuse and are in any case too small to use. We need
2678 two to make sizes and alignments work out.
2681 if (old_size != 0)
2684 Shrink old_top to insert fenceposts, keeping size a
2685 multiple of MALLOC_ALIGNMENT. We know there is at least
2686 enough space in old_top to do this.
2688 old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK;
2689 set_head (old_top, old_size | PREV_INUSE);
2692 Note that the following assignments completely overwrite
2693 old_top when old_size was previously MINSIZE. This is
2694 intentional. We need the fencepost, even if old_top otherwise gets
2695 lost.
2697 chunk_at_offset (old_top, old_size)->size =
2698 (2 * SIZE_SZ) | PREV_INUSE;
2700 chunk_at_offset (old_top, old_size + 2 * SIZE_SZ)->size =
2701 (2 * SIZE_SZ) | PREV_INUSE;
2703 /* If possible, release the rest. */
2704 if (old_size >= MINSIZE)
2706 _int_free (av, old_top, 1);
2712 } /* if (av != &main_arena) */
2714 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2715 av->max_system_mem = av->system_mem;
2716 check_malloc_state (av);
2718 /* finally, do the allocation */
2719 p = av->top;
2720 size = chunksize (p);
2722 /* check that one of the above allocation paths succeeded */
2723 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2725 remainder_size = size - nb;
2726 remainder = chunk_at_offset (p, nb);
2727 av->top = remainder;
2728 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2729 set_head (remainder, remainder_size | PREV_INUSE);
2730 check_malloced_chunk (av, p, nb);
2731 return chunk2mem (p);
2734 /* catch all failure paths */
2735 __set_errno (ENOMEM);
2736 return 0;
2741 systrim is an inverse of sorts to sysmalloc. It gives memory back
2742 to the system (via negative arguments to sbrk) if there is unused
2743 memory at the `high' end of the malloc pool. It is called
2744 automatically by free() when top space exceeds the trim
2745 threshold. It is also called by the public malloc_trim routine. It
2746 returns 1 if it actually released any memory, else 0.
2749 static int
2750 systrim (size_t pad, mstate av)
2752 long top_size; /* Amount of top-most memory */
2753 long extra; /* Amount to release */
2754 long released; /* Amount actually released */
2755 char *current_brk; /* address returned by pre-check sbrk call */
2756 char *new_brk; /* address returned by post-check sbrk call */
2757 size_t pagesize;
2758 long top_area;
2760 pagesize = GLRO (dl_pagesize);
2761 top_size = chunksize (av->top);
2763 top_area = top_size - MINSIZE - 1;
2764 if (top_area <= pad)
2765 return 0;
2767 /* Release in pagesize units and round down to the nearest page. */
2768 extra = ALIGN_DOWN(top_area - pad, pagesize);
2770 if (extra == 0)
2771 return 0;
2774 Only proceed if end of memory is where we last set it.
2775 This avoids problems if there were foreign sbrk calls.
2777 current_brk = (char *) (MORECORE (0));
2778 if (current_brk == (char *) (av->top) + top_size)
2781 Attempt to release memory. We ignore MORECORE return value,
2782 and instead call again to find out where new end of memory is.
2783 This avoids problems if first call releases less than we asked,
2784 of if failure somehow altered brk value. (We could still
2785 encounter problems if it altered brk in some very bad way,
2786 but the only thing we can do is adjust anyway, which will cause
2787 some downstream failure.)
2790 MORECORE (-extra);
2791 /* Call the `morecore' hook if necessary. */
2792 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2793 if (__builtin_expect (hook != NULL, 0))
2794 (*hook)();
2795 new_brk = (char *) (MORECORE (0));
2797 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2799 if (new_brk != (char *) MORECORE_FAILURE)
2801 released = (long) (current_brk - new_brk);
2803 if (released != 0)
2805 /* Success. Adjust top. */
2806 av->system_mem -= released;
2807 set_head (av->top, (top_size - released) | PREV_INUSE);
2808 check_malloc_state (av);
2809 return 1;
2813 return 0;
2816 static void
2817 internal_function
2818 munmap_chunk (mchunkptr p)
2820 INTERNAL_SIZE_T size = chunksize (p);
2822 assert (chunk_is_mmapped (p));
2824 /* Do nothing if the chunk is a faked mmapped chunk in the dumped
2825 main arena. We never free this memory. */
2826 if (DUMPED_MAIN_ARENA_CHUNK (p))
2827 return;
2829 uintptr_t block = (uintptr_t) p - p->prev_size;
2830 size_t total_size = p->prev_size + size;
2831 /* Unfortunately we have to do the compilers job by hand here. Normally
2832 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2833 page size. But gcc does not recognize the optimization possibility
2834 (in the moment at least) so we combine the two values into one before
2835 the bit test. */
2836 if (__builtin_expect (((block | total_size) & (GLRO (dl_pagesize) - 1)) != 0, 0))
2838 malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
2839 chunk2mem (p), NULL);
2840 return;
2843 atomic_decrement (&mp_.n_mmaps);
2844 atomic_add (&mp_.mmapped_mem, -total_size);
2846 /* If munmap failed the process virtual memory address space is in a
2847 bad shape. Just leave the block hanging around, the process will
2848 terminate shortly anyway since not much can be done. */
2849 __munmap ((char *) block, total_size);
2852 #if HAVE_MREMAP
2854 static mchunkptr
2855 internal_function
2856 mremap_chunk (mchunkptr p, size_t new_size)
2858 size_t pagesize = GLRO (dl_pagesize);
2859 INTERNAL_SIZE_T offset = p->prev_size;
2860 INTERNAL_SIZE_T size = chunksize (p);
2861 char *cp;
2863 assert (chunk_is_mmapped (p));
2864 assert (((size + offset) & (GLRO (dl_pagesize) - 1)) == 0);
2866 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2867 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
2869 /* No need to remap if the number of pages does not change. */
2870 if (size + offset == new_size)
2871 return p;
2873 cp = (char *) __mremap ((char *) p - offset, size + offset, new_size,
2874 MREMAP_MAYMOVE);
2876 if (cp == MAP_FAILED)
2877 return 0;
2879 p = (mchunkptr) (cp + offset);
2881 assert (aligned_OK (chunk2mem (p)));
2883 assert ((p->prev_size == offset));
2884 set_head (p, (new_size - offset) | IS_MMAPPED);
2886 INTERNAL_SIZE_T new;
2887 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
2888 + new_size - size - offset;
2889 atomic_max (&mp_.max_mmapped_mem, new);
2890 return p;
2892 #endif /* HAVE_MREMAP */
2894 /*------------------------ Public wrappers. --------------------------------*/
2896 void *
2897 __libc_malloc (size_t bytes)
2899 mstate ar_ptr;
2900 void *victim;
2902 void *(*hook) (size_t, const void *)
2903 = atomic_forced_read (__malloc_hook);
2904 if (__builtin_expect (hook != NULL, 0))
2905 return (*hook)(bytes, RETURN_ADDRESS (0));
2907 arena_get (ar_ptr, bytes);
2909 victim = _int_malloc (ar_ptr, bytes);
2910 /* Retry with another arena only if we were able to find a usable arena
2911 before. */
2912 if (!victim && ar_ptr != NULL)
2914 LIBC_PROBE (memory_malloc_retry, 1, bytes);
2915 ar_ptr = arena_get_retry (ar_ptr, bytes);
2916 victim = _int_malloc (ar_ptr, bytes);
2919 if (ar_ptr != NULL)
2920 (void) mutex_unlock (&ar_ptr->mutex);
2922 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
2923 ar_ptr == arena_for_chunk (mem2chunk (victim)));
2924 return victim;
2926 libc_hidden_def (__libc_malloc)
2928 void
2929 __libc_free (void *mem)
2931 mstate ar_ptr;
2932 mchunkptr p; /* chunk corresponding to mem */
2934 void (*hook) (void *, const void *)
2935 = atomic_forced_read (__free_hook);
2936 if (__builtin_expect (hook != NULL, 0))
2938 (*hook)(mem, RETURN_ADDRESS (0));
2939 return;
2942 if (mem == 0) /* free(0) has no effect */
2943 return;
2945 p = mem2chunk (mem);
2947 if (chunk_is_mmapped (p)) /* release mmapped memory. */
2949 /* See if the dynamic brk/mmap threshold needs adjusting.
2950 Dumped fake mmapped chunks do not affect the threshold. */
2951 if (!mp_.no_dyn_threshold
2952 && p->size > mp_.mmap_threshold
2953 && p->size <= DEFAULT_MMAP_THRESHOLD_MAX
2954 && !DUMPED_MAIN_ARENA_CHUNK (p))
2956 mp_.mmap_threshold = chunksize (p);
2957 mp_.trim_threshold = 2 * mp_.mmap_threshold;
2958 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
2959 mp_.mmap_threshold, mp_.trim_threshold);
2961 munmap_chunk (p);
2962 return;
2965 ar_ptr = arena_for_chunk (p);
2966 _int_free (ar_ptr, p, 0);
2968 libc_hidden_def (__libc_free)
2970 void *
2971 __libc_realloc (void *oldmem, size_t bytes)
2973 mstate ar_ptr;
2974 INTERNAL_SIZE_T nb; /* padded request size */
2976 void *newp; /* chunk to return */
2978 void *(*hook) (void *, size_t, const void *) =
2979 atomic_forced_read (__realloc_hook);
2980 if (__builtin_expect (hook != NULL, 0))
2981 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
2983 #if REALLOC_ZERO_BYTES_FREES
2984 if (bytes == 0 && oldmem != NULL)
2986 __libc_free (oldmem); return 0;
2988 #endif
2990 /* realloc of null is supposed to be same as malloc */
2991 if (oldmem == 0)
2992 return __libc_malloc (bytes);
2994 /* chunk corresponding to oldmem */
2995 const mchunkptr oldp = mem2chunk (oldmem);
2996 /* its size */
2997 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
2999 if (chunk_is_mmapped (oldp))
3000 ar_ptr = NULL;
3001 else
3002 ar_ptr = arena_for_chunk (oldp);
3004 /* Little security check which won't hurt performance: the allocator
3005 never wrapps around at the end of the address space. Therefore
3006 we can exclude some size values which might appear here by
3007 accident or by "design" from some intruder. We need to bypass
3008 this check for dumped fake mmap chunks from the old main arena
3009 because the new malloc may provide additional alignment. */
3010 if ((__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
3011 || __builtin_expect (misaligned_chunk (oldp), 0))
3012 && !DUMPED_MAIN_ARENA_CHUNK (oldp))
3014 malloc_printerr (check_action, "realloc(): invalid pointer", oldmem,
3015 ar_ptr);
3016 return NULL;
3019 checked_request2size (bytes, nb);
3021 if (chunk_is_mmapped (oldp))
3023 /* If this is a faked mmapped chunk from the dumped main arena,
3024 always make a copy (and do not free the old chunk). */
3025 if (DUMPED_MAIN_ARENA_CHUNK (oldp))
3027 /* Must alloc, copy, free. */
3028 void *newmem = __libc_malloc (bytes);
3029 if (newmem == 0)
3030 return NULL;
3031 /* Copy as many bytes as are available from the old chunk
3032 and fit into the new size. */
3033 if (bytes > oldsize - 2 * SIZE_SZ)
3034 bytes = oldsize - 2 * SIZE_SZ;
3035 memcpy (newmem, oldmem, bytes);
3036 return newmem;
3039 void *newmem;
3041 #if HAVE_MREMAP
3042 newp = mremap_chunk (oldp, nb);
3043 if (newp)
3044 return chunk2mem (newp);
3045 #endif
3046 /* Note the extra SIZE_SZ overhead. */
3047 if (oldsize - SIZE_SZ >= nb)
3048 return oldmem; /* do nothing */
3050 /* Must alloc, copy, free. */
3051 newmem = __libc_malloc (bytes);
3052 if (newmem == 0)
3053 return 0; /* propagate failure */
3055 memcpy (newmem, oldmem, oldsize - 2 * SIZE_SZ);
3056 munmap_chunk (oldp);
3057 return newmem;
3060 (void) mutex_lock (&ar_ptr->mutex);
3062 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3064 (void) mutex_unlock (&ar_ptr->mutex);
3065 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3066 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3068 if (newp == NULL)
3070 /* Try harder to allocate memory in other arenas. */
3071 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3072 newp = __libc_malloc (bytes);
3073 if (newp != NULL)
3075 memcpy (newp, oldmem, oldsize - SIZE_SZ);
3076 _int_free (ar_ptr, oldp, 0);
3080 return newp;
3082 libc_hidden_def (__libc_realloc)
3084 void *
3085 __libc_memalign (size_t alignment, size_t bytes)
3087 void *address = RETURN_ADDRESS (0);
3088 return _mid_memalign (alignment, bytes, address);
3091 static void *
3092 _mid_memalign (size_t alignment, size_t bytes, void *address)
3094 mstate ar_ptr;
3095 void *p;
3097 void *(*hook) (size_t, size_t, const void *) =
3098 atomic_forced_read (__memalign_hook);
3099 if (__builtin_expect (hook != NULL, 0))
3100 return (*hook)(alignment, bytes, address);
3102 /* If we need less alignment than we give anyway, just relay to malloc. */
3103 if (alignment <= MALLOC_ALIGNMENT)
3104 return __libc_malloc (bytes);
3106 /* Otherwise, ensure that it is at least a minimum chunk size */
3107 if (alignment < MINSIZE)
3108 alignment = MINSIZE;
3110 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3111 power of 2 and will cause overflow in the check below. */
3112 if (alignment > SIZE_MAX / 2 + 1)
3114 __set_errno (EINVAL);
3115 return 0;
3118 /* Check for overflow. */
3119 if (bytes > SIZE_MAX - alignment - MINSIZE)
3121 __set_errno (ENOMEM);
3122 return 0;
3126 /* Make sure alignment is power of 2. */
3127 if (!powerof2 (alignment))
3129 size_t a = MALLOC_ALIGNMENT * 2;
3130 while (a < alignment)
3131 a <<= 1;
3132 alignment = a;
3135 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3137 p = _int_memalign (ar_ptr, alignment, bytes);
3138 if (!p && ar_ptr != NULL)
3140 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3141 ar_ptr = arena_get_retry (ar_ptr, bytes);
3142 p = _int_memalign (ar_ptr, alignment, bytes);
3145 if (ar_ptr != NULL)
3146 (void) mutex_unlock (&ar_ptr->mutex);
3148 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3149 ar_ptr == arena_for_chunk (mem2chunk (p)));
3150 return p;
3152 /* For ISO C11. */
3153 weak_alias (__libc_memalign, aligned_alloc)
3154 libc_hidden_def (__libc_memalign)
3156 void *
3157 __libc_valloc (size_t bytes)
3159 if (__malloc_initialized < 0)
3160 ptmalloc_init ();
3162 void *address = RETURN_ADDRESS (0);
3163 size_t pagesize = GLRO (dl_pagesize);
3164 return _mid_memalign (pagesize, bytes, address);
3167 void *
3168 __libc_pvalloc (size_t bytes)
3170 if (__malloc_initialized < 0)
3171 ptmalloc_init ();
3173 void *address = RETURN_ADDRESS (0);
3174 size_t pagesize = GLRO (dl_pagesize);
3175 size_t rounded_bytes = ALIGN_UP (bytes, pagesize);
3177 /* Check for overflow. */
3178 if (bytes > SIZE_MAX - 2 * pagesize - MINSIZE)
3180 __set_errno (ENOMEM);
3181 return 0;
3184 return _mid_memalign (pagesize, rounded_bytes, address);
3187 void *
3188 __libc_calloc (size_t n, size_t elem_size)
3190 mstate av;
3191 mchunkptr oldtop, p;
3192 INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
3193 void *mem;
3194 unsigned long clearsize;
3195 unsigned long nclears;
3196 INTERNAL_SIZE_T *d;
3198 /* size_t is unsigned so the behavior on overflow is defined. */
3199 bytes = n * elem_size;
3200 #define HALF_INTERNAL_SIZE_T \
3201 (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
3202 if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0))
3204 if (elem_size != 0 && bytes / elem_size != n)
3206 __set_errno (ENOMEM);
3207 return 0;
3211 void *(*hook) (size_t, const void *) =
3212 atomic_forced_read (__malloc_hook);
3213 if (__builtin_expect (hook != NULL, 0))
3215 sz = bytes;
3216 mem = (*hook)(sz, RETURN_ADDRESS (0));
3217 if (mem == 0)
3218 return 0;
3220 return memset (mem, 0, sz);
3223 sz = bytes;
3225 arena_get (av, sz);
3226 if (av)
3228 /* Check if we hand out the top chunk, in which case there may be no
3229 need to clear. */
3230 #if MORECORE_CLEARS
3231 oldtop = top (av);
3232 oldtopsize = chunksize (top (av));
3233 # if MORECORE_CLEARS < 2
3234 /* Only newly allocated memory is guaranteed to be cleared. */
3235 if (av == &main_arena &&
3236 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3237 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3238 # endif
3239 if (av != &main_arena)
3241 heap_info *heap = heap_for_ptr (oldtop);
3242 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3243 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3245 #endif
3247 else
3249 /* No usable arenas. */
3250 oldtop = 0;
3251 oldtopsize = 0;
3253 mem = _int_malloc (av, sz);
3256 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3257 av == arena_for_chunk (mem2chunk (mem)));
3259 if (mem == 0 && av != NULL)
3261 LIBC_PROBE (memory_calloc_retry, 1, sz);
3262 av = arena_get_retry (av, sz);
3263 mem = _int_malloc (av, sz);
3266 if (av != NULL)
3267 (void) mutex_unlock (&av->mutex);
3269 /* Allocation failed even after a retry. */
3270 if (mem == 0)
3271 return 0;
3273 p = mem2chunk (mem);
3275 /* Two optional cases in which clearing not necessary */
3276 if (chunk_is_mmapped (p))
3278 if (__builtin_expect (perturb_byte, 0))
3279 return memset (mem, 0, sz);
3281 return mem;
3284 csz = chunksize (p);
3286 #if MORECORE_CLEARS
3287 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3289 /* clear only the bytes from non-freshly-sbrked memory */
3290 csz = oldtopsize;
3292 #endif
3294 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3295 contents have an odd number of INTERNAL_SIZE_T-sized words;
3296 minimally 3. */
3297 d = (INTERNAL_SIZE_T *) mem;
3298 clearsize = csz - SIZE_SZ;
3299 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3300 assert (nclears >= 3);
3302 if (nclears > 9)
3303 return memset (d, 0, clearsize);
3305 else
3307 *(d + 0) = 0;
3308 *(d + 1) = 0;
3309 *(d + 2) = 0;
3310 if (nclears > 4)
3312 *(d + 3) = 0;
3313 *(d + 4) = 0;
3314 if (nclears > 6)
3316 *(d + 5) = 0;
3317 *(d + 6) = 0;
3318 if (nclears > 8)
3320 *(d + 7) = 0;
3321 *(d + 8) = 0;
3327 return mem;
3331 ------------------------------ malloc ------------------------------
3334 static void *
3335 _int_malloc (mstate av, size_t bytes)
3337 INTERNAL_SIZE_T nb; /* normalized request size */
3338 unsigned int idx; /* associated bin index */
3339 mbinptr bin; /* associated bin */
3341 mchunkptr victim; /* inspected/selected chunk */
3342 INTERNAL_SIZE_T size; /* its size */
3343 int victim_index; /* its bin index */
3345 mchunkptr remainder; /* remainder from a split */
3346 unsigned long remainder_size; /* its size */
3348 unsigned int block; /* bit map traverser */
3349 unsigned int bit; /* bit map traverser */
3350 unsigned int map; /* current word of binmap */
3352 mchunkptr fwd; /* misc temp for linking */
3353 mchunkptr bck; /* misc temp for linking */
3355 const char *errstr = NULL;
3358 Convert request size to internal form by adding SIZE_SZ bytes
3359 overhead plus possibly more to obtain necessary alignment and/or
3360 to obtain a size of at least MINSIZE, the smallest allocatable
3361 size. Also, checked_request2size traps (returning 0) request sizes
3362 that are so large that they wrap around zero when padded and
3363 aligned.
3366 checked_request2size (bytes, nb);
3368 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3369 mmap. */
3370 if (__glibc_unlikely (av == NULL))
3372 void *p = sysmalloc (nb, av);
3373 if (p != NULL)
3374 alloc_perturb (p, bytes);
3375 return p;
3379 If the size qualifies as a fastbin, first check corresponding bin.
3380 This code is safe to execute even if av is not yet initialized, so we
3381 can try it without checking, which saves some time on this fast path.
3384 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3386 idx = fastbin_index (nb);
3387 mfastbinptr *fb = &fastbin (av, idx);
3388 mchunkptr pp = *fb;
3391 victim = pp;
3392 if (victim == NULL)
3393 break;
3395 while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim))
3396 != victim);
3397 if (victim != 0)
3399 if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
3401 errstr = "malloc(): memory corruption (fast)";
3402 errout:
3403 malloc_printerr (check_action, errstr, chunk2mem (victim), av);
3404 return NULL;
3406 check_remalloced_chunk (av, victim, nb);
3407 void *p = chunk2mem (victim);
3408 alloc_perturb (p, bytes);
3409 return p;
3414 If a small request, check regular bin. Since these "smallbins"
3415 hold one size each, no searching within bins is necessary.
3416 (For a large request, we need to wait until unsorted chunks are
3417 processed to find best fit. But for small ones, fits are exact
3418 anyway, so we can check now, which is faster.)
3421 if (in_smallbin_range (nb))
3423 idx = smallbin_index (nb);
3424 bin = bin_at (av, idx);
3426 if ((victim = last (bin)) != bin)
3428 if (victim == 0) /* initialization check */
3429 malloc_consolidate (av);
3430 else
3432 bck = victim->bk;
3433 if (__glibc_unlikely (bck->fd != victim))
3435 errstr = "malloc(): smallbin double linked list corrupted";
3436 goto errout;
3438 set_inuse_bit_at_offset (victim, nb);
3439 bin->bk = bck;
3440 bck->fd = bin;
3442 if (av != &main_arena)
3443 victim->size |= NON_MAIN_ARENA;
3444 check_malloced_chunk (av, victim, nb);
3445 void *p = chunk2mem (victim);
3446 alloc_perturb (p, bytes);
3447 return p;
3453 If this is a large request, consolidate fastbins before continuing.
3454 While it might look excessive to kill all fastbins before
3455 even seeing if there is space available, this avoids
3456 fragmentation problems normally associated with fastbins.
3457 Also, in practice, programs tend to have runs of either small or
3458 large requests, but less often mixtures, so consolidation is not
3459 invoked all that often in most programs. And the programs that
3460 it is called frequently in otherwise tend to fragment.
3463 else
3465 idx = largebin_index (nb);
3466 if (have_fastchunks (av))
3467 malloc_consolidate (av);
3471 Process recently freed or remaindered chunks, taking one only if
3472 it is exact fit, or, if this a small request, the chunk is remainder from
3473 the most recent non-exact fit. Place other traversed chunks in
3474 bins. Note that this step is the only place in any routine where
3475 chunks are placed in bins.
3477 The outer loop here is needed because we might not realize until
3478 near the end of malloc that we should have consolidated, so must
3479 do so and retry. This happens at most once, and only when we would
3480 otherwise need to expand memory to service a "small" request.
3483 for (;; )
3485 int iters = 0;
3486 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3488 bck = victim->bk;
3489 if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0)
3490 || __builtin_expect (victim->size > av->system_mem, 0))
3491 malloc_printerr (check_action, "malloc(): memory corruption",
3492 chunk2mem (victim), av);
3493 size = chunksize (victim);
3496 If a small request, try to use last remainder if it is the
3497 only chunk in unsorted bin. This helps promote locality for
3498 runs of consecutive small requests. This is the only
3499 exception to best-fit, and applies only when there is
3500 no exact fit for a small chunk.
3503 if (in_smallbin_range (nb) &&
3504 bck == unsorted_chunks (av) &&
3505 victim == av->last_remainder &&
3506 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
3508 /* split and reattach remainder */
3509 remainder_size = size - nb;
3510 remainder = chunk_at_offset (victim, nb);
3511 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
3512 av->last_remainder = remainder;
3513 remainder->bk = remainder->fd = unsorted_chunks (av);
3514 if (!in_smallbin_range (remainder_size))
3516 remainder->fd_nextsize = NULL;
3517 remainder->bk_nextsize = NULL;
3520 set_head (victim, nb | PREV_INUSE |
3521 (av != &main_arena ? NON_MAIN_ARENA : 0));
3522 set_head (remainder, remainder_size | PREV_INUSE);
3523 set_foot (remainder, remainder_size);
3525 check_malloced_chunk (av, victim, nb);
3526 void *p = chunk2mem (victim);
3527 alloc_perturb (p, bytes);
3528 return p;
3531 /* remove from unsorted list */
3532 unsorted_chunks (av)->bk = bck;
3533 bck->fd = unsorted_chunks (av);
3535 /* Take now instead of binning if exact fit */
3537 if (size == nb)
3539 set_inuse_bit_at_offset (victim, size);
3540 if (av != &main_arena)
3541 victim->size |= NON_MAIN_ARENA;
3542 check_malloced_chunk (av, victim, nb);
3543 void *p = chunk2mem (victim);
3544 alloc_perturb (p, bytes);
3545 return p;
3548 /* place chunk in bin */
3550 if (in_smallbin_range (size))
3552 victim_index = smallbin_index (size);
3553 bck = bin_at (av, victim_index);
3554 fwd = bck->fd;
3556 else
3558 victim_index = largebin_index (size);
3559 bck = bin_at (av, victim_index);
3560 fwd = bck->fd;
3562 /* maintain large bins in sorted order */
3563 if (fwd != bck)
3565 /* Or with inuse bit to speed comparisons */
3566 size |= PREV_INUSE;
3567 /* if smaller than smallest, bypass loop below */
3568 assert ((bck->bk->size & NON_MAIN_ARENA) == 0);
3569 if ((unsigned long) (size) < (unsigned long) (bck->bk->size))
3571 fwd = bck;
3572 bck = bck->bk;
3574 victim->fd_nextsize = fwd->fd;
3575 victim->bk_nextsize = fwd->fd->bk_nextsize;
3576 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
3578 else
3580 assert ((fwd->size & NON_MAIN_ARENA) == 0);
3581 while ((unsigned long) size < fwd->size)
3583 fwd = fwd->fd_nextsize;
3584 assert ((fwd->size & NON_MAIN_ARENA) == 0);
3587 if ((unsigned long) size == (unsigned long) fwd->size)
3588 /* Always insert in the second position. */
3589 fwd = fwd->fd;
3590 else
3592 victim->fd_nextsize = fwd;
3593 victim->bk_nextsize = fwd->bk_nextsize;
3594 fwd->bk_nextsize = victim;
3595 victim->bk_nextsize->fd_nextsize = victim;
3597 bck = fwd->bk;
3600 else
3601 victim->fd_nextsize = victim->bk_nextsize = victim;
3604 mark_bin (av, victim_index);
3605 victim->bk = bck;
3606 victim->fd = fwd;
3607 fwd->bk = victim;
3608 bck->fd = victim;
3610 #define MAX_ITERS 10000
3611 if (++iters >= MAX_ITERS)
3612 break;
3616 If a large request, scan through the chunks of current bin in
3617 sorted order to find smallest that fits. Use the skip list for this.
3620 if (!in_smallbin_range (nb))
3622 bin = bin_at (av, idx);
3624 /* skip scan if empty or largest chunk is too small */
3625 if ((victim = first (bin)) != bin &&
3626 (unsigned long) (victim->size) >= (unsigned long) (nb))
3628 victim = victim->bk_nextsize;
3629 while (((unsigned long) (size = chunksize (victim)) <
3630 (unsigned long) (nb)))
3631 victim = victim->bk_nextsize;
3633 /* Avoid removing the first entry for a size so that the skip
3634 list does not have to be rerouted. */
3635 if (victim != last (bin) && victim->size == victim->fd->size)
3636 victim = victim->fd;
3638 remainder_size = size - nb;
3639 unlink (av, victim, bck, fwd);
3641 /* Exhaust */
3642 if (remainder_size < MINSIZE)
3644 set_inuse_bit_at_offset (victim, size);
3645 if (av != &main_arena)
3646 victim->size |= NON_MAIN_ARENA;
3648 /* Split */
3649 else
3651 remainder = chunk_at_offset (victim, nb);
3652 /* We cannot assume the unsorted list is empty and therefore
3653 have to perform a complete insert here. */
3654 bck = unsorted_chunks (av);
3655 fwd = bck->fd;
3656 if (__glibc_unlikely (fwd->bk != bck))
3658 errstr = "malloc(): corrupted unsorted chunks";
3659 goto errout;
3661 remainder->bk = bck;
3662 remainder->fd = fwd;
3663 bck->fd = remainder;
3664 fwd->bk = remainder;
3665 if (!in_smallbin_range (remainder_size))
3667 remainder->fd_nextsize = NULL;
3668 remainder->bk_nextsize = NULL;
3670 set_head (victim, nb | PREV_INUSE |
3671 (av != &main_arena ? NON_MAIN_ARENA : 0));
3672 set_head (remainder, remainder_size | PREV_INUSE);
3673 set_foot (remainder, remainder_size);
3675 check_malloced_chunk (av, victim, nb);
3676 void *p = chunk2mem (victim);
3677 alloc_perturb (p, bytes);
3678 return p;
3683 Search for a chunk by scanning bins, starting with next largest
3684 bin. This search is strictly by best-fit; i.e., the smallest
3685 (with ties going to approximately the least recently used) chunk
3686 that fits is selected.
3688 The bitmap avoids needing to check that most blocks are nonempty.
3689 The particular case of skipping all bins during warm-up phases
3690 when no chunks have been returned yet is faster than it might look.
3693 ++idx;
3694 bin = bin_at (av, idx);
3695 block = idx2block (idx);
3696 map = av->binmap[block];
3697 bit = idx2bit (idx);
3699 for (;; )
3701 /* Skip rest of block if there are no more set bits in this block. */
3702 if (bit > map || bit == 0)
3706 if (++block >= BINMAPSIZE) /* out of bins */
3707 goto use_top;
3709 while ((map = av->binmap[block]) == 0);
3711 bin = bin_at (av, (block << BINMAPSHIFT));
3712 bit = 1;
3715 /* Advance to bin with set bit. There must be one. */
3716 while ((bit & map) == 0)
3718 bin = next_bin (bin);
3719 bit <<= 1;
3720 assert (bit != 0);
3723 /* Inspect the bin. It is likely to be non-empty */
3724 victim = last (bin);
3726 /* If a false alarm (empty bin), clear the bit. */
3727 if (victim == bin)
3729 av->binmap[block] = map &= ~bit; /* Write through */
3730 bin = next_bin (bin);
3731 bit <<= 1;
3734 else
3736 size = chunksize (victim);
3738 /* We know the first chunk in this bin is big enough to use. */
3739 assert ((unsigned long) (size) >= (unsigned long) (nb));
3741 remainder_size = size - nb;
3743 /* unlink */
3744 unlink (av, victim, bck, fwd);
3746 /* Exhaust */
3747 if (remainder_size < MINSIZE)
3749 set_inuse_bit_at_offset (victim, size);
3750 if (av != &main_arena)
3751 victim->size |= NON_MAIN_ARENA;
3754 /* Split */
3755 else
3757 remainder = chunk_at_offset (victim, nb);
3759 /* We cannot assume the unsorted list is empty and therefore
3760 have to perform a complete insert here. */
3761 bck = unsorted_chunks (av);
3762 fwd = bck->fd;
3763 if (__glibc_unlikely (fwd->bk != bck))
3765 errstr = "malloc(): corrupted unsorted chunks 2";
3766 goto errout;
3768 remainder->bk = bck;
3769 remainder->fd = fwd;
3770 bck->fd = remainder;
3771 fwd->bk = remainder;
3773 /* advertise as last remainder */
3774 if (in_smallbin_range (nb))
3775 av->last_remainder = remainder;
3776 if (!in_smallbin_range (remainder_size))
3778 remainder->fd_nextsize = NULL;
3779 remainder->bk_nextsize = NULL;
3781 set_head (victim, nb | PREV_INUSE |
3782 (av != &main_arena ? NON_MAIN_ARENA : 0));
3783 set_head (remainder, remainder_size | PREV_INUSE);
3784 set_foot (remainder, remainder_size);
3786 check_malloced_chunk (av, victim, nb);
3787 void *p = chunk2mem (victim);
3788 alloc_perturb (p, bytes);
3789 return p;
3793 use_top:
3795 If large enough, split off the chunk bordering the end of memory
3796 (held in av->top). Note that this is in accord with the best-fit
3797 search rule. In effect, av->top is treated as larger (and thus
3798 less well fitting) than any other available chunk since it can
3799 be extended to be as large as necessary (up to system
3800 limitations).
3802 We require that av->top always exists (i.e., has size >=
3803 MINSIZE) after initialization, so if it would otherwise be
3804 exhausted by current request, it is replenished. (The main
3805 reason for ensuring it exists is that we may need MINSIZE space
3806 to put in fenceposts in sysmalloc.)
3809 victim = av->top;
3810 size = chunksize (victim);
3812 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
3814 remainder_size = size - nb;
3815 remainder = chunk_at_offset (victim, nb);
3816 av->top = remainder;
3817 set_head (victim, nb | PREV_INUSE |
3818 (av != &main_arena ? NON_MAIN_ARENA : 0));
3819 set_head (remainder, remainder_size | PREV_INUSE);
3821 check_malloced_chunk (av, victim, nb);
3822 void *p = chunk2mem (victim);
3823 alloc_perturb (p, bytes);
3824 return p;
3827 /* When we are using atomic ops to free fast chunks we can get
3828 here for all block sizes. */
3829 else if (have_fastchunks (av))
3831 malloc_consolidate (av);
3832 /* restore original bin index */
3833 if (in_smallbin_range (nb))
3834 idx = smallbin_index (nb);
3835 else
3836 idx = largebin_index (nb);
3840 Otherwise, relay to handle system-dependent cases
3842 else
3844 void *p = sysmalloc (nb, av);
3845 if (p != NULL)
3846 alloc_perturb (p, bytes);
3847 return p;
3853 ------------------------------ free ------------------------------
3856 static void
3857 _int_free (mstate av, mchunkptr p, int have_lock)
3859 INTERNAL_SIZE_T size; /* its size */
3860 mfastbinptr *fb; /* associated fastbin */
3861 mchunkptr nextchunk; /* next contiguous chunk */
3862 INTERNAL_SIZE_T nextsize; /* its size */
3863 int nextinuse; /* true if nextchunk is used */
3864 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
3865 mchunkptr bck; /* misc temp for linking */
3866 mchunkptr fwd; /* misc temp for linking */
3868 const char *errstr = NULL;
3869 int locked = 0;
3871 size = chunksize (p);
3873 /* Little security check which won't hurt performance: the
3874 allocator never wrapps around at the end of the address space.
3875 Therefore we can exclude some size values which might appear
3876 here by accident or by "design" from some intruder. */
3877 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
3878 || __builtin_expect (misaligned_chunk (p), 0))
3880 errstr = "free(): invalid pointer";
3881 errout:
3882 if (!have_lock && locked)
3883 (void) mutex_unlock (&av->mutex);
3884 malloc_printerr (check_action, errstr, chunk2mem (p), av);
3885 return;
3887 /* We know that each chunk is at least MINSIZE bytes in size or a
3888 multiple of MALLOC_ALIGNMENT. */
3889 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
3891 errstr = "free(): invalid size";
3892 goto errout;
3895 check_inuse_chunk(av, p);
3898 If eligible, place chunk on a fastbin so it can be found
3899 and used quickly in malloc.
3902 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
3904 #if TRIM_FASTBINS
3906 If TRIM_FASTBINS set, don't place chunks
3907 bordering top into fastbins
3909 && (chunk_at_offset(p, size) != av->top)
3910 #endif
3913 if (__builtin_expect (chunk_at_offset (p, size)->size <= 2 * SIZE_SZ, 0)
3914 || __builtin_expect (chunksize (chunk_at_offset (p, size))
3915 >= av->system_mem, 0))
3917 /* We might not have a lock at this point and concurrent modifications
3918 of system_mem might have let to a false positive. Redo the test
3919 after getting the lock. */
3920 if (have_lock
3921 || ({ assert (locked == 0);
3922 mutex_lock(&av->mutex);
3923 locked = 1;
3924 chunk_at_offset (p, size)->size <= 2 * SIZE_SZ
3925 || chunksize (chunk_at_offset (p, size)) >= av->system_mem;
3928 errstr = "free(): invalid next size (fast)";
3929 goto errout;
3931 if (! have_lock)
3933 (void)mutex_unlock(&av->mutex);
3934 locked = 0;
3938 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3940 set_fastchunks(av);
3941 unsigned int idx = fastbin_index(size);
3942 fb = &fastbin (av, idx);
3944 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
3945 mchunkptr old = *fb, old2;
3946 unsigned int old_idx = ~0u;
3949 /* Check that the top of the bin is not the record we are going to add
3950 (i.e., double free). */
3951 if (__builtin_expect (old == p, 0))
3953 errstr = "double free or corruption (fasttop)";
3954 goto errout;
3956 /* Check that size of fastbin chunk at the top is the same as
3957 size of the chunk that we are adding. We can dereference OLD
3958 only if we have the lock, otherwise it might have already been
3959 deallocated. See use of OLD_IDX below for the actual check. */
3960 if (have_lock && old != NULL)
3961 old_idx = fastbin_index(chunksize(old));
3962 p->fd = old2 = old;
3964 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2)) != old2);
3966 if (have_lock && old != NULL && __builtin_expect (old_idx != idx, 0))
3968 errstr = "invalid fastbin entry (free)";
3969 goto errout;
3974 Consolidate other non-mmapped chunks as they arrive.
3977 else if (!chunk_is_mmapped(p)) {
3978 if (! have_lock) {
3979 (void)mutex_lock(&av->mutex);
3980 locked = 1;
3983 nextchunk = chunk_at_offset(p, size);
3985 /* Lightweight tests: check whether the block is already the
3986 top block. */
3987 if (__glibc_unlikely (p == av->top))
3989 errstr = "double free or corruption (top)";
3990 goto errout;
3992 /* Or whether the next chunk is beyond the boundaries of the arena. */
3993 if (__builtin_expect (contiguous (av)
3994 && (char *) nextchunk
3995 >= ((char *) av->top + chunksize(av->top)), 0))
3997 errstr = "double free or corruption (out)";
3998 goto errout;
4000 /* Or whether the block is actually not marked used. */
4001 if (__glibc_unlikely (!prev_inuse(nextchunk)))
4003 errstr = "double free or corruption (!prev)";
4004 goto errout;
4007 nextsize = chunksize(nextchunk);
4008 if (__builtin_expect (nextchunk->size <= 2 * SIZE_SZ, 0)
4009 || __builtin_expect (nextsize >= av->system_mem, 0))
4011 errstr = "free(): invalid next size (normal)";
4012 goto errout;
4015 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
4017 /* consolidate backward */
4018 if (!prev_inuse(p)) {
4019 prevsize = p->prev_size;
4020 size += prevsize;
4021 p = chunk_at_offset(p, -((long) prevsize));
4022 unlink(av, p, bck, fwd);
4025 if (nextchunk != av->top) {
4026 /* get and clear inuse bit */
4027 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4029 /* consolidate forward */
4030 if (!nextinuse) {
4031 unlink(av, nextchunk, bck, fwd);
4032 size += nextsize;
4033 } else
4034 clear_inuse_bit_at_offset(nextchunk, 0);
4037 Place the chunk in unsorted chunk list. Chunks are
4038 not placed into regular bins until after they have
4039 been given one chance to be used in malloc.
4042 bck = unsorted_chunks(av);
4043 fwd = bck->fd;
4044 if (__glibc_unlikely (fwd->bk != bck))
4046 errstr = "free(): corrupted unsorted chunks";
4047 goto errout;
4049 p->fd = fwd;
4050 p->bk = bck;
4051 if (!in_smallbin_range(size))
4053 p->fd_nextsize = NULL;
4054 p->bk_nextsize = NULL;
4056 bck->fd = p;
4057 fwd->bk = p;
4059 set_head(p, size | PREV_INUSE);
4060 set_foot(p, size);
4062 check_free_chunk(av, p);
4066 If the chunk borders the current high end of memory,
4067 consolidate into top
4070 else {
4071 size += nextsize;
4072 set_head(p, size | PREV_INUSE);
4073 av->top = p;
4074 check_chunk(av, p);
4078 If freeing a large space, consolidate possibly-surrounding
4079 chunks. Then, if the total unused topmost memory exceeds trim
4080 threshold, ask malloc_trim to reduce top.
4082 Unless max_fast is 0, we don't know if there are fastbins
4083 bordering top, so we cannot tell for sure whether threshold
4084 has been reached unless fastbins are consolidated. But we
4085 don't want to consolidate on each free. As a compromise,
4086 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4087 is reached.
4090 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4091 if (have_fastchunks(av))
4092 malloc_consolidate(av);
4094 if (av == &main_arena) {
4095 #ifndef MORECORE_CANNOT_TRIM
4096 if ((unsigned long)(chunksize(av->top)) >=
4097 (unsigned long)(mp_.trim_threshold))
4098 systrim(mp_.top_pad, av);
4099 #endif
4100 } else {
4101 /* Always try heap_trim(), even if the top chunk is not
4102 large, because the corresponding heap might go away. */
4103 heap_info *heap = heap_for_ptr(top(av));
4105 assert(heap->ar_ptr == av);
4106 heap_trim(heap, mp_.top_pad);
4110 if (! have_lock) {
4111 assert (locked);
4112 (void)mutex_unlock(&av->mutex);
4116 If the chunk was allocated via mmap, release via munmap().
4119 else {
4120 munmap_chunk (p);
4125 ------------------------- malloc_consolidate -------------------------
4127 malloc_consolidate is a specialized version of free() that tears
4128 down chunks held in fastbins. Free itself cannot be used for this
4129 purpose since, among other things, it might place chunks back onto
4130 fastbins. So, instead, we need to use a minor variant of the same
4131 code.
4133 Also, because this routine needs to be called the first time through
4134 malloc anyway, it turns out to be the perfect place to trigger
4135 initialization code.
4138 static void malloc_consolidate(mstate av)
4140 mfastbinptr* fb; /* current fastbin being consolidated */
4141 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4142 mchunkptr p; /* current chunk being consolidated */
4143 mchunkptr nextp; /* next chunk to consolidate */
4144 mchunkptr unsorted_bin; /* bin header */
4145 mchunkptr first_unsorted; /* chunk to link to */
4147 /* These have same use as in free() */
4148 mchunkptr nextchunk;
4149 INTERNAL_SIZE_T size;
4150 INTERNAL_SIZE_T nextsize;
4151 INTERNAL_SIZE_T prevsize;
4152 int nextinuse;
4153 mchunkptr bck;
4154 mchunkptr fwd;
4157 If max_fast is 0, we know that av hasn't
4158 yet been initialized, in which case do so below
4161 if (get_max_fast () != 0) {
4162 clear_fastchunks(av);
4164 unsorted_bin = unsorted_chunks(av);
4167 Remove each chunk from fast bin and consolidate it, placing it
4168 then in unsorted bin. Among other reasons for doing this,
4169 placing in unsorted bin avoids needing to calculate actual bins
4170 until malloc is sure that chunks aren't immediately going to be
4171 reused anyway.
4174 maxfb = &fastbin (av, NFASTBINS - 1);
4175 fb = &fastbin (av, 0);
4176 do {
4177 p = atomic_exchange_acq (fb, NULL);
4178 if (p != 0) {
4179 do {
4180 check_inuse_chunk(av, p);
4181 nextp = p->fd;
4183 /* Slightly streamlined version of consolidation code in free() */
4184 size = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
4185 nextchunk = chunk_at_offset(p, size);
4186 nextsize = chunksize(nextchunk);
4188 if (!prev_inuse(p)) {
4189 prevsize = p->prev_size;
4190 size += prevsize;
4191 p = chunk_at_offset(p, -((long) prevsize));
4192 unlink(av, p, bck, fwd);
4195 if (nextchunk != av->top) {
4196 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4198 if (!nextinuse) {
4199 size += nextsize;
4200 unlink(av, nextchunk, bck, fwd);
4201 } else
4202 clear_inuse_bit_at_offset(nextchunk, 0);
4204 first_unsorted = unsorted_bin->fd;
4205 unsorted_bin->fd = p;
4206 first_unsorted->bk = p;
4208 if (!in_smallbin_range (size)) {
4209 p->fd_nextsize = NULL;
4210 p->bk_nextsize = NULL;
4213 set_head(p, size | PREV_INUSE);
4214 p->bk = unsorted_bin;
4215 p->fd = first_unsorted;
4216 set_foot(p, size);
4219 else {
4220 size += nextsize;
4221 set_head(p, size | PREV_INUSE);
4222 av->top = p;
4225 } while ( (p = nextp) != 0);
4228 } while (fb++ != maxfb);
4230 else {
4231 malloc_init_state(av);
4232 check_malloc_state(av);
4237 ------------------------------ realloc ------------------------------
4240 void*
4241 _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4242 INTERNAL_SIZE_T nb)
4244 mchunkptr newp; /* chunk to return */
4245 INTERNAL_SIZE_T newsize; /* its size */
4246 void* newmem; /* corresponding user mem */
4248 mchunkptr next; /* next contiguous chunk after oldp */
4250 mchunkptr remainder; /* extra space at end of newp */
4251 unsigned long remainder_size; /* its size */
4253 mchunkptr bck; /* misc temp for linking */
4254 mchunkptr fwd; /* misc temp for linking */
4256 unsigned long copysize; /* bytes to copy */
4257 unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
4258 INTERNAL_SIZE_T* s; /* copy source */
4259 INTERNAL_SIZE_T* d; /* copy destination */
4261 const char *errstr = NULL;
4263 /* oldmem size */
4264 if (__builtin_expect (oldp->size <= 2 * SIZE_SZ, 0)
4265 || __builtin_expect (oldsize >= av->system_mem, 0))
4267 errstr = "realloc(): invalid old size";
4268 errout:
4269 malloc_printerr (check_action, errstr, chunk2mem (oldp), av);
4270 return NULL;
4273 check_inuse_chunk (av, oldp);
4275 /* All callers already filter out mmap'ed chunks. */
4276 assert (!chunk_is_mmapped (oldp));
4278 next = chunk_at_offset (oldp, oldsize);
4279 INTERNAL_SIZE_T nextsize = chunksize (next);
4280 if (__builtin_expect (next->size <= 2 * SIZE_SZ, 0)
4281 || __builtin_expect (nextsize >= av->system_mem, 0))
4283 errstr = "realloc(): invalid next size";
4284 goto errout;
4287 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4289 /* already big enough; split below */
4290 newp = oldp;
4291 newsize = oldsize;
4294 else
4296 /* Try to expand forward into top */
4297 if (next == av->top &&
4298 (unsigned long) (newsize = oldsize + nextsize) >=
4299 (unsigned long) (nb + MINSIZE))
4301 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4302 av->top = chunk_at_offset (oldp, nb);
4303 set_head (av->top, (newsize - nb) | PREV_INUSE);
4304 check_inuse_chunk (av, oldp);
4305 return chunk2mem (oldp);
4308 /* Try to expand forward into next chunk; split off remainder below */
4309 else if (next != av->top &&
4310 !inuse (next) &&
4311 (unsigned long) (newsize = oldsize + nextsize) >=
4312 (unsigned long) (nb))
4314 newp = oldp;
4315 unlink (av, next, bck, fwd);
4318 /* allocate, copy, free */
4319 else
4321 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4322 if (newmem == 0)
4323 return 0; /* propagate failure */
4325 newp = mem2chunk (newmem);
4326 newsize = chunksize (newp);
4329 Avoid copy if newp is next chunk after oldp.
4331 if (newp == next)
4333 newsize += oldsize;
4334 newp = oldp;
4336 else
4339 Unroll copy of <= 36 bytes (72 if 8byte sizes)
4340 We know that contents have an odd number of
4341 INTERNAL_SIZE_T-sized words; minimally 3.
4344 copysize = oldsize - SIZE_SZ;
4345 s = (INTERNAL_SIZE_T *) (chunk2mem (oldp));
4346 d = (INTERNAL_SIZE_T *) (newmem);
4347 ncopies = copysize / sizeof (INTERNAL_SIZE_T);
4348 assert (ncopies >= 3);
4350 if (ncopies > 9)
4351 memcpy (d, s, copysize);
4353 else
4355 *(d + 0) = *(s + 0);
4356 *(d + 1) = *(s + 1);
4357 *(d + 2) = *(s + 2);
4358 if (ncopies > 4)
4360 *(d + 3) = *(s + 3);
4361 *(d + 4) = *(s + 4);
4362 if (ncopies > 6)
4364 *(d + 5) = *(s + 5);
4365 *(d + 6) = *(s + 6);
4366 if (ncopies > 8)
4368 *(d + 7) = *(s + 7);
4369 *(d + 8) = *(s + 8);
4375 _int_free (av, oldp, 1);
4376 check_inuse_chunk (av, newp);
4377 return chunk2mem (newp);
4382 /* If possible, free extra space in old or extended chunk */
4384 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
4386 remainder_size = newsize - nb;
4388 if (remainder_size < MINSIZE) /* not enough extra to split off */
4390 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4391 set_inuse_bit_at_offset (newp, newsize);
4393 else /* split remainder */
4395 remainder = chunk_at_offset (newp, nb);
4396 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4397 set_head (remainder, remainder_size | PREV_INUSE |
4398 (av != &main_arena ? NON_MAIN_ARENA : 0));
4399 /* Mark remainder as inuse so free() won't complain */
4400 set_inuse_bit_at_offset (remainder, remainder_size);
4401 _int_free (av, remainder, 1);
4404 check_inuse_chunk (av, newp);
4405 return chunk2mem (newp);
4409 ------------------------------ memalign ------------------------------
4412 static void *
4413 _int_memalign (mstate av, size_t alignment, size_t bytes)
4415 INTERNAL_SIZE_T nb; /* padded request size */
4416 char *m; /* memory returned by malloc call */
4417 mchunkptr p; /* corresponding chunk */
4418 char *brk; /* alignment point within p */
4419 mchunkptr newp; /* chunk to return */
4420 INTERNAL_SIZE_T newsize; /* its size */
4421 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4422 mchunkptr remainder; /* spare room at end to split off */
4423 unsigned long remainder_size; /* its size */
4424 INTERNAL_SIZE_T size;
4428 checked_request2size (bytes, nb);
4431 Strategy: find a spot within that chunk that meets the alignment
4432 request, and then possibly free the leading and trailing space.
4436 /* Call malloc with worst case padding to hit alignment. */
4438 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4440 if (m == 0)
4441 return 0; /* propagate failure */
4443 p = mem2chunk (m);
4445 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4447 { /*
4448 Find an aligned spot inside chunk. Since we need to give back
4449 leading space in a chunk of at least MINSIZE, if the first
4450 calculation places us at a spot with less than MINSIZE leader,
4451 we can move to the next aligned spot -- we've allocated enough
4452 total room so that this is always possible.
4454 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4455 - ((signed long) alignment));
4456 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4457 brk += alignment;
4459 newp = (mchunkptr) brk;
4460 leadsize = brk - (char *) (p);
4461 newsize = chunksize (p) - leadsize;
4463 /* For mmapped chunks, just adjust offset */
4464 if (chunk_is_mmapped (p))
4466 newp->prev_size = p->prev_size + leadsize;
4467 set_head (newp, newsize | IS_MMAPPED);
4468 return chunk2mem (newp);
4471 /* Otherwise, give back leader, use the rest */
4472 set_head (newp, newsize | PREV_INUSE |
4473 (av != &main_arena ? NON_MAIN_ARENA : 0));
4474 set_inuse_bit_at_offset (newp, newsize);
4475 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4476 _int_free (av, p, 1);
4477 p = newp;
4479 assert (newsize >= nb &&
4480 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
4483 /* Also give back spare room at the end */
4484 if (!chunk_is_mmapped (p))
4486 size = chunksize (p);
4487 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4489 remainder_size = size - nb;
4490 remainder = chunk_at_offset (p, nb);
4491 set_head (remainder, remainder_size | PREV_INUSE |
4492 (av != &main_arena ? NON_MAIN_ARENA : 0));
4493 set_head_size (p, nb);
4494 _int_free (av, remainder, 1);
4498 check_inuse_chunk (av, p);
4499 return chunk2mem (p);
4504 ------------------------------ malloc_trim ------------------------------
4507 static int
4508 mtrim (mstate av, size_t pad)
4510 /* Don't touch corrupt arenas. */
4511 if (arena_is_corrupt (av))
4512 return 0;
4514 /* Ensure initialization/consolidation */
4515 malloc_consolidate (av);
4517 const size_t ps = GLRO (dl_pagesize);
4518 int psindex = bin_index (ps);
4519 const size_t psm1 = ps - 1;
4521 int result = 0;
4522 for (int i = 1; i < NBINS; ++i)
4523 if (i == 1 || i >= psindex)
4525 mbinptr bin = bin_at (av, i);
4527 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4529 INTERNAL_SIZE_T size = chunksize (p);
4531 if (size > psm1 + sizeof (struct malloc_chunk))
4533 /* See whether the chunk contains at least one unused page. */
4534 char *paligned_mem = (char *) (((uintptr_t) p
4535 + sizeof (struct malloc_chunk)
4536 + psm1) & ~psm1);
4538 assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
4539 assert ((char *) p + size > paligned_mem);
4541 /* This is the size we could potentially free. */
4542 size -= paligned_mem - (char *) p;
4544 if (size > psm1)
4546 #if MALLOC_DEBUG
4547 /* When debugging we simulate destroying the memory
4548 content. */
4549 memset (paligned_mem, 0x89, size & ~psm1);
4550 #endif
4551 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
4553 result = 1;
4559 #ifndef MORECORE_CANNOT_TRIM
4560 return result | (av == &main_arena ? systrim (pad, av) : 0);
4562 #else
4563 return result;
4564 #endif
4569 __malloc_trim (size_t s)
4571 int result = 0;
4573 if (__malloc_initialized < 0)
4574 ptmalloc_init ();
4576 mstate ar_ptr = &main_arena;
4579 (void) mutex_lock (&ar_ptr->mutex);
4580 result |= mtrim (ar_ptr, s);
4581 (void) mutex_unlock (&ar_ptr->mutex);
4583 ar_ptr = ar_ptr->next;
4585 while (ar_ptr != &main_arena);
4587 return result;
4592 ------------------------- malloc_usable_size -------------------------
4595 static size_t
4596 musable (void *mem)
4598 mchunkptr p;
4599 if (mem != 0)
4601 p = mem2chunk (mem);
4603 if (__builtin_expect (using_malloc_checking == 1, 0))
4604 return malloc_check_get_size (p);
4606 if (chunk_is_mmapped (p))
4607 return chunksize (p) - 2 * SIZE_SZ;
4608 else if (inuse (p))
4609 return chunksize (p) - SIZE_SZ;
4611 return 0;
4615 size_t
4616 __malloc_usable_size (void *m)
4618 size_t result;
4620 result = musable (m);
4621 return result;
4625 ------------------------------ mallinfo ------------------------------
4626 Accumulate malloc statistics for arena AV into M.
4629 static void
4630 int_mallinfo (mstate av, struct mallinfo *m)
4632 size_t i;
4633 mbinptr b;
4634 mchunkptr p;
4635 INTERNAL_SIZE_T avail;
4636 INTERNAL_SIZE_T fastavail;
4637 int nblocks;
4638 int nfastblocks;
4640 /* Ensure initialization */
4641 if (av->top == 0)
4642 malloc_consolidate (av);
4644 check_malloc_state (av);
4646 /* Account for top */
4647 avail = chunksize (av->top);
4648 nblocks = 1; /* top always exists */
4650 /* traverse fastbins */
4651 nfastblocks = 0;
4652 fastavail = 0;
4654 for (i = 0; i < NFASTBINS; ++i)
4656 for (p = fastbin (av, i); p != 0; p = p->fd)
4658 ++nfastblocks;
4659 fastavail += chunksize (p);
4663 avail += fastavail;
4665 /* traverse regular bins */
4666 for (i = 1; i < NBINS; ++i)
4668 b = bin_at (av, i);
4669 for (p = last (b); p != b; p = p->bk)
4671 ++nblocks;
4672 avail += chunksize (p);
4676 m->smblks += nfastblocks;
4677 m->ordblks += nblocks;
4678 m->fordblks += avail;
4679 m->uordblks += av->system_mem - avail;
4680 m->arena += av->system_mem;
4681 m->fsmblks += fastavail;
4682 if (av == &main_arena)
4684 m->hblks = mp_.n_mmaps;
4685 m->hblkhd = mp_.mmapped_mem;
4686 m->usmblks = 0;
4687 m->keepcost = chunksize (av->top);
4692 struct mallinfo
4693 __libc_mallinfo (void)
4695 struct mallinfo m;
4696 mstate ar_ptr;
4698 if (__malloc_initialized < 0)
4699 ptmalloc_init ();
4701 memset (&m, 0, sizeof (m));
4702 ar_ptr = &main_arena;
4705 (void) mutex_lock (&ar_ptr->mutex);
4706 int_mallinfo (ar_ptr, &m);
4707 (void) mutex_unlock (&ar_ptr->mutex);
4709 ar_ptr = ar_ptr->next;
4711 while (ar_ptr != &main_arena);
4713 return m;
4717 ------------------------------ malloc_stats ------------------------------
4720 void
4721 __malloc_stats (void)
4723 int i;
4724 mstate ar_ptr;
4725 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
4727 if (__malloc_initialized < 0)
4728 ptmalloc_init ();
4729 _IO_flockfile (stderr);
4730 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
4731 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
4732 for (i = 0, ar_ptr = &main_arena;; i++)
4734 struct mallinfo mi;
4736 memset (&mi, 0, sizeof (mi));
4737 (void) mutex_lock (&ar_ptr->mutex);
4738 int_mallinfo (ar_ptr, &mi);
4739 fprintf (stderr, "Arena %d:\n", i);
4740 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
4741 fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
4742 #if MALLOC_DEBUG > 1
4743 if (i > 0)
4744 dump_heap (heap_for_ptr (top (ar_ptr)));
4745 #endif
4746 system_b += mi.arena;
4747 in_use_b += mi.uordblks;
4748 (void) mutex_unlock (&ar_ptr->mutex);
4749 ar_ptr = ar_ptr->next;
4750 if (ar_ptr == &main_arena)
4751 break;
4753 fprintf (stderr, "Total (incl. mmap):\n");
4754 fprintf (stderr, "system bytes = %10u\n", system_b);
4755 fprintf (stderr, "in use bytes = %10u\n", in_use_b);
4756 fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
4757 fprintf (stderr, "max mmap bytes = %10lu\n",
4758 (unsigned long) mp_.max_mmapped_mem);
4759 ((_IO_FILE *) stderr)->_flags2 |= old_flags2;
4760 _IO_funlockfile (stderr);
4765 ------------------------------ mallopt ------------------------------
4769 __libc_mallopt (int param_number, int value)
4771 mstate av = &main_arena;
4772 int res = 1;
4774 if (__malloc_initialized < 0)
4775 ptmalloc_init ();
4776 (void) mutex_lock (&av->mutex);
4777 /* Ensure initialization/consolidation */
4778 malloc_consolidate (av);
4780 LIBC_PROBE (memory_mallopt, 2, param_number, value);
4782 switch (param_number)
4784 case M_MXFAST:
4785 if (value >= 0 && value <= MAX_FAST_SIZE)
4787 LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
4788 set_max_fast (value);
4790 else
4791 res = 0;
4792 break;
4794 case M_TRIM_THRESHOLD:
4795 LIBC_PROBE (memory_mallopt_trim_threshold, 3, value,
4796 mp_.trim_threshold, mp_.no_dyn_threshold);
4797 mp_.trim_threshold = value;
4798 mp_.no_dyn_threshold = 1;
4799 break;
4801 case M_TOP_PAD:
4802 LIBC_PROBE (memory_mallopt_top_pad, 3, value,
4803 mp_.top_pad, mp_.no_dyn_threshold);
4804 mp_.top_pad = value;
4805 mp_.no_dyn_threshold = 1;
4806 break;
4808 case M_MMAP_THRESHOLD:
4809 /* Forbid setting the threshold too high. */
4810 if ((unsigned long) value > HEAP_MAX_SIZE / 2)
4811 res = 0;
4812 else
4814 LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value,
4815 mp_.mmap_threshold, mp_.no_dyn_threshold);
4816 mp_.mmap_threshold = value;
4817 mp_.no_dyn_threshold = 1;
4819 break;
4821 case M_MMAP_MAX:
4822 LIBC_PROBE (memory_mallopt_mmap_max, 3, value,
4823 mp_.n_mmaps_max, mp_.no_dyn_threshold);
4824 mp_.n_mmaps_max = value;
4825 mp_.no_dyn_threshold = 1;
4826 break;
4828 case M_CHECK_ACTION:
4829 LIBC_PROBE (memory_mallopt_check_action, 2, value, check_action);
4830 check_action = value;
4831 break;
4833 case M_PERTURB:
4834 LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
4835 perturb_byte = value;
4836 break;
4838 case M_ARENA_TEST:
4839 if (value > 0)
4841 LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
4842 mp_.arena_test = value;
4844 break;
4846 case M_ARENA_MAX:
4847 if (value > 0)
4849 LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
4850 mp_.arena_max = value;
4852 break;
4854 (void) mutex_unlock (&av->mutex);
4855 return res;
4857 libc_hidden_def (__libc_mallopt)
4861 -------------------- Alternative MORECORE functions --------------------
4866 General Requirements for MORECORE.
4868 The MORECORE function must have the following properties:
4870 If MORECORE_CONTIGUOUS is false:
4872 * MORECORE must allocate in multiples of pagesize. It will
4873 only be called with arguments that are multiples of pagesize.
4875 * MORECORE(0) must return an address that is at least
4876 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
4878 else (i.e. If MORECORE_CONTIGUOUS is true):
4880 * Consecutive calls to MORECORE with positive arguments
4881 return increasing addresses, indicating that space has been
4882 contiguously extended.
4884 * MORECORE need not allocate in multiples of pagesize.
4885 Calls to MORECORE need not have args of multiples of pagesize.
4887 * MORECORE need not page-align.
4889 In either case:
4891 * MORECORE may allocate more memory than requested. (Or even less,
4892 but this will generally result in a malloc failure.)
4894 * MORECORE must not allocate memory when given argument zero, but
4895 instead return one past the end address of memory from previous
4896 nonzero call. This malloc does NOT call MORECORE(0)
4897 until at least one call with positive arguments is made, so
4898 the initial value returned is not important.
4900 * Even though consecutive calls to MORECORE need not return contiguous
4901 addresses, it must be OK for malloc'ed chunks to span multiple
4902 regions in those cases where they do happen to be contiguous.
4904 * MORECORE need not handle negative arguments -- it may instead
4905 just return MORECORE_FAILURE when given negative arguments.
4906 Negative arguments are always multiples of pagesize. MORECORE
4907 must not misinterpret negative args as large positive unsigned
4908 args. You can suppress all such calls from even occurring by defining
4909 MORECORE_CANNOT_TRIM,
4911 There is some variation across systems about the type of the
4912 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
4913 actually be size_t, because sbrk supports negative args, so it is
4914 normally the signed type of the same width as size_t (sometimes
4915 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
4916 matter though. Internally, we use "long" as arguments, which should
4917 work across all reasonable possibilities.
4919 Additionally, if MORECORE ever returns failure for a positive
4920 request, then mmap is used as a noncontiguous system allocator. This
4921 is a useful backup strategy for systems with holes in address spaces
4922 -- in this case sbrk cannot contiguously expand the heap, but mmap
4923 may be able to map noncontiguous space.
4925 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
4926 a function that always returns MORECORE_FAILURE.
4928 If you are using this malloc with something other than sbrk (or its
4929 emulation) to supply memory regions, you probably want to set
4930 MORECORE_CONTIGUOUS as false. As an example, here is a custom
4931 allocator kindly contributed for pre-OSX macOS. It uses virtually
4932 but not necessarily physically contiguous non-paged memory (locked
4933 in, present and won't get swapped out). You can use it by
4934 uncommenting this section, adding some #includes, and setting up the
4935 appropriate defines above:
4937 *#define MORECORE osMoreCore
4938 *#define MORECORE_CONTIGUOUS 0
4940 There is also a shutdown routine that should somehow be called for
4941 cleanup upon program exit.
4943 *#define MAX_POOL_ENTRIES 100
4944 *#define MINIMUM_MORECORE_SIZE (64 * 1024)
4945 static int next_os_pool;
4946 void *our_os_pools[MAX_POOL_ENTRIES];
4948 void *osMoreCore(int size)
4950 void *ptr = 0;
4951 static void *sbrk_top = 0;
4953 if (size > 0)
4955 if (size < MINIMUM_MORECORE_SIZE)
4956 size = MINIMUM_MORECORE_SIZE;
4957 if (CurrentExecutionLevel() == kTaskLevel)
4958 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
4959 if (ptr == 0)
4961 return (void *) MORECORE_FAILURE;
4963 // save ptrs so they can be freed during cleanup
4964 our_os_pools[next_os_pool] = ptr;
4965 next_os_pool++;
4966 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
4967 sbrk_top = (char *) ptr + size;
4968 return ptr;
4970 else if (size < 0)
4972 // we don't currently support shrink behavior
4973 return (void *) MORECORE_FAILURE;
4975 else
4977 return sbrk_top;
4981 // cleanup any allocated memory pools
4982 // called as last thing before shutting down driver
4984 void osCleanupMem(void)
4986 void **ptr;
4988 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
4989 if (*ptr)
4991 PoolDeallocate(*ptr);
4992 * ptr = 0;
4999 /* Helper code. */
5001 extern char **__libc_argv attribute_hidden;
5003 static void
5004 malloc_printerr (int action, const char *str, void *ptr, mstate ar_ptr)
5006 /* Avoid using this arena in future. We do not attempt to synchronize this
5007 with anything else because we minimally want to ensure that __libc_message
5008 gets its resources safely without stumbling on the current corruption. */
5009 if (ar_ptr)
5010 set_arena_corrupt (ar_ptr);
5012 if ((action & 5) == 5)
5013 __libc_message (action & 2, "%s\n", str);
5014 else if (action & 1)
5016 char buf[2 * sizeof (uintptr_t) + 1];
5018 buf[sizeof (buf) - 1] = '\0';
5019 char *cp = _itoa_word ((uintptr_t) ptr, &buf[sizeof (buf) - 1], 16, 0);
5020 while (cp > buf)
5021 *--cp = '0';
5023 __libc_message (action & 2, "*** Error in `%s': %s: 0x%s ***\n",
5024 __libc_argv[0] ? : "<unknown>", str, cp);
5026 else if (action & 2)
5027 abort ();
5030 /* We need a wrapper function for one of the additions of POSIX. */
5032 __posix_memalign (void **memptr, size_t alignment, size_t size)
5034 void *mem;
5036 /* Test whether the SIZE argument is valid. It must be a power of
5037 two multiple of sizeof (void *). */
5038 if (alignment % sizeof (void *) != 0
5039 || !powerof2 (alignment / sizeof (void *))
5040 || alignment == 0)
5041 return EINVAL;
5044 void *address = RETURN_ADDRESS (0);
5045 mem = _mid_memalign (alignment, size, address);
5047 if (mem != NULL)
5049 *memptr = mem;
5050 return 0;
5053 return ENOMEM;
5055 weak_alias (__posix_memalign, posix_memalign)
5059 __malloc_info (int options, FILE *fp)
5061 /* For now, at least. */
5062 if (options != 0)
5063 return EINVAL;
5065 int n = 0;
5066 size_t total_nblocks = 0;
5067 size_t total_nfastblocks = 0;
5068 size_t total_avail = 0;
5069 size_t total_fastavail = 0;
5070 size_t total_system = 0;
5071 size_t total_max_system = 0;
5072 size_t total_aspace = 0;
5073 size_t total_aspace_mprotect = 0;
5077 if (__malloc_initialized < 0)
5078 ptmalloc_init ();
5080 fputs ("<malloc version=\"1\">\n", fp);
5082 /* Iterate over all arenas currently in use. */
5083 mstate ar_ptr = &main_arena;
5086 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
5088 size_t nblocks = 0;
5089 size_t nfastblocks = 0;
5090 size_t avail = 0;
5091 size_t fastavail = 0;
5092 struct
5094 size_t from;
5095 size_t to;
5096 size_t total;
5097 size_t count;
5098 } sizes[NFASTBINS + NBINS - 1];
5099 #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
5101 mutex_lock (&ar_ptr->mutex);
5103 for (size_t i = 0; i < NFASTBINS; ++i)
5105 mchunkptr p = fastbin (ar_ptr, i);
5106 if (p != NULL)
5108 size_t nthissize = 0;
5109 size_t thissize = chunksize (p);
5111 while (p != NULL)
5113 ++nthissize;
5114 p = p->fd;
5117 fastavail += nthissize * thissize;
5118 nfastblocks += nthissize;
5119 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
5120 sizes[i].to = thissize;
5121 sizes[i].count = nthissize;
5123 else
5124 sizes[i].from = sizes[i].to = sizes[i].count = 0;
5126 sizes[i].total = sizes[i].count * sizes[i].to;
5130 mbinptr bin;
5131 struct malloc_chunk *r;
5133 for (size_t i = 1; i < NBINS; ++i)
5135 bin = bin_at (ar_ptr, i);
5136 r = bin->fd;
5137 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5138 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5139 = sizes[NFASTBINS - 1 + i].count = 0;
5141 if (r != NULL)
5142 while (r != bin)
5144 ++sizes[NFASTBINS - 1 + i].count;
5145 sizes[NFASTBINS - 1 + i].total += r->size;
5146 sizes[NFASTBINS - 1 + i].from
5147 = MIN (sizes[NFASTBINS - 1 + i].from, r->size);
5148 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5149 r->size);
5151 r = r->fd;
5154 if (sizes[NFASTBINS - 1 + i].count == 0)
5155 sizes[NFASTBINS - 1 + i].from = 0;
5156 nblocks += sizes[NFASTBINS - 1 + i].count;
5157 avail += sizes[NFASTBINS - 1 + i].total;
5160 mutex_unlock (&ar_ptr->mutex);
5162 total_nfastblocks += nfastblocks;
5163 total_fastavail += fastavail;
5165 total_nblocks += nblocks;
5166 total_avail += avail;
5168 for (size_t i = 0; i < nsizes; ++i)
5169 if (sizes[i].count != 0 && i != NFASTBINS)
5170 fprintf (fp, " \
5171 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5172 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
5174 if (sizes[NFASTBINS].count != 0)
5175 fprintf (fp, "\
5176 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5177 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5178 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
5180 total_system += ar_ptr->system_mem;
5181 total_max_system += ar_ptr->max_system_mem;
5183 fprintf (fp,
5184 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5185 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5186 "<system type=\"current\" size=\"%zu\"/>\n"
5187 "<system type=\"max\" size=\"%zu\"/>\n",
5188 nfastblocks, fastavail, nblocks, avail,
5189 ar_ptr->system_mem, ar_ptr->max_system_mem);
5191 if (ar_ptr != &main_arena)
5193 heap_info *heap = heap_for_ptr (top (ar_ptr));
5194 fprintf (fp,
5195 "<aspace type=\"total\" size=\"%zu\"/>\n"
5196 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5197 heap->size, heap->mprotect_size);
5198 total_aspace += heap->size;
5199 total_aspace_mprotect += heap->mprotect_size;
5201 else
5203 fprintf (fp,
5204 "<aspace type=\"total\" size=\"%zu\"/>\n"
5205 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5206 ar_ptr->system_mem, ar_ptr->system_mem);
5207 total_aspace += ar_ptr->system_mem;
5208 total_aspace_mprotect += ar_ptr->system_mem;
5211 fputs ("</heap>\n", fp);
5212 ar_ptr = ar_ptr->next;
5214 while (ar_ptr != &main_arena);
5216 fprintf (fp,
5217 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5218 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5219 "<total type=\"mmap\" count=\"%d\" size=\"%zu\"/>\n"
5220 "<system type=\"current\" size=\"%zu\"/>\n"
5221 "<system type=\"max\" size=\"%zu\"/>\n"
5222 "<aspace type=\"total\" size=\"%zu\"/>\n"
5223 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5224 "</malloc>\n",
5225 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
5226 mp_.n_mmaps, mp_.mmapped_mem,
5227 total_system, total_max_system,
5228 total_aspace, total_aspace_mprotect);
5230 return 0;
5232 weak_alias (__malloc_info, malloc_info)
5235 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5236 strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5237 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5238 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5239 strong_alias (__libc_memalign, __memalign)
5240 weak_alias (__libc_memalign, memalign)
5241 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5242 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5243 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5244 strong_alias (__libc_mallinfo, __mallinfo)
5245 weak_alias (__libc_mallinfo, mallinfo)
5246 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5248 weak_alias (__malloc_stats, malloc_stats)
5249 weak_alias (__malloc_usable_size, malloc_usable_size)
5250 weak_alias (__malloc_trim, malloc_trim)
5251 weak_alias (__malloc_get_state, malloc_get_state)
5252 weak_alias (__malloc_set_state, malloc_set_state)
5255 /* ------------------------------------------------------------
5256 History:
5258 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
5262 * Local variables:
5263 * c-basic-offset: 2
5264 * End: