malloc: Move MTAG_MMAP_FLAGS definition
[glibc.git] / malloc / malloc.c
blob9dd811b26a3e1efe32671d61fd3337c3139dc8a6
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2021 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 <https://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 malloc_trim(size_t pad);
88 malloc_usable_size(void* p);
89 malloc_stats();
91 * Vital statistics:
93 Supported pointer representation: 4 or 8 bytes
94 Supported size_t representation: 4 or 8 bytes
95 Note that size_t is allowed to be 4 bytes even if pointers are 8.
96 You can adjust this by defining INTERNAL_SIZE_T
98 Alignment: 2 * sizeof(size_t) (default)
99 (i.e., 8 byte alignment with 4byte size_t). This suffices for
100 nearly all current machines and C compilers. However, you can
101 define MALLOC_ALIGNMENT to be wider than this if necessary.
103 Minimum overhead per allocated chunk: 4 or 8 bytes
104 Each malloced chunk has a hidden word of overhead holding size
105 and status information.
107 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
108 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
110 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
111 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
112 needed; 4 (8) for a trailing size field and 8 (16) bytes for
113 free list pointers. Thus, the minimum allocatable size is
114 16/24/32 bytes.
116 Even a request for zero bytes (i.e., malloc(0)) returns a
117 pointer to something of the minimum allocatable size.
119 The maximum overhead wastage (i.e., number of extra bytes
120 allocated than were requested in malloc) is less than or equal
121 to the minimum size, except for requests >= mmap_threshold that
122 are serviced via mmap(), where the worst case wastage is 2 *
123 sizeof(size_t) bytes plus the remainder from a system page (the
124 minimal mmap unit); typically 4096 or 8192 bytes.
126 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
127 8-byte size_t: 2^64 minus about two pages
129 It is assumed that (possibly signed) size_t values suffice to
130 represent chunk sizes. `Possibly signed' is due to the fact
131 that `size_t' may be defined on a system as either a signed or
132 an unsigned type. The ISO C standard says that it must be
133 unsigned, but a few systems are known not to adhere to this.
134 Additionally, even when size_t is unsigned, sbrk (which is by
135 default used to obtain memory from system) accepts signed
136 arguments, and may not be able to handle size_t-wide arguments
137 with negative sign bit. Generally, values that would
138 appear as negative after accounting for overhead and alignment
139 are supported only via mmap(), which does not have this
140 limitation.
142 Requests for sizes outside the allowed range will perform an optional
143 failure action and then return null. (Requests may also
144 also fail because a system is out of memory.)
146 Thread-safety: thread-safe
148 Compliance: I believe it is compliant with the 1997 Single Unix Specification
149 Also SVID/XPG, ANSI C, and probably others as well.
151 * Synopsis of compile-time options:
153 People have reported using previous versions of this malloc on all
154 versions of Unix, sometimes by tweaking some of the defines
155 below. It has been tested most extensively on Solaris and Linux.
156 People also report using it in stand-alone embedded systems.
158 The implementation is in straight, hand-tuned ANSI C. It is not
159 at all modular. (Sorry!) It uses a lot of macros. To be at all
160 usable, this code should be compiled using an optimizing compiler
161 (for example gcc -O3) that can simplify expressions and control
162 paths. (FAQ: some macros import variables as arguments rather than
163 declare locals because people reported that some debuggers
164 otherwise get confused.)
166 OPTION DEFAULT VALUE
168 Compilation Environment options:
170 HAVE_MREMAP 0
172 Changing default word sizes:
174 INTERNAL_SIZE_T size_t
176 Configuration and functionality options:
178 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
179 USE_MALLOC_LOCK NOT defined
180 MALLOC_DEBUG NOT defined
181 REALLOC_ZERO_BYTES_FREES 1
182 TRIM_FASTBINS 0
184 Options for customizing MORECORE:
186 MORECORE sbrk
187 MORECORE_FAILURE -1
188 MORECORE_CONTIGUOUS 1
189 MORECORE_CANNOT_TRIM NOT defined
190 MORECORE_CLEARS 1
191 MMAP_AS_MORECORE_SIZE (1024 * 1024)
193 Tuning options that are also dynamically changeable via mallopt:
195 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
196 DEFAULT_TRIM_THRESHOLD 128 * 1024
197 DEFAULT_TOP_PAD 0
198 DEFAULT_MMAP_THRESHOLD 128 * 1024
199 DEFAULT_MMAP_MAX 65536
201 There are several other #defined constants and macros that you
202 probably don't want to touch unless you are extending or adapting malloc. */
205 void* is the pointer type that malloc should say it returns
208 #ifndef void
209 #define void void
210 #endif /*void*/
212 #include <stddef.h> /* for size_t */
213 #include <stdlib.h> /* for getenv(), abort() */
214 #include <unistd.h> /* for __libc_enable_secure */
216 #include <atomic.h>
217 #include <_itoa.h>
218 #include <bits/wordsize.h>
219 #include <sys/sysinfo.h>
221 #include <ldsodefs.h>
223 #include <unistd.h>
224 #include <stdio.h> /* needed for malloc_stats */
225 #include <errno.h>
226 #include <assert.h>
228 #include <shlib-compat.h>
230 /* For uintptr_t. */
231 #include <stdint.h>
233 /* For va_arg, va_start, va_end. */
234 #include <stdarg.h>
236 /* For MIN, MAX, powerof2. */
237 #include <sys/param.h>
239 /* For ALIGN_UP et. al. */
240 #include <libc-pointer-arith.h>
242 /* For DIAG_PUSH/POP_NEEDS_COMMENT et al. */
243 #include <libc-diag.h>
245 /* For memory tagging. */
246 #include <libc-mtag.h>
248 #include <malloc/malloc-internal.h>
250 /* For SINGLE_THREAD_P. */
251 #include <sysdep-cancel.h>
253 #include <libc-internal.h>
256 Debugging:
258 Because freed chunks may be overwritten with bookkeeping fields, this
259 malloc will often die when freed memory is overwritten by user
260 programs. This can be very effective (albeit in an annoying way)
261 in helping track down dangling pointers.
263 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
264 enabled that will catch more memory errors. You probably won't be
265 able to make much sense of the actual assertion errors, but they
266 should help you locate incorrectly overwritten memory. The checking
267 is fairly extensive, and will slow down execution
268 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
269 will attempt to check every non-mmapped allocated and free chunk in
270 the course of computing the summmaries. (By nature, mmapped regions
271 cannot be checked very much automatically.)
273 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
274 this code. The assertions in the check routines spell out in more
275 detail the assumptions and invariants underlying the algorithms.
277 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
278 checking that all accesses to malloced memory stay within their
279 bounds. However, there are several add-ons and adaptations of this
280 or other mallocs available that do this.
283 #ifndef MALLOC_DEBUG
284 #define MALLOC_DEBUG 0
285 #endif
287 #ifndef NDEBUG
288 # define __assert_fail(assertion, file, line, function) \
289 __malloc_assert(assertion, file, line, function)
291 extern const char *__progname;
293 static void
294 __malloc_assert (const char *assertion, const char *file, unsigned int line,
295 const char *function)
297 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
298 __progname, __progname[0] ? ": " : "",
299 file, line,
300 function ? function : "", function ? ": " : "",
301 assertion);
302 fflush (stderr);
303 abort ();
305 #endif
307 #if USE_TCACHE
308 /* We want 64 entries. This is an arbitrary limit, which tunables can reduce. */
309 # define TCACHE_MAX_BINS 64
310 # define MAX_TCACHE_SIZE tidx2usize (TCACHE_MAX_BINS-1)
312 /* Only used to pre-fill the tunables. */
313 # define tidx2usize(idx) (((size_t) idx) * MALLOC_ALIGNMENT + MINSIZE - SIZE_SZ)
315 /* When "x" is from chunksize(). */
316 # define csize2tidx(x) (((x) - MINSIZE + MALLOC_ALIGNMENT - 1) / MALLOC_ALIGNMENT)
317 /* When "x" is a user-provided size. */
318 # define usize2tidx(x) csize2tidx (request2size (x))
320 /* With rounding and alignment, the bins are...
321 idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit)
322 idx 1 bytes 25..40 or 13..20
323 idx 2 bytes 41..56 or 21..28
324 etc. */
326 /* This is another arbitrary limit, which tunables can change. Each
327 tcache bin will hold at most this number of chunks. */
328 # define TCACHE_FILL_COUNT 7
330 /* Maximum chunks in tcache bins for tunables. This value must fit the range
331 of tcache->counts[] entries, else they may overflow. */
332 # define MAX_TCACHE_COUNT UINT16_MAX
333 #endif
335 /* Safe-Linking:
336 Use randomness from ASLR (mmap_base) to protect single-linked lists
337 of Fast-Bins and TCache. That is, mask the "next" pointers of the
338 lists' chunks, and also perform allocation alignment checks on them.
339 This mechanism reduces the risk of pointer hijacking, as was done with
340 Safe-Unlinking in the double-linked lists of Small-Bins.
341 It assumes a minimum page size of 4096 bytes (12 bits). Systems with
342 larger pages provide less entropy, although the pointer mangling
343 still works. */
344 #define PROTECT_PTR(pos, ptr) \
345 ((__typeof (ptr)) ((((size_t) pos) >> 12) ^ ((size_t) ptr)))
346 #define REVEAL_PTR(ptr) PROTECT_PTR (&ptr, ptr)
349 REALLOC_ZERO_BYTES_FREES should be set if a call to
350 realloc with zero bytes should be the same as a call to free.
351 This is required by the C standard. Otherwise, since this malloc
352 returns a unique pointer for malloc(0), so does realloc(p, 0).
355 #ifndef REALLOC_ZERO_BYTES_FREES
356 #define REALLOC_ZERO_BYTES_FREES 1
357 #endif
360 TRIM_FASTBINS controls whether free() of a very small chunk can
361 immediately lead to trimming. Setting to true (1) can reduce memory
362 footprint, but will almost always slow down programs that use a lot
363 of small chunks.
365 Define this only if you are willing to give up some speed to more
366 aggressively reduce system-level memory footprint when releasing
367 memory in programs that use many small chunks. You can get
368 essentially the same effect by setting MXFAST to 0, but this can
369 lead to even greater slowdowns in programs using many small chunks.
370 TRIM_FASTBINS is an in-between compile-time option, that disables
371 only those chunks bordering topmost memory from being placed in
372 fastbins.
375 #ifndef TRIM_FASTBINS
376 #define TRIM_FASTBINS 0
377 #endif
380 /* Definition for getting more memory from the OS. */
381 #define MORECORE (*__morecore)
382 #define MORECORE_FAILURE 0
383 void * __default_morecore (ptrdiff_t);
384 void *(*__morecore)(ptrdiff_t) = __default_morecore;
386 /* Memory tagging. */
388 /* Some systems support the concept of tagging (sometimes known as
389 coloring) memory locations on a fine grained basis. Each memory
390 location is given a color (normally allocated randomly) and
391 pointers are also colored. When the pointer is dereferenced, the
392 pointer's color is checked against the memory's color and if they
393 differ the access is faulted (sometimes lazily).
395 We use this in glibc by maintaining a single color for the malloc
396 data structures that are interleaved with the user data and then
397 assigning separate colors for each block allocation handed out. In
398 this way simple buffer overruns will be rapidly detected. When
399 memory is freed, the memory is recolored back to the glibc default
400 so that simple use-after-free errors can also be detected.
402 If memory is reallocated the buffer is recolored even if the
403 address remains the same. This has a performance impact, but
404 guarantees that the old pointer cannot mistakenly be reused (code
405 that compares old against new will see a mismatch and will then
406 need to behave as though realloc moved the data to a new location).
408 Internal API for memory tagging support.
410 The aim is to keep the code for memory tagging support as close to
411 the normal APIs in glibc as possible, so that if tagging is not
412 enabled in the library, or is disabled at runtime then standard
413 operations can continue to be used. Support macros are used to do
414 this:
416 void *TAG_NEW_MEMSET (void *ptr, int, val, size_t size)
418 Has the same interface as memset(), but additionally allocates a
419 new tag, colors the memory with that tag and returns a pointer that
420 is correctly colored for that location. The non-tagging version
421 will simply call memset.
423 void *TAG_REGION (void *ptr, size_t size)
425 Color the region of memory pointed to by PTR and size SIZE with
426 the color of PTR. Returns the original pointer.
428 void *TAG_NEW_USABLE (void *ptr)
430 Allocate a new random color and use it to color the user region of
431 a chunk; this may include data from the subsequent chunk's header
432 if tagging is sufficiently fine grained. Returns PTR suitably
433 recolored for accessing the memory there.
435 void *TAG_AT (void *ptr)
437 Read the current color of the memory at the address pointed to by
438 PTR (ignoring it's current color) and return PTR recolored to that
439 color. PTR must be valid address in all other respects. When
440 tagging is not enabled, it simply returns the original pointer.
443 #ifdef USE_MTAG
445 /* Default implementaions when memory tagging is supported, but disabled. */
446 static void *
447 __default_tag_region (void *ptr, size_t size)
449 return ptr;
452 static void *
453 __default_tag_nop (void *ptr)
455 return ptr;
458 static int __mtag_mmap_flags = 0;
459 static size_t __mtag_granule_mask = ~(size_t)0;
461 static void *(*__tag_new_memset)(void *, int, size_t) = memset;
462 static void *(*__tag_region)(void *, size_t) = __default_tag_region;
463 static void *(*__tag_new_usable)(void *) = __default_tag_nop;
464 static void *(*__tag_at)(void *) = __default_tag_nop;
466 # define MTAG_MMAP_FLAGS __mtag_mmap_flags
467 # define TAG_NEW_MEMSET(ptr, val, size) __tag_new_memset (ptr, val, size)
468 # define TAG_REGION(ptr, size) __tag_region (ptr, size)
469 # define TAG_NEW_USABLE(ptr) __tag_new_usable (ptr)
470 # define TAG_AT(ptr) __tag_at (ptr)
471 #else
472 # define MTAG_MMAP_FLAGS 0
473 # define TAG_NEW_MEMSET(ptr, val, size) memset (ptr, val, size)
474 # define TAG_REGION(ptr, size) (ptr)
475 # define TAG_NEW_USABLE(ptr) (ptr)
476 # define TAG_AT(ptr) (ptr)
477 #endif
479 #include <string.h>
482 MORECORE-related declarations. By default, rely on sbrk
487 MORECORE is the name of the routine to call to obtain more memory
488 from the system. See below for general guidance on writing
489 alternative MORECORE functions, as well as a version for WIN32 and a
490 sample version for pre-OSX macos.
493 #ifndef MORECORE
494 #define MORECORE sbrk
495 #endif
498 MORECORE_FAILURE is the value returned upon failure of MORECORE
499 as well as mmap. Since it cannot be an otherwise valid memory address,
500 and must reflect values of standard sys calls, you probably ought not
501 try to redefine it.
504 #ifndef MORECORE_FAILURE
505 #define MORECORE_FAILURE (-1)
506 #endif
509 If MORECORE_CONTIGUOUS is true, take advantage of fact that
510 consecutive calls to MORECORE with positive arguments always return
511 contiguous increasing addresses. This is true of unix sbrk. Even
512 if not defined, when regions happen to be contiguous, malloc will
513 permit allocations spanning regions obtained from different
514 calls. But defining this when applicable enables some stronger
515 consistency checks and space efficiencies.
518 #ifndef MORECORE_CONTIGUOUS
519 #define MORECORE_CONTIGUOUS 1
520 #endif
523 Define MORECORE_CANNOT_TRIM if your version of MORECORE
524 cannot release space back to the system when given negative
525 arguments. This is generally necessary only if you are using
526 a hand-crafted MORECORE function that cannot handle negative arguments.
529 /* #define MORECORE_CANNOT_TRIM */
531 /* MORECORE_CLEARS (default 1)
532 The degree to which the routine mapped to MORECORE zeroes out
533 memory: never (0), only for newly allocated space (1) or always
534 (2). The distinction between (1) and (2) is necessary because on
535 some systems, if the application first decrements and then
536 increments the break value, the contents of the reallocated space
537 are unspecified.
540 #ifndef MORECORE_CLEARS
541 # define MORECORE_CLEARS 1
542 #endif
546 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
547 sbrk fails, and mmap is used as a backup. The value must be a
548 multiple of page size. This backup strategy generally applies only
549 when systems have "holes" in address space, so sbrk cannot perform
550 contiguous expansion, but there is still space available on system.
551 On systems for which this is known to be useful (i.e. most linux
552 kernels), this occurs only when programs allocate huge amounts of
553 memory. Between this, and the fact that mmap regions tend to be
554 limited, the size should be large, to avoid too many mmap calls and
555 thus avoid running out of kernel resources. */
557 #ifndef MMAP_AS_MORECORE_SIZE
558 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
559 #endif
562 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
563 large blocks.
566 #ifndef HAVE_MREMAP
567 #define HAVE_MREMAP 0
568 #endif
570 /* We may need to support __malloc_initialize_hook for backwards
571 compatibility. */
573 #if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_24)
574 # define HAVE_MALLOC_INIT_HOOK 1
575 #else
576 # define HAVE_MALLOC_INIT_HOOK 0
577 #endif
581 This version of malloc supports the standard SVID/XPG mallinfo
582 routine that returns a struct containing usage properties and
583 statistics. It should work on any SVID/XPG compliant system that has
584 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
585 install such a thing yourself, cut out the preliminary declarations
586 as described above and below and save them in a malloc.h file. But
587 there's no compelling reason to bother to do this.)
589 The main declaration needed is the mallinfo struct that is returned
590 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
591 bunch of fields that are not even meaningful in this version of
592 malloc. These fields are are instead filled by mallinfo() with
593 other numbers that might be of interest.
597 /* ---------- description of public routines ------------ */
600 malloc(size_t n)
601 Returns a pointer to a newly allocated chunk of at least n bytes, or null
602 if no space is available. Additionally, on failure, errno is
603 set to ENOMEM on ANSI C systems.
605 If n is zero, malloc returns a minimum-sized chunk. (The minimum
606 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
607 systems.) On most systems, size_t is an unsigned type, so calls
608 with negative arguments are interpreted as requests for huge amounts
609 of space, which will often fail. The maximum supported value of n
610 differs across systems, but is in all cases less than the maximum
611 representable value of a size_t.
613 void* __libc_malloc(size_t);
614 libc_hidden_proto (__libc_malloc)
617 free(void* p)
618 Releases the chunk of memory pointed to by p, that had been previously
619 allocated using malloc or a related routine such as realloc.
620 It has no effect if p is null. It can have arbitrary (i.e., bad!)
621 effects if p has already been freed.
623 Unless disabled (using mallopt), freeing very large spaces will
624 when possible, automatically trigger operations that give
625 back unused memory to the system, thus reducing program footprint.
627 void __libc_free(void*);
628 libc_hidden_proto (__libc_free)
631 calloc(size_t n_elements, size_t element_size);
632 Returns a pointer to n_elements * element_size bytes, with all locations
633 set to zero.
635 void* __libc_calloc(size_t, size_t);
638 realloc(void* p, size_t n)
639 Returns a pointer to a chunk of size n that contains the same data
640 as does chunk p up to the minimum of (n, p's size) bytes, or null
641 if no space is available.
643 The returned pointer may or may not be the same as p. The algorithm
644 prefers extending p when possible, otherwise it employs the
645 equivalent of a malloc-copy-free sequence.
647 If p is null, realloc is equivalent to malloc.
649 If space is not available, realloc returns null, errno is set (if on
650 ANSI) and p is NOT freed.
652 if n is for fewer bytes than already held by p, the newly unused
653 space is lopped off and freed if possible. Unless the #define
654 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
655 zero (re)allocates a minimum-sized chunk.
657 Large chunks that were internally obtained via mmap will always be
658 grown using malloc-copy-free sequences unless the system supports
659 MREMAP (currently only linux).
661 The old unix realloc convention of allowing the last-free'd chunk
662 to be used as an argument to realloc is not supported.
664 void* __libc_realloc(void*, size_t);
665 libc_hidden_proto (__libc_realloc)
668 memalign(size_t alignment, size_t n);
669 Returns a pointer to a newly allocated chunk of n bytes, aligned
670 in accord with the alignment argument.
672 The alignment argument should be a power of two. If the argument is
673 not a power of two, the nearest greater power is used.
674 8-byte alignment is guaranteed by normal malloc calls, so don't
675 bother calling memalign with an argument of 8 or less.
677 Overreliance on memalign is a sure way to fragment space.
679 void* __libc_memalign(size_t, size_t);
680 libc_hidden_proto (__libc_memalign)
683 valloc(size_t n);
684 Equivalent to memalign(pagesize, n), where pagesize is the page
685 size of the system. If the pagesize is unknown, 4096 is used.
687 void* __libc_valloc(size_t);
692 mallopt(int parameter_number, int parameter_value)
693 Sets tunable parameters The format is to provide a
694 (parameter-number, parameter-value) pair. mallopt then sets the
695 corresponding parameter to the argument value if it can (i.e., so
696 long as the value is meaningful), and returns 1 if successful else
697 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
698 normally defined in malloc.h. Only one of these (M_MXFAST) is used
699 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
700 so setting them has no effect. But this malloc also supports four
701 other options in mallopt. See below for details. Briefly, supported
702 parameters are as follows (listed defaults are for "typical"
703 configurations).
705 Symbol param # default allowed param values
706 M_MXFAST 1 64 0-80 (0 disables fastbins)
707 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
708 M_TOP_PAD -2 0 any
709 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
710 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
712 int __libc_mallopt(int, int);
713 libc_hidden_proto (__libc_mallopt)
717 mallinfo()
718 Returns (by copy) a struct containing various summary statistics:
720 arena: current total non-mmapped bytes allocated from system
721 ordblks: the number of free chunks
722 smblks: the number of fastbin blocks (i.e., small chunks that
723 have been freed but not use resused or consolidated)
724 hblks: current number of mmapped regions
725 hblkhd: total bytes held in mmapped regions
726 usmblks: always 0
727 fsmblks: total bytes held in fastbin blocks
728 uordblks: current total allocated space (normal or mmapped)
729 fordblks: total free space
730 keepcost: the maximum number of bytes that could ideally be released
731 back to system via malloc_trim. ("ideally" means that
732 it ignores page restrictions etc.)
734 Because these fields are ints, but internal bookkeeping may
735 be kept as longs, the reported values may wrap around zero and
736 thus be inaccurate.
738 struct mallinfo2 __libc_mallinfo2(void);
739 libc_hidden_proto (__libc_mallinfo2)
741 struct mallinfo __libc_mallinfo(void);
745 pvalloc(size_t n);
746 Equivalent to valloc(minimum-page-that-holds(n)), that is,
747 round up n to nearest pagesize.
749 void* __libc_pvalloc(size_t);
752 malloc_trim(size_t pad);
754 If possible, gives memory back to the system (via negative
755 arguments to sbrk) if there is unused memory at the `high' end of
756 the malloc pool. You can call this after freeing large blocks of
757 memory to potentially reduce the system-level memory requirements
758 of a program. However, it cannot guarantee to reduce memory. Under
759 some allocation patterns, some large free blocks of memory will be
760 locked between two used chunks, so they cannot be given back to
761 the system.
763 The `pad' argument to malloc_trim represents the amount of free
764 trailing space to leave untrimmed. If this argument is zero,
765 only the minimum amount of memory to maintain internal data
766 structures will be left (one page or less). Non-zero arguments
767 can be supplied to maintain enough trailing space to service
768 future expected allocations without having to re-obtain memory
769 from the system.
771 Malloc_trim returns 1 if it actually released any memory, else 0.
772 On systems that do not support "negative sbrks", it will always
773 return 0.
775 int __malloc_trim(size_t);
778 malloc_usable_size(void* p);
780 Returns the number of bytes you can actually use in
781 an allocated chunk, which may be more than you requested (although
782 often not) due to alignment and minimum size constraints.
783 You can use this many bytes without worrying about
784 overwriting other allocated objects. This is not a particularly great
785 programming practice. malloc_usable_size can be more useful in
786 debugging and assertions, for example:
788 p = malloc(n);
789 assert(malloc_usable_size(p) >= 256);
792 size_t __malloc_usable_size(void*);
795 malloc_stats();
796 Prints on stderr the amount of space obtained from the system (both
797 via sbrk and mmap), the maximum amount (which may be more than
798 current if malloc_trim and/or munmap got called), and the current
799 number of bytes allocated via malloc (or realloc, etc) but not yet
800 freed. Note that this is the number of bytes allocated, not the
801 number requested. It will be larger than the number requested
802 because of alignment and bookkeeping overhead. Because it includes
803 alignment wastage as being in use, this figure may be greater than
804 zero even when no user-level chunks are allocated.
806 The reported current and maximum system memory can be inaccurate if
807 a program makes other calls to system memory allocation functions
808 (normally sbrk) outside of malloc.
810 malloc_stats prints only the most commonly interesting statistics.
811 More information can be obtained by calling mallinfo.
814 void __malloc_stats(void);
817 posix_memalign(void **memptr, size_t alignment, size_t size);
819 POSIX wrapper like memalign(), checking for validity of size.
821 int __posix_memalign(void **, size_t, size_t);
823 /* mallopt tuning options */
826 M_MXFAST is the maximum request size used for "fastbins", special bins
827 that hold returned chunks without consolidating their spaces. This
828 enables future requests for chunks of the same size to be handled
829 very quickly, but can increase fragmentation, and thus increase the
830 overall memory footprint of a program.
832 This malloc manages fastbins very conservatively yet still
833 efficiently, so fragmentation is rarely a problem for values less
834 than or equal to the default. The maximum supported value of MXFAST
835 is 80. You wouldn't want it any higher than this anyway. Fastbins
836 are designed especially for use with many small structs, objects or
837 strings -- the default handles structs/objects/arrays with sizes up
838 to 8 4byte fields, or small strings representing words, tokens,
839 etc. Using fastbins for larger objects normally worsens
840 fragmentation without improving speed.
842 M_MXFAST is set in REQUEST size units. It is internally used in
843 chunksize units, which adds padding and alignment. You can reduce
844 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
845 algorithm to be a closer approximation of fifo-best-fit in all cases,
846 not just for larger requests, but will generally cause it to be
847 slower.
851 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
852 #ifndef M_MXFAST
853 #define M_MXFAST 1
854 #endif
856 #ifndef DEFAULT_MXFAST
857 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
858 #endif
862 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
863 to keep before releasing via malloc_trim in free().
865 Automatic trimming is mainly useful in long-lived programs.
866 Because trimming via sbrk can be slow on some systems, and can
867 sometimes be wasteful (in cases where programs immediately
868 afterward allocate more large chunks) the value should be high
869 enough so that your overall system performance would improve by
870 releasing this much memory.
872 The trim threshold and the mmap control parameters (see below)
873 can be traded off with one another. Trimming and mmapping are
874 two different ways of releasing unused memory back to the
875 system. Between these two, it is often possible to keep
876 system-level demands of a long-lived program down to a bare
877 minimum. For example, in one test suite of sessions measuring
878 the XF86 X server on Linux, using a trim threshold of 128K and a
879 mmap threshold of 192K led to near-minimal long term resource
880 consumption.
882 If you are using this malloc in a long-lived program, it should
883 pay to experiment with these values. As a rough guide, you
884 might set to a value close to the average size of a process
885 (program) running on your system. Releasing this much memory
886 would allow such a process to run in memory. Generally, it's
887 worth it to tune for trimming rather tham memory mapping when a
888 program undergoes phases where several large chunks are
889 allocated and released in ways that can reuse each other's
890 storage, perhaps mixed with phases where there are no such
891 chunks at all. And in well-behaved long-lived programs,
892 controlling release of large blocks via trimming versus mapping
893 is usually faster.
895 However, in most programs, these parameters serve mainly as
896 protection against the system-level effects of carrying around
897 massive amounts of unneeded memory. Since frequent calls to
898 sbrk, mmap, and munmap otherwise degrade performance, the default
899 parameters are set to relatively high values that serve only as
900 safeguards.
902 The trim value It must be greater than page size to have any useful
903 effect. To disable trimming completely, you can set to
904 (unsigned long)(-1)
906 Trim settings interact with fastbin (MXFAST) settings: Unless
907 TRIM_FASTBINS is defined, automatic trimming never takes place upon
908 freeing a chunk with size less than or equal to MXFAST. Trimming is
909 instead delayed until subsequent freeing of larger chunks. However,
910 you can still force an attempted trim by calling malloc_trim.
912 Also, trimming is not generally possible in cases where
913 the main arena is obtained via mmap.
915 Note that the trick some people use of mallocing a huge space and
916 then freeing it at program startup, in an attempt to reserve system
917 memory, doesn't have the intended effect under automatic trimming,
918 since that memory will immediately be returned to the system.
921 #define M_TRIM_THRESHOLD -1
923 #ifndef DEFAULT_TRIM_THRESHOLD
924 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
925 #endif
928 M_TOP_PAD is the amount of extra `padding' space to allocate or
929 retain whenever sbrk is called. It is used in two ways internally:
931 * When sbrk is called to extend the top of the arena to satisfy
932 a new malloc request, this much padding is added to the sbrk
933 request.
935 * When malloc_trim is called automatically from free(),
936 it is used as the `pad' argument.
938 In both cases, the actual amount of padding is rounded
939 so that the end of the arena is always a system page boundary.
941 The main reason for using padding is to avoid calling sbrk so
942 often. Having even a small pad greatly reduces the likelihood
943 that nearly every malloc request during program start-up (or
944 after trimming) will invoke sbrk, which needlessly wastes
945 time.
947 Automatic rounding-up to page-size units is normally sufficient
948 to avoid measurable overhead, so the default is 0. However, in
949 systems where sbrk is relatively slow, it can pay to increase
950 this value, at the expense of carrying around more memory than
951 the program needs.
954 #define M_TOP_PAD -2
956 #ifndef DEFAULT_TOP_PAD
957 #define DEFAULT_TOP_PAD (0)
958 #endif
961 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
962 adjusted MMAP_THRESHOLD.
965 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
966 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
967 #endif
969 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
970 /* For 32-bit platforms we cannot increase the maximum mmap
971 threshold much because it is also the minimum value for the
972 maximum heap size and its alignment. Going above 512k (i.e., 1M
973 for new heaps) wastes too much address space. */
974 # if __WORDSIZE == 32
975 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
976 # else
977 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
978 # endif
979 #endif
982 M_MMAP_THRESHOLD is the request size threshold for using mmap()
983 to service a request. Requests of at least this size that cannot
984 be allocated using already-existing space will be serviced via mmap.
985 (If enough normal freed space already exists it is used instead.)
987 Using mmap segregates relatively large chunks of memory so that
988 they can be individually obtained and released from the host
989 system. A request serviced through mmap is never reused by any
990 other request (at least not directly; the system may just so
991 happen to remap successive requests to the same locations).
993 Segregating space in this way has the benefits that:
995 1. Mmapped space can ALWAYS be individually released back
996 to the system, which helps keep the system level memory
997 demands of a long-lived program low.
998 2. Mapped memory can never become `locked' between
999 other chunks, as can happen with normally allocated chunks, which
1000 means that even trimming via malloc_trim would not release them.
1001 3. On some systems with "holes" in address spaces, mmap can obtain
1002 memory that sbrk cannot.
1004 However, it has the disadvantages that:
1006 1. The space cannot be reclaimed, consolidated, and then
1007 used to service later requests, as happens with normal chunks.
1008 2. It can lead to more wastage because of mmap page alignment
1009 requirements
1010 3. It causes malloc performance to be more dependent on host
1011 system memory management support routines which may vary in
1012 implementation quality and may impose arbitrary
1013 limitations. Generally, servicing a request via normal
1014 malloc steps is faster than going through a system's mmap.
1016 The advantages of mmap nearly always outweigh disadvantages for
1017 "large" chunks, but the value of "large" varies across systems. The
1018 default is an empirically derived value that works well in most
1019 systems.
1022 Update in 2006:
1023 The above was written in 2001. Since then the world has changed a lot.
1024 Memory got bigger. Applications got bigger. The virtual address space
1025 layout in 32 bit linux changed.
1027 In the new situation, brk() and mmap space is shared and there are no
1028 artificial limits on brk size imposed by the kernel. What is more,
1029 applications have started using transient allocations larger than the
1030 128Kb as was imagined in 2001.
1032 The price for mmap is also high now; each time glibc mmaps from the
1033 kernel, the kernel is forced to zero out the memory it gives to the
1034 application. Zeroing memory is expensive and eats a lot of cache and
1035 memory bandwidth. This has nothing to do with the efficiency of the
1036 virtual memory system, by doing mmap the kernel just has no choice but
1037 to zero.
1039 In 2001, the kernel had a maximum size for brk() which was about 800
1040 megabytes on 32 bit x86, at that point brk() would hit the first
1041 mmaped shared libaries and couldn't expand anymore. With current 2.6
1042 kernels, the VA space layout is different and brk() and mmap
1043 both can span the entire heap at will.
1045 Rather than using a static threshold for the brk/mmap tradeoff,
1046 we are now using a simple dynamic one. The goal is still to avoid
1047 fragmentation. The old goals we kept are
1048 1) try to get the long lived large allocations to use mmap()
1049 2) really large allocations should always use mmap()
1050 and we're adding now:
1051 3) transient allocations should use brk() to avoid forcing the kernel
1052 having to zero memory over and over again
1054 The implementation works with a sliding threshold, which is by default
1055 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
1056 out at 128Kb as per the 2001 default.
1058 This allows us to satisfy requirement 1) under the assumption that long
1059 lived allocations are made early in the process' lifespan, before it has
1060 started doing dynamic allocations of the same size (which will
1061 increase the threshold).
1063 The upperbound on the threshold satisfies requirement 2)
1065 The threshold goes up in value when the application frees memory that was
1066 allocated with the mmap allocator. The idea is that once the application
1067 starts freeing memory of a certain size, it's highly probable that this is
1068 a size the application uses for transient allocations. This estimator
1069 is there to satisfy the new third requirement.
1073 #define M_MMAP_THRESHOLD -3
1075 #ifndef DEFAULT_MMAP_THRESHOLD
1076 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1077 #endif
1080 M_MMAP_MAX is the maximum number of requests to simultaneously
1081 service using mmap. This parameter exists because
1082 some systems have a limited number of internal tables for
1083 use by mmap, and using more than a few of them may degrade
1084 performance.
1086 The default is set to a value that serves only as a safeguard.
1087 Setting to 0 disables use of mmap for servicing large requests.
1090 #define M_MMAP_MAX -4
1092 #ifndef DEFAULT_MMAP_MAX
1093 #define DEFAULT_MMAP_MAX (65536)
1094 #endif
1096 #include <malloc.h>
1098 #ifndef RETURN_ADDRESS
1099 #define RETURN_ADDRESS(X_) (NULL)
1100 #endif
1102 /* Forward declarations. */
1103 struct malloc_chunk;
1104 typedef struct malloc_chunk* mchunkptr;
1106 /* Internal routines. */
1108 static void* _int_malloc(mstate, size_t);
1109 static void _int_free(mstate, mchunkptr, int);
1110 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1111 INTERNAL_SIZE_T);
1112 static void* _int_memalign(mstate, size_t, size_t);
1113 static void* _mid_memalign(size_t, size_t, void *);
1115 static void malloc_printerr(const char *str) __attribute__ ((noreturn));
1117 static void* mem2mem_check(void *p, size_t sz);
1118 static void top_check(void);
1119 static void munmap_chunk(mchunkptr p);
1120 #if HAVE_MREMAP
1121 static mchunkptr mremap_chunk(mchunkptr p, size_t new_size);
1122 #endif
1124 static void* malloc_check(size_t sz, const void *caller);
1125 static void free_check(void* mem, const void *caller);
1126 static void* realloc_check(void* oldmem, size_t bytes,
1127 const void *caller);
1128 static void* memalign_check(size_t alignment, size_t bytes,
1129 const void *caller);
1131 /* ------------------ MMAP support ------------------ */
1134 #include <fcntl.h>
1135 #include <sys/mman.h>
1137 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1138 # define MAP_ANONYMOUS MAP_ANON
1139 #endif
1141 #ifndef MAP_NORESERVE
1142 # define MAP_NORESERVE 0
1143 #endif
1145 #define MMAP(addr, size, prot, flags) \
1146 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1150 ----------------------- Chunk representations -----------------------
1155 This struct declaration is misleading (but accurate and necessary).
1156 It declares a "view" into memory allowing access to necessary
1157 fields at known offsets from a given base. See explanation below.
1160 struct malloc_chunk {
1162 INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk (if free). */
1163 INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
1165 struct malloc_chunk* fd; /* double links -- used only if free. */
1166 struct malloc_chunk* bk;
1168 /* Only used for large blocks: pointer to next larger size. */
1169 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1170 struct malloc_chunk* bk_nextsize;
1175 malloc_chunk details:
1177 (The following includes lightly edited explanations by Colin Plumb.)
1179 Chunks of memory are maintained using a `boundary tag' method as
1180 described in e.g., Knuth or Standish. (See the paper by Paul
1181 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1182 survey of such techniques.) Sizes of free chunks are stored both
1183 in the front of each chunk and at the end. This makes
1184 consolidating fragmented chunks into bigger chunks very fast. The
1185 size fields also hold bits representing whether chunks are free or
1186 in use.
1188 An allocated chunk looks like this:
1191 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1192 | Size of previous chunk, if unallocated (P clear) |
1193 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1194 | Size of chunk, in bytes |A|M|P|
1195 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1196 | User data starts here... .
1198 . (malloc_usable_size() bytes) .
1200 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1201 | (size of chunk, but used for application data) |
1202 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1203 | Size of next chunk, in bytes |A|0|1|
1204 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1206 Where "chunk" is the front of the chunk for the purpose of most of
1207 the malloc code, but "mem" is the pointer that is returned to the
1208 user. "Nextchunk" is the beginning of the next contiguous chunk.
1210 Chunks always begin on even word boundaries, so the mem portion
1211 (which is returned to the user) is also on an even word boundary, and
1212 thus at least double-word aligned.
1214 Free chunks are stored in circular doubly-linked lists, and look like this:
1216 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1217 | Size of previous chunk, if unallocated (P clear) |
1218 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1219 `head:' | Size of chunk, in bytes |A|0|P|
1220 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1221 | Forward pointer to next chunk in list |
1222 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1223 | Back pointer to previous chunk in list |
1224 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1225 | Unused space (may be 0 bytes long) .
1228 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1229 `foot:' | Size of chunk, in bytes |
1230 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1231 | Size of next chunk, in bytes |A|0|0|
1232 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1234 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1235 chunk size (which is always a multiple of two words), is an in-use
1236 bit for the *previous* chunk. If that bit is *clear*, then the
1237 word before the current chunk size contains the previous chunk
1238 size, and can be used to find the front of the previous chunk.
1239 The very first chunk allocated always has this bit set,
1240 preventing access to non-existent (or non-owned) memory. If
1241 prev_inuse is set for any given chunk, then you CANNOT determine
1242 the size of the previous chunk, and might even get a memory
1243 addressing fault when trying to do so.
1245 The A (NON_MAIN_ARENA) bit is cleared for chunks on the initial,
1246 main arena, described by the main_arena variable. When additional
1247 threads are spawned, each thread receives its own arena (up to a
1248 configurable limit, after which arenas are reused for multiple
1249 threads), and the chunks in these arenas have the A bit set. To
1250 find the arena for a chunk on such a non-main arena, heap_for_ptr
1251 performs a bit mask operation and indirection through the ar_ptr
1252 member of the per-heap header heap_info (see arena.c).
1254 Note that the `foot' of the current chunk is actually represented
1255 as the prev_size of the NEXT chunk. This makes it easier to
1256 deal with alignments etc but can be very confusing when trying
1257 to extend or adapt this code.
1259 The three exceptions to all this are:
1261 1. The special chunk `top' doesn't bother using the
1262 trailing size field since there is no next contiguous chunk
1263 that would have to index off it. After initialization, `top'
1264 is forced to always exist. If it would become less than
1265 MINSIZE bytes long, it is replenished.
1267 2. Chunks allocated via mmap, which have the second-lowest-order
1268 bit M (IS_MMAPPED) set in their size fields. Because they are
1269 allocated one-by-one, each must contain its own trailing size
1270 field. If the M bit is set, the other bits are ignored
1271 (because mmapped chunks are neither in an arena, nor adjacent
1272 to a freed chunk). The M bit is also used for chunks which
1273 originally came from a dumped heap via malloc_set_state in
1274 hooks.c.
1276 3. Chunks in fastbins are treated as allocated chunks from the
1277 point of view of the chunk allocator. They are consolidated
1278 with their neighbors only in bulk, in malloc_consolidate.
1282 ---------- Size and alignment checks and conversions ----------
1285 /* Conversion from malloc headers to user pointers, and back. When
1286 using memory tagging the user data and the malloc data structure
1287 headers have distinct tags. Converting fully from one to the other
1288 involves extracting the tag at the other address and creating a
1289 suitable pointer using it. That can be quite expensive. There are
1290 many occasions, though when the pointer will not be dereferenced
1291 (for example, because we only want to assert that the pointer is
1292 correctly aligned). In these cases it is more efficient not
1293 to extract the tag, since the answer will be the same either way.
1294 chunk2rawmem() can be used in these cases.
1297 /* The chunk header is two SIZE_SZ elements, but this is used widely, so
1298 we define it here for clarity later. */
1299 #define CHUNK_HDR_SZ (2 * SIZE_SZ)
1301 /* Convert a user mem pointer to a chunk address without correcting
1302 the tag. */
1303 #define chunk2rawmem(p) ((void*)((char*)(p) + CHUNK_HDR_SZ))
1305 /* Convert between user mem pointers and chunk pointers, updating any
1306 memory tags on the pointer to respect the tag value at that
1307 location. */
1308 #define chunk2mem(p) ((void*)TAG_AT (((char*)(p) + CHUNK_HDR_SZ)))
1309 #define mem2chunk(mem) ((mchunkptr)TAG_AT (((char*)(mem) - CHUNK_HDR_SZ)))
1311 /* The smallest possible chunk */
1312 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1314 /* The smallest size we can malloc is an aligned minimal chunk */
1316 #define MINSIZE \
1317 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1319 /* Check if m has acceptable alignment */
1321 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1323 #define misaligned_chunk(p) \
1324 ((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \
1325 & MALLOC_ALIGN_MASK)
1327 /* pad request bytes into a usable size -- internal version */
1328 /* Note: This must be a macro that evaluates to a compile time constant
1329 if passed a literal constant. */
1330 #define request2size(req) \
1331 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1332 MINSIZE : \
1333 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1335 /* Available size of chunk. This is the size of the real usable data
1336 in the chunk, plus the chunk header. */
1337 #ifdef USE_MTAG
1338 #define CHUNK_AVAILABLE_SIZE(p) \
1339 ((chunksize (p) + (chunk_is_mmapped (p) ? 0 : SIZE_SZ)) \
1340 & __mtag_granule_mask)
1341 #else
1342 #define CHUNK_AVAILABLE_SIZE(p) \
1343 (chunksize (p) + (chunk_is_mmapped (p) ? 0 : SIZE_SZ))
1344 #endif
1346 /* Check if REQ overflows when padded and aligned and if the resulting value
1347 is less than PTRDIFF_T. Returns TRUE and the requested size or MINSIZE in
1348 case the value is less than MINSIZE on SZ or false if any of the previous
1349 check fail. */
1350 static inline bool
1351 checked_request2size (size_t req, size_t *sz) __nonnull (1)
1353 if (__glibc_unlikely (req > PTRDIFF_MAX))
1354 return false;
1356 #ifdef USE_MTAG
1357 /* When using tagged memory, we cannot share the end of the user
1358 block with the header for the next chunk, so ensure that we
1359 allocate blocks that are rounded up to the granule size. Take
1360 care not to overflow from close to MAX_SIZE_T to a small
1361 number. Ideally, this would be part of request2size(), but that
1362 must be a macro that produces a compile time constant if passed
1363 a constant literal. */
1364 req = (req + ~__mtag_granule_mask) & __mtag_granule_mask;
1365 #endif
1367 *sz = request2size (req);
1368 return true;
1372 --------------- Physical chunk operations ---------------
1376 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1377 #define PREV_INUSE 0x1
1379 /* extract inuse bit of previous chunk */
1380 #define prev_inuse(p) ((p)->mchunk_size & PREV_INUSE)
1383 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1384 #define IS_MMAPPED 0x2
1386 /* check for mmap()'ed chunk */
1387 #define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)
1390 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1391 from a non-main arena. This is only set immediately before handing
1392 the chunk to the user, if necessary. */
1393 #define NON_MAIN_ARENA 0x4
1395 /* Check for chunk from main arena. */
1396 #define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)
1398 /* Mark a chunk as not being on the main arena. */
1399 #define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
1403 Bits to mask off when extracting size
1405 Note: IS_MMAPPED is intentionally not masked off from size field in
1406 macros for which mmapped chunks should never be seen. This should
1407 cause helpful core dumps to occur if it is tried by accident by
1408 people extending or adapting this malloc.
1410 #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1412 /* Get size, ignoring use bits */
1413 #define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))
1415 /* Like chunksize, but do not mask SIZE_BITS. */
1416 #define chunksize_nomask(p) ((p)->mchunk_size)
1418 /* Ptr to next physical malloc_chunk. */
1419 #define next_chunk(p) ((mchunkptr) (((char *) (p)) + chunksize (p)))
1421 /* Size of the chunk below P. Only valid if !prev_inuse (P). */
1422 #define prev_size(p) ((p)->mchunk_prev_size)
1424 /* Set the size of the chunk below P. Only valid if !prev_inuse (P). */
1425 #define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))
1427 /* Ptr to previous physical malloc_chunk. Only valid if !prev_inuse (P). */
1428 #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - prev_size (p)))
1430 /* Treat space at ptr + offset as a chunk */
1431 #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1433 /* extract p's inuse bit */
1434 #define inuse(p) \
1435 ((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
1437 /* set/clear chunk as being inuse without otherwise disturbing */
1438 #define set_inuse(p) \
1439 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
1441 #define clear_inuse(p) \
1442 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
1445 /* check/set/clear inuse bits in known places */
1446 #define inuse_bit_at_offset(p, s) \
1447 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
1449 #define set_inuse_bit_at_offset(p, s) \
1450 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
1452 #define clear_inuse_bit_at_offset(p, s) \
1453 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
1456 /* Set size at head, without disturbing its use bit */
1457 #define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
1459 /* Set size/use field */
1460 #define set_head(p, s) ((p)->mchunk_size = (s))
1462 /* Set size at footer (only when chunk is not in use) */
1463 #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
1465 #pragma GCC poison mchunk_size
1466 #pragma GCC poison mchunk_prev_size
1469 -------------------- Internal data structures --------------------
1471 All internal state is held in an instance of malloc_state defined
1472 below. There are no other static variables, except in two optional
1473 cases:
1474 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1475 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1476 for mmap.
1478 Beware of lots of tricks that minimize the total bookkeeping space
1479 requirements. The result is a little over 1K bytes (for 4byte
1480 pointers and size_t.)
1484 Bins
1486 An array of bin headers for free chunks. Each bin is doubly
1487 linked. The bins are approximately proportionally (log) spaced.
1488 There are a lot of these bins (128). This may look excessive, but
1489 works very well in practice. Most bins hold sizes that are
1490 unusual as malloc request sizes, but are more usual for fragments
1491 and consolidated sets of chunks, which is what these bins hold, so
1492 they can be found quickly. All procedures maintain the invariant
1493 that no consolidated chunk physically borders another one, so each
1494 chunk in a list is known to be preceeded and followed by either
1495 inuse chunks or the ends of memory.
1497 Chunks in bins are kept in size order, with ties going to the
1498 approximately least recently used chunk. Ordering isn't needed
1499 for the small bins, which all contain the same-sized chunks, but
1500 facilitates best-fit allocation for larger chunks. These lists
1501 are just sequential. Keeping them in order almost never requires
1502 enough traversal to warrant using fancier ordered data
1503 structures.
1505 Chunks of the same size are linked with the most
1506 recently freed at the front, and allocations are taken from the
1507 back. This results in LRU (FIFO) allocation order, which tends
1508 to give each chunk an equal opportunity to be consolidated with
1509 adjacent freed chunks, resulting in larger free chunks and less
1510 fragmentation.
1512 To simplify use in double-linked lists, each bin header acts
1513 as a malloc_chunk. This avoids special-casing for headers.
1514 But to conserve space and improve locality, we allocate
1515 only the fd/bk pointers of bins, and then use repositioning tricks
1516 to treat these as the fields of a malloc_chunk*.
1519 typedef struct malloc_chunk *mbinptr;
1521 /* addressing -- note that bin_at(0) does not exist */
1522 #define bin_at(m, i) \
1523 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1524 - offsetof (struct malloc_chunk, fd))
1526 /* analog of ++bin */
1527 #define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
1529 /* Reminders about list directionality within bins */
1530 #define first(b) ((b)->fd)
1531 #define last(b) ((b)->bk)
1534 Indexing
1536 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1537 8 bytes apart. Larger bins are approximately logarithmically spaced:
1539 64 bins of size 8
1540 32 bins of size 64
1541 16 bins of size 512
1542 8 bins of size 4096
1543 4 bins of size 32768
1544 2 bins of size 262144
1545 1 bin of size what's left
1547 There is actually a little bit of slop in the numbers in bin_index
1548 for the sake of speed. This makes no difference elsewhere.
1550 The bins top out around 1MB because we expect to service large
1551 requests via mmap.
1553 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1554 a valid chunk size the small bins are bumped up one.
1557 #define NBINS 128
1558 #define NSMALLBINS 64
1559 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1560 #define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > CHUNK_HDR_SZ)
1561 #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
1563 #define in_smallbin_range(sz) \
1564 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
1566 #define smallbin_index(sz) \
1567 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
1568 + SMALLBIN_CORRECTION)
1570 #define largebin_index_32(sz) \
1571 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1572 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1573 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1574 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1575 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1576 126)
1578 #define largebin_index_32_big(sz) \
1579 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1580 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1581 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1582 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1583 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1584 126)
1586 // XXX It remains to be seen whether it is good to keep the widths of
1587 // XXX the buckets the same or whether it should be scaled by a factor
1588 // XXX of two as well.
1589 #define largebin_index_64(sz) \
1590 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1591 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1592 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1593 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1594 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1595 126)
1597 #define largebin_index(sz) \
1598 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1599 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1600 : largebin_index_32 (sz))
1602 #define bin_index(sz) \
1603 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
1605 /* Take a chunk off a bin list. */
1606 static void
1607 unlink_chunk (mstate av, mchunkptr p)
1609 if (chunksize (p) != prev_size (next_chunk (p)))
1610 malloc_printerr ("corrupted size vs. prev_size");
1612 mchunkptr fd = p->fd;
1613 mchunkptr bk = p->bk;
1615 if (__builtin_expect (fd->bk != p || bk->fd != p, 0))
1616 malloc_printerr ("corrupted double-linked list");
1618 fd->bk = bk;
1619 bk->fd = fd;
1620 if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL)
1622 if (p->fd_nextsize->bk_nextsize != p
1623 || p->bk_nextsize->fd_nextsize != p)
1624 malloc_printerr ("corrupted double-linked list (not small)");
1626 if (fd->fd_nextsize == NULL)
1628 if (p->fd_nextsize == p)
1629 fd->fd_nextsize = fd->bk_nextsize = fd;
1630 else
1632 fd->fd_nextsize = p->fd_nextsize;
1633 fd->bk_nextsize = p->bk_nextsize;
1634 p->fd_nextsize->bk_nextsize = fd;
1635 p->bk_nextsize->fd_nextsize = fd;
1638 else
1640 p->fd_nextsize->bk_nextsize = p->bk_nextsize;
1641 p->bk_nextsize->fd_nextsize = p->fd_nextsize;
1647 Unsorted chunks
1649 All remainders from chunk splits, as well as all returned chunks,
1650 are first placed in the "unsorted" bin. They are then placed
1651 in regular bins after malloc gives them ONE chance to be used before
1652 binning. So, basically, the unsorted_chunks list acts as a queue,
1653 with chunks being placed on it in free (and malloc_consolidate),
1654 and taken off (to be either used or placed in bins) in malloc.
1656 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1657 does not have to be taken into account in size comparisons.
1660 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1661 #define unsorted_chunks(M) (bin_at (M, 1))
1666 The top-most available chunk (i.e., the one bordering the end of
1667 available memory) is treated specially. It is never included in
1668 any bin, is used only if no other chunk is available, and is
1669 released back to the system if it is very large (see
1670 M_TRIM_THRESHOLD). Because top initially
1671 points to its own bin with initial zero size, thus forcing
1672 extension on the first malloc request, we avoid having any special
1673 code in malloc to check whether it even exists yet. But we still
1674 need to do so when getting memory from system, so we make
1675 initial_top treat the bin as a legal but unusable chunk during the
1676 interval between initialization and the first call to
1677 sysmalloc. (This is somewhat delicate, since it relies on
1678 the 2 preceding words to be zero during this interval as well.)
1681 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1682 #define initial_top(M) (unsorted_chunks (M))
1685 Binmap
1687 To help compensate for the large number of bins, a one-level index
1688 structure is used for bin-by-bin searching. `binmap' is a
1689 bitvector recording whether bins are definitely empty so they can
1690 be skipped over during during traversals. The bits are NOT always
1691 cleared as soon as bins are empty, but instead only
1692 when they are noticed to be empty during traversal in malloc.
1695 /* Conservatively use 32 bits per map word, even if on 64bit system */
1696 #define BINMAPSHIFT 5
1697 #define BITSPERMAP (1U << BINMAPSHIFT)
1698 #define BINMAPSIZE (NBINS / BITSPERMAP)
1700 #define idx2block(i) ((i) >> BINMAPSHIFT)
1701 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
1703 #define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1704 #define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1705 #define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
1708 Fastbins
1710 An array of lists holding recently freed small chunks. Fastbins
1711 are not doubly linked. It is faster to single-link them, and
1712 since chunks are never removed from the middles of these lists,
1713 double linking is not necessary. Also, unlike regular bins, they
1714 are not even processed in FIFO order (they use faster LIFO) since
1715 ordering doesn't much matter in the transient contexts in which
1716 fastbins are normally used.
1718 Chunks in fastbins keep their inuse bit set, so they cannot
1719 be consolidated with other free chunks. malloc_consolidate
1720 releases all chunks in fastbins and consolidates them with
1721 other free chunks.
1724 typedef struct malloc_chunk *mfastbinptr;
1725 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1727 /* offset 2 to use otherwise unindexable first 2 bins */
1728 #define fastbin_index(sz) \
1729 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1732 /* The maximum fastbin request size we support */
1733 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1735 #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
1738 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1739 that triggers automatic consolidation of possibly-surrounding
1740 fastbin chunks. This is a heuristic, so the exact value should not
1741 matter too much. It is defined at half the default trim threshold as a
1742 compromise heuristic to only attempt consolidation if it is likely
1743 to lead to trimming. However, it is not dynamically tunable, since
1744 consolidation reduces fragmentation surrounding large chunks even
1745 if trimming is not used.
1748 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1751 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1752 regions. Otherwise, contiguity is exploited in merging together,
1753 when possible, results from consecutive MORECORE calls.
1755 The initial value comes from MORECORE_CONTIGUOUS, but is
1756 changed dynamically if mmap is ever used as an sbrk substitute.
1759 #define NONCONTIGUOUS_BIT (2U)
1761 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1762 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1763 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1764 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1766 /* Maximum size of memory handled in fastbins. */
1767 static INTERNAL_SIZE_T global_max_fast;
1770 Set value of max_fast.
1771 Use impossibly small value if 0.
1772 Precondition: there are no existing fastbin chunks in the main arena.
1773 Since do_check_malloc_state () checks this, we call malloc_consolidate ()
1774 before changing max_fast. Note other arenas will leak their fast bin
1775 entries if max_fast is reduced.
1778 #define set_max_fast(s) \
1779 global_max_fast = (((size_t) (s) <= MALLOC_ALIGN_MASK - SIZE_SZ) \
1780 ? MIN_CHUNK_SIZE / 2 : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1782 static inline INTERNAL_SIZE_T
1783 get_max_fast (void)
1785 /* Tell the GCC optimizers that global_max_fast is never larger
1786 than MAX_FAST_SIZE. This avoids out-of-bounds array accesses in
1787 _int_malloc after constant propagation of the size parameter.
1788 (The code never executes because malloc preserves the
1789 global_max_fast invariant, but the optimizers may not recognize
1790 this.) */
1791 if (global_max_fast > MAX_FAST_SIZE)
1792 __builtin_unreachable ();
1793 return global_max_fast;
1797 ----------- Internal state representation and initialization -----------
1801 have_fastchunks indicates that there are probably some fastbin chunks.
1802 It is set true on entering a chunk into any fastbin, and cleared early in
1803 malloc_consolidate. The value is approximate since it may be set when there
1804 are no fastbin chunks, or it may be clear even if there are fastbin chunks
1805 available. Given it's sole purpose is to reduce number of redundant calls to
1806 malloc_consolidate, it does not affect correctness. As a result we can safely
1807 use relaxed atomic accesses.
1811 struct malloc_state
1813 /* Serialize access. */
1814 __libc_lock_define (, mutex);
1816 /* Flags (formerly in max_fast). */
1817 int flags;
1819 /* Set if the fastbin chunks contain recently inserted free blocks. */
1820 /* Note this is a bool but not all targets support atomics on booleans. */
1821 int have_fastchunks;
1823 /* Fastbins */
1824 mfastbinptr fastbinsY[NFASTBINS];
1826 /* Base of the topmost chunk -- not otherwise kept in a bin */
1827 mchunkptr top;
1829 /* The remainder from the most recent split of a small request */
1830 mchunkptr last_remainder;
1832 /* Normal bins packed as described above */
1833 mchunkptr bins[NBINS * 2 - 2];
1835 /* Bitmap of bins */
1836 unsigned int binmap[BINMAPSIZE];
1838 /* Linked list */
1839 struct malloc_state *next;
1841 /* Linked list for free arenas. Access to this field is serialized
1842 by free_list_lock in arena.c. */
1843 struct malloc_state *next_free;
1845 /* Number of threads attached to this arena. 0 if the arena is on
1846 the free list. Access to this field is serialized by
1847 free_list_lock in arena.c. */
1848 INTERNAL_SIZE_T attached_threads;
1850 /* Memory allocated from the system in this arena. */
1851 INTERNAL_SIZE_T system_mem;
1852 INTERNAL_SIZE_T max_system_mem;
1855 struct malloc_par
1857 /* Tunable parameters */
1858 unsigned long trim_threshold;
1859 INTERNAL_SIZE_T top_pad;
1860 INTERNAL_SIZE_T mmap_threshold;
1861 INTERNAL_SIZE_T arena_test;
1862 INTERNAL_SIZE_T arena_max;
1864 /* Memory map support */
1865 int n_mmaps;
1866 int n_mmaps_max;
1867 int max_n_mmaps;
1868 /* the mmap_threshold is dynamic, until the user sets
1869 it manually, at which point we need to disable any
1870 dynamic behavior. */
1871 int no_dyn_threshold;
1873 /* Statistics */
1874 INTERNAL_SIZE_T mmapped_mem;
1875 INTERNAL_SIZE_T max_mmapped_mem;
1877 /* First address handed out by MORECORE/sbrk. */
1878 char *sbrk_base;
1880 #if USE_TCACHE
1881 /* Maximum number of buckets to use. */
1882 size_t tcache_bins;
1883 size_t tcache_max_bytes;
1884 /* Maximum number of chunks in each bucket. */
1885 size_t tcache_count;
1886 /* Maximum number of chunks to remove from the unsorted list, which
1887 aren't used to prefill the cache. */
1888 size_t tcache_unsorted_limit;
1889 #endif
1892 /* There are several instances of this struct ("arenas") in this
1893 malloc. If you are adapting this malloc in a way that does NOT use
1894 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1895 before using. This malloc relies on the property that malloc_state
1896 is initialized to all zeroes (as is true of C statics). */
1898 static struct malloc_state main_arena =
1900 .mutex = _LIBC_LOCK_INITIALIZER,
1901 .next = &main_arena,
1902 .attached_threads = 1
1905 /* These variables are used for undumping support. Chunked are marked
1906 as using mmap, but we leave them alone if they fall into this
1907 range. NB: The chunk size for these chunks only includes the
1908 initial size field (of SIZE_SZ bytes), there is no trailing size
1909 field (unlike with regular mmapped chunks). */
1910 static mchunkptr dumped_main_arena_start; /* Inclusive. */
1911 static mchunkptr dumped_main_arena_end; /* Exclusive. */
1913 /* True if the pointer falls into the dumped arena. Use this after
1914 chunk_is_mmapped indicates a chunk is mmapped. */
1915 #define DUMPED_MAIN_ARENA_CHUNK(p) \
1916 ((p) >= dumped_main_arena_start && (p) < dumped_main_arena_end)
1918 /* There is only one instance of the malloc parameters. */
1920 static struct malloc_par mp_ =
1922 .top_pad = DEFAULT_TOP_PAD,
1923 .n_mmaps_max = DEFAULT_MMAP_MAX,
1924 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1925 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1926 #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1927 .arena_test = NARENAS_FROM_NCORES (1)
1928 #if USE_TCACHE
1930 .tcache_count = TCACHE_FILL_COUNT,
1931 .tcache_bins = TCACHE_MAX_BINS,
1932 .tcache_max_bytes = tidx2usize (TCACHE_MAX_BINS-1),
1933 .tcache_unsorted_limit = 0 /* No limit. */
1934 #endif
1938 Initialize a malloc_state struct.
1940 This is called from ptmalloc_init () or from _int_new_arena ()
1941 when creating a new arena.
1944 static void
1945 malloc_init_state (mstate av)
1947 int i;
1948 mbinptr bin;
1950 /* Establish circular links for normal bins */
1951 for (i = 1; i < NBINS; ++i)
1953 bin = bin_at (av, i);
1954 bin->fd = bin->bk = bin;
1957 #if MORECORE_CONTIGUOUS
1958 if (av != &main_arena)
1959 #endif
1960 set_noncontiguous (av);
1961 if (av == &main_arena)
1962 set_max_fast (DEFAULT_MXFAST);
1963 atomic_store_relaxed (&av->have_fastchunks, false);
1965 av->top = initial_top (av);
1969 Other internal utilities operating on mstates
1972 static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1973 static int systrim (size_t, mstate);
1974 static void malloc_consolidate (mstate);
1977 /* -------------- Early definitions for debugging hooks ---------------- */
1979 /* Define and initialize the hook variables. These weak definitions must
1980 appear before any use of the variables in a function (arena.c uses one). */
1981 #ifndef weak_variable
1982 /* In GNU libc we want the hook variables to be weak definitions to
1983 avoid a problem with Emacs. */
1984 # define weak_variable weak_function
1985 #endif
1987 /* Forward declarations. */
1988 static void *malloc_hook_ini (size_t sz,
1989 const void *caller) __THROW;
1990 static void *realloc_hook_ini (void *ptr, size_t sz,
1991 const void *caller) __THROW;
1992 static void *memalign_hook_ini (size_t alignment, size_t sz,
1993 const void *caller) __THROW;
1995 #if HAVE_MALLOC_INIT_HOOK
1996 void (*__malloc_initialize_hook) (void) __attribute__ ((nocommon));
1997 compat_symbol (libc, __malloc_initialize_hook,
1998 __malloc_initialize_hook, GLIBC_2_0);
1999 #endif
2001 void weak_variable (*__free_hook) (void *__ptr,
2002 const void *) = NULL;
2003 void *weak_variable (*__malloc_hook)
2004 (size_t __size, const void *) = malloc_hook_ini;
2005 void *weak_variable (*__realloc_hook)
2006 (void *__ptr, size_t __size, const void *)
2007 = realloc_hook_ini;
2008 void *weak_variable (*__memalign_hook)
2009 (size_t __alignment, size_t __size, const void *)
2010 = memalign_hook_ini;
2011 void weak_variable (*__after_morecore_hook) (void) = NULL;
2013 /* This function is called from the arena shutdown hook, to free the
2014 thread cache (if it exists). */
2015 static void tcache_thread_shutdown (void);
2017 /* ------------------ Testing support ----------------------------------*/
2019 static int perturb_byte;
2021 static void
2022 alloc_perturb (char *p, size_t n)
2024 if (__glibc_unlikely (perturb_byte))
2025 memset (p, perturb_byte ^ 0xff, n);
2028 static void
2029 free_perturb (char *p, size_t n)
2031 if (__glibc_unlikely (perturb_byte))
2032 memset (p, perturb_byte, n);
2037 #include <stap-probe.h>
2039 /* ------------------- Support for multiple arenas -------------------- */
2040 #include "arena.c"
2043 Debugging support
2045 These routines make a number of assertions about the states
2046 of data structures that should be true at all times. If any
2047 are not true, it's very likely that a user program has somehow
2048 trashed memory. (It's also possible that there is a coding error
2049 in malloc. In which case, please report it!)
2052 #if !MALLOC_DEBUG
2054 # define check_chunk(A, P)
2055 # define check_free_chunk(A, P)
2056 # define check_inuse_chunk(A, P)
2057 # define check_remalloced_chunk(A, P, N)
2058 # define check_malloced_chunk(A, P, N)
2059 # define check_malloc_state(A)
2061 #else
2063 # define check_chunk(A, P) do_check_chunk (A, P)
2064 # define check_free_chunk(A, P) do_check_free_chunk (A, P)
2065 # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
2066 # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
2067 # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
2068 # define check_malloc_state(A) do_check_malloc_state (A)
2071 Properties of all chunks
2074 static void
2075 do_check_chunk (mstate av, mchunkptr p)
2077 unsigned long sz = chunksize (p);
2078 /* min and max possible addresses assuming contiguous allocation */
2079 char *max_address = (char *) (av->top) + chunksize (av->top);
2080 char *min_address = max_address - av->system_mem;
2082 if (!chunk_is_mmapped (p))
2084 /* Has legal address ... */
2085 if (p != av->top)
2087 if (contiguous (av))
2089 assert (((char *) p) >= min_address);
2090 assert (((char *) p + sz) <= ((char *) (av->top)));
2093 else
2095 /* top size is always at least MINSIZE */
2096 assert ((unsigned long) (sz) >= MINSIZE);
2097 /* top predecessor always marked inuse */
2098 assert (prev_inuse (p));
2101 else if (!DUMPED_MAIN_ARENA_CHUNK (p))
2103 /* address is outside main heap */
2104 if (contiguous (av) && av->top != initial_top (av))
2106 assert (((char *) p) < min_address || ((char *) p) >= max_address);
2108 /* chunk is page-aligned */
2109 assert (((prev_size (p) + sz) & (GLRO (dl_pagesize) - 1)) == 0);
2110 /* mem is aligned */
2111 assert (aligned_OK (chunk2rawmem (p)));
2116 Properties of free chunks
2119 static void
2120 do_check_free_chunk (mstate av, mchunkptr p)
2122 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2123 mchunkptr next = chunk_at_offset (p, sz);
2125 do_check_chunk (av, p);
2127 /* Chunk must claim to be free ... */
2128 assert (!inuse (p));
2129 assert (!chunk_is_mmapped (p));
2131 /* Unless a special marker, must have OK fields */
2132 if ((unsigned long) (sz) >= MINSIZE)
2134 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2135 assert (aligned_OK (chunk2rawmem (p)));
2136 /* ... matching footer field */
2137 assert (prev_size (next_chunk (p)) == sz);
2138 /* ... and is fully consolidated */
2139 assert (prev_inuse (p));
2140 assert (next == av->top || inuse (next));
2142 /* ... and has minimally sane links */
2143 assert (p->fd->bk == p);
2144 assert (p->bk->fd == p);
2146 else /* markers are always of size SIZE_SZ */
2147 assert (sz == SIZE_SZ);
2151 Properties of inuse chunks
2154 static void
2155 do_check_inuse_chunk (mstate av, mchunkptr p)
2157 mchunkptr next;
2159 do_check_chunk (av, p);
2161 if (chunk_is_mmapped (p))
2162 return; /* mmapped chunks have no next/prev */
2164 /* Check whether it claims to be in use ... */
2165 assert (inuse (p));
2167 next = next_chunk (p);
2169 /* ... and is surrounded by OK chunks.
2170 Since more things can be checked with free chunks than inuse ones,
2171 if an inuse chunk borders them and debug is on, it's worth doing them.
2173 if (!prev_inuse (p))
2175 /* Note that we cannot even look at prev unless it is not inuse */
2176 mchunkptr prv = prev_chunk (p);
2177 assert (next_chunk (prv) == p);
2178 do_check_free_chunk (av, prv);
2181 if (next == av->top)
2183 assert (prev_inuse (next));
2184 assert (chunksize (next) >= MINSIZE);
2186 else if (!inuse (next))
2187 do_check_free_chunk (av, next);
2191 Properties of chunks recycled from fastbins
2194 static void
2195 do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2197 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2199 if (!chunk_is_mmapped (p))
2201 assert (av == arena_for_chunk (p));
2202 if (chunk_main_arena (p))
2203 assert (av == &main_arena);
2204 else
2205 assert (av != &main_arena);
2208 do_check_inuse_chunk (av, p);
2210 /* Legal size ... */
2211 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2212 assert ((unsigned long) (sz) >= MINSIZE);
2213 /* ... and alignment */
2214 assert (aligned_OK (chunk2rawmem (p)));
2215 /* chunk is less than MINSIZE more than request */
2216 assert ((long) (sz) - (long) (s) >= 0);
2217 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2221 Properties of nonrecycled chunks at the point they are malloced
2224 static void
2225 do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2227 /* same as recycled case ... */
2228 do_check_remalloced_chunk (av, p, s);
2231 ... plus, must obey implementation invariant that prev_inuse is
2232 always true of any allocated chunk; i.e., that each allocated
2233 chunk borders either a previously allocated and still in-use
2234 chunk, or the base of its memory arena. This is ensured
2235 by making all allocations from the `lowest' part of any found
2236 chunk. This does not necessarily hold however for chunks
2237 recycled via fastbins.
2240 assert (prev_inuse (p));
2245 Properties of malloc_state.
2247 This may be useful for debugging malloc, as well as detecting user
2248 programmer errors that somehow write into malloc_state.
2250 If you are extending or experimenting with this malloc, you can
2251 probably figure out how to hack this routine to print out or
2252 display chunk addresses, sizes, bins, and other instrumentation.
2255 static void
2256 do_check_malloc_state (mstate av)
2258 int i;
2259 mchunkptr p;
2260 mchunkptr q;
2261 mbinptr b;
2262 unsigned int idx;
2263 INTERNAL_SIZE_T size;
2264 unsigned long total = 0;
2265 int max_fast_bin;
2267 /* internal size_t must be no wider than pointer type */
2268 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2270 /* alignment is a power of 2 */
2271 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2273 /* Check the arena is initialized. */
2274 assert (av->top != 0);
2276 /* No memory has been allocated yet, so doing more tests is not possible. */
2277 if (av->top == initial_top (av))
2278 return;
2280 /* pagesize is a power of 2 */
2281 assert (powerof2(GLRO (dl_pagesize)));
2283 /* A contiguous main_arena is consistent with sbrk_base. */
2284 if (av == &main_arena && contiguous (av))
2285 assert ((char *) mp_.sbrk_base + av->system_mem ==
2286 (char *) av->top + chunksize (av->top));
2288 /* properties of fastbins */
2290 /* max_fast is in allowed range */
2291 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2293 max_fast_bin = fastbin_index (get_max_fast ());
2295 for (i = 0; i < NFASTBINS; ++i)
2297 p = fastbin (av, i);
2299 /* The following test can only be performed for the main arena.
2300 While mallopt calls malloc_consolidate to get rid of all fast
2301 bins (especially those larger than the new maximum) this does
2302 only happen for the main arena. Trying to do this for any
2303 other arena would mean those arenas have to be locked and
2304 malloc_consolidate be called for them. This is excessive. And
2305 even if this is acceptable to somebody it still cannot solve
2306 the problem completely since if the arena is locked a
2307 concurrent malloc call might create a new arena which then
2308 could use the newly invalid fast bins. */
2310 /* all bins past max_fast are empty */
2311 if (av == &main_arena && i > max_fast_bin)
2312 assert (p == 0);
2314 while (p != 0)
2316 if (__glibc_unlikely (misaligned_chunk (p)))
2317 malloc_printerr ("do_check_malloc_state(): "
2318 "unaligned fastbin chunk detected");
2319 /* each chunk claims to be inuse */
2320 do_check_inuse_chunk (av, p);
2321 total += chunksize (p);
2322 /* chunk belongs in this bin */
2323 assert (fastbin_index (chunksize (p)) == i);
2324 p = REVEAL_PTR (p->fd);
2328 /* check normal bins */
2329 for (i = 1; i < NBINS; ++i)
2331 b = bin_at (av, i);
2333 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2334 if (i >= 2)
2336 unsigned int binbit = get_binmap (av, i);
2337 int empty = last (b) == b;
2338 if (!binbit)
2339 assert (empty);
2340 else if (!empty)
2341 assert (binbit);
2344 for (p = last (b); p != b; p = p->bk)
2346 /* each chunk claims to be free */
2347 do_check_free_chunk (av, p);
2348 size = chunksize (p);
2349 total += size;
2350 if (i >= 2)
2352 /* chunk belongs in bin */
2353 idx = bin_index (size);
2354 assert (idx == i);
2355 /* lists are sorted */
2356 assert (p->bk == b ||
2357 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2359 if (!in_smallbin_range (size))
2361 if (p->fd_nextsize != NULL)
2363 if (p->fd_nextsize == p)
2364 assert (p->bk_nextsize == p);
2365 else
2367 if (p->fd_nextsize == first (b))
2368 assert (chunksize (p) < chunksize (p->fd_nextsize));
2369 else
2370 assert (chunksize (p) > chunksize (p->fd_nextsize));
2372 if (p == first (b))
2373 assert (chunksize (p) > chunksize (p->bk_nextsize));
2374 else
2375 assert (chunksize (p) < chunksize (p->bk_nextsize));
2378 else
2379 assert (p->bk_nextsize == NULL);
2382 else if (!in_smallbin_range (size))
2383 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2384 /* chunk is followed by a legal chain of inuse chunks */
2385 for (q = next_chunk (p);
2386 (q != av->top && inuse (q) &&
2387 (unsigned long) (chunksize (q)) >= MINSIZE);
2388 q = next_chunk (q))
2389 do_check_inuse_chunk (av, q);
2393 /* top chunk is OK */
2394 check_chunk (av, av->top);
2396 #endif
2399 /* ----------------- Support for debugging hooks -------------------- */
2400 #include "hooks.c"
2403 /* ----------- Routines dealing with system allocation -------------- */
2406 sysmalloc handles malloc cases requiring more memory from the system.
2407 On entry, it is assumed that av->top does not have enough
2408 space to service request for nb bytes, thus requiring that av->top
2409 be extended or replaced.
2412 static void *
2413 sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2415 mchunkptr old_top; /* incoming value of av->top */
2416 INTERNAL_SIZE_T old_size; /* its size */
2417 char *old_end; /* its end address */
2419 long size; /* arg to first MORECORE or mmap call */
2420 char *brk; /* return value from MORECORE */
2422 long correction; /* arg to 2nd MORECORE call */
2423 char *snd_brk; /* 2nd return val */
2425 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2426 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2427 char *aligned_brk; /* aligned offset into brk */
2429 mchunkptr p; /* the allocated/returned chunk */
2430 mchunkptr remainder; /* remainder from allocation */
2431 unsigned long remainder_size; /* its size */
2434 size_t pagesize = GLRO (dl_pagesize);
2435 bool tried_mmap = false;
2439 If have mmap, and the request size meets the mmap threshold, and
2440 the system supports mmap, and there are few enough currently
2441 allocated mmapped regions, try to directly map this request
2442 rather than expanding top.
2445 if (av == NULL
2446 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2447 && (mp_.n_mmaps < mp_.n_mmaps_max)))
2449 char *mm; /* return value from mmap call*/
2451 try_mmap:
2453 Round up size to nearest page. For mmapped chunks, the overhead
2454 is one SIZE_SZ unit larger than for normal chunks, because there
2455 is no following chunk whose prev_size field could be used.
2457 See the front_misalign handling below, for glibc there is no
2458 need for further alignments unless we have have high alignment.
2460 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2461 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2462 else
2463 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2464 tried_mmap = true;
2466 /* Don't try if size wraps around 0 */
2467 if ((unsigned long) (size) > (unsigned long) (nb))
2469 mm = (char *) (MMAP (0, size,
2470 MTAG_MMAP_FLAGS | PROT_READ | PROT_WRITE, 0));
2472 if (mm != MAP_FAILED)
2475 The offset to the start of the mmapped region is stored
2476 in the prev_size field of the chunk. This allows us to adjust
2477 returned start address to meet alignment requirements here
2478 and in memalign(), and still be able to compute proper
2479 address argument for later munmap in free() and realloc().
2482 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2484 /* For glibc, chunk2rawmem increases the address by
2485 CHUNK_HDR_SZ and MALLOC_ALIGN_MASK is
2486 CHUNK_HDR_SZ-1. Each mmap'ed area is page
2487 aligned and therefore definitely
2488 MALLOC_ALIGN_MASK-aligned. */
2489 assert (((INTERNAL_SIZE_T) chunk2rawmem (mm) & MALLOC_ALIGN_MASK) == 0);
2490 front_misalign = 0;
2492 else
2493 front_misalign = (INTERNAL_SIZE_T) chunk2rawmem (mm) & MALLOC_ALIGN_MASK;
2494 if (front_misalign > 0)
2496 correction = MALLOC_ALIGNMENT - front_misalign;
2497 p = (mchunkptr) (mm + correction);
2498 set_prev_size (p, correction);
2499 set_head (p, (size - correction) | IS_MMAPPED);
2501 else
2503 p = (mchunkptr) mm;
2504 set_prev_size (p, 0);
2505 set_head (p, size | IS_MMAPPED);
2508 /* update statistics */
2510 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2511 atomic_max (&mp_.max_n_mmaps, new);
2513 unsigned long sum;
2514 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2515 atomic_max (&mp_.max_mmapped_mem, sum);
2517 check_chunk (av, p);
2519 return chunk2mem (p);
2524 /* There are no usable arenas and mmap also failed. */
2525 if (av == NULL)
2526 return 0;
2528 /* Record incoming configuration of top */
2530 old_top = av->top;
2531 old_size = chunksize (old_top);
2532 old_end = (char *) (chunk_at_offset (old_top, old_size));
2534 brk = snd_brk = (char *) (MORECORE_FAILURE);
2537 If not the first time through, we require old_size to be
2538 at least MINSIZE and to have prev_inuse set.
2541 assert ((old_top == initial_top (av) && old_size == 0) ||
2542 ((unsigned long) (old_size) >= MINSIZE &&
2543 prev_inuse (old_top) &&
2544 ((unsigned long) old_end & (pagesize - 1)) == 0));
2546 /* Precondition: not enough current space to satisfy nb request */
2547 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2550 if (av != &main_arena)
2552 heap_info *old_heap, *heap;
2553 size_t old_heap_size;
2555 /* First try to extend the current heap. */
2556 old_heap = heap_for_ptr (old_top);
2557 old_heap_size = old_heap->size;
2558 if ((long) (MINSIZE + nb - old_size) > 0
2559 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2561 av->system_mem += old_heap->size - old_heap_size;
2562 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2563 | PREV_INUSE);
2565 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2567 /* Use a newly allocated heap. */
2568 heap->ar_ptr = av;
2569 heap->prev = old_heap;
2570 av->system_mem += heap->size;
2571 /* Set up the new top. */
2572 top (av) = chunk_at_offset (heap, sizeof (*heap));
2573 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2575 /* Setup fencepost and free the old top chunk with a multiple of
2576 MALLOC_ALIGNMENT in size. */
2577 /* The fencepost takes at least MINSIZE bytes, because it might
2578 become the top chunk again later. Note that a footer is set
2579 up, too, although the chunk is marked in use. */
2580 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2581 set_head (chunk_at_offset (old_top, old_size + CHUNK_HDR_SZ),
2582 0 | PREV_INUSE);
2583 if (old_size >= MINSIZE)
2585 set_head (chunk_at_offset (old_top, old_size),
2586 CHUNK_HDR_SZ | PREV_INUSE);
2587 set_foot (chunk_at_offset (old_top, old_size), CHUNK_HDR_SZ);
2588 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2589 _int_free (av, old_top, 1);
2591 else
2593 set_head (old_top, (old_size + CHUNK_HDR_SZ) | PREV_INUSE);
2594 set_foot (old_top, (old_size + CHUNK_HDR_SZ));
2597 else if (!tried_mmap)
2598 /* We can at least try to use to mmap memory. */
2599 goto try_mmap;
2601 else /* av == main_arena */
2604 { /* Request enough space for nb + pad + overhead */
2605 size = nb + mp_.top_pad + MINSIZE;
2608 If contiguous, we can subtract out existing space that we hope to
2609 combine with new space. We add it back later only if
2610 we don't actually get contiguous space.
2613 if (contiguous (av))
2614 size -= old_size;
2617 Round to a multiple of page size.
2618 If MORECORE is not contiguous, this ensures that we only call it
2619 with whole-page arguments. And if MORECORE is contiguous and
2620 this is not first time through, this preserves page-alignment of
2621 previous calls. Otherwise, we correct to page-align below.
2624 size = ALIGN_UP (size, pagesize);
2627 Don't try to call MORECORE if argument is so big as to appear
2628 negative. Note that since mmap takes size_t arg, it may succeed
2629 below even if we cannot call MORECORE.
2632 if (size > 0)
2634 brk = (char *) (MORECORE (size));
2635 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2638 if (brk != (char *) (MORECORE_FAILURE))
2640 /* Call the `morecore' hook if necessary. */
2641 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2642 if (__builtin_expect (hook != NULL, 0))
2643 (*hook)();
2645 else
2648 If have mmap, try using it as a backup when MORECORE fails or
2649 cannot be used. This is worth doing on systems that have "holes" in
2650 address space, so sbrk cannot extend to give contiguous space, but
2651 space is available elsewhere. Note that we ignore mmap max count
2652 and threshold limits, since the space will not be used as a
2653 segregated mmap region.
2656 /* Cannot merge with old top, so add its size back in */
2657 if (contiguous (av))
2658 size = ALIGN_UP (size + old_size, pagesize);
2660 /* If we are relying on mmap as backup, then use larger units */
2661 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2662 size = MMAP_AS_MORECORE_SIZE;
2664 /* Don't try if size wraps around 0 */
2665 if ((unsigned long) (size) > (unsigned long) (nb))
2667 char *mbrk = (char *) (MMAP (0, size,
2668 MTAG_MMAP_FLAGS | PROT_READ | PROT_WRITE,
2669 0));
2671 if (mbrk != MAP_FAILED)
2673 /* We do not need, and cannot use, another sbrk call to find end */
2674 brk = mbrk;
2675 snd_brk = brk + size;
2678 Record that we no longer have a contiguous sbrk region.
2679 After the first time mmap is used as backup, we do not
2680 ever rely on contiguous space since this could incorrectly
2681 bridge regions.
2683 set_noncontiguous (av);
2688 if (brk != (char *) (MORECORE_FAILURE))
2690 if (mp_.sbrk_base == 0)
2691 mp_.sbrk_base = brk;
2692 av->system_mem += size;
2695 If MORECORE extends previous space, we can likewise extend top size.
2698 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2699 set_head (old_top, (size + old_size) | PREV_INUSE);
2701 else if (contiguous (av) && old_size && brk < old_end)
2702 /* Oops! Someone else killed our space.. Can't touch anything. */
2703 malloc_printerr ("break adjusted to free malloc space");
2706 Otherwise, make adjustments:
2708 * If the first time through or noncontiguous, we need to call sbrk
2709 just to find out where the end of memory lies.
2711 * We need to ensure that all returned chunks from malloc will meet
2712 MALLOC_ALIGNMENT
2714 * If there was an intervening foreign sbrk, we need to adjust sbrk
2715 request size to account for fact that we will not be able to
2716 combine new space with existing space in old_top.
2718 * Almost all systems internally allocate whole pages at a time, in
2719 which case we might as well use the whole last page of request.
2720 So we allocate enough more memory to hit a page boundary now,
2721 which in turn causes future contiguous calls to page-align.
2724 else
2726 front_misalign = 0;
2727 end_misalign = 0;
2728 correction = 0;
2729 aligned_brk = brk;
2731 /* handle contiguous cases */
2732 if (contiguous (av))
2734 /* Count foreign sbrk as system_mem. */
2735 if (old_size)
2736 av->system_mem += brk - old_end;
2738 /* Guarantee alignment of first new chunk made from this space */
2740 front_misalign = (INTERNAL_SIZE_T) chunk2rawmem (brk) & MALLOC_ALIGN_MASK;
2741 if (front_misalign > 0)
2744 Skip over some bytes to arrive at an aligned position.
2745 We don't need to specially mark these wasted front bytes.
2746 They will never be accessed anyway because
2747 prev_inuse of av->top (and any chunk created from its start)
2748 is always true after initialization.
2751 correction = MALLOC_ALIGNMENT - front_misalign;
2752 aligned_brk += correction;
2756 If this isn't adjacent to existing space, then we will not
2757 be able to merge with old_top space, so must add to 2nd request.
2760 correction += old_size;
2762 /* Extend the end address to hit a page boundary */
2763 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2764 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2766 assert (correction >= 0);
2767 snd_brk = (char *) (MORECORE (correction));
2770 If can't allocate correction, try to at least find out current
2771 brk. It might be enough to proceed without failing.
2773 Note that if second sbrk did NOT fail, we assume that space
2774 is contiguous with first sbrk. This is a safe assumption unless
2775 program is multithreaded but doesn't use locks and a foreign sbrk
2776 occurred between our first and second calls.
2779 if (snd_brk == (char *) (MORECORE_FAILURE))
2781 correction = 0;
2782 snd_brk = (char *) (MORECORE (0));
2784 else
2786 /* Call the `morecore' hook if necessary. */
2787 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2788 if (__builtin_expect (hook != NULL, 0))
2789 (*hook)();
2793 /* handle non-contiguous cases */
2794 else
2796 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2797 /* MORECORE/mmap must correctly align */
2798 assert (((unsigned long) chunk2rawmem (brk) & MALLOC_ALIGN_MASK) == 0);
2799 else
2801 front_misalign = (INTERNAL_SIZE_T) chunk2rawmem (brk) & MALLOC_ALIGN_MASK;
2802 if (front_misalign > 0)
2805 Skip over some bytes to arrive at an aligned position.
2806 We don't need to specially mark these wasted front bytes.
2807 They will never be accessed anyway because
2808 prev_inuse of av->top (and any chunk created from its start)
2809 is always true after initialization.
2812 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2816 /* Find out current end of memory */
2817 if (snd_brk == (char *) (MORECORE_FAILURE))
2819 snd_brk = (char *) (MORECORE (0));
2823 /* Adjust top based on results of second sbrk */
2824 if (snd_brk != (char *) (MORECORE_FAILURE))
2826 av->top = (mchunkptr) aligned_brk;
2827 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2828 av->system_mem += correction;
2831 If not the first time through, we either have a
2832 gap due to foreign sbrk or a non-contiguous region. Insert a
2833 double fencepost at old_top to prevent consolidation with space
2834 we don't own. These fenceposts are artificial chunks that are
2835 marked as inuse and are in any case too small to use. We need
2836 two to make sizes and alignments work out.
2839 if (old_size != 0)
2842 Shrink old_top to insert fenceposts, keeping size a
2843 multiple of MALLOC_ALIGNMENT. We know there is at least
2844 enough space in old_top to do this.
2846 old_size = (old_size - 2 * CHUNK_HDR_SZ) & ~MALLOC_ALIGN_MASK;
2847 set_head (old_top, old_size | PREV_INUSE);
2850 Note that the following assignments completely overwrite
2851 old_top when old_size was previously MINSIZE. This is
2852 intentional. We need the fencepost, even if old_top otherwise gets
2853 lost.
2855 set_head (chunk_at_offset (old_top, old_size),
2856 CHUNK_HDR_SZ | PREV_INUSE);
2857 set_head (chunk_at_offset (old_top,
2858 old_size + CHUNK_HDR_SZ),
2859 CHUNK_HDR_SZ | PREV_INUSE);
2861 /* If possible, release the rest. */
2862 if (old_size >= MINSIZE)
2864 _int_free (av, old_top, 1);
2870 } /* if (av != &main_arena) */
2872 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2873 av->max_system_mem = av->system_mem;
2874 check_malloc_state (av);
2876 /* finally, do the allocation */
2877 p = av->top;
2878 size = chunksize (p);
2880 /* check that one of the above allocation paths succeeded */
2881 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2883 remainder_size = size - nb;
2884 remainder = chunk_at_offset (p, nb);
2885 av->top = remainder;
2886 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2887 set_head (remainder, remainder_size | PREV_INUSE);
2888 check_malloced_chunk (av, p, nb);
2889 return chunk2mem (p);
2892 /* catch all failure paths */
2893 __set_errno (ENOMEM);
2894 return 0;
2899 systrim is an inverse of sorts to sysmalloc. It gives memory back
2900 to the system (via negative arguments to sbrk) if there is unused
2901 memory at the `high' end of the malloc pool. It is called
2902 automatically by free() when top space exceeds the trim
2903 threshold. It is also called by the public malloc_trim routine. It
2904 returns 1 if it actually released any memory, else 0.
2907 static int
2908 systrim (size_t pad, mstate av)
2910 long top_size; /* Amount of top-most memory */
2911 long extra; /* Amount to release */
2912 long released; /* Amount actually released */
2913 char *current_brk; /* address returned by pre-check sbrk call */
2914 char *new_brk; /* address returned by post-check sbrk call */
2915 size_t pagesize;
2916 long top_area;
2918 pagesize = GLRO (dl_pagesize);
2919 top_size = chunksize (av->top);
2921 top_area = top_size - MINSIZE - 1;
2922 if (top_area <= pad)
2923 return 0;
2925 /* Release in pagesize units and round down to the nearest page. */
2926 extra = ALIGN_DOWN(top_area - pad, pagesize);
2928 if (extra == 0)
2929 return 0;
2932 Only proceed if end of memory is where we last set it.
2933 This avoids problems if there were foreign sbrk calls.
2935 current_brk = (char *) (MORECORE (0));
2936 if (current_brk == (char *) (av->top) + top_size)
2939 Attempt to release memory. We ignore MORECORE return value,
2940 and instead call again to find out where new end of memory is.
2941 This avoids problems if first call releases less than we asked,
2942 of if failure somehow altered brk value. (We could still
2943 encounter problems if it altered brk in some very bad way,
2944 but the only thing we can do is adjust anyway, which will cause
2945 some downstream failure.)
2948 MORECORE (-extra);
2949 /* Call the `morecore' hook if necessary. */
2950 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2951 if (__builtin_expect (hook != NULL, 0))
2952 (*hook)();
2953 new_brk = (char *) (MORECORE (0));
2955 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2957 if (new_brk != (char *) MORECORE_FAILURE)
2959 released = (long) (current_brk - new_brk);
2961 if (released != 0)
2963 /* Success. Adjust top. */
2964 av->system_mem -= released;
2965 set_head (av->top, (top_size - released) | PREV_INUSE);
2966 check_malloc_state (av);
2967 return 1;
2971 return 0;
2974 static void
2975 munmap_chunk (mchunkptr p)
2977 size_t pagesize = GLRO (dl_pagesize);
2978 INTERNAL_SIZE_T size = chunksize (p);
2980 assert (chunk_is_mmapped (p));
2982 /* Do nothing if the chunk is a faked mmapped chunk in the dumped
2983 main arena. We never free this memory. */
2984 if (DUMPED_MAIN_ARENA_CHUNK (p))
2985 return;
2987 uintptr_t mem = (uintptr_t) chunk2rawmem (p);
2988 uintptr_t block = (uintptr_t) p - prev_size (p);
2989 size_t total_size = prev_size (p) + size;
2990 /* Unfortunately we have to do the compilers job by hand here. Normally
2991 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2992 page size. But gcc does not recognize the optimization possibility
2993 (in the moment at least) so we combine the two values into one before
2994 the bit test. */
2995 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
2996 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
2997 malloc_printerr ("munmap_chunk(): invalid pointer");
2999 atomic_decrement (&mp_.n_mmaps);
3000 atomic_add (&mp_.mmapped_mem, -total_size);
3002 /* If munmap failed the process virtual memory address space is in a
3003 bad shape. Just leave the block hanging around, the process will
3004 terminate shortly anyway since not much can be done. */
3005 __munmap ((char *) block, total_size);
3008 #if HAVE_MREMAP
3010 static mchunkptr
3011 mremap_chunk (mchunkptr p, size_t new_size)
3013 size_t pagesize = GLRO (dl_pagesize);
3014 INTERNAL_SIZE_T offset = prev_size (p);
3015 INTERNAL_SIZE_T size = chunksize (p);
3016 char *cp;
3018 assert (chunk_is_mmapped (p));
3020 uintptr_t block = (uintptr_t) p - offset;
3021 uintptr_t mem = (uintptr_t) chunk2mem(p);
3022 size_t total_size = offset + size;
3023 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
3024 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
3025 malloc_printerr("mremap_chunk(): invalid pointer");
3027 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
3028 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
3030 /* No need to remap if the number of pages does not change. */
3031 if (total_size == new_size)
3032 return p;
3034 cp = (char *) __mremap ((char *) block, total_size, new_size,
3035 MREMAP_MAYMOVE);
3037 if (cp == MAP_FAILED)
3038 return 0;
3040 p = (mchunkptr) (cp + offset);
3042 assert (aligned_OK (chunk2rawmem (p)));
3044 assert (prev_size (p) == offset);
3045 set_head (p, (new_size - offset) | IS_MMAPPED);
3047 INTERNAL_SIZE_T new;
3048 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
3049 + new_size - size - offset;
3050 atomic_max (&mp_.max_mmapped_mem, new);
3051 return p;
3053 #endif /* HAVE_MREMAP */
3055 /*------------------------ Public wrappers. --------------------------------*/
3057 #if USE_TCACHE
3059 /* We overlay this structure on the user-data portion of a chunk when
3060 the chunk is stored in the per-thread cache. */
3061 typedef struct tcache_entry
3063 struct tcache_entry *next;
3064 /* This field exists to detect double frees. */
3065 struct tcache_perthread_struct *key;
3066 } tcache_entry;
3068 /* There is one of these for each thread, which contains the
3069 per-thread cache (hence "tcache_perthread_struct"). Keeping
3070 overall size low is mildly important. Note that COUNTS and ENTRIES
3071 are redundant (we could have just counted the linked list each
3072 time), this is for performance reasons. */
3073 typedef struct tcache_perthread_struct
3075 uint16_t counts[TCACHE_MAX_BINS];
3076 tcache_entry *entries[TCACHE_MAX_BINS];
3077 } tcache_perthread_struct;
3079 static __thread bool tcache_shutting_down = false;
3080 static __thread tcache_perthread_struct *tcache = NULL;
3082 /* Caller must ensure that we know tc_idx is valid and there's room
3083 for more chunks. */
3084 static __always_inline void
3085 tcache_put (mchunkptr chunk, size_t tc_idx)
3087 tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
3089 /* Mark this chunk as "in the tcache" so the test in _int_free will
3090 detect a double free. */
3091 e->key = tcache;
3093 e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]);
3094 tcache->entries[tc_idx] = e;
3095 ++(tcache->counts[tc_idx]);
3098 /* Caller must ensure that we know tc_idx is valid and there's
3099 available chunks to remove. */
3100 static __always_inline void *
3101 tcache_get (size_t tc_idx)
3103 tcache_entry *e = tcache->entries[tc_idx];
3104 if (__glibc_unlikely (!aligned_OK (e)))
3105 malloc_printerr ("malloc(): unaligned tcache chunk detected");
3106 tcache->entries[tc_idx] = REVEAL_PTR (e->next);
3107 --(tcache->counts[tc_idx]);
3108 e->key = NULL;
3109 return (void *) e;
3112 static void
3113 tcache_thread_shutdown (void)
3115 int i;
3116 tcache_perthread_struct *tcache_tmp = tcache;
3118 if (!tcache)
3119 return;
3121 /* Disable the tcache and prevent it from being reinitialized. */
3122 tcache = NULL;
3123 tcache_shutting_down = true;
3125 /* Free all of the entries and the tcache itself back to the arena
3126 heap for coalescing. */
3127 for (i = 0; i < TCACHE_MAX_BINS; ++i)
3129 while (tcache_tmp->entries[i])
3131 tcache_entry *e = tcache_tmp->entries[i];
3132 if (__glibc_unlikely (!aligned_OK (e)))
3133 malloc_printerr ("tcache_thread_shutdown(): "
3134 "unaligned tcache chunk detected");
3135 tcache_tmp->entries[i] = REVEAL_PTR (e->next);
3136 __libc_free (e);
3140 __libc_free (tcache_tmp);
3143 static void
3144 tcache_init(void)
3146 mstate ar_ptr;
3147 void *victim = 0;
3148 const size_t bytes = sizeof (tcache_perthread_struct);
3150 if (tcache_shutting_down)
3151 return;
3153 arena_get (ar_ptr, bytes);
3154 victim = _int_malloc (ar_ptr, bytes);
3155 if (!victim && ar_ptr != NULL)
3157 ar_ptr = arena_get_retry (ar_ptr, bytes);
3158 victim = _int_malloc (ar_ptr, bytes);
3162 if (ar_ptr != NULL)
3163 __libc_lock_unlock (ar_ptr->mutex);
3165 /* In a low memory situation, we may not be able to allocate memory
3166 - in which case, we just keep trying later. However, we
3167 typically do this very early, so either there is sufficient
3168 memory, or there isn't enough memory to do non-trivial
3169 allocations anyway. */
3170 if (victim)
3172 tcache = (tcache_perthread_struct *) victim;
3173 memset (tcache, 0, sizeof (tcache_perthread_struct));
3178 # define MAYBE_INIT_TCACHE() \
3179 if (__glibc_unlikely (tcache == NULL)) \
3180 tcache_init();
3182 #else /* !USE_TCACHE */
3183 # define MAYBE_INIT_TCACHE()
3185 static void
3186 tcache_thread_shutdown (void)
3188 /* Nothing to do if there is no thread cache. */
3191 #endif /* !USE_TCACHE */
3193 void *
3194 __libc_malloc (size_t bytes)
3196 mstate ar_ptr;
3197 void *victim;
3199 _Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2,
3200 "PTRDIFF_MAX is not more than half of SIZE_MAX");
3202 void *(*hook) (size_t, const void *)
3203 = atomic_forced_read (__malloc_hook);
3204 if (__builtin_expect (hook != NULL, 0))
3205 return (*hook)(bytes, RETURN_ADDRESS (0));
3206 #if USE_TCACHE
3207 /* int_free also calls request2size, be careful to not pad twice. */
3208 size_t tbytes;
3209 if (!checked_request2size (bytes, &tbytes))
3211 __set_errno (ENOMEM);
3212 return NULL;
3214 size_t tc_idx = csize2tidx (tbytes);
3216 MAYBE_INIT_TCACHE ();
3218 DIAG_PUSH_NEEDS_COMMENT;
3219 if (tc_idx < mp_.tcache_bins
3220 && tcache
3221 && tcache->counts[tc_idx] > 0)
3223 victim = tcache_get (tc_idx);
3224 return TAG_NEW_USABLE (victim);
3226 DIAG_POP_NEEDS_COMMENT;
3227 #endif
3229 if (SINGLE_THREAD_P)
3231 victim = TAG_NEW_USABLE (_int_malloc (&main_arena, bytes));
3232 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3233 &main_arena == arena_for_chunk (mem2chunk (victim)));
3234 return victim;
3237 arena_get (ar_ptr, bytes);
3239 victim = _int_malloc (ar_ptr, bytes);
3240 /* Retry with another arena only if we were able to find a usable arena
3241 before. */
3242 if (!victim && ar_ptr != NULL)
3244 LIBC_PROBE (memory_malloc_retry, 1, bytes);
3245 ar_ptr = arena_get_retry (ar_ptr, bytes);
3246 victim = _int_malloc (ar_ptr, bytes);
3249 if (ar_ptr != NULL)
3250 __libc_lock_unlock (ar_ptr->mutex);
3252 victim = TAG_NEW_USABLE (victim);
3254 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3255 ar_ptr == arena_for_chunk (mem2chunk (victim)));
3256 return victim;
3258 libc_hidden_def (__libc_malloc)
3260 void
3261 __libc_free (void *mem)
3263 mstate ar_ptr;
3264 mchunkptr p; /* chunk corresponding to mem */
3266 void (*hook) (void *, const void *)
3267 = atomic_forced_read (__free_hook);
3268 if (__builtin_expect (hook != NULL, 0))
3270 (*hook)(mem, RETURN_ADDRESS (0));
3271 return;
3274 if (mem == 0) /* free(0) has no effect */
3275 return;
3277 #ifdef USE_MTAG
3278 /* Quickly check that the freed pointer matches the tag for the memory.
3279 This gives a useful double-free detection. */
3280 *(volatile char *)mem;
3281 #endif
3283 int err = errno;
3285 p = mem2chunk (mem);
3287 /* Mark the chunk as belonging to the library again. */
3288 (void)TAG_REGION (chunk2rawmem (p), CHUNK_AVAILABLE_SIZE (p) - CHUNK_HDR_SZ);
3290 if (chunk_is_mmapped (p)) /* release mmapped memory. */
3292 /* See if the dynamic brk/mmap threshold needs adjusting.
3293 Dumped fake mmapped chunks do not affect the threshold. */
3294 if (!mp_.no_dyn_threshold
3295 && chunksize_nomask (p) > mp_.mmap_threshold
3296 && chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX
3297 && !DUMPED_MAIN_ARENA_CHUNK (p))
3299 mp_.mmap_threshold = chunksize (p);
3300 mp_.trim_threshold = 2 * mp_.mmap_threshold;
3301 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
3302 mp_.mmap_threshold, mp_.trim_threshold);
3304 munmap_chunk (p);
3306 else
3308 MAYBE_INIT_TCACHE ();
3310 ar_ptr = arena_for_chunk (p);
3311 _int_free (ar_ptr, p, 0);
3314 __set_errno (err);
3316 libc_hidden_def (__libc_free)
3318 void *
3319 __libc_realloc (void *oldmem, size_t bytes)
3321 mstate ar_ptr;
3322 INTERNAL_SIZE_T nb; /* padded request size */
3324 void *newp; /* chunk to return */
3326 void *(*hook) (void *, size_t, const void *) =
3327 atomic_forced_read (__realloc_hook);
3328 if (__builtin_expect (hook != NULL, 0))
3329 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
3331 #if REALLOC_ZERO_BYTES_FREES
3332 if (bytes == 0 && oldmem != NULL)
3334 __libc_free (oldmem); return 0;
3336 #endif
3338 /* realloc of null is supposed to be same as malloc */
3339 if (oldmem == 0)
3340 return __libc_malloc (bytes);
3342 #ifdef USE_MTAG
3343 /* Perform a quick check to ensure that the pointer's tag matches the
3344 memory's tag. */
3345 *(volatile char*) oldmem;
3346 #endif
3348 /* chunk corresponding to oldmem */
3349 const mchunkptr oldp = mem2chunk (oldmem);
3350 /* its size */
3351 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
3353 if (chunk_is_mmapped (oldp))
3354 ar_ptr = NULL;
3355 else
3357 MAYBE_INIT_TCACHE ();
3358 ar_ptr = arena_for_chunk (oldp);
3361 /* Little security check which won't hurt performance: the allocator
3362 never wrapps around at the end of the address space. Therefore
3363 we can exclude some size values which might appear here by
3364 accident or by "design" from some intruder. We need to bypass
3365 this check for dumped fake mmap chunks from the old main arena
3366 because the new malloc may provide additional alignment. */
3367 if ((__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
3368 || __builtin_expect (misaligned_chunk (oldp), 0))
3369 && !DUMPED_MAIN_ARENA_CHUNK (oldp))
3370 malloc_printerr ("realloc(): invalid pointer");
3372 if (!checked_request2size (bytes, &nb))
3374 __set_errno (ENOMEM);
3375 return NULL;
3378 if (chunk_is_mmapped (oldp))
3380 /* If this is a faked mmapped chunk from the dumped main arena,
3381 always make a copy (and do not free the old chunk). */
3382 if (DUMPED_MAIN_ARENA_CHUNK (oldp))
3384 /* Must alloc, copy, free. */
3385 void *newmem = __libc_malloc (bytes);
3386 if (newmem == 0)
3387 return NULL;
3388 /* Copy as many bytes as are available from the old chunk
3389 and fit into the new size. NB: The overhead for faked
3390 mmapped chunks is only SIZE_SZ, not CHUNK_HDR_SZ as for
3391 regular mmapped chunks. */
3392 if (bytes > oldsize - SIZE_SZ)
3393 bytes = oldsize - SIZE_SZ;
3394 memcpy (newmem, oldmem, bytes);
3395 return newmem;
3398 void *newmem;
3400 #if HAVE_MREMAP
3401 newp = mremap_chunk (oldp, nb);
3402 if (newp)
3404 void *newmem = chunk2rawmem (newp);
3405 /* Give the new block a different tag. This helps to ensure
3406 that stale handles to the previous mapping are not
3407 reused. There's a performance hit for both us and the
3408 caller for doing this, so we might want to
3409 reconsider. */
3410 return TAG_NEW_USABLE (newmem);
3412 #endif
3413 /* Note the extra SIZE_SZ overhead. */
3414 if (oldsize - SIZE_SZ >= nb)
3415 return oldmem; /* do nothing */
3417 /* Must alloc, copy, free. */
3418 newmem = __libc_malloc (bytes);
3419 if (newmem == 0)
3420 return 0; /* propagate failure */
3422 memcpy (newmem, oldmem, oldsize - CHUNK_HDR_SZ);
3423 munmap_chunk (oldp);
3424 return newmem;
3427 if (SINGLE_THREAD_P)
3429 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3430 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3431 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3433 return newp;
3436 __libc_lock_lock (ar_ptr->mutex);
3438 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3440 __libc_lock_unlock (ar_ptr->mutex);
3441 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3442 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3444 if (newp == NULL)
3446 /* Try harder to allocate memory in other arenas. */
3447 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3448 newp = __libc_malloc (bytes);
3449 if (newp != NULL)
3451 size_t sz = CHUNK_AVAILABLE_SIZE (oldp) - CHUNK_HDR_SZ;
3452 memcpy (newp, oldmem, sz);
3453 (void) TAG_REGION (chunk2rawmem (oldp), sz);
3454 _int_free (ar_ptr, oldp, 0);
3458 return newp;
3460 libc_hidden_def (__libc_realloc)
3462 void *
3463 __libc_memalign (size_t alignment, size_t bytes)
3465 void *address = RETURN_ADDRESS (0);
3466 return _mid_memalign (alignment, bytes, address);
3469 static void *
3470 _mid_memalign (size_t alignment, size_t bytes, void *address)
3472 mstate ar_ptr;
3473 void *p;
3475 void *(*hook) (size_t, size_t, const void *) =
3476 atomic_forced_read (__memalign_hook);
3477 if (__builtin_expect (hook != NULL, 0))
3478 return (*hook)(alignment, bytes, address);
3480 /* If we need less alignment than we give anyway, just relay to malloc. */
3481 if (alignment <= MALLOC_ALIGNMENT)
3482 return __libc_malloc (bytes);
3484 /* Otherwise, ensure that it is at least a minimum chunk size */
3485 if (alignment < MINSIZE)
3486 alignment = MINSIZE;
3488 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3489 power of 2 and will cause overflow in the check below. */
3490 if (alignment > SIZE_MAX / 2 + 1)
3492 __set_errno (EINVAL);
3493 return 0;
3497 /* Make sure alignment is power of 2. */
3498 if (!powerof2 (alignment))
3500 size_t a = MALLOC_ALIGNMENT * 2;
3501 while (a < alignment)
3502 a <<= 1;
3503 alignment = a;
3506 if (SINGLE_THREAD_P)
3508 p = _int_memalign (&main_arena, alignment, bytes);
3509 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3510 &main_arena == arena_for_chunk (mem2chunk (p)));
3511 return TAG_NEW_USABLE (p);
3514 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3516 p = _int_memalign (ar_ptr, alignment, bytes);
3517 if (!p && ar_ptr != NULL)
3519 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3520 ar_ptr = arena_get_retry (ar_ptr, bytes);
3521 p = _int_memalign (ar_ptr, alignment, bytes);
3524 if (ar_ptr != NULL)
3525 __libc_lock_unlock (ar_ptr->mutex);
3527 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3528 ar_ptr == arena_for_chunk (mem2chunk (p)));
3529 return TAG_NEW_USABLE (p);
3531 /* For ISO C11. */
3532 weak_alias (__libc_memalign, aligned_alloc)
3533 libc_hidden_def (__libc_memalign)
3535 void *
3536 __libc_valloc (size_t bytes)
3538 void *p;
3540 if (__malloc_initialized < 0)
3541 ptmalloc_init ();
3543 void *address = RETURN_ADDRESS (0);
3544 size_t pagesize = GLRO (dl_pagesize);
3545 p = _mid_memalign (pagesize, bytes, address);
3546 return TAG_NEW_USABLE (p);
3549 void *
3550 __libc_pvalloc (size_t bytes)
3552 void *p;
3554 if (__malloc_initialized < 0)
3555 ptmalloc_init ();
3557 void *address = RETURN_ADDRESS (0);
3558 size_t pagesize = GLRO (dl_pagesize);
3559 size_t rounded_bytes;
3560 /* ALIGN_UP with overflow check. */
3561 if (__glibc_unlikely (__builtin_add_overflow (bytes,
3562 pagesize - 1,
3563 &rounded_bytes)))
3565 __set_errno (ENOMEM);
3566 return 0;
3568 rounded_bytes = rounded_bytes & -(pagesize - 1);
3570 p = _mid_memalign (pagesize, rounded_bytes, address);
3571 return TAG_NEW_USABLE (p);
3574 void *
3575 __libc_calloc (size_t n, size_t elem_size)
3577 mstate av;
3578 mchunkptr oldtop;
3579 INTERNAL_SIZE_T sz, oldtopsize;
3580 void *mem;
3581 #ifndef USE_MTAG
3582 unsigned long clearsize;
3583 unsigned long nclears;
3584 INTERNAL_SIZE_T *d;
3585 #endif
3586 ptrdiff_t bytes;
3588 if (__glibc_unlikely (__builtin_mul_overflow (n, elem_size, &bytes)))
3590 __set_errno (ENOMEM);
3591 return NULL;
3594 sz = bytes;
3596 void *(*hook) (size_t, const void *) =
3597 atomic_forced_read (__malloc_hook);
3598 if (__builtin_expect (hook != NULL, 0))
3600 mem = (*hook)(sz, RETURN_ADDRESS (0));
3601 if (mem == 0)
3602 return 0;
3604 return memset (mem, 0, sz);
3607 MAYBE_INIT_TCACHE ();
3609 if (SINGLE_THREAD_P)
3610 av = &main_arena;
3611 else
3612 arena_get (av, sz);
3614 if (av)
3616 /* Check if we hand out the top chunk, in which case there may be no
3617 need to clear. */
3618 #if MORECORE_CLEARS
3619 oldtop = top (av);
3620 oldtopsize = chunksize (top (av));
3621 # if MORECORE_CLEARS < 2
3622 /* Only newly allocated memory is guaranteed to be cleared. */
3623 if (av == &main_arena &&
3624 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3625 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3626 # endif
3627 if (av != &main_arena)
3629 heap_info *heap = heap_for_ptr (oldtop);
3630 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3631 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3633 #endif
3635 else
3637 /* No usable arenas. */
3638 oldtop = 0;
3639 oldtopsize = 0;
3641 mem = _int_malloc (av, sz);
3643 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3644 av == arena_for_chunk (mem2chunk (mem)));
3646 if (!SINGLE_THREAD_P)
3648 if (mem == 0 && av != NULL)
3650 LIBC_PROBE (memory_calloc_retry, 1, sz);
3651 av = arena_get_retry (av, sz);
3652 mem = _int_malloc (av, sz);
3655 if (av != NULL)
3656 __libc_lock_unlock (av->mutex);
3659 /* Allocation failed even after a retry. */
3660 if (mem == 0)
3661 return 0;
3663 mchunkptr p = mem2chunk (mem);
3664 /* If we are using memory tagging, then we need to set the tags
3665 regardless of MORECORE_CLEARS, so we zero the whole block while
3666 doing so. */
3667 #ifdef USE_MTAG
3668 return TAG_NEW_MEMSET (mem, 0, CHUNK_AVAILABLE_SIZE (p) - CHUNK_HDR_SZ);
3669 #else
3670 INTERNAL_SIZE_T csz = chunksize (p);
3672 /* Two optional cases in which clearing not necessary */
3673 if (chunk_is_mmapped (p))
3675 if (__builtin_expect (perturb_byte, 0))
3676 return memset (mem, 0, sz);
3678 return mem;
3681 #if MORECORE_CLEARS
3682 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3684 /* clear only the bytes from non-freshly-sbrked memory */
3685 csz = oldtopsize;
3687 #endif
3689 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3690 contents have an odd number of INTERNAL_SIZE_T-sized words;
3691 minimally 3. */
3692 d = (INTERNAL_SIZE_T *) mem;
3693 clearsize = csz - SIZE_SZ;
3694 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3695 assert (nclears >= 3);
3697 if (nclears > 9)
3698 return memset (d, 0, clearsize);
3700 else
3702 *(d + 0) = 0;
3703 *(d + 1) = 0;
3704 *(d + 2) = 0;
3705 if (nclears > 4)
3707 *(d + 3) = 0;
3708 *(d + 4) = 0;
3709 if (nclears > 6)
3711 *(d + 5) = 0;
3712 *(d + 6) = 0;
3713 if (nclears > 8)
3715 *(d + 7) = 0;
3716 *(d + 8) = 0;
3722 return mem;
3723 #endif
3727 ------------------------------ malloc ------------------------------
3730 static void *
3731 _int_malloc (mstate av, size_t bytes)
3733 INTERNAL_SIZE_T nb; /* normalized request size */
3734 unsigned int idx; /* associated bin index */
3735 mbinptr bin; /* associated bin */
3737 mchunkptr victim; /* inspected/selected chunk */
3738 INTERNAL_SIZE_T size; /* its size */
3739 int victim_index; /* its bin index */
3741 mchunkptr remainder; /* remainder from a split */
3742 unsigned long remainder_size; /* its size */
3744 unsigned int block; /* bit map traverser */
3745 unsigned int bit; /* bit map traverser */
3746 unsigned int map; /* current word of binmap */
3748 mchunkptr fwd; /* misc temp for linking */
3749 mchunkptr bck; /* misc temp for linking */
3751 #if USE_TCACHE
3752 size_t tcache_unsorted_count; /* count of unsorted chunks processed */
3753 #endif
3756 Convert request size to internal form by adding SIZE_SZ bytes
3757 overhead plus possibly more to obtain necessary alignment and/or
3758 to obtain a size of at least MINSIZE, the smallest allocatable
3759 size. Also, checked_request2size returns false for request sizes
3760 that are so large that they wrap around zero when padded and
3761 aligned.
3764 if (!checked_request2size (bytes, &nb))
3766 __set_errno (ENOMEM);
3767 return NULL;
3770 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3771 mmap. */
3772 if (__glibc_unlikely (av == NULL))
3774 void *p = sysmalloc (nb, av);
3775 if (p != NULL)
3776 alloc_perturb (p, bytes);
3777 return p;
3781 If the size qualifies as a fastbin, first check corresponding bin.
3782 This code is safe to execute even if av is not yet initialized, so we
3783 can try it without checking, which saves some time on this fast path.
3786 #define REMOVE_FB(fb, victim, pp) \
3787 do \
3789 victim = pp; \
3790 if (victim == NULL) \
3791 break; \
3792 pp = REVEAL_PTR (victim->fd); \
3793 if (__glibc_unlikely (pp != NULL && misaligned_chunk (pp))) \
3794 malloc_printerr ("malloc(): unaligned fastbin chunk detected"); \
3796 while ((pp = catomic_compare_and_exchange_val_acq (fb, pp, victim)) \
3797 != victim); \
3799 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3801 idx = fastbin_index (nb);
3802 mfastbinptr *fb = &fastbin (av, idx);
3803 mchunkptr pp;
3804 victim = *fb;
3806 if (victim != NULL)
3808 if (__glibc_unlikely (misaligned_chunk (victim)))
3809 malloc_printerr ("malloc(): unaligned fastbin chunk detected 2");
3811 if (SINGLE_THREAD_P)
3812 *fb = REVEAL_PTR (victim->fd);
3813 else
3814 REMOVE_FB (fb, pp, victim);
3815 if (__glibc_likely (victim != NULL))
3817 size_t victim_idx = fastbin_index (chunksize (victim));
3818 if (__builtin_expect (victim_idx != idx, 0))
3819 malloc_printerr ("malloc(): memory corruption (fast)");
3820 check_remalloced_chunk (av, victim, nb);
3821 #if USE_TCACHE
3822 /* While we're here, if we see other chunks of the same size,
3823 stash them in the tcache. */
3824 size_t tc_idx = csize2tidx (nb);
3825 if (tcache && tc_idx < mp_.tcache_bins)
3827 mchunkptr tc_victim;
3829 /* While bin not empty and tcache not full, copy chunks. */
3830 while (tcache->counts[tc_idx] < mp_.tcache_count
3831 && (tc_victim = *fb) != NULL)
3833 if (__glibc_unlikely (misaligned_chunk (tc_victim)))
3834 malloc_printerr ("malloc(): unaligned fastbin chunk detected 3");
3835 if (SINGLE_THREAD_P)
3836 *fb = REVEAL_PTR (tc_victim->fd);
3837 else
3839 REMOVE_FB (fb, pp, tc_victim);
3840 if (__glibc_unlikely (tc_victim == NULL))
3841 break;
3843 tcache_put (tc_victim, tc_idx);
3846 #endif
3847 void *p = chunk2mem (victim);
3848 alloc_perturb (p, bytes);
3849 return p;
3855 If a small request, check regular bin. Since these "smallbins"
3856 hold one size each, no searching within bins is necessary.
3857 (For a large request, we need to wait until unsorted chunks are
3858 processed to find best fit. But for small ones, fits are exact
3859 anyway, so we can check now, which is faster.)
3862 if (in_smallbin_range (nb))
3864 idx = smallbin_index (nb);
3865 bin = bin_at (av, idx);
3867 if ((victim = last (bin)) != bin)
3869 bck = victim->bk;
3870 if (__glibc_unlikely (bck->fd != victim))
3871 malloc_printerr ("malloc(): smallbin double linked list corrupted");
3872 set_inuse_bit_at_offset (victim, nb);
3873 bin->bk = bck;
3874 bck->fd = bin;
3876 if (av != &main_arena)
3877 set_non_main_arena (victim);
3878 check_malloced_chunk (av, victim, nb);
3879 #if USE_TCACHE
3880 /* While we're here, if we see other chunks of the same size,
3881 stash them in the tcache. */
3882 size_t tc_idx = csize2tidx (nb);
3883 if (tcache && tc_idx < mp_.tcache_bins)
3885 mchunkptr tc_victim;
3887 /* While bin not empty and tcache not full, copy chunks over. */
3888 while (tcache->counts[tc_idx] < mp_.tcache_count
3889 && (tc_victim = last (bin)) != bin)
3891 if (tc_victim != 0)
3893 bck = tc_victim->bk;
3894 set_inuse_bit_at_offset (tc_victim, nb);
3895 if (av != &main_arena)
3896 set_non_main_arena (tc_victim);
3897 bin->bk = bck;
3898 bck->fd = bin;
3900 tcache_put (tc_victim, tc_idx);
3904 #endif
3905 void *p = chunk2mem (victim);
3906 alloc_perturb (p, bytes);
3907 return p;
3912 If this is a large request, consolidate fastbins before continuing.
3913 While it might look excessive to kill all fastbins before
3914 even seeing if there is space available, this avoids
3915 fragmentation problems normally associated with fastbins.
3916 Also, in practice, programs tend to have runs of either small or
3917 large requests, but less often mixtures, so consolidation is not
3918 invoked all that often in most programs. And the programs that
3919 it is called frequently in otherwise tend to fragment.
3922 else
3924 idx = largebin_index (nb);
3925 if (atomic_load_relaxed (&av->have_fastchunks))
3926 malloc_consolidate (av);
3930 Process recently freed or remaindered chunks, taking one only if
3931 it is exact fit, or, if this a small request, the chunk is remainder from
3932 the most recent non-exact fit. Place other traversed chunks in
3933 bins. Note that this step is the only place in any routine where
3934 chunks are placed in bins.
3936 The outer loop here is needed because we might not realize until
3937 near the end of malloc that we should have consolidated, so must
3938 do so and retry. This happens at most once, and only when we would
3939 otherwise need to expand memory to service a "small" request.
3942 #if USE_TCACHE
3943 INTERNAL_SIZE_T tcache_nb = 0;
3944 size_t tc_idx = csize2tidx (nb);
3945 if (tcache && tc_idx < mp_.tcache_bins)
3946 tcache_nb = nb;
3947 int return_cached = 0;
3949 tcache_unsorted_count = 0;
3950 #endif
3952 for (;; )
3954 int iters = 0;
3955 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3957 bck = victim->bk;
3958 size = chunksize (victim);
3959 mchunkptr next = chunk_at_offset (victim, size);
3961 if (__glibc_unlikely (size <= CHUNK_HDR_SZ)
3962 || __glibc_unlikely (size > av->system_mem))
3963 malloc_printerr ("malloc(): invalid size (unsorted)");
3964 if (__glibc_unlikely (chunksize_nomask (next) < CHUNK_HDR_SZ)
3965 || __glibc_unlikely (chunksize_nomask (next) > av->system_mem))
3966 malloc_printerr ("malloc(): invalid next size (unsorted)");
3967 if (__glibc_unlikely ((prev_size (next) & ~(SIZE_BITS)) != size))
3968 malloc_printerr ("malloc(): mismatching next->prev_size (unsorted)");
3969 if (__glibc_unlikely (bck->fd != victim)
3970 || __glibc_unlikely (victim->fd != unsorted_chunks (av)))
3971 malloc_printerr ("malloc(): unsorted double linked list corrupted");
3972 if (__glibc_unlikely (prev_inuse (next)))
3973 malloc_printerr ("malloc(): invalid next->prev_inuse (unsorted)");
3976 If a small request, try to use last remainder if it is the
3977 only chunk in unsorted bin. This helps promote locality for
3978 runs of consecutive small requests. This is the only
3979 exception to best-fit, and applies only when there is
3980 no exact fit for a small chunk.
3983 if (in_smallbin_range (nb) &&
3984 bck == unsorted_chunks (av) &&
3985 victim == av->last_remainder &&
3986 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
3988 /* split and reattach remainder */
3989 remainder_size = size - nb;
3990 remainder = chunk_at_offset (victim, nb);
3991 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
3992 av->last_remainder = remainder;
3993 remainder->bk = remainder->fd = unsorted_chunks (av);
3994 if (!in_smallbin_range (remainder_size))
3996 remainder->fd_nextsize = NULL;
3997 remainder->bk_nextsize = NULL;
4000 set_head (victim, nb | PREV_INUSE |
4001 (av != &main_arena ? NON_MAIN_ARENA : 0));
4002 set_head (remainder, remainder_size | PREV_INUSE);
4003 set_foot (remainder, remainder_size);
4005 check_malloced_chunk (av, victim, nb);
4006 void *p = chunk2mem (victim);
4007 alloc_perturb (p, bytes);
4008 return p;
4011 /* remove from unsorted list */
4012 if (__glibc_unlikely (bck->fd != victim))
4013 malloc_printerr ("malloc(): corrupted unsorted chunks 3");
4014 unsorted_chunks (av)->bk = bck;
4015 bck->fd = unsorted_chunks (av);
4017 /* Take now instead of binning if exact fit */
4019 if (size == nb)
4021 set_inuse_bit_at_offset (victim, size);
4022 if (av != &main_arena)
4023 set_non_main_arena (victim);
4024 #if USE_TCACHE
4025 /* Fill cache first, return to user only if cache fills.
4026 We may return one of these chunks later. */
4027 if (tcache_nb
4028 && tcache->counts[tc_idx] < mp_.tcache_count)
4030 tcache_put (victim, tc_idx);
4031 return_cached = 1;
4032 continue;
4034 else
4036 #endif
4037 check_malloced_chunk (av, victim, nb);
4038 void *p = chunk2mem (victim);
4039 alloc_perturb (p, bytes);
4040 return p;
4041 #if USE_TCACHE
4043 #endif
4046 /* place chunk in bin */
4048 if (in_smallbin_range (size))
4050 victim_index = smallbin_index (size);
4051 bck = bin_at (av, victim_index);
4052 fwd = bck->fd;
4054 else
4056 victim_index = largebin_index (size);
4057 bck = bin_at (av, victim_index);
4058 fwd = bck->fd;
4060 /* maintain large bins in sorted order */
4061 if (fwd != bck)
4063 /* Or with inuse bit to speed comparisons */
4064 size |= PREV_INUSE;
4065 /* if smaller than smallest, bypass loop below */
4066 assert (chunk_main_arena (bck->bk));
4067 if ((unsigned long) (size)
4068 < (unsigned long) chunksize_nomask (bck->bk))
4070 fwd = bck;
4071 bck = bck->bk;
4073 victim->fd_nextsize = fwd->fd;
4074 victim->bk_nextsize = fwd->fd->bk_nextsize;
4075 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
4077 else
4079 assert (chunk_main_arena (fwd));
4080 while ((unsigned long) size < chunksize_nomask (fwd))
4082 fwd = fwd->fd_nextsize;
4083 assert (chunk_main_arena (fwd));
4086 if ((unsigned long) size
4087 == (unsigned long) chunksize_nomask (fwd))
4088 /* Always insert in the second position. */
4089 fwd = fwd->fd;
4090 else
4092 victim->fd_nextsize = fwd;
4093 victim->bk_nextsize = fwd->bk_nextsize;
4094 if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd))
4095 malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)");
4096 fwd->bk_nextsize = victim;
4097 victim->bk_nextsize->fd_nextsize = victim;
4099 bck = fwd->bk;
4100 if (bck->fd != fwd)
4101 malloc_printerr ("malloc(): largebin double linked list corrupted (bk)");
4104 else
4105 victim->fd_nextsize = victim->bk_nextsize = victim;
4108 mark_bin (av, victim_index);
4109 victim->bk = bck;
4110 victim->fd = fwd;
4111 fwd->bk = victim;
4112 bck->fd = victim;
4114 #if USE_TCACHE
4115 /* If we've processed as many chunks as we're allowed while
4116 filling the cache, return one of the cached ones. */
4117 ++tcache_unsorted_count;
4118 if (return_cached
4119 && mp_.tcache_unsorted_limit > 0
4120 && tcache_unsorted_count > mp_.tcache_unsorted_limit)
4122 return tcache_get (tc_idx);
4124 #endif
4126 #define MAX_ITERS 10000
4127 if (++iters >= MAX_ITERS)
4128 break;
4131 #if USE_TCACHE
4132 /* If all the small chunks we found ended up cached, return one now. */
4133 if (return_cached)
4135 return tcache_get (tc_idx);
4137 #endif
4140 If a large request, scan through the chunks of current bin in
4141 sorted order to find smallest that fits. Use the skip list for this.
4144 if (!in_smallbin_range (nb))
4146 bin = bin_at (av, idx);
4148 /* skip scan if empty or largest chunk is too small */
4149 if ((victim = first (bin)) != bin
4150 && (unsigned long) chunksize_nomask (victim)
4151 >= (unsigned long) (nb))
4153 victim = victim->bk_nextsize;
4154 while (((unsigned long) (size = chunksize (victim)) <
4155 (unsigned long) (nb)))
4156 victim = victim->bk_nextsize;
4158 /* Avoid removing the first entry for a size so that the skip
4159 list does not have to be rerouted. */
4160 if (victim != last (bin)
4161 && chunksize_nomask (victim)
4162 == chunksize_nomask (victim->fd))
4163 victim = victim->fd;
4165 remainder_size = size - nb;
4166 unlink_chunk (av, victim);
4168 /* Exhaust */
4169 if (remainder_size < MINSIZE)
4171 set_inuse_bit_at_offset (victim, size);
4172 if (av != &main_arena)
4173 set_non_main_arena (victim);
4175 /* Split */
4176 else
4178 remainder = chunk_at_offset (victim, nb);
4179 /* We cannot assume the unsorted list is empty and therefore
4180 have to perform a complete insert here. */
4181 bck = unsorted_chunks (av);
4182 fwd = bck->fd;
4183 if (__glibc_unlikely (fwd->bk != bck))
4184 malloc_printerr ("malloc(): corrupted unsorted chunks");
4185 remainder->bk = bck;
4186 remainder->fd = fwd;
4187 bck->fd = remainder;
4188 fwd->bk = remainder;
4189 if (!in_smallbin_range (remainder_size))
4191 remainder->fd_nextsize = NULL;
4192 remainder->bk_nextsize = NULL;
4194 set_head (victim, nb | PREV_INUSE |
4195 (av != &main_arena ? NON_MAIN_ARENA : 0));
4196 set_head (remainder, remainder_size | PREV_INUSE);
4197 set_foot (remainder, remainder_size);
4199 check_malloced_chunk (av, victim, nb);
4200 void *p = chunk2mem (victim);
4201 alloc_perturb (p, bytes);
4202 return p;
4207 Search for a chunk by scanning bins, starting with next largest
4208 bin. This search is strictly by best-fit; i.e., the smallest
4209 (with ties going to approximately the least recently used) chunk
4210 that fits is selected.
4212 The bitmap avoids needing to check that most blocks are nonempty.
4213 The particular case of skipping all bins during warm-up phases
4214 when no chunks have been returned yet is faster than it might look.
4217 ++idx;
4218 bin = bin_at (av, idx);
4219 block = idx2block (idx);
4220 map = av->binmap[block];
4221 bit = idx2bit (idx);
4223 for (;; )
4225 /* Skip rest of block if there are no more set bits in this block. */
4226 if (bit > map || bit == 0)
4230 if (++block >= BINMAPSIZE) /* out of bins */
4231 goto use_top;
4233 while ((map = av->binmap[block]) == 0);
4235 bin = bin_at (av, (block << BINMAPSHIFT));
4236 bit = 1;
4239 /* Advance to bin with set bit. There must be one. */
4240 while ((bit & map) == 0)
4242 bin = next_bin (bin);
4243 bit <<= 1;
4244 assert (bit != 0);
4247 /* Inspect the bin. It is likely to be non-empty */
4248 victim = last (bin);
4250 /* If a false alarm (empty bin), clear the bit. */
4251 if (victim == bin)
4253 av->binmap[block] = map &= ~bit; /* Write through */
4254 bin = next_bin (bin);
4255 bit <<= 1;
4258 else
4260 size = chunksize (victim);
4262 /* We know the first chunk in this bin is big enough to use. */
4263 assert ((unsigned long) (size) >= (unsigned long) (nb));
4265 remainder_size = size - nb;
4267 /* unlink */
4268 unlink_chunk (av, victim);
4270 /* Exhaust */
4271 if (remainder_size < MINSIZE)
4273 set_inuse_bit_at_offset (victim, size);
4274 if (av != &main_arena)
4275 set_non_main_arena (victim);
4278 /* Split */
4279 else
4281 remainder = chunk_at_offset (victim, nb);
4283 /* We cannot assume the unsorted list is empty and therefore
4284 have to perform a complete insert here. */
4285 bck = unsorted_chunks (av);
4286 fwd = bck->fd;
4287 if (__glibc_unlikely (fwd->bk != bck))
4288 malloc_printerr ("malloc(): corrupted unsorted chunks 2");
4289 remainder->bk = bck;
4290 remainder->fd = fwd;
4291 bck->fd = remainder;
4292 fwd->bk = remainder;
4294 /* advertise as last remainder */
4295 if (in_smallbin_range (nb))
4296 av->last_remainder = remainder;
4297 if (!in_smallbin_range (remainder_size))
4299 remainder->fd_nextsize = NULL;
4300 remainder->bk_nextsize = NULL;
4302 set_head (victim, nb | PREV_INUSE |
4303 (av != &main_arena ? NON_MAIN_ARENA : 0));
4304 set_head (remainder, remainder_size | PREV_INUSE);
4305 set_foot (remainder, remainder_size);
4307 check_malloced_chunk (av, victim, nb);
4308 void *p = chunk2mem (victim);
4309 alloc_perturb (p, bytes);
4310 return p;
4314 use_top:
4316 If large enough, split off the chunk bordering the end of memory
4317 (held in av->top). Note that this is in accord with the best-fit
4318 search rule. In effect, av->top is treated as larger (and thus
4319 less well fitting) than any other available chunk since it can
4320 be extended to be as large as necessary (up to system
4321 limitations).
4323 We require that av->top always exists (i.e., has size >=
4324 MINSIZE) after initialization, so if it would otherwise be
4325 exhausted by current request, it is replenished. (The main
4326 reason for ensuring it exists is that we may need MINSIZE space
4327 to put in fenceposts in sysmalloc.)
4330 victim = av->top;
4331 size = chunksize (victim);
4333 if (__glibc_unlikely (size > av->system_mem))
4334 malloc_printerr ("malloc(): corrupted top size");
4336 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
4338 remainder_size = size - nb;
4339 remainder = chunk_at_offset (victim, nb);
4340 av->top = remainder;
4341 set_head (victim, nb | PREV_INUSE |
4342 (av != &main_arena ? NON_MAIN_ARENA : 0));
4343 set_head (remainder, remainder_size | PREV_INUSE);
4345 check_malloced_chunk (av, victim, nb);
4346 void *p = chunk2mem (victim);
4347 alloc_perturb (p, bytes);
4348 return p;
4351 /* When we are using atomic ops to free fast chunks we can get
4352 here for all block sizes. */
4353 else if (atomic_load_relaxed (&av->have_fastchunks))
4355 malloc_consolidate (av);
4356 /* restore original bin index */
4357 if (in_smallbin_range (nb))
4358 idx = smallbin_index (nb);
4359 else
4360 idx = largebin_index (nb);
4364 Otherwise, relay to handle system-dependent cases
4366 else
4368 void *p = sysmalloc (nb, av);
4369 if (p != NULL)
4370 alloc_perturb (p, bytes);
4371 return p;
4377 ------------------------------ free ------------------------------
4380 static void
4381 _int_free (mstate av, mchunkptr p, int have_lock)
4383 INTERNAL_SIZE_T size; /* its size */
4384 mfastbinptr *fb; /* associated fastbin */
4385 mchunkptr nextchunk; /* next contiguous chunk */
4386 INTERNAL_SIZE_T nextsize; /* its size */
4387 int nextinuse; /* true if nextchunk is used */
4388 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
4389 mchunkptr bck; /* misc temp for linking */
4390 mchunkptr fwd; /* misc temp for linking */
4392 size = chunksize (p);
4394 /* Little security check which won't hurt performance: the
4395 allocator never wrapps around at the end of the address space.
4396 Therefore we can exclude some size values which might appear
4397 here by accident or by "design" from some intruder. */
4398 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
4399 || __builtin_expect (misaligned_chunk (p), 0))
4400 malloc_printerr ("free(): invalid pointer");
4401 /* We know that each chunk is at least MINSIZE bytes in size or a
4402 multiple of MALLOC_ALIGNMENT. */
4403 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
4404 malloc_printerr ("free(): invalid size");
4406 check_inuse_chunk(av, p);
4408 #if USE_TCACHE
4410 size_t tc_idx = csize2tidx (size);
4411 if (tcache != NULL && tc_idx < mp_.tcache_bins)
4413 /* Check to see if it's already in the tcache. */
4414 tcache_entry *e = (tcache_entry *) chunk2mem (p);
4416 /* This test succeeds on double free. However, we don't 100%
4417 trust it (it also matches random payload data at a 1 in
4418 2^<size_t> chance), so verify it's not an unlikely
4419 coincidence before aborting. */
4420 if (__glibc_unlikely (e->key == tcache))
4422 tcache_entry *tmp;
4423 size_t cnt = 0;
4424 LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
4425 for (tmp = tcache->entries[tc_idx];
4426 tmp;
4427 tmp = REVEAL_PTR (tmp->next), ++cnt)
4429 if (cnt >= mp_.tcache_count)
4430 malloc_printerr ("free(): too many chunks detected in tcache");
4431 if (__glibc_unlikely (!aligned_OK (tmp)))
4432 malloc_printerr ("free(): unaligned chunk detected in tcache 2");
4433 if (tmp == e)
4434 malloc_printerr ("free(): double free detected in tcache 2");
4435 /* If we get here, it was a coincidence. We've wasted a
4436 few cycles, but don't abort. */
4440 if (tcache->counts[tc_idx] < mp_.tcache_count)
4442 tcache_put (p, tc_idx);
4443 return;
4447 #endif
4450 If eligible, place chunk on a fastbin so it can be found
4451 and used quickly in malloc.
4454 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
4456 #if TRIM_FASTBINS
4458 If TRIM_FASTBINS set, don't place chunks
4459 bordering top into fastbins
4461 && (chunk_at_offset(p, size) != av->top)
4462 #endif
4465 if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
4466 <= CHUNK_HDR_SZ, 0)
4467 || __builtin_expect (chunksize (chunk_at_offset (p, size))
4468 >= av->system_mem, 0))
4470 bool fail = true;
4471 /* We might not have a lock at this point and concurrent modifications
4472 of system_mem might result in a false positive. Redo the test after
4473 getting the lock. */
4474 if (!have_lock)
4476 __libc_lock_lock (av->mutex);
4477 fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ
4478 || chunksize (chunk_at_offset (p, size)) >= av->system_mem);
4479 __libc_lock_unlock (av->mutex);
4482 if (fail)
4483 malloc_printerr ("free(): invalid next size (fast)");
4486 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4488 atomic_store_relaxed (&av->have_fastchunks, true);
4489 unsigned int idx = fastbin_index(size);
4490 fb = &fastbin (av, idx);
4492 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
4493 mchunkptr old = *fb, old2;
4495 if (SINGLE_THREAD_P)
4497 /* Check that the top of the bin is not the record we are going to
4498 add (i.e., double free). */
4499 if (__builtin_expect (old == p, 0))
4500 malloc_printerr ("double free or corruption (fasttop)");
4501 p->fd = PROTECT_PTR (&p->fd, old);
4502 *fb = p;
4504 else
4507 /* Check that the top of the bin is not the record we are going to
4508 add (i.e., double free). */
4509 if (__builtin_expect (old == p, 0))
4510 malloc_printerr ("double free or corruption (fasttop)");
4511 old2 = old;
4512 p->fd = PROTECT_PTR (&p->fd, old);
4514 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2))
4515 != old2);
4517 /* Check that size of fastbin chunk at the top is the same as
4518 size of the chunk that we are adding. We can dereference OLD
4519 only if we have the lock, otherwise it might have already been
4520 allocated again. */
4521 if (have_lock && old != NULL
4522 && __builtin_expect (fastbin_index (chunksize (old)) != idx, 0))
4523 malloc_printerr ("invalid fastbin entry (free)");
4527 Consolidate other non-mmapped chunks as they arrive.
4530 else if (!chunk_is_mmapped(p)) {
4532 /* If we're single-threaded, don't lock the arena. */
4533 if (SINGLE_THREAD_P)
4534 have_lock = true;
4536 if (!have_lock)
4537 __libc_lock_lock (av->mutex);
4539 nextchunk = chunk_at_offset(p, size);
4541 /* Lightweight tests: check whether the block is already the
4542 top block. */
4543 if (__glibc_unlikely (p == av->top))
4544 malloc_printerr ("double free or corruption (top)");
4545 /* Or whether the next chunk is beyond the boundaries of the arena. */
4546 if (__builtin_expect (contiguous (av)
4547 && (char *) nextchunk
4548 >= ((char *) av->top + chunksize(av->top)), 0))
4549 malloc_printerr ("double free or corruption (out)");
4550 /* Or whether the block is actually not marked used. */
4551 if (__glibc_unlikely (!prev_inuse(nextchunk)))
4552 malloc_printerr ("double free or corruption (!prev)");
4554 nextsize = chunksize(nextchunk);
4555 if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0)
4556 || __builtin_expect (nextsize >= av->system_mem, 0))
4557 malloc_printerr ("free(): invalid next size (normal)");
4559 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4561 /* consolidate backward */
4562 if (!prev_inuse(p)) {
4563 prevsize = prev_size (p);
4564 size += prevsize;
4565 p = chunk_at_offset(p, -((long) prevsize));
4566 if (__glibc_unlikely (chunksize(p) != prevsize))
4567 malloc_printerr ("corrupted size vs. prev_size while consolidating");
4568 unlink_chunk (av, p);
4571 if (nextchunk != av->top) {
4572 /* get and clear inuse bit */
4573 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4575 /* consolidate forward */
4576 if (!nextinuse) {
4577 unlink_chunk (av, nextchunk);
4578 size += nextsize;
4579 } else
4580 clear_inuse_bit_at_offset(nextchunk, 0);
4583 Place the chunk in unsorted chunk list. Chunks are
4584 not placed into regular bins until after they have
4585 been given one chance to be used in malloc.
4588 bck = unsorted_chunks(av);
4589 fwd = bck->fd;
4590 if (__glibc_unlikely (fwd->bk != bck))
4591 malloc_printerr ("free(): corrupted unsorted chunks");
4592 p->fd = fwd;
4593 p->bk = bck;
4594 if (!in_smallbin_range(size))
4596 p->fd_nextsize = NULL;
4597 p->bk_nextsize = NULL;
4599 bck->fd = p;
4600 fwd->bk = p;
4602 set_head(p, size | PREV_INUSE);
4603 set_foot(p, size);
4605 check_free_chunk(av, p);
4609 If the chunk borders the current high end of memory,
4610 consolidate into top
4613 else {
4614 size += nextsize;
4615 set_head(p, size | PREV_INUSE);
4616 av->top = p;
4617 check_chunk(av, p);
4621 If freeing a large space, consolidate possibly-surrounding
4622 chunks. Then, if the total unused topmost memory exceeds trim
4623 threshold, ask malloc_trim to reduce top.
4625 Unless max_fast is 0, we don't know if there are fastbins
4626 bordering top, so we cannot tell for sure whether threshold
4627 has been reached unless fastbins are consolidated. But we
4628 don't want to consolidate on each free. As a compromise,
4629 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4630 is reached.
4633 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4634 if (atomic_load_relaxed (&av->have_fastchunks))
4635 malloc_consolidate(av);
4637 if (av == &main_arena) {
4638 #ifndef MORECORE_CANNOT_TRIM
4639 if ((unsigned long)(chunksize(av->top)) >=
4640 (unsigned long)(mp_.trim_threshold))
4641 systrim(mp_.top_pad, av);
4642 #endif
4643 } else {
4644 /* Always try heap_trim(), even if the top chunk is not
4645 large, because the corresponding heap might go away. */
4646 heap_info *heap = heap_for_ptr(top(av));
4648 assert(heap->ar_ptr == av);
4649 heap_trim(heap, mp_.top_pad);
4653 if (!have_lock)
4654 __libc_lock_unlock (av->mutex);
4657 If the chunk was allocated via mmap, release via munmap().
4660 else {
4661 munmap_chunk (p);
4666 ------------------------- malloc_consolidate -------------------------
4668 malloc_consolidate is a specialized version of free() that tears
4669 down chunks held in fastbins. Free itself cannot be used for this
4670 purpose since, among other things, it might place chunks back onto
4671 fastbins. So, instead, we need to use a minor variant of the same
4672 code.
4675 static void malloc_consolidate(mstate av)
4677 mfastbinptr* fb; /* current fastbin being consolidated */
4678 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4679 mchunkptr p; /* current chunk being consolidated */
4680 mchunkptr nextp; /* next chunk to consolidate */
4681 mchunkptr unsorted_bin; /* bin header */
4682 mchunkptr first_unsorted; /* chunk to link to */
4684 /* These have same use as in free() */
4685 mchunkptr nextchunk;
4686 INTERNAL_SIZE_T size;
4687 INTERNAL_SIZE_T nextsize;
4688 INTERNAL_SIZE_T prevsize;
4689 int nextinuse;
4691 atomic_store_relaxed (&av->have_fastchunks, false);
4693 unsorted_bin = unsorted_chunks(av);
4696 Remove each chunk from fast bin and consolidate it, placing it
4697 then in unsorted bin. Among other reasons for doing this,
4698 placing in unsorted bin avoids needing to calculate actual bins
4699 until malloc is sure that chunks aren't immediately going to be
4700 reused anyway.
4703 maxfb = &fastbin (av, NFASTBINS - 1);
4704 fb = &fastbin (av, 0);
4705 do {
4706 p = atomic_exchange_acq (fb, NULL);
4707 if (p != 0) {
4708 do {
4710 if (__glibc_unlikely (misaligned_chunk (p)))
4711 malloc_printerr ("malloc_consolidate(): "
4712 "unaligned fastbin chunk detected");
4714 unsigned int idx = fastbin_index (chunksize (p));
4715 if ((&fastbin (av, idx)) != fb)
4716 malloc_printerr ("malloc_consolidate(): invalid chunk size");
4719 check_inuse_chunk(av, p);
4720 nextp = REVEAL_PTR (p->fd);
4722 /* Slightly streamlined version of consolidation code in free() */
4723 size = chunksize (p);
4724 nextchunk = chunk_at_offset(p, size);
4725 nextsize = chunksize(nextchunk);
4727 if (!prev_inuse(p)) {
4728 prevsize = prev_size (p);
4729 size += prevsize;
4730 p = chunk_at_offset(p, -((long) prevsize));
4731 if (__glibc_unlikely (chunksize(p) != prevsize))
4732 malloc_printerr ("corrupted size vs. prev_size in fastbins");
4733 unlink_chunk (av, p);
4736 if (nextchunk != av->top) {
4737 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4739 if (!nextinuse) {
4740 size += nextsize;
4741 unlink_chunk (av, nextchunk);
4742 } else
4743 clear_inuse_bit_at_offset(nextchunk, 0);
4745 first_unsorted = unsorted_bin->fd;
4746 unsorted_bin->fd = p;
4747 first_unsorted->bk = p;
4749 if (!in_smallbin_range (size)) {
4750 p->fd_nextsize = NULL;
4751 p->bk_nextsize = NULL;
4754 set_head(p, size | PREV_INUSE);
4755 p->bk = unsorted_bin;
4756 p->fd = first_unsorted;
4757 set_foot(p, size);
4760 else {
4761 size += nextsize;
4762 set_head(p, size | PREV_INUSE);
4763 av->top = p;
4766 } while ( (p = nextp) != 0);
4769 } while (fb++ != maxfb);
4773 ------------------------------ realloc ------------------------------
4776 void*
4777 _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4778 INTERNAL_SIZE_T nb)
4780 mchunkptr newp; /* chunk to return */
4781 INTERNAL_SIZE_T newsize; /* its size */
4782 void* newmem; /* corresponding user mem */
4784 mchunkptr next; /* next contiguous chunk after oldp */
4786 mchunkptr remainder; /* extra space at end of newp */
4787 unsigned long remainder_size; /* its size */
4789 /* oldmem size */
4790 if (__builtin_expect (chunksize_nomask (oldp) <= CHUNK_HDR_SZ, 0)
4791 || __builtin_expect (oldsize >= av->system_mem, 0))
4792 malloc_printerr ("realloc(): invalid old size");
4794 check_inuse_chunk (av, oldp);
4796 /* All callers already filter out mmap'ed chunks. */
4797 assert (!chunk_is_mmapped (oldp));
4799 next = chunk_at_offset (oldp, oldsize);
4800 INTERNAL_SIZE_T nextsize = chunksize (next);
4801 if (__builtin_expect (chunksize_nomask (next) <= CHUNK_HDR_SZ, 0)
4802 || __builtin_expect (nextsize >= av->system_mem, 0))
4803 malloc_printerr ("realloc(): invalid next size");
4805 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4807 /* already big enough; split below */
4808 newp = oldp;
4809 newsize = oldsize;
4812 else
4814 /* Try to expand forward into top */
4815 if (next == av->top &&
4816 (unsigned long) (newsize = oldsize + nextsize) >=
4817 (unsigned long) (nb + MINSIZE))
4819 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4820 av->top = chunk_at_offset (oldp, nb);
4821 set_head (av->top, (newsize - nb) | PREV_INUSE);
4822 check_inuse_chunk (av, oldp);
4823 return TAG_NEW_USABLE (chunk2rawmem (oldp));
4826 /* Try to expand forward into next chunk; split off remainder below */
4827 else if (next != av->top &&
4828 !inuse (next) &&
4829 (unsigned long) (newsize = oldsize + nextsize) >=
4830 (unsigned long) (nb))
4832 newp = oldp;
4833 unlink_chunk (av, next);
4836 /* allocate, copy, free */
4837 else
4839 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4840 if (newmem == 0)
4841 return 0; /* propagate failure */
4843 newp = mem2chunk (newmem);
4844 newsize = chunksize (newp);
4847 Avoid copy if newp is next chunk after oldp.
4849 if (newp == next)
4851 newsize += oldsize;
4852 newp = oldp;
4854 else
4856 void *oldmem = chunk2rawmem (oldp);
4857 size_t sz = CHUNK_AVAILABLE_SIZE (oldp) - CHUNK_HDR_SZ;
4858 (void) TAG_REGION (oldmem, sz);
4859 newmem = TAG_NEW_USABLE (newmem);
4860 memcpy (newmem, oldmem, sz);
4861 _int_free (av, oldp, 1);
4862 check_inuse_chunk (av, newp);
4863 return newmem;
4868 /* If possible, free extra space in old or extended chunk */
4870 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
4872 remainder_size = newsize - nb;
4874 if (remainder_size < MINSIZE) /* not enough extra to split off */
4876 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4877 set_inuse_bit_at_offset (newp, newsize);
4879 else /* split remainder */
4881 remainder = chunk_at_offset (newp, nb);
4882 /* Clear any user-space tags before writing the header. */
4883 remainder = TAG_REGION (remainder, remainder_size);
4884 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4885 set_head (remainder, remainder_size | PREV_INUSE |
4886 (av != &main_arena ? NON_MAIN_ARENA : 0));
4887 /* Mark remainder as inuse so free() won't complain */
4888 set_inuse_bit_at_offset (remainder, remainder_size);
4889 _int_free (av, remainder, 1);
4892 check_inuse_chunk (av, newp);
4893 return TAG_NEW_USABLE (chunk2rawmem (newp));
4897 ------------------------------ memalign ------------------------------
4900 static void *
4901 _int_memalign (mstate av, size_t alignment, size_t bytes)
4903 INTERNAL_SIZE_T nb; /* padded request size */
4904 char *m; /* memory returned by malloc call */
4905 mchunkptr p; /* corresponding chunk */
4906 char *brk; /* alignment point within p */
4907 mchunkptr newp; /* chunk to return */
4908 INTERNAL_SIZE_T newsize; /* its size */
4909 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4910 mchunkptr remainder; /* spare room at end to split off */
4911 unsigned long remainder_size; /* its size */
4912 INTERNAL_SIZE_T size;
4916 if (!checked_request2size (bytes, &nb))
4918 __set_errno (ENOMEM);
4919 return NULL;
4923 Strategy: find a spot within that chunk that meets the alignment
4924 request, and then possibly free the leading and trailing space.
4927 /* Call malloc with worst case padding to hit alignment. */
4929 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4931 if (m == 0)
4932 return 0; /* propagate failure */
4934 p = mem2chunk (m);
4936 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4938 { /*
4939 Find an aligned spot inside chunk. Since we need to give back
4940 leading space in a chunk of at least MINSIZE, if the first
4941 calculation places us at a spot with less than MINSIZE leader,
4942 we can move to the next aligned spot -- we've allocated enough
4943 total room so that this is always possible.
4945 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4946 - ((signed long) alignment));
4947 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4948 brk += alignment;
4950 newp = (mchunkptr) brk;
4951 leadsize = brk - (char *) (p);
4952 newsize = chunksize (p) - leadsize;
4954 /* For mmapped chunks, just adjust offset */
4955 if (chunk_is_mmapped (p))
4957 set_prev_size (newp, prev_size (p) + leadsize);
4958 set_head (newp, newsize | IS_MMAPPED);
4959 return chunk2mem (newp);
4962 /* Otherwise, give back leader, use the rest */
4963 set_head (newp, newsize | PREV_INUSE |
4964 (av != &main_arena ? NON_MAIN_ARENA : 0));
4965 set_inuse_bit_at_offset (newp, newsize);
4966 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4967 _int_free (av, p, 1);
4968 p = newp;
4970 assert (newsize >= nb &&
4971 (((unsigned long) (chunk2rawmem (p))) % alignment) == 0);
4974 /* Also give back spare room at the end */
4975 if (!chunk_is_mmapped (p))
4977 size = chunksize (p);
4978 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4980 remainder_size = size - nb;
4981 remainder = chunk_at_offset (p, nb);
4982 set_head (remainder, remainder_size | PREV_INUSE |
4983 (av != &main_arena ? NON_MAIN_ARENA : 0));
4984 set_head_size (p, nb);
4985 _int_free (av, remainder, 1);
4989 check_inuse_chunk (av, p);
4990 return chunk2mem (p);
4995 ------------------------------ malloc_trim ------------------------------
4998 static int
4999 mtrim (mstate av, size_t pad)
5001 /* Ensure all blocks are consolidated. */
5002 malloc_consolidate (av);
5004 const size_t ps = GLRO (dl_pagesize);
5005 int psindex = bin_index (ps);
5006 const size_t psm1 = ps - 1;
5008 int result = 0;
5009 for (int i = 1; i < NBINS; ++i)
5010 if (i == 1 || i >= psindex)
5012 mbinptr bin = bin_at (av, i);
5014 for (mchunkptr p = last (bin); p != bin; p = p->bk)
5016 INTERNAL_SIZE_T size = chunksize (p);
5018 if (size > psm1 + sizeof (struct malloc_chunk))
5020 /* See whether the chunk contains at least one unused page. */
5021 char *paligned_mem = (char *) (((uintptr_t) p
5022 + sizeof (struct malloc_chunk)
5023 + psm1) & ~psm1);
5025 assert ((char *) chunk2rawmem (p) + 2 * CHUNK_HDR_SZ
5026 <= paligned_mem);
5027 assert ((char *) p + size > paligned_mem);
5029 /* This is the size we could potentially free. */
5030 size -= paligned_mem - (char *) p;
5032 if (size > psm1)
5034 #if MALLOC_DEBUG
5035 /* When debugging we simulate destroying the memory
5036 content. */
5037 memset (paligned_mem, 0x89, size & ~psm1);
5038 #endif
5039 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
5041 result = 1;
5047 #ifndef MORECORE_CANNOT_TRIM
5048 return result | (av == &main_arena ? systrim (pad, av) : 0);
5050 #else
5051 return result;
5052 #endif
5057 __malloc_trim (size_t s)
5059 int result = 0;
5061 if (__malloc_initialized < 0)
5062 ptmalloc_init ();
5064 mstate ar_ptr = &main_arena;
5067 __libc_lock_lock (ar_ptr->mutex);
5068 result |= mtrim (ar_ptr, s);
5069 __libc_lock_unlock (ar_ptr->mutex);
5071 ar_ptr = ar_ptr->next;
5073 while (ar_ptr != &main_arena);
5075 return result;
5080 ------------------------- malloc_usable_size -------------------------
5083 static size_t
5084 musable (void *mem)
5086 mchunkptr p;
5087 if (mem != 0)
5089 size_t result = 0;
5091 p = mem2chunk (mem);
5093 if (__builtin_expect (using_malloc_checking == 1, 0))
5094 return malloc_check_get_size (p);
5096 if (chunk_is_mmapped (p))
5098 if (DUMPED_MAIN_ARENA_CHUNK (p))
5099 result = chunksize (p) - SIZE_SZ;
5100 else
5101 result = chunksize (p) - CHUNK_HDR_SZ;
5103 else if (inuse (p))
5104 result = chunksize (p) - SIZE_SZ;
5106 #ifdef USE_MTAG
5107 /* The usable space may be reduced if memory tagging is needed,
5108 since we cannot share the user-space data with malloc's internal
5109 data structure. */
5110 result &= __mtag_granule_mask;
5111 #endif
5112 return result;
5114 return 0;
5118 size_t
5119 __malloc_usable_size (void *m)
5121 size_t result;
5123 result = musable (m);
5124 return result;
5128 ------------------------------ mallinfo ------------------------------
5129 Accumulate malloc statistics for arena AV into M.
5132 static void
5133 int_mallinfo (mstate av, struct mallinfo2 *m)
5135 size_t i;
5136 mbinptr b;
5137 mchunkptr p;
5138 INTERNAL_SIZE_T avail;
5139 INTERNAL_SIZE_T fastavail;
5140 int nblocks;
5141 int nfastblocks;
5143 check_malloc_state (av);
5145 /* Account for top */
5146 avail = chunksize (av->top);
5147 nblocks = 1; /* top always exists */
5149 /* traverse fastbins */
5150 nfastblocks = 0;
5151 fastavail = 0;
5153 for (i = 0; i < NFASTBINS; ++i)
5155 for (p = fastbin (av, i);
5156 p != 0;
5157 p = REVEAL_PTR (p->fd))
5159 if (__glibc_unlikely (misaligned_chunk (p)))
5160 malloc_printerr ("int_mallinfo(): "
5161 "unaligned fastbin chunk detected");
5162 ++nfastblocks;
5163 fastavail += chunksize (p);
5167 avail += fastavail;
5169 /* traverse regular bins */
5170 for (i = 1; i < NBINS; ++i)
5172 b = bin_at (av, i);
5173 for (p = last (b); p != b; p = p->bk)
5175 ++nblocks;
5176 avail += chunksize (p);
5180 m->smblks += nfastblocks;
5181 m->ordblks += nblocks;
5182 m->fordblks += avail;
5183 m->uordblks += av->system_mem - avail;
5184 m->arena += av->system_mem;
5185 m->fsmblks += fastavail;
5186 if (av == &main_arena)
5188 m->hblks = mp_.n_mmaps;
5189 m->hblkhd = mp_.mmapped_mem;
5190 m->usmblks = 0;
5191 m->keepcost = chunksize (av->top);
5196 struct mallinfo2
5197 __libc_mallinfo2 (void)
5199 struct mallinfo2 m;
5200 mstate ar_ptr;
5202 if (__malloc_initialized < 0)
5203 ptmalloc_init ();
5205 memset (&m, 0, sizeof (m));
5206 ar_ptr = &main_arena;
5209 __libc_lock_lock (ar_ptr->mutex);
5210 int_mallinfo (ar_ptr, &m);
5211 __libc_lock_unlock (ar_ptr->mutex);
5213 ar_ptr = ar_ptr->next;
5215 while (ar_ptr != &main_arena);
5217 return m;
5219 libc_hidden_def (__libc_mallinfo2)
5221 struct mallinfo
5222 __libc_mallinfo (void)
5224 struct mallinfo m;
5225 struct mallinfo2 m2 = __libc_mallinfo2 ();
5227 m.arena = m2.arena;
5228 m.ordblks = m2.ordblks;
5229 m.smblks = m2.smblks;
5230 m.hblks = m2.hblks;
5231 m.hblkhd = m2.hblkhd;
5232 m.usmblks = m2.usmblks;
5233 m.fsmblks = m2.fsmblks;
5234 m.uordblks = m2.uordblks;
5235 m.fordblks = m2.fordblks;
5236 m.keepcost = m2.keepcost;
5238 return m;
5243 ------------------------------ malloc_stats ------------------------------
5246 void
5247 __malloc_stats (void)
5249 int i;
5250 mstate ar_ptr;
5251 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
5253 if (__malloc_initialized < 0)
5254 ptmalloc_init ();
5255 _IO_flockfile (stderr);
5256 int old_flags2 = stderr->_flags2;
5257 stderr->_flags2 |= _IO_FLAGS2_NOTCANCEL;
5258 for (i = 0, ar_ptr = &main_arena;; i++)
5260 struct mallinfo2 mi;
5262 memset (&mi, 0, sizeof (mi));
5263 __libc_lock_lock (ar_ptr->mutex);
5264 int_mallinfo (ar_ptr, &mi);
5265 fprintf (stderr, "Arena %d:\n", i);
5266 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
5267 fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
5268 #if MALLOC_DEBUG > 1
5269 if (i > 0)
5270 dump_heap (heap_for_ptr (top (ar_ptr)));
5271 #endif
5272 system_b += mi.arena;
5273 in_use_b += mi.uordblks;
5274 __libc_lock_unlock (ar_ptr->mutex);
5275 ar_ptr = ar_ptr->next;
5276 if (ar_ptr == &main_arena)
5277 break;
5279 fprintf (stderr, "Total (incl. mmap):\n");
5280 fprintf (stderr, "system bytes = %10u\n", system_b);
5281 fprintf (stderr, "in use bytes = %10u\n", in_use_b);
5282 fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
5283 fprintf (stderr, "max mmap bytes = %10lu\n",
5284 (unsigned long) mp_.max_mmapped_mem);
5285 stderr->_flags2 = old_flags2;
5286 _IO_funlockfile (stderr);
5291 ------------------------------ mallopt ------------------------------
5293 static __always_inline int
5294 do_set_trim_threshold (size_t value)
5296 LIBC_PROBE (memory_mallopt_trim_threshold, 3, value, mp_.trim_threshold,
5297 mp_.no_dyn_threshold);
5298 mp_.trim_threshold = value;
5299 mp_.no_dyn_threshold = 1;
5300 return 1;
5303 static __always_inline int
5304 do_set_top_pad (size_t value)
5306 LIBC_PROBE (memory_mallopt_top_pad, 3, value, mp_.top_pad,
5307 mp_.no_dyn_threshold);
5308 mp_.top_pad = value;
5309 mp_.no_dyn_threshold = 1;
5310 return 1;
5313 static __always_inline int
5314 do_set_mmap_threshold (size_t value)
5316 /* Forbid setting the threshold too high. */
5317 if (value <= HEAP_MAX_SIZE / 2)
5319 LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value, mp_.mmap_threshold,
5320 mp_.no_dyn_threshold);
5321 mp_.mmap_threshold = value;
5322 mp_.no_dyn_threshold = 1;
5323 return 1;
5325 return 0;
5328 static __always_inline int
5329 do_set_mmaps_max (int32_t value)
5331 LIBC_PROBE (memory_mallopt_mmap_max, 3, value, mp_.n_mmaps_max,
5332 mp_.no_dyn_threshold);
5333 mp_.n_mmaps_max = value;
5334 mp_.no_dyn_threshold = 1;
5335 return 1;
5338 static __always_inline int
5339 do_set_mallopt_check (int32_t value)
5341 return 1;
5344 static __always_inline int
5345 do_set_perturb_byte (int32_t value)
5347 LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
5348 perturb_byte = value;
5349 return 1;
5352 static __always_inline int
5353 do_set_arena_test (size_t value)
5355 LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
5356 mp_.arena_test = value;
5357 return 1;
5360 static __always_inline int
5361 do_set_arena_max (size_t value)
5363 LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
5364 mp_.arena_max = value;
5365 return 1;
5368 #if USE_TCACHE
5369 static __always_inline int
5370 do_set_tcache_max (size_t value)
5372 if (value <= MAX_TCACHE_SIZE)
5374 LIBC_PROBE (memory_tunable_tcache_max_bytes, 2, value, mp_.tcache_max_bytes);
5375 mp_.tcache_max_bytes = value;
5376 mp_.tcache_bins = csize2tidx (request2size(value)) + 1;
5377 return 1;
5379 return 0;
5382 static __always_inline int
5383 do_set_tcache_count (size_t value)
5385 if (value <= MAX_TCACHE_COUNT)
5387 LIBC_PROBE (memory_tunable_tcache_count, 2, value, mp_.tcache_count);
5388 mp_.tcache_count = value;
5389 return 1;
5391 return 0;
5394 static __always_inline int
5395 do_set_tcache_unsorted_limit (size_t value)
5397 LIBC_PROBE (memory_tunable_tcache_unsorted_limit, 2, value, mp_.tcache_unsorted_limit);
5398 mp_.tcache_unsorted_limit = value;
5399 return 1;
5401 #endif
5403 static inline int
5404 __always_inline
5405 do_set_mxfast (size_t value)
5407 if (value <= MAX_FAST_SIZE)
5409 LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
5410 set_max_fast (value);
5411 return 1;
5413 return 0;
5417 __libc_mallopt (int param_number, int value)
5419 mstate av = &main_arena;
5420 int res = 1;
5422 if (__malloc_initialized < 0)
5423 ptmalloc_init ();
5424 __libc_lock_lock (av->mutex);
5426 LIBC_PROBE (memory_mallopt, 2, param_number, value);
5428 /* We must consolidate main arena before changing max_fast
5429 (see definition of set_max_fast). */
5430 malloc_consolidate (av);
5432 /* Many of these helper functions take a size_t. We do not worry
5433 about overflow here, because negative int values will wrap to
5434 very large size_t values and the helpers have sufficient range
5435 checking for such conversions. Many of these helpers are also
5436 used by the tunables macros in arena.c. */
5438 switch (param_number)
5440 case M_MXFAST:
5441 res = do_set_mxfast (value);
5442 break;
5444 case M_TRIM_THRESHOLD:
5445 res = do_set_trim_threshold (value);
5446 break;
5448 case M_TOP_PAD:
5449 res = do_set_top_pad (value);
5450 break;
5452 case M_MMAP_THRESHOLD:
5453 res = do_set_mmap_threshold (value);
5454 break;
5456 case M_MMAP_MAX:
5457 res = do_set_mmaps_max (value);
5458 break;
5460 case M_CHECK_ACTION:
5461 res = do_set_mallopt_check (value);
5462 break;
5464 case M_PERTURB:
5465 res = do_set_perturb_byte (value);
5466 break;
5468 case M_ARENA_TEST:
5469 if (value > 0)
5470 res = do_set_arena_test (value);
5471 break;
5473 case M_ARENA_MAX:
5474 if (value > 0)
5475 res = do_set_arena_max (value);
5476 break;
5478 __libc_lock_unlock (av->mutex);
5479 return res;
5481 libc_hidden_def (__libc_mallopt)
5485 -------------------- Alternative MORECORE functions --------------------
5490 General Requirements for MORECORE.
5492 The MORECORE function must have the following properties:
5494 If MORECORE_CONTIGUOUS is false:
5496 * MORECORE must allocate in multiples of pagesize. It will
5497 only be called with arguments that are multiples of pagesize.
5499 * MORECORE(0) must return an address that is at least
5500 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
5502 else (i.e. If MORECORE_CONTIGUOUS is true):
5504 * Consecutive calls to MORECORE with positive arguments
5505 return increasing addresses, indicating that space has been
5506 contiguously extended.
5508 * MORECORE need not allocate in multiples of pagesize.
5509 Calls to MORECORE need not have args of multiples of pagesize.
5511 * MORECORE need not page-align.
5513 In either case:
5515 * MORECORE may allocate more memory than requested. (Or even less,
5516 but this will generally result in a malloc failure.)
5518 * MORECORE must not allocate memory when given argument zero, but
5519 instead return one past the end address of memory from previous
5520 nonzero call. This malloc does NOT call MORECORE(0)
5521 until at least one call with positive arguments is made, so
5522 the initial value returned is not important.
5524 * Even though consecutive calls to MORECORE need not return contiguous
5525 addresses, it must be OK for malloc'ed chunks to span multiple
5526 regions in those cases where they do happen to be contiguous.
5528 * MORECORE need not handle negative arguments -- it may instead
5529 just return MORECORE_FAILURE when given negative arguments.
5530 Negative arguments are always multiples of pagesize. MORECORE
5531 must not misinterpret negative args as large positive unsigned
5532 args. You can suppress all such calls from even occurring by defining
5533 MORECORE_CANNOT_TRIM,
5535 There is some variation across systems about the type of the
5536 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
5537 actually be size_t, because sbrk supports negative args, so it is
5538 normally the signed type of the same width as size_t (sometimes
5539 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
5540 matter though. Internally, we use "long" as arguments, which should
5541 work across all reasonable possibilities.
5543 Additionally, if MORECORE ever returns failure for a positive
5544 request, then mmap is used as a noncontiguous system allocator. This
5545 is a useful backup strategy for systems with holes in address spaces
5546 -- in this case sbrk cannot contiguously expand the heap, but mmap
5547 may be able to map noncontiguous space.
5549 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
5550 a function that always returns MORECORE_FAILURE.
5552 If you are using this malloc with something other than sbrk (or its
5553 emulation) to supply memory regions, you probably want to set
5554 MORECORE_CONTIGUOUS as false. As an example, here is a custom
5555 allocator kindly contributed for pre-OSX macOS. It uses virtually
5556 but not necessarily physically contiguous non-paged memory (locked
5557 in, present and won't get swapped out). You can use it by
5558 uncommenting this section, adding some #includes, and setting up the
5559 appropriate defines above:
5561 *#define MORECORE osMoreCore
5562 *#define MORECORE_CONTIGUOUS 0
5564 There is also a shutdown routine that should somehow be called for
5565 cleanup upon program exit.
5567 *#define MAX_POOL_ENTRIES 100
5568 *#define MINIMUM_MORECORE_SIZE (64 * 1024)
5569 static int next_os_pool;
5570 void *our_os_pools[MAX_POOL_ENTRIES];
5572 void *osMoreCore(int size)
5574 void *ptr = 0;
5575 static void *sbrk_top = 0;
5577 if (size > 0)
5579 if (size < MINIMUM_MORECORE_SIZE)
5580 size = MINIMUM_MORECORE_SIZE;
5581 if (CurrentExecutionLevel() == kTaskLevel)
5582 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
5583 if (ptr == 0)
5585 return (void *) MORECORE_FAILURE;
5587 // save ptrs so they can be freed during cleanup
5588 our_os_pools[next_os_pool] = ptr;
5589 next_os_pool++;
5590 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
5591 sbrk_top = (char *) ptr + size;
5592 return ptr;
5594 else if (size < 0)
5596 // we don't currently support shrink behavior
5597 return (void *) MORECORE_FAILURE;
5599 else
5601 return sbrk_top;
5605 // cleanup any allocated memory pools
5606 // called as last thing before shutting down driver
5608 void osCleanupMem(void)
5610 void **ptr;
5612 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
5613 if (*ptr)
5615 PoolDeallocate(*ptr);
5616 * ptr = 0;
5623 /* Helper code. */
5625 extern char **__libc_argv attribute_hidden;
5627 static void
5628 malloc_printerr (const char *str)
5630 __libc_message (do_abort, "%s\n", str);
5631 __builtin_unreachable ();
5634 /* We need a wrapper function for one of the additions of POSIX. */
5636 __posix_memalign (void **memptr, size_t alignment, size_t size)
5638 void *mem;
5640 /* Test whether the SIZE argument is valid. It must be a power of
5641 two multiple of sizeof (void *). */
5642 if (alignment % sizeof (void *) != 0
5643 || !powerof2 (alignment / sizeof (void *))
5644 || alignment == 0)
5645 return EINVAL;
5648 void *address = RETURN_ADDRESS (0);
5649 mem = _mid_memalign (alignment, size, address);
5651 if (mem != NULL)
5653 *memptr = mem;
5654 return 0;
5657 return ENOMEM;
5659 weak_alias (__posix_memalign, posix_memalign)
5663 __malloc_info (int options, FILE *fp)
5665 /* For now, at least. */
5666 if (options != 0)
5667 return EINVAL;
5669 int n = 0;
5670 size_t total_nblocks = 0;
5671 size_t total_nfastblocks = 0;
5672 size_t total_avail = 0;
5673 size_t total_fastavail = 0;
5674 size_t total_system = 0;
5675 size_t total_max_system = 0;
5676 size_t total_aspace = 0;
5677 size_t total_aspace_mprotect = 0;
5681 if (__malloc_initialized < 0)
5682 ptmalloc_init ();
5684 fputs ("<malloc version=\"1\">\n", fp);
5686 /* Iterate over all arenas currently in use. */
5687 mstate ar_ptr = &main_arena;
5690 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
5692 size_t nblocks = 0;
5693 size_t nfastblocks = 0;
5694 size_t avail = 0;
5695 size_t fastavail = 0;
5696 struct
5698 size_t from;
5699 size_t to;
5700 size_t total;
5701 size_t count;
5702 } sizes[NFASTBINS + NBINS - 1];
5703 #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
5705 __libc_lock_lock (ar_ptr->mutex);
5707 /* Account for top chunk. The top-most available chunk is
5708 treated specially and is never in any bin. See "initial_top"
5709 comments. */
5710 avail = chunksize (ar_ptr->top);
5711 nblocks = 1; /* Top always exists. */
5713 for (size_t i = 0; i < NFASTBINS; ++i)
5715 mchunkptr p = fastbin (ar_ptr, i);
5716 if (p != NULL)
5718 size_t nthissize = 0;
5719 size_t thissize = chunksize (p);
5721 while (p != NULL)
5723 if (__glibc_unlikely (misaligned_chunk (p)))
5724 malloc_printerr ("__malloc_info(): "
5725 "unaligned fastbin chunk detected");
5726 ++nthissize;
5727 p = REVEAL_PTR (p->fd);
5730 fastavail += nthissize * thissize;
5731 nfastblocks += nthissize;
5732 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
5733 sizes[i].to = thissize;
5734 sizes[i].count = nthissize;
5736 else
5737 sizes[i].from = sizes[i].to = sizes[i].count = 0;
5739 sizes[i].total = sizes[i].count * sizes[i].to;
5743 mbinptr bin;
5744 struct malloc_chunk *r;
5746 for (size_t i = 1; i < NBINS; ++i)
5748 bin = bin_at (ar_ptr, i);
5749 r = bin->fd;
5750 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5751 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5752 = sizes[NFASTBINS - 1 + i].count = 0;
5754 if (r != NULL)
5755 while (r != bin)
5757 size_t r_size = chunksize_nomask (r);
5758 ++sizes[NFASTBINS - 1 + i].count;
5759 sizes[NFASTBINS - 1 + i].total += r_size;
5760 sizes[NFASTBINS - 1 + i].from
5761 = MIN (sizes[NFASTBINS - 1 + i].from, r_size);
5762 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5763 r_size);
5765 r = r->fd;
5768 if (sizes[NFASTBINS - 1 + i].count == 0)
5769 sizes[NFASTBINS - 1 + i].from = 0;
5770 nblocks += sizes[NFASTBINS - 1 + i].count;
5771 avail += sizes[NFASTBINS - 1 + i].total;
5774 size_t heap_size = 0;
5775 size_t heap_mprotect_size = 0;
5776 size_t heap_count = 0;
5777 if (ar_ptr != &main_arena)
5779 /* Iterate over the arena heaps from back to front. */
5780 heap_info *heap = heap_for_ptr (top (ar_ptr));
5783 heap_size += heap->size;
5784 heap_mprotect_size += heap->mprotect_size;
5785 heap = heap->prev;
5786 ++heap_count;
5788 while (heap != NULL);
5791 __libc_lock_unlock (ar_ptr->mutex);
5793 total_nfastblocks += nfastblocks;
5794 total_fastavail += fastavail;
5796 total_nblocks += nblocks;
5797 total_avail += avail;
5799 for (size_t i = 0; i < nsizes; ++i)
5800 if (sizes[i].count != 0 && i != NFASTBINS)
5801 fprintf (fp, "\
5802 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5803 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
5805 if (sizes[NFASTBINS].count != 0)
5806 fprintf (fp, "\
5807 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5808 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5809 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
5811 total_system += ar_ptr->system_mem;
5812 total_max_system += ar_ptr->max_system_mem;
5814 fprintf (fp,
5815 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5816 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5817 "<system type=\"current\" size=\"%zu\"/>\n"
5818 "<system type=\"max\" size=\"%zu\"/>\n",
5819 nfastblocks, fastavail, nblocks, avail,
5820 ar_ptr->system_mem, ar_ptr->max_system_mem);
5822 if (ar_ptr != &main_arena)
5824 fprintf (fp,
5825 "<aspace type=\"total\" size=\"%zu\"/>\n"
5826 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5827 "<aspace type=\"subheaps\" size=\"%zu\"/>\n",
5828 heap_size, heap_mprotect_size, heap_count);
5829 total_aspace += heap_size;
5830 total_aspace_mprotect += heap_mprotect_size;
5832 else
5834 fprintf (fp,
5835 "<aspace type=\"total\" size=\"%zu\"/>\n"
5836 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5837 ar_ptr->system_mem, ar_ptr->system_mem);
5838 total_aspace += ar_ptr->system_mem;
5839 total_aspace_mprotect += ar_ptr->system_mem;
5842 fputs ("</heap>\n", fp);
5843 ar_ptr = ar_ptr->next;
5845 while (ar_ptr != &main_arena);
5847 fprintf (fp,
5848 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5849 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5850 "<total type=\"mmap\" count=\"%d\" size=\"%zu\"/>\n"
5851 "<system type=\"current\" size=\"%zu\"/>\n"
5852 "<system type=\"max\" size=\"%zu\"/>\n"
5853 "<aspace type=\"total\" size=\"%zu\"/>\n"
5854 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5855 "</malloc>\n",
5856 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
5857 mp_.n_mmaps, mp_.mmapped_mem,
5858 total_system, total_max_system,
5859 total_aspace, total_aspace_mprotect);
5861 return 0;
5863 weak_alias (__malloc_info, malloc_info)
5866 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5867 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5868 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5869 strong_alias (__libc_memalign, __memalign)
5870 weak_alias (__libc_memalign, memalign)
5871 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5872 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5873 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5874 strong_alias (__libc_mallinfo, __mallinfo)
5875 weak_alias (__libc_mallinfo, mallinfo)
5876 strong_alias (__libc_mallinfo2, __mallinfo2)
5877 weak_alias (__libc_mallinfo2, mallinfo2)
5878 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5880 weak_alias (__malloc_stats, malloc_stats)
5881 weak_alias (__malloc_usable_size, malloc_usable_size)
5882 weak_alias (__malloc_trim, malloc_trim)
5884 #if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_26)
5885 compat_symbol (libc, __libc_free, cfree, GLIBC_2_0);
5886 #endif
5888 /* ------------------------------------------------------------
5889 History:
5891 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
5895 * Local variables:
5896 * c-basic-offset: 2
5897 * End: