stdlib: Remove use of mergesort on qsort (BZ 21719)
[glibc.git] / malloc / malloc.c
blobd0bbbf371048ee8aa8a30c03b189cb268b8ad9e4
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2023 Free Software Foundation, Inc.
3 Copyright The GNU Toolchain Authors.
4 This file is part of the GNU C Library.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If
18 not, see <https://www.gnu.org/licenses/>. */
21 This is a version (aka ptmalloc2) of malloc/free/realloc written by
22 Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
24 There have been substantial changes made after the integration into
25 glibc in all parts of the code. Do not look for much commonality
26 with the ptmalloc2 version.
28 * Version ptmalloc2-20011215
29 based on:
30 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
32 * Quickstart
34 In order to compile this implementation, a Makefile is provided with
35 the ptmalloc2 distribution, which has pre-defined targets for some
36 popular systems (e.g. "make posix" for Posix threads). All that is
37 typically required with regard to compiler flags is the selection of
38 the thread package via defining one out of USE_PTHREADS, USE_THR or
39 USE_SPROC. Check the thread-m.h file for what effects this has.
40 Many/most systems will additionally require USE_TSD_DATA_HACK to be
41 defined, so this is the default for "make posix".
43 * Why use this malloc?
45 This is not the fastest, most space-conserving, most portable, or
46 most tunable malloc ever written. However it is among the fastest
47 while also being among the most space-conserving, portable and tunable.
48 Consistent balance across these factors results in a good general-purpose
49 allocator for malloc-intensive programs.
51 The main properties of the algorithms are:
52 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
53 with ties normally decided via FIFO (i.e. least recently used).
54 * For small (<= 64 bytes by default) requests, it is a caching
55 allocator, that maintains pools of quickly recycled chunks.
56 * In between, and for combinations of large and small requests, it does
57 the best it can trying to meet both goals at once.
58 * For very large requests (>= 128KB by default), it relies on system
59 memory mapping facilities, if supported.
61 For a longer but slightly out of date high-level description, see
62 http://gee.cs.oswego.edu/dl/html/malloc.html
64 You may already by default be using a C library containing a malloc
65 that is based on some version of this malloc (for example in
66 linux). You might still want to use the one in this file in order to
67 customize settings or to avoid overheads associated with library
68 versions.
70 * Contents, described in more detail in "description of public routines" below.
72 Standard (ANSI/SVID/...) functions:
73 malloc(size_t n);
74 calloc(size_t n_elements, size_t element_size);
75 free(void* p);
76 realloc(void* p, size_t n);
77 memalign(size_t alignment, size_t n);
78 valloc(size_t n);
79 mallinfo()
80 mallopt(int parameter_number, int parameter_value)
82 Additional functions:
83 independent_calloc(size_t n_elements, size_t size, void* chunks[]);
84 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
85 pvalloc(size_t n);
86 malloc_trim(size_t pad);
87 malloc_usable_size(void* p);
88 malloc_stats();
90 * Vital statistics:
92 Supported pointer representation: 4 or 8 bytes
93 Supported size_t representation: 4 or 8 bytes
94 Note that size_t is allowed to be 4 bytes even if pointers are 8.
95 You can adjust this by defining INTERNAL_SIZE_T
97 Alignment: 2 * sizeof(size_t) (default)
98 (i.e., 8 byte alignment with 4byte size_t). This suffices for
99 nearly all current machines and C compilers. However, you can
100 define MALLOC_ALIGNMENT to be wider than this if necessary.
102 Minimum overhead per allocated chunk: 4 or 8 bytes
103 Each malloced chunk has a hidden word of overhead holding size
104 and status information.
106 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
107 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
109 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
110 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
111 needed; 4 (8) for a trailing size field and 8 (16) bytes for
112 free list pointers. Thus, the minimum allocatable size is
113 16/24/32 bytes.
115 Even a request for zero bytes (i.e., malloc(0)) returns a
116 pointer to something of the minimum allocatable size.
118 The maximum overhead wastage (i.e., number of extra bytes
119 allocated than were requested in malloc) is less than or equal
120 to the minimum size, except for requests >= mmap_threshold that
121 are serviced via mmap(), where the worst case wastage is 2 *
122 sizeof(size_t) bytes plus the remainder from a system page (the
123 minimal mmap unit); typically 4096 or 8192 bytes.
125 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
126 8-byte size_t: 2^64 minus about two pages
128 It is assumed that (possibly signed) size_t values suffice to
129 represent chunk sizes. `Possibly signed' is due to the fact
130 that `size_t' may be defined on a system as either a signed or
131 an unsigned type. The ISO C standard says that it must be
132 unsigned, but a few systems are known not to adhere to this.
133 Additionally, even when size_t is unsigned, sbrk (which is by
134 default used to obtain memory from system) accepts signed
135 arguments, and may not be able to handle size_t-wide arguments
136 with negative sign bit. Generally, values that would
137 appear as negative after accounting for overhead and alignment
138 are supported only via mmap(), which does not have this
139 limitation.
141 Requests for sizes outside the allowed range will perform an optional
142 failure action and then return null. (Requests may also
143 also fail because a system is out of memory.)
145 Thread-safety: thread-safe
147 Compliance: I believe it is compliant with the 1997 Single Unix Specification
148 Also SVID/XPG, ANSI C, and probably others as well.
150 * Synopsis of compile-time options:
152 People have reported using previous versions of this malloc on all
153 versions of Unix, sometimes by tweaking some of the defines
154 below. It has been tested most extensively on Solaris and Linux.
155 People also report using it in stand-alone embedded systems.
157 The implementation is in straight, hand-tuned ANSI C. It is not
158 at all modular. (Sorry!) It uses a lot of macros. To be at all
159 usable, this code should be compiled using an optimizing compiler
160 (for example gcc -O3) that can simplify expressions and control
161 paths. (FAQ: some macros import variables as arguments rather than
162 declare locals because people reported that some debuggers
163 otherwise get confused.)
165 OPTION DEFAULT VALUE
167 Compilation Environment options:
169 HAVE_MREMAP 0
171 Changing default word sizes:
173 INTERNAL_SIZE_T size_t
175 Configuration and functionality options:
177 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
178 USE_MALLOC_LOCK NOT defined
179 MALLOC_DEBUG NOT defined
180 REALLOC_ZERO_BYTES_FREES 1
181 TRIM_FASTBINS 0
183 Options for customizing MORECORE:
185 MORECORE sbrk
186 MORECORE_FAILURE -1
187 MORECORE_CONTIGUOUS 1
188 MORECORE_CANNOT_TRIM NOT defined
189 MORECORE_CLEARS 1
190 MMAP_AS_MORECORE_SIZE (1024 * 1024)
192 Tuning options that are also dynamically changeable via mallopt:
194 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
195 DEFAULT_TRIM_THRESHOLD 128 * 1024
196 DEFAULT_TOP_PAD 0
197 DEFAULT_MMAP_THRESHOLD 128 * 1024
198 DEFAULT_MMAP_MAX 65536
200 There are several other #defined constants and macros that you
201 probably don't want to touch unless you are extending or adapting malloc. */
204 void* is the pointer type that malloc should say it returns
207 #ifndef void
208 #define void void
209 #endif /*void*/
211 #include <stddef.h> /* for size_t */
212 #include <stdlib.h> /* for getenv(), abort() */
213 #include <unistd.h> /* for __libc_enable_secure */
215 #include <atomic.h>
216 #include <_itoa.h>
217 #include <bits/wordsize.h>
218 #include <sys/sysinfo.h>
220 #include <ldsodefs.h>
222 #include <unistd.h>
223 #include <stdio.h> /* needed for malloc_stats */
224 #include <errno.h>
225 #include <assert.h>
227 #include <shlib-compat.h>
229 /* For uintptr_t. */
230 #include <stdint.h>
232 /* For va_arg, va_start, va_end. */
233 #include <stdarg.h>
235 /* For MIN, MAX, powerof2. */
236 #include <sys/param.h>
238 /* For ALIGN_UP et. al. */
239 #include <libc-pointer-arith.h>
241 /* For DIAG_PUSH/POP_NEEDS_COMMENT et al. */
242 #include <libc-diag.h>
244 /* For memory tagging. */
245 #include <libc-mtag.h>
247 #include <malloc/malloc-internal.h>
249 /* For SINGLE_THREAD_P. */
250 #include <sysdep-cancel.h>
252 #include <libc-internal.h>
254 /* For tcache double-free check. */
255 #include <random-bits.h>
256 #include <sys/random.h>
257 #include <not-cancel.h>
260 Debugging:
262 Because freed chunks may be overwritten with bookkeeping fields, this
263 malloc will often die when freed memory is overwritten by user
264 programs. This can be very effective (albeit in an annoying way)
265 in helping track down dangling pointers.
267 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
268 enabled that will catch more memory errors. You probably won't be
269 able to make much sense of the actual assertion errors, but they
270 should help you locate incorrectly overwritten memory. The checking
271 is fairly extensive, and will slow down execution
272 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
273 will attempt to check every non-mmapped allocated and free chunk in
274 the course of computing the summaries. (By nature, mmapped regions
275 cannot be checked very much automatically.)
277 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
278 this code. The assertions in the check routines spell out in more
279 detail the assumptions and invariants underlying the algorithms.
281 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
282 checking that all accesses to malloced memory stay within their
283 bounds. However, there are several add-ons and adaptations of this
284 or other mallocs available that do this.
287 #ifndef MALLOC_DEBUG
288 #define MALLOC_DEBUG 0
289 #endif
291 #if USE_TCACHE
292 /* We want 64 entries. This is an arbitrary limit, which tunables can reduce. */
293 # define TCACHE_MAX_BINS 64
294 # define MAX_TCACHE_SIZE tidx2usize (TCACHE_MAX_BINS-1)
296 /* Only used to pre-fill the tunables. */
297 # define tidx2usize(idx) (((size_t) idx) * MALLOC_ALIGNMENT + MINSIZE - SIZE_SZ)
299 /* When "x" is from chunksize(). */
300 # define csize2tidx(x) (((x) - MINSIZE + MALLOC_ALIGNMENT - 1) / MALLOC_ALIGNMENT)
301 /* When "x" is a user-provided size. */
302 # define usize2tidx(x) csize2tidx (request2size (x))
304 /* With rounding and alignment, the bins are...
305 idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit)
306 idx 1 bytes 25..40 or 13..20
307 idx 2 bytes 41..56 or 21..28
308 etc. */
310 /* This is another arbitrary limit, which tunables can change. Each
311 tcache bin will hold at most this number of chunks. */
312 # define TCACHE_FILL_COUNT 7
314 /* Maximum chunks in tcache bins for tunables. This value must fit the range
315 of tcache->counts[] entries, else they may overflow. */
316 # define MAX_TCACHE_COUNT UINT16_MAX
317 #endif
319 /* Safe-Linking:
320 Use randomness from ASLR (mmap_base) to protect single-linked lists
321 of Fast-Bins and TCache. That is, mask the "next" pointers of the
322 lists' chunks, and also perform allocation alignment checks on them.
323 This mechanism reduces the risk of pointer hijacking, as was done with
324 Safe-Unlinking in the double-linked lists of Small-Bins.
325 It assumes a minimum page size of 4096 bytes (12 bits). Systems with
326 larger pages provide less entropy, although the pointer mangling
327 still works. */
328 #define PROTECT_PTR(pos, ptr) \
329 ((__typeof (ptr)) ((((size_t) pos) >> 12) ^ ((size_t) ptr)))
330 #define REVEAL_PTR(ptr) PROTECT_PTR (&ptr, ptr)
333 The REALLOC_ZERO_BYTES_FREES macro controls the behavior of realloc (p, 0)
334 when p is nonnull. If the macro is nonzero, the realloc call returns NULL;
335 otherwise, the call returns what malloc (0) would. In either case,
336 p is freed. Glibc uses a nonzero REALLOC_ZERO_BYTES_FREES, which
337 implements common historical practice.
339 ISO C17 says the realloc call has implementation-defined behavior,
340 and it might not even free p.
343 #ifndef REALLOC_ZERO_BYTES_FREES
344 #define REALLOC_ZERO_BYTES_FREES 1
345 #endif
348 TRIM_FASTBINS controls whether free() of a very small chunk can
349 immediately lead to trimming. Setting to true (1) can reduce memory
350 footprint, but will almost always slow down programs that use a lot
351 of small chunks.
353 Define this only if you are willing to give up some speed to more
354 aggressively reduce system-level memory footprint when releasing
355 memory in programs that use many small chunks. You can get
356 essentially the same effect by setting MXFAST to 0, but this can
357 lead to even greater slowdowns in programs using many small chunks.
358 TRIM_FASTBINS is an in-between compile-time option, that disables
359 only those chunks bordering topmost memory from being placed in
360 fastbins.
363 #ifndef TRIM_FASTBINS
364 #define TRIM_FASTBINS 0
365 #endif
367 /* Definition for getting more memory from the OS. */
368 #include "morecore.c"
370 #define MORECORE (*__glibc_morecore)
371 #define MORECORE_FAILURE 0
373 /* Memory tagging. */
375 /* Some systems support the concept of tagging (sometimes known as
376 coloring) memory locations on a fine grained basis. Each memory
377 location is given a color (normally allocated randomly) and
378 pointers are also colored. When the pointer is dereferenced, the
379 pointer's color is checked against the memory's color and if they
380 differ the access is faulted (sometimes lazily).
382 We use this in glibc by maintaining a single color for the malloc
383 data structures that are interleaved with the user data and then
384 assigning separate colors for each block allocation handed out. In
385 this way simple buffer overruns will be rapidly detected. When
386 memory is freed, the memory is recolored back to the glibc default
387 so that simple use-after-free errors can also be detected.
389 If memory is reallocated the buffer is recolored even if the
390 address remains the same. This has a performance impact, but
391 guarantees that the old pointer cannot mistakenly be reused (code
392 that compares old against new will see a mismatch and will then
393 need to behave as though realloc moved the data to a new location).
395 Internal API for memory tagging support.
397 The aim is to keep the code for memory tagging support as close to
398 the normal APIs in glibc as possible, so that if tagging is not
399 enabled in the library, or is disabled at runtime then standard
400 operations can continue to be used. Support macros are used to do
401 this:
403 void *tag_new_zero_region (void *ptr, size_t size)
405 Allocates a new tag, colors the memory with that tag, zeros the
406 memory and returns a pointer that is correctly colored for that
407 location. The non-tagging version will simply call memset with 0.
409 void *tag_region (void *ptr, size_t size)
411 Color the region of memory pointed to by PTR and size SIZE with
412 the color of PTR. Returns the original pointer.
414 void *tag_new_usable (void *ptr)
416 Allocate a new random color and use it to color the user region of
417 a chunk; this may include data from the subsequent chunk's header
418 if tagging is sufficiently fine grained. Returns PTR suitably
419 recolored for accessing the memory there.
421 void *tag_at (void *ptr)
423 Read the current color of the memory at the address pointed to by
424 PTR (ignoring it's current color) and return PTR recolored to that
425 color. PTR must be valid address in all other respects. When
426 tagging is not enabled, it simply returns the original pointer.
429 #ifdef USE_MTAG
430 static bool mtag_enabled = false;
431 static int mtag_mmap_flags = 0;
432 #else
433 # define mtag_enabled false
434 # define mtag_mmap_flags 0
435 #endif
437 static __always_inline void *
438 tag_region (void *ptr, size_t size)
440 if (__glibc_unlikely (mtag_enabled))
441 return __libc_mtag_tag_region (ptr, size);
442 return ptr;
445 static __always_inline void *
446 tag_new_zero_region (void *ptr, size_t size)
448 if (__glibc_unlikely (mtag_enabled))
449 return __libc_mtag_tag_zero_region (__libc_mtag_new_tag (ptr), size);
450 return memset (ptr, 0, size);
453 /* Defined later. */
454 static void *
455 tag_new_usable (void *ptr);
457 static __always_inline void *
458 tag_at (void *ptr)
460 if (__glibc_unlikely (mtag_enabled))
461 return __libc_mtag_address_get_tag (ptr);
462 return ptr;
465 #include <string.h>
468 MORECORE-related declarations. By default, rely on sbrk
473 MORECORE is the name of the routine to call to obtain more memory
474 from the system. See below for general guidance on writing
475 alternative MORECORE functions, as well as a version for WIN32 and a
476 sample version for pre-OSX macos.
479 #ifndef MORECORE
480 #define MORECORE sbrk
481 #endif
484 MORECORE_FAILURE is the value returned upon failure of MORECORE
485 as well as mmap. Since it cannot be an otherwise valid memory address,
486 and must reflect values of standard sys calls, you probably ought not
487 try to redefine it.
490 #ifndef MORECORE_FAILURE
491 #define MORECORE_FAILURE (-1)
492 #endif
495 If MORECORE_CONTIGUOUS is true, take advantage of fact that
496 consecutive calls to MORECORE with positive arguments always return
497 contiguous increasing addresses. This is true of unix sbrk. Even
498 if not defined, when regions happen to be contiguous, malloc will
499 permit allocations spanning regions obtained from different
500 calls. But defining this when applicable enables some stronger
501 consistency checks and space efficiencies.
504 #ifndef MORECORE_CONTIGUOUS
505 #define MORECORE_CONTIGUOUS 1
506 #endif
509 Define MORECORE_CANNOT_TRIM if your version of MORECORE
510 cannot release space back to the system when given negative
511 arguments. This is generally necessary only if you are using
512 a hand-crafted MORECORE function that cannot handle negative arguments.
515 /* #define MORECORE_CANNOT_TRIM */
517 /* MORECORE_CLEARS (default 1)
518 The degree to which the routine mapped to MORECORE zeroes out
519 memory: never (0), only for newly allocated space (1) or always
520 (2). The distinction between (1) and (2) is necessary because on
521 some systems, if the application first decrements and then
522 increments the break value, the contents of the reallocated space
523 are unspecified.
526 #ifndef MORECORE_CLEARS
527 # define MORECORE_CLEARS 1
528 #endif
532 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
533 sbrk fails, and mmap is used as a backup. The value must be a
534 multiple of page size. This backup strategy generally applies only
535 when systems have "holes" in address space, so sbrk cannot perform
536 contiguous expansion, but there is still space available on system.
537 On systems for which this is known to be useful (i.e. most linux
538 kernels), this occurs only when programs allocate huge amounts of
539 memory. Between this, and the fact that mmap regions tend to be
540 limited, the size should be large, to avoid too many mmap calls and
541 thus avoid running out of kernel resources. */
543 #ifndef MMAP_AS_MORECORE_SIZE
544 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
545 #endif
548 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
549 large blocks.
552 #ifndef HAVE_MREMAP
553 #define HAVE_MREMAP 0
554 #endif
557 This version of malloc supports the standard SVID/XPG mallinfo
558 routine that returns a struct containing usage properties and
559 statistics. It should work on any SVID/XPG compliant system that has
560 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
561 install such a thing yourself, cut out the preliminary declarations
562 as described above and below and save them in a malloc.h file. But
563 there's no compelling reason to bother to do this.)
565 The main declaration needed is the mallinfo struct that is returned
566 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
567 bunch of fields that are not even meaningful in this version of
568 malloc. These fields are are instead filled by mallinfo() with
569 other numbers that might be of interest.
573 /* ---------- description of public routines ------------ */
575 #if IS_IN (libc)
577 malloc(size_t n)
578 Returns a pointer to a newly allocated chunk of at least n bytes, or null
579 if no space is available. Additionally, on failure, errno is
580 set to ENOMEM on ANSI C systems.
582 If n is zero, malloc returns a minimum-sized chunk. (The minimum
583 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
584 systems.) On most systems, size_t is an unsigned type, so calls
585 with negative arguments are interpreted as requests for huge amounts
586 of space, which will often fail. The maximum supported value of n
587 differs across systems, but is in all cases less than the maximum
588 representable value of a size_t.
590 void* __libc_malloc(size_t);
591 libc_hidden_proto (__libc_malloc)
594 free(void* p)
595 Releases the chunk of memory pointed to by p, that had been previously
596 allocated using malloc or a related routine such as realloc.
597 It has no effect if p is null. It can have arbitrary (i.e., bad!)
598 effects if p has already been freed.
600 Unless disabled (using mallopt), freeing very large spaces will
601 when possible, automatically trigger operations that give
602 back unused memory to the system, thus reducing program footprint.
604 void __libc_free(void*);
605 libc_hidden_proto (__libc_free)
608 calloc(size_t n_elements, size_t element_size);
609 Returns a pointer to n_elements * element_size bytes, with all locations
610 set to zero.
612 void* __libc_calloc(size_t, size_t);
615 realloc(void* p, size_t n)
616 Returns a pointer to a chunk of size n that contains the same data
617 as does chunk p up to the minimum of (n, p's size) bytes, or null
618 if no space is available.
620 The returned pointer may or may not be the same as p. The algorithm
621 prefers extending p when possible, otherwise it employs the
622 equivalent of a malloc-copy-free sequence.
624 If p is null, realloc is equivalent to malloc.
626 If space is not available, realloc returns null, errno is set (if on
627 ANSI) and p is NOT freed.
629 if n is for fewer bytes than already held by p, the newly unused
630 space is lopped off and freed if possible. Unless the #define
631 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
632 zero (re)allocates a minimum-sized chunk.
634 Large chunks that were internally obtained via mmap will always be
635 grown using malloc-copy-free sequences unless the system supports
636 MREMAP (currently only linux).
638 The old unix realloc convention of allowing the last-free'd chunk
639 to be used as an argument to realloc is not supported.
641 void* __libc_realloc(void*, size_t);
642 libc_hidden_proto (__libc_realloc)
645 memalign(size_t alignment, size_t n);
646 Returns a pointer to a newly allocated chunk of n bytes, aligned
647 in accord with the alignment argument.
649 The alignment argument should be a power of two. If the argument is
650 not a power of two, the nearest greater power is used.
651 8-byte alignment is guaranteed by normal malloc calls, so don't
652 bother calling memalign with an argument of 8 or less.
654 Overreliance on memalign is a sure way to fragment space.
656 void* __libc_memalign(size_t, size_t);
657 libc_hidden_proto (__libc_memalign)
660 valloc(size_t n);
661 Equivalent to memalign(pagesize, n), where pagesize is the page
662 size of the system. If the pagesize is unknown, 4096 is used.
664 void* __libc_valloc(size_t);
669 mallinfo()
670 Returns (by copy) a struct containing various summary statistics:
672 arena: current total non-mmapped bytes allocated from system
673 ordblks: the number of free chunks
674 smblks: the number of fastbin blocks (i.e., small chunks that
675 have been freed but not reused or consolidated)
676 hblks: current number of mmapped regions
677 hblkhd: total bytes held in mmapped regions
678 usmblks: always 0
679 fsmblks: total bytes held in fastbin blocks
680 uordblks: current total allocated space (normal or mmapped)
681 fordblks: total free space
682 keepcost: the maximum number of bytes that could ideally be released
683 back to system via malloc_trim. ("ideally" means that
684 it ignores page restrictions etc.)
686 Because these fields are ints, but internal bookkeeping may
687 be kept as longs, the reported values may wrap around zero and
688 thus be inaccurate.
690 struct mallinfo2 __libc_mallinfo2(void);
691 libc_hidden_proto (__libc_mallinfo2)
693 struct mallinfo __libc_mallinfo(void);
697 pvalloc(size_t n);
698 Equivalent to valloc(minimum-page-that-holds(n)), that is,
699 round up n to nearest pagesize.
701 void* __libc_pvalloc(size_t);
704 malloc_trim(size_t pad);
706 If possible, gives memory back to the system (via negative
707 arguments to sbrk) if there is unused memory at the `high' end of
708 the malloc pool. You can call this after freeing large blocks of
709 memory to potentially reduce the system-level memory requirements
710 of a program. However, it cannot guarantee to reduce memory. Under
711 some allocation patterns, some large free blocks of memory will be
712 locked between two used chunks, so they cannot be given back to
713 the system.
715 The `pad' argument to malloc_trim represents the amount of free
716 trailing space to leave untrimmed. If this argument is zero,
717 only the minimum amount of memory to maintain internal data
718 structures will be left (one page or less). Non-zero arguments
719 can be supplied to maintain enough trailing space to service
720 future expected allocations without having to re-obtain memory
721 from the system.
723 Malloc_trim returns 1 if it actually released any memory, else 0.
724 On systems that do not support "negative sbrks", it will always
725 return 0.
727 int __malloc_trim(size_t);
730 malloc_usable_size(void* p);
732 Returns the number of bytes you can actually use in
733 an allocated chunk, which may be more than you requested (although
734 often not) due to alignment and minimum size constraints.
735 You can use this many bytes without worrying about
736 overwriting other allocated objects. This is not a particularly great
737 programming practice. malloc_usable_size can be more useful in
738 debugging and assertions, for example:
740 p = malloc(n);
741 assert(malloc_usable_size(p) >= 256);
744 size_t __malloc_usable_size(void*);
747 malloc_stats();
748 Prints on stderr the amount of space obtained from the system (both
749 via sbrk and mmap), the maximum amount (which may be more than
750 current if malloc_trim and/or munmap got called), and the current
751 number of bytes allocated via malloc (or realloc, etc) but not yet
752 freed. Note that this is the number of bytes allocated, not the
753 number requested. It will be larger than the number requested
754 because of alignment and bookkeeping overhead. Because it includes
755 alignment wastage as being in use, this figure may be greater than
756 zero even when no user-level chunks are allocated.
758 The reported current and maximum system memory can be inaccurate if
759 a program makes other calls to system memory allocation functions
760 (normally sbrk) outside of malloc.
762 malloc_stats prints only the most commonly interesting statistics.
763 More information can be obtained by calling mallinfo.
766 void __malloc_stats(void);
769 posix_memalign(void **memptr, size_t alignment, size_t size);
771 POSIX wrapper like memalign(), checking for validity of size.
773 int __posix_memalign(void **, size_t, size_t);
774 #endif /* IS_IN (libc) */
777 mallopt(int parameter_number, int parameter_value)
778 Sets tunable parameters The format is to provide a
779 (parameter-number, parameter-value) pair. mallopt then sets the
780 corresponding parameter to the argument value if it can (i.e., so
781 long as the value is meaningful), and returns 1 if successful else
782 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
783 normally defined in malloc.h. Only one of these (M_MXFAST) is used
784 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
785 so setting them has no effect. But this malloc also supports four
786 other options in mallopt. See below for details. Briefly, supported
787 parameters are as follows (listed defaults are for "typical"
788 configurations).
790 Symbol param # default allowed param values
791 M_MXFAST 1 64 0-80 (0 disables fastbins)
792 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
793 M_TOP_PAD -2 0 any
794 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
795 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
797 int __libc_mallopt(int, int);
798 #if IS_IN (libc)
799 libc_hidden_proto (__libc_mallopt)
800 #endif
802 /* mallopt tuning options */
805 M_MXFAST is the maximum request size used for "fastbins", special bins
806 that hold returned chunks without consolidating their spaces. This
807 enables future requests for chunks of the same size to be handled
808 very quickly, but can increase fragmentation, and thus increase the
809 overall memory footprint of a program.
811 This malloc manages fastbins very conservatively yet still
812 efficiently, so fragmentation is rarely a problem for values less
813 than or equal to the default. The maximum supported value of MXFAST
814 is 80. You wouldn't want it any higher than this anyway. Fastbins
815 are designed especially for use with many small structs, objects or
816 strings -- the default handles structs/objects/arrays with sizes up
817 to 8 4byte fields, or small strings representing words, tokens,
818 etc. Using fastbins for larger objects normally worsens
819 fragmentation without improving speed.
821 M_MXFAST is set in REQUEST size units. It is internally used in
822 chunksize units, which adds padding and alignment. You can reduce
823 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
824 algorithm to be a closer approximation of fifo-best-fit in all cases,
825 not just for larger requests, but will generally cause it to be
826 slower.
830 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
831 #ifndef M_MXFAST
832 #define M_MXFAST 1
833 #endif
835 #ifndef DEFAULT_MXFAST
836 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
837 #endif
841 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
842 to keep before releasing via malloc_trim in free().
844 Automatic trimming is mainly useful in long-lived programs.
845 Because trimming via sbrk can be slow on some systems, and can
846 sometimes be wasteful (in cases where programs immediately
847 afterward allocate more large chunks) the value should be high
848 enough so that your overall system performance would improve by
849 releasing this much memory.
851 The trim threshold and the mmap control parameters (see below)
852 can be traded off with one another. Trimming and mmapping are
853 two different ways of releasing unused memory back to the
854 system. Between these two, it is often possible to keep
855 system-level demands of a long-lived program down to a bare
856 minimum. For example, in one test suite of sessions measuring
857 the XF86 X server on Linux, using a trim threshold of 128K and a
858 mmap threshold of 192K led to near-minimal long term resource
859 consumption.
861 If you are using this malloc in a long-lived program, it should
862 pay to experiment with these values. As a rough guide, you
863 might set to a value close to the average size of a process
864 (program) running on your system. Releasing this much memory
865 would allow such a process to run in memory. Generally, it's
866 worth it to tune for trimming rather tham memory mapping when a
867 program undergoes phases where several large chunks are
868 allocated and released in ways that can reuse each other's
869 storage, perhaps mixed with phases where there are no such
870 chunks at all. And in well-behaved long-lived programs,
871 controlling release of large blocks via trimming versus mapping
872 is usually faster.
874 However, in most programs, these parameters serve mainly as
875 protection against the system-level effects of carrying around
876 massive amounts of unneeded memory. Since frequent calls to
877 sbrk, mmap, and munmap otherwise degrade performance, the default
878 parameters are set to relatively high values that serve only as
879 safeguards.
881 The trim value It must be greater than page size to have any useful
882 effect. To disable trimming completely, you can set to
883 (unsigned long)(-1)
885 Trim settings interact with fastbin (MXFAST) settings: Unless
886 TRIM_FASTBINS is defined, automatic trimming never takes place upon
887 freeing a chunk with size less than or equal to MXFAST. Trimming is
888 instead delayed until subsequent freeing of larger chunks. However,
889 you can still force an attempted trim by calling malloc_trim.
891 Also, trimming is not generally possible in cases where
892 the main arena is obtained via mmap.
894 Note that the trick some people use of mallocing a huge space and
895 then freeing it at program startup, in an attempt to reserve system
896 memory, doesn't have the intended effect under automatic trimming,
897 since that memory will immediately be returned to the system.
900 #define M_TRIM_THRESHOLD -1
902 #ifndef DEFAULT_TRIM_THRESHOLD
903 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
904 #endif
907 M_TOP_PAD is the amount of extra `padding' space to allocate or
908 retain whenever sbrk is called. It is used in two ways internally:
910 * When sbrk is called to extend the top of the arena to satisfy
911 a new malloc request, this much padding is added to the sbrk
912 request.
914 * When malloc_trim is called automatically from free(),
915 it is used as the `pad' argument.
917 In both cases, the actual amount of padding is rounded
918 so that the end of the arena is always a system page boundary.
920 The main reason for using padding is to avoid calling sbrk so
921 often. Having even a small pad greatly reduces the likelihood
922 that nearly every malloc request during program start-up (or
923 after trimming) will invoke sbrk, which needlessly wastes
924 time.
926 Automatic rounding-up to page-size units is normally sufficient
927 to avoid measurable overhead, so the default is 0. However, in
928 systems where sbrk is relatively slow, it can pay to increase
929 this value, at the expense of carrying around more memory than
930 the program needs.
933 #define M_TOP_PAD -2
935 #ifndef DEFAULT_TOP_PAD
936 #define DEFAULT_TOP_PAD (0)
937 #endif
940 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
941 adjusted MMAP_THRESHOLD.
944 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
945 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
946 #endif
948 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
949 /* For 32-bit platforms we cannot increase the maximum mmap
950 threshold much because it is also the minimum value for the
951 maximum heap size and its alignment. Going above 512k (i.e., 1M
952 for new heaps) wastes too much address space. */
953 # if __WORDSIZE == 32
954 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
955 # else
956 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
957 # endif
958 #endif
961 M_MMAP_THRESHOLD is the request size threshold for using mmap()
962 to service a request. Requests of at least this size that cannot
963 be allocated using already-existing space will be serviced via mmap.
964 (If enough normal freed space already exists it is used instead.)
966 Using mmap segregates relatively large chunks of memory so that
967 they can be individually obtained and released from the host
968 system. A request serviced through mmap is never reused by any
969 other request (at least not directly; the system may just so
970 happen to remap successive requests to the same locations).
972 Segregating space in this way has the benefits that:
974 1. Mmapped space can ALWAYS be individually released back
975 to the system, which helps keep the system level memory
976 demands of a long-lived program low.
977 2. Mapped memory can never become `locked' between
978 other chunks, as can happen with normally allocated chunks, which
979 means that even trimming via malloc_trim would not release them.
980 3. On some systems with "holes" in address spaces, mmap can obtain
981 memory that sbrk cannot.
983 However, it has the disadvantages that:
985 1. The space cannot be reclaimed, consolidated, and then
986 used to service later requests, as happens with normal chunks.
987 2. It can lead to more wastage because of mmap page alignment
988 requirements
989 3. It causes malloc performance to be more dependent on host
990 system memory management support routines which may vary in
991 implementation quality and may impose arbitrary
992 limitations. Generally, servicing a request via normal
993 malloc steps is faster than going through a system's mmap.
995 The advantages of mmap nearly always outweigh disadvantages for
996 "large" chunks, but the value of "large" varies across systems. The
997 default is an empirically derived value that works well in most
998 systems.
1001 Update in 2006:
1002 The above was written in 2001. Since then the world has changed a lot.
1003 Memory got bigger. Applications got bigger. The virtual address space
1004 layout in 32 bit linux changed.
1006 In the new situation, brk() and mmap space is shared and there are no
1007 artificial limits on brk size imposed by the kernel. What is more,
1008 applications have started using transient allocations larger than the
1009 128Kb as was imagined in 2001.
1011 The price for mmap is also high now; each time glibc mmaps from the
1012 kernel, the kernel is forced to zero out the memory it gives to the
1013 application. Zeroing memory is expensive and eats a lot of cache and
1014 memory bandwidth. This has nothing to do with the efficiency of the
1015 virtual memory system, by doing mmap the kernel just has no choice but
1016 to zero.
1018 In 2001, the kernel had a maximum size for brk() which was about 800
1019 megabytes on 32 bit x86, at that point brk() would hit the first
1020 mmaped shared libraries and couldn't expand anymore. With current 2.6
1021 kernels, the VA space layout is different and brk() and mmap
1022 both can span the entire heap at will.
1024 Rather than using a static threshold for the brk/mmap tradeoff,
1025 we are now using a simple dynamic one. The goal is still to avoid
1026 fragmentation. The old goals we kept are
1027 1) try to get the long lived large allocations to use mmap()
1028 2) really large allocations should always use mmap()
1029 and we're adding now:
1030 3) transient allocations should use brk() to avoid forcing the kernel
1031 having to zero memory over and over again
1033 The implementation works with a sliding threshold, which is by default
1034 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
1035 out at 128Kb as per the 2001 default.
1037 This allows us to satisfy requirement 1) under the assumption that long
1038 lived allocations are made early in the process' lifespan, before it has
1039 started doing dynamic allocations of the same size (which will
1040 increase the threshold).
1042 The upperbound on the threshold satisfies requirement 2)
1044 The threshold goes up in value when the application frees memory that was
1045 allocated with the mmap allocator. The idea is that once the application
1046 starts freeing memory of a certain size, it's highly probable that this is
1047 a size the application uses for transient allocations. This estimator
1048 is there to satisfy the new third requirement.
1052 #define M_MMAP_THRESHOLD -3
1054 #ifndef DEFAULT_MMAP_THRESHOLD
1055 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1056 #endif
1059 M_MMAP_MAX is the maximum number of requests to simultaneously
1060 service using mmap. This parameter exists because
1061 some systems have a limited number of internal tables for
1062 use by mmap, and using more than a few of them may degrade
1063 performance.
1065 The default is set to a value that serves only as a safeguard.
1066 Setting to 0 disables use of mmap for servicing large requests.
1069 #define M_MMAP_MAX -4
1071 #ifndef DEFAULT_MMAP_MAX
1072 #define DEFAULT_MMAP_MAX (65536)
1073 #endif
1075 #include <malloc.h>
1077 #ifndef RETURN_ADDRESS
1078 #define RETURN_ADDRESS(X_) (NULL)
1079 #endif
1081 /* Forward declarations. */
1082 struct malloc_chunk;
1083 typedef struct malloc_chunk* mchunkptr;
1085 /* Internal routines. */
1087 static void* _int_malloc(mstate, size_t);
1088 static void _int_free(mstate, mchunkptr, int);
1089 static void _int_free_merge_chunk (mstate, mchunkptr, INTERNAL_SIZE_T);
1090 static INTERNAL_SIZE_T _int_free_create_chunk (mstate,
1091 mchunkptr, INTERNAL_SIZE_T,
1092 mchunkptr, INTERNAL_SIZE_T);
1093 static void _int_free_maybe_consolidate (mstate, INTERNAL_SIZE_T);
1094 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1095 INTERNAL_SIZE_T);
1096 static void* _int_memalign(mstate, size_t, size_t);
1097 #if IS_IN (libc)
1098 static void* _mid_memalign(size_t, size_t, void *);
1099 #endif
1101 static void malloc_printerr(const char *str) __attribute__ ((noreturn));
1103 static void munmap_chunk(mchunkptr p);
1104 #if HAVE_MREMAP
1105 static mchunkptr mremap_chunk(mchunkptr p, size_t new_size);
1106 #endif
1108 static size_t musable (void *mem);
1110 /* ------------------ MMAP support ------------------ */
1113 #include <fcntl.h>
1114 #include <sys/mman.h>
1116 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1117 # define MAP_ANONYMOUS MAP_ANON
1118 #endif
1120 #define MMAP(addr, size, prot, flags) \
1121 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1125 ----------------------- Chunk representations -----------------------
1130 This struct declaration is misleading (but accurate and necessary).
1131 It declares a "view" into memory allowing access to necessary
1132 fields at known offsets from a given base. See explanation below.
1135 struct malloc_chunk {
1137 INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk (if free). */
1138 INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
1140 struct malloc_chunk* fd; /* double links -- used only if free. */
1141 struct malloc_chunk* bk;
1143 /* Only used for large blocks: pointer to next larger size. */
1144 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1145 struct malloc_chunk* bk_nextsize;
1150 malloc_chunk details:
1152 (The following includes lightly edited explanations by Colin Plumb.)
1154 Chunks of memory are maintained using a `boundary tag' method as
1155 described in e.g., Knuth or Standish. (See the paper by Paul
1156 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1157 survey of such techniques.) Sizes of free chunks are stored both
1158 in the front of each chunk and at the end. This makes
1159 consolidating fragmented chunks into bigger chunks very fast. The
1160 size fields also hold bits representing whether chunks are free or
1161 in use.
1163 An allocated chunk looks like this:
1166 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1167 | Size of previous chunk, if unallocated (P clear) |
1168 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1169 | Size of chunk, in bytes |A|M|P|
1170 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1171 | User data starts here... .
1173 . (malloc_usable_size() bytes) .
1175 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1176 | (size of chunk, but used for application data) |
1177 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1178 | Size of next chunk, in bytes |A|0|1|
1179 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1181 Where "chunk" is the front of the chunk for the purpose of most of
1182 the malloc code, but "mem" is the pointer that is returned to the
1183 user. "Nextchunk" is the beginning of the next contiguous chunk.
1185 Chunks always begin on even word boundaries, so the mem portion
1186 (which is returned to the user) is also on an even word boundary, and
1187 thus at least double-word aligned.
1189 Free chunks are stored in circular doubly-linked lists, and look like this:
1191 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1192 | Size of previous chunk, if unallocated (P clear) |
1193 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1194 `head:' | Size of chunk, in bytes |A|0|P|
1195 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1196 | Forward pointer to next chunk in list |
1197 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1198 | Back pointer to previous chunk in list |
1199 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1200 | Unused space (may be 0 bytes long) .
1203 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1204 `foot:' | Size of chunk, in bytes |
1205 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1206 | Size of next chunk, in bytes |A|0|0|
1207 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1209 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1210 chunk size (which is always a multiple of two words), is an in-use
1211 bit for the *previous* chunk. If that bit is *clear*, then the
1212 word before the current chunk size contains the previous chunk
1213 size, and can be used to find the front of the previous chunk.
1214 The very first chunk allocated always has this bit set,
1215 preventing access to non-existent (or non-owned) memory. If
1216 prev_inuse is set for any given chunk, then you CANNOT determine
1217 the size of the previous chunk, and might even get a memory
1218 addressing fault when trying to do so.
1220 The A (NON_MAIN_ARENA) bit is cleared for chunks on the initial,
1221 main arena, described by the main_arena variable. When additional
1222 threads are spawned, each thread receives its own arena (up to a
1223 configurable limit, after which arenas are reused for multiple
1224 threads), and the chunks in these arenas have the A bit set. To
1225 find the arena for a chunk on such a non-main arena, heap_for_ptr
1226 performs a bit mask operation and indirection through the ar_ptr
1227 member of the per-heap header heap_info (see arena.c).
1229 Note that the `foot' of the current chunk is actually represented
1230 as the prev_size of the NEXT chunk. This makes it easier to
1231 deal with alignments etc but can be very confusing when trying
1232 to extend or adapt this code.
1234 The three exceptions to all this are:
1236 1. The special chunk `top' doesn't bother using the
1237 trailing size field since there is no next contiguous chunk
1238 that would have to index off it. After initialization, `top'
1239 is forced to always exist. If it would become less than
1240 MINSIZE bytes long, it is replenished.
1242 2. Chunks allocated via mmap, which have the second-lowest-order
1243 bit M (IS_MMAPPED) set in their size fields. Because they are
1244 allocated one-by-one, each must contain its own trailing size
1245 field. If the M bit is set, the other bits are ignored
1246 (because mmapped chunks are neither in an arena, nor adjacent
1247 to a freed chunk). The M bit is also used for chunks which
1248 originally came from a dumped heap via malloc_set_state in
1249 hooks.c.
1251 3. Chunks in fastbins are treated as allocated chunks from the
1252 point of view of the chunk allocator. They are consolidated
1253 with their neighbors only in bulk, in malloc_consolidate.
1257 ---------- Size and alignment checks and conversions ----------
1260 /* Conversion from malloc headers to user pointers, and back. When
1261 using memory tagging the user data and the malloc data structure
1262 headers have distinct tags. Converting fully from one to the other
1263 involves extracting the tag at the other address and creating a
1264 suitable pointer using it. That can be quite expensive. There are
1265 cases when the pointers are not dereferenced (for example only used
1266 for alignment check) so the tags are not relevant, and there are
1267 cases when user data is not tagged distinctly from malloc headers
1268 (user data is untagged because tagging is done late in malloc and
1269 early in free). User memory tagging across internal interfaces:
1271 sysmalloc: Returns untagged memory.
1272 _int_malloc: Returns untagged memory.
1273 _int_free: Takes untagged memory.
1274 _int_memalign: Returns untagged memory.
1275 _int_memalign: Returns untagged memory.
1276 _mid_memalign: Returns tagged memory.
1277 _int_realloc: Takes and returns tagged memory.
1280 /* The chunk header is two SIZE_SZ elements, but this is used widely, so
1281 we define it here for clarity later. */
1282 #define CHUNK_HDR_SZ (2 * SIZE_SZ)
1284 /* Convert a chunk address to a user mem pointer without correcting
1285 the tag. */
1286 #define chunk2mem(p) ((void*)((char*)(p) + CHUNK_HDR_SZ))
1288 /* Convert a chunk address to a user mem pointer and extract the right tag. */
1289 #define chunk2mem_tag(p) ((void*)tag_at ((char*)(p) + CHUNK_HDR_SZ))
1291 /* Convert a user mem pointer to a chunk address and extract the right tag. */
1292 #define mem2chunk(mem) ((mchunkptr)tag_at (((char*)(mem) - CHUNK_HDR_SZ)))
1294 /* The smallest possible chunk */
1295 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1297 /* The smallest size we can malloc is an aligned minimal chunk */
1299 #define MINSIZE \
1300 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1302 /* Check if m has acceptable alignment */
1304 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1306 #define misaligned_chunk(p) \
1307 ((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \
1308 & MALLOC_ALIGN_MASK)
1310 /* pad request bytes into a usable size -- internal version */
1311 /* Note: This must be a macro that evaluates to a compile time constant
1312 if passed a literal constant. */
1313 #define request2size(req) \
1314 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1315 MINSIZE : \
1316 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1318 /* Check if REQ overflows when padded and aligned and if the resulting
1319 value is less than PTRDIFF_T. Returns the requested size or
1320 MINSIZE in case the value is less than MINSIZE, or 0 if any of the
1321 previous checks fail. */
1322 static inline size_t
1323 checked_request2size (size_t req) __nonnull (1)
1325 if (__glibc_unlikely (req > PTRDIFF_MAX))
1326 return 0;
1328 /* When using tagged memory, we cannot share the end of the user
1329 block with the header for the next chunk, so ensure that we
1330 allocate blocks that are rounded up to the granule size. Take
1331 care not to overflow from close to MAX_SIZE_T to a small
1332 number. Ideally, this would be part of request2size(), but that
1333 must be a macro that produces a compile time constant if passed
1334 a constant literal. */
1335 if (__glibc_unlikely (mtag_enabled))
1337 /* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551. */
1338 asm ("");
1340 req = (req + (__MTAG_GRANULE_SIZE - 1)) &
1341 ~(size_t)(__MTAG_GRANULE_SIZE - 1);
1344 return request2size (req);
1348 --------------- Physical chunk operations ---------------
1352 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1353 #define PREV_INUSE 0x1
1355 /* extract inuse bit of previous chunk */
1356 #define prev_inuse(p) ((p)->mchunk_size & PREV_INUSE)
1359 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1360 #define IS_MMAPPED 0x2
1362 /* check for mmap()'ed chunk */
1363 #define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)
1366 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1367 from a non-main arena. This is only set immediately before handing
1368 the chunk to the user, if necessary. */
1369 #define NON_MAIN_ARENA 0x4
1371 /* Check for chunk from main arena. */
1372 #define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)
1374 /* Mark a chunk as not being on the main arena. */
1375 #define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
1379 Bits to mask off when extracting size
1381 Note: IS_MMAPPED is intentionally not masked off from size field in
1382 macros for which mmapped chunks should never be seen. This should
1383 cause helpful core dumps to occur if it is tried by accident by
1384 people extending or adapting this malloc.
1386 #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1388 /* Get size, ignoring use bits */
1389 #define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))
1391 /* Like chunksize, but do not mask SIZE_BITS. */
1392 #define chunksize_nomask(p) ((p)->mchunk_size)
1394 /* Ptr to next physical malloc_chunk. */
1395 #define next_chunk(p) ((mchunkptr) (((char *) (p)) + chunksize (p)))
1397 /* Size of the chunk below P. Only valid if !prev_inuse (P). */
1398 #define prev_size(p) ((p)->mchunk_prev_size)
1400 /* Set the size of the chunk below P. Only valid if !prev_inuse (P). */
1401 #define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))
1403 /* Ptr to previous physical malloc_chunk. Only valid if !prev_inuse (P). */
1404 #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - prev_size (p)))
1406 /* Treat space at ptr + offset as a chunk */
1407 #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1409 /* extract p's inuse bit */
1410 #define inuse(p) \
1411 ((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
1413 /* set/clear chunk as being inuse without otherwise disturbing */
1414 #define set_inuse(p) \
1415 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
1417 #define clear_inuse(p) \
1418 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
1421 /* check/set/clear inuse bits in known places */
1422 #define inuse_bit_at_offset(p, s) \
1423 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
1425 #define set_inuse_bit_at_offset(p, s) \
1426 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
1428 #define clear_inuse_bit_at_offset(p, s) \
1429 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
1432 /* Set size at head, without disturbing its use bit */
1433 #define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
1435 /* Set size/use field */
1436 #define set_head(p, s) ((p)->mchunk_size = (s))
1438 /* Set size at footer (only when chunk is not in use) */
1439 #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
1441 #pragma GCC poison mchunk_size
1442 #pragma GCC poison mchunk_prev_size
1444 /* This is the size of the real usable data in the chunk. Not valid for
1445 dumped heap chunks. */
1446 #define memsize(p) \
1447 (__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \
1448 chunksize (p) - CHUNK_HDR_SZ : \
1449 chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ))
1451 /* If memory tagging is enabled the layout changes to accommodate the granule
1452 size, this is wasteful for small allocations so not done by default.
1453 Both the chunk header and user data has to be granule aligned. */
1454 _Static_assert (__MTAG_GRANULE_SIZE <= CHUNK_HDR_SZ,
1455 "memory tagging is not supported with large granule.");
1457 static __always_inline void *
1458 tag_new_usable (void *ptr)
1460 if (__glibc_unlikely (mtag_enabled) && ptr)
1462 mchunkptr cp = mem2chunk(ptr);
1463 ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp));
1465 return ptr;
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 preceded 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 uint8_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 /* Transparent Large Page support. */
1865 INTERNAL_SIZE_T thp_pagesize;
1866 /* A value different than 0 means to align mmap allocation to hp_pagesize
1867 add hp_flags on flags. */
1868 INTERNAL_SIZE_T hp_pagesize;
1869 int hp_flags;
1871 /* Memory map support */
1872 int n_mmaps;
1873 int n_mmaps_max;
1874 int max_n_mmaps;
1875 /* the mmap_threshold is dynamic, until the user sets
1876 it manually, at which point we need to disable any
1877 dynamic behavior. */
1878 int no_dyn_threshold;
1880 /* Statistics */
1881 INTERNAL_SIZE_T mmapped_mem;
1882 INTERNAL_SIZE_T max_mmapped_mem;
1884 /* First address handed out by MORECORE/sbrk. */
1885 char *sbrk_base;
1887 #if USE_TCACHE
1888 /* Maximum number of buckets to use. */
1889 size_t tcache_bins;
1890 size_t tcache_max_bytes;
1891 /* Maximum number of chunks in each bucket. */
1892 size_t tcache_count;
1893 /* Maximum number of chunks to remove from the unsorted list, which
1894 aren't used to prefill the cache. */
1895 size_t tcache_unsorted_limit;
1896 #endif
1899 /* There are several instances of this struct ("arenas") in this
1900 malloc. If you are adapting this malloc in a way that does NOT use
1901 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1902 before using. This malloc relies on the property that malloc_state
1903 is initialized to all zeroes (as is true of C statics). */
1905 static struct malloc_state main_arena =
1907 .mutex = _LIBC_LOCK_INITIALIZER,
1908 .next = &main_arena,
1909 .attached_threads = 1
1912 /* There is only one instance of the malloc parameters. */
1914 static struct malloc_par mp_ =
1916 .top_pad = DEFAULT_TOP_PAD,
1917 .n_mmaps_max = DEFAULT_MMAP_MAX,
1918 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1919 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1920 #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1921 .arena_test = NARENAS_FROM_NCORES (1)
1922 #if USE_TCACHE
1924 .tcache_count = TCACHE_FILL_COUNT,
1925 .tcache_bins = TCACHE_MAX_BINS,
1926 .tcache_max_bytes = tidx2usize (TCACHE_MAX_BINS-1),
1927 .tcache_unsorted_limit = 0 /* No limit. */
1928 #endif
1932 Initialize a malloc_state struct.
1934 This is called from ptmalloc_init () or from _int_new_arena ()
1935 when creating a new arena.
1938 static void
1939 malloc_init_state (mstate av)
1941 int i;
1942 mbinptr bin;
1944 /* Establish circular links for normal bins */
1945 for (i = 1; i < NBINS; ++i)
1947 bin = bin_at (av, i);
1948 bin->fd = bin->bk = bin;
1951 #if MORECORE_CONTIGUOUS
1952 if (av != &main_arena)
1953 #endif
1954 set_noncontiguous (av);
1955 if (av == &main_arena)
1956 set_max_fast (DEFAULT_MXFAST);
1957 atomic_store_relaxed (&av->have_fastchunks, false);
1959 av->top = initial_top (av);
1963 Other internal utilities operating on mstates
1966 static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1967 static int systrim (size_t, mstate);
1968 static void malloc_consolidate (mstate);
1971 /* -------------- Early definitions for debugging hooks ---------------- */
1973 /* This function is called from the arena shutdown hook, to free the
1974 thread cache (if it exists). */
1975 static void tcache_thread_shutdown (void);
1977 /* ------------------ Testing support ----------------------------------*/
1979 static int perturb_byte;
1981 static void
1982 alloc_perturb (char *p, size_t n)
1984 if (__glibc_unlikely (perturb_byte))
1985 memset (p, perturb_byte ^ 0xff, n);
1988 static void
1989 free_perturb (char *p, size_t n)
1991 if (__glibc_unlikely (perturb_byte))
1992 memset (p, perturb_byte, n);
1997 #include <stap-probe.h>
1999 /* ----------- Routines dealing with transparent huge pages ----------- */
2001 static inline void
2002 madvise_thp (void *p, INTERNAL_SIZE_T size)
2004 #ifdef MADV_HUGEPAGE
2005 /* Do not consider areas smaller than a huge page or if the tunable is
2006 not active. */
2007 if (mp_.thp_pagesize == 0 || size < mp_.thp_pagesize)
2008 return;
2010 /* Linux requires the input address to be page-aligned, and unaligned
2011 inputs happens only for initial data segment. */
2012 if (__glibc_unlikely (!PTR_IS_ALIGNED (p, GLRO (dl_pagesize))))
2014 void *q = PTR_ALIGN_DOWN (p, GLRO (dl_pagesize));
2015 size += PTR_DIFF (p, q);
2016 p = q;
2019 __madvise (p, size, MADV_HUGEPAGE);
2020 #endif
2023 /* ------------------- Support for multiple arenas -------------------- */
2024 #include "arena.c"
2027 Debugging support
2029 These routines make a number of assertions about the states
2030 of data structures that should be true at all times. If any
2031 are not true, it's very likely that a user program has somehow
2032 trashed memory. (It's also possible that there is a coding error
2033 in malloc. In which case, please report it!)
2036 #if !MALLOC_DEBUG
2038 # define check_chunk(A, P)
2039 # define check_free_chunk(A, P)
2040 # define check_inuse_chunk(A, P)
2041 # define check_remalloced_chunk(A, P, N)
2042 # define check_malloced_chunk(A, P, N)
2043 # define check_malloc_state(A)
2045 #else
2047 # define check_chunk(A, P) do_check_chunk (A, P)
2048 # define check_free_chunk(A, P) do_check_free_chunk (A, P)
2049 # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
2050 # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
2051 # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
2052 # define check_malloc_state(A) do_check_malloc_state (A)
2055 Properties of all chunks
2058 static void
2059 do_check_chunk (mstate av, mchunkptr p)
2061 unsigned long sz = chunksize (p);
2062 /* min and max possible addresses assuming contiguous allocation */
2063 char *max_address = (char *) (av->top) + chunksize (av->top);
2064 char *min_address = max_address - av->system_mem;
2066 if (!chunk_is_mmapped (p))
2068 /* Has legal address ... */
2069 if (p != av->top)
2071 if (contiguous (av))
2073 assert (((char *) p) >= min_address);
2074 assert (((char *) p + sz) <= ((char *) (av->top)));
2077 else
2079 /* top size is always at least MINSIZE */
2080 assert ((unsigned long) (sz) >= MINSIZE);
2081 /* top predecessor always marked inuse */
2082 assert (prev_inuse (p));
2085 else
2087 /* address is outside main heap */
2088 if (contiguous (av) && av->top != initial_top (av))
2090 assert (((char *) p) < min_address || ((char *) p) >= max_address);
2092 /* chunk is page-aligned */
2093 assert (((prev_size (p) + sz) & (GLRO (dl_pagesize) - 1)) == 0);
2094 /* mem is aligned */
2095 assert (aligned_OK (chunk2mem (p)));
2100 Properties of free chunks
2103 static void
2104 do_check_free_chunk (mstate av, mchunkptr p)
2106 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2107 mchunkptr next = chunk_at_offset (p, sz);
2109 do_check_chunk (av, p);
2111 /* Chunk must claim to be free ... */
2112 assert (!inuse (p));
2113 assert (!chunk_is_mmapped (p));
2115 /* Unless a special marker, must have OK fields */
2116 if ((unsigned long) (sz) >= MINSIZE)
2118 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2119 assert (aligned_OK (chunk2mem (p)));
2120 /* ... matching footer field */
2121 assert (prev_size (next_chunk (p)) == sz);
2122 /* ... and is fully consolidated */
2123 assert (prev_inuse (p));
2124 assert (next == av->top || inuse (next));
2126 /* ... and has minimally sane links */
2127 assert (p->fd->bk == p);
2128 assert (p->bk->fd == p);
2130 else /* markers are always of size SIZE_SZ */
2131 assert (sz == SIZE_SZ);
2135 Properties of inuse chunks
2138 static void
2139 do_check_inuse_chunk (mstate av, mchunkptr p)
2141 mchunkptr next;
2143 do_check_chunk (av, p);
2145 if (chunk_is_mmapped (p))
2146 return; /* mmapped chunks have no next/prev */
2148 /* Check whether it claims to be in use ... */
2149 assert (inuse (p));
2151 next = next_chunk (p);
2153 /* ... and is surrounded by OK chunks.
2154 Since more things can be checked with free chunks than inuse ones,
2155 if an inuse chunk borders them and debug is on, it's worth doing them.
2157 if (!prev_inuse (p))
2159 /* Note that we cannot even look at prev unless it is not inuse */
2160 mchunkptr prv = prev_chunk (p);
2161 assert (next_chunk (prv) == p);
2162 do_check_free_chunk (av, prv);
2165 if (next == av->top)
2167 assert (prev_inuse (next));
2168 assert (chunksize (next) >= MINSIZE);
2170 else if (!inuse (next))
2171 do_check_free_chunk (av, next);
2175 Properties of chunks recycled from fastbins
2178 static void
2179 do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2181 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2183 if (!chunk_is_mmapped (p))
2185 assert (av == arena_for_chunk (p));
2186 if (chunk_main_arena (p))
2187 assert (av == &main_arena);
2188 else
2189 assert (av != &main_arena);
2192 do_check_inuse_chunk (av, p);
2194 /* Legal size ... */
2195 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2196 assert ((unsigned long) (sz) >= MINSIZE);
2197 /* ... and alignment */
2198 assert (aligned_OK (chunk2mem (p)));
2199 /* chunk is less than MINSIZE more than request */
2200 assert ((long) (sz) - (long) (s) >= 0);
2201 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2205 Properties of nonrecycled chunks at the point they are malloced
2208 static void
2209 do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2211 /* same as recycled case ... */
2212 do_check_remalloced_chunk (av, p, s);
2215 ... plus, must obey implementation invariant that prev_inuse is
2216 always true of any allocated chunk; i.e., that each allocated
2217 chunk borders either a previously allocated and still in-use
2218 chunk, or the base of its memory arena. This is ensured
2219 by making all allocations from the `lowest' part of any found
2220 chunk. This does not necessarily hold however for chunks
2221 recycled via fastbins.
2224 assert (prev_inuse (p));
2229 Properties of malloc_state.
2231 This may be useful for debugging malloc, as well as detecting user
2232 programmer errors that somehow write into malloc_state.
2234 If you are extending or experimenting with this malloc, you can
2235 probably figure out how to hack this routine to print out or
2236 display chunk addresses, sizes, bins, and other instrumentation.
2239 static void
2240 do_check_malloc_state (mstate av)
2242 int i;
2243 mchunkptr p;
2244 mchunkptr q;
2245 mbinptr b;
2246 unsigned int idx;
2247 INTERNAL_SIZE_T size;
2248 unsigned long total = 0;
2249 int max_fast_bin;
2251 /* internal size_t must be no wider than pointer type */
2252 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2254 /* alignment is a power of 2 */
2255 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2257 /* Check the arena is initialized. */
2258 assert (av->top != 0);
2260 /* No memory has been allocated yet, so doing more tests is not possible. */
2261 if (av->top == initial_top (av))
2262 return;
2264 /* pagesize is a power of 2 */
2265 assert (powerof2(GLRO (dl_pagesize)));
2267 /* A contiguous main_arena is consistent with sbrk_base. */
2268 if (av == &main_arena && contiguous (av))
2269 assert ((char *) mp_.sbrk_base + av->system_mem ==
2270 (char *) av->top + chunksize (av->top));
2272 /* properties of fastbins */
2274 /* max_fast is in allowed range */
2275 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2277 max_fast_bin = fastbin_index (get_max_fast ());
2279 for (i = 0; i < NFASTBINS; ++i)
2281 p = fastbin (av, i);
2283 /* The following test can only be performed for the main arena.
2284 While mallopt calls malloc_consolidate to get rid of all fast
2285 bins (especially those larger than the new maximum) this does
2286 only happen for the main arena. Trying to do this for any
2287 other arena would mean those arenas have to be locked and
2288 malloc_consolidate be called for them. This is excessive. And
2289 even if this is acceptable to somebody it still cannot solve
2290 the problem completely since if the arena is locked a
2291 concurrent malloc call might create a new arena which then
2292 could use the newly invalid fast bins. */
2294 /* all bins past max_fast are empty */
2295 if (av == &main_arena && i > max_fast_bin)
2296 assert (p == 0);
2298 while (p != 0)
2300 if (__glibc_unlikely (misaligned_chunk (p)))
2301 malloc_printerr ("do_check_malloc_state(): "
2302 "unaligned fastbin chunk detected");
2303 /* each chunk claims to be inuse */
2304 do_check_inuse_chunk (av, p);
2305 total += chunksize (p);
2306 /* chunk belongs in this bin */
2307 assert (fastbin_index (chunksize (p)) == i);
2308 p = REVEAL_PTR (p->fd);
2312 /* check normal bins */
2313 for (i = 1; i < NBINS; ++i)
2315 b = bin_at (av, i);
2317 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2318 if (i >= 2)
2320 unsigned int binbit = get_binmap (av, i);
2321 int empty = last (b) == b;
2322 if (!binbit)
2323 assert (empty);
2324 else if (!empty)
2325 assert (binbit);
2328 for (p = last (b); p != b; p = p->bk)
2330 /* each chunk claims to be free */
2331 do_check_free_chunk (av, p);
2332 size = chunksize (p);
2333 total += size;
2334 if (i >= 2)
2336 /* chunk belongs in bin */
2337 idx = bin_index (size);
2338 assert (idx == i);
2339 /* lists are sorted */
2340 assert (p->bk == b ||
2341 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2343 if (!in_smallbin_range (size))
2345 if (p->fd_nextsize != NULL)
2347 if (p->fd_nextsize == p)
2348 assert (p->bk_nextsize == p);
2349 else
2351 if (p->fd_nextsize == first (b))
2352 assert (chunksize (p) < chunksize (p->fd_nextsize));
2353 else
2354 assert (chunksize (p) > chunksize (p->fd_nextsize));
2356 if (p == first (b))
2357 assert (chunksize (p) > chunksize (p->bk_nextsize));
2358 else
2359 assert (chunksize (p) < chunksize (p->bk_nextsize));
2362 else
2363 assert (p->bk_nextsize == NULL);
2366 else if (!in_smallbin_range (size))
2367 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2368 /* chunk is followed by a legal chain of inuse chunks */
2369 for (q = next_chunk (p);
2370 (q != av->top && inuse (q) &&
2371 (unsigned long) (chunksize (q)) >= MINSIZE);
2372 q = next_chunk (q))
2373 do_check_inuse_chunk (av, q);
2377 /* top chunk is OK */
2378 check_chunk (av, av->top);
2380 #endif
2383 /* ----------------- Support for debugging hooks -------------------- */
2384 #if IS_IN (libc)
2385 #include "hooks.c"
2386 #endif
2389 /* ----------- Routines dealing with system allocation -------------- */
2392 sysmalloc handles malloc cases requiring more memory from the system.
2393 On entry, it is assumed that av->top does not have enough
2394 space to service request for nb bytes, thus requiring that av->top
2395 be extended or replaced.
2398 static void *
2399 sysmalloc_mmap (INTERNAL_SIZE_T nb, size_t pagesize, int extra_flags, mstate av)
2401 long int size;
2404 Round up size to nearest page. For mmapped chunks, the overhead is one
2405 SIZE_SZ unit larger than for normal chunks, because there is no
2406 following chunk whose prev_size field could be used.
2408 See the front_misalign handling below, for glibc there is no need for
2409 further alignments unless we have have high alignment.
2411 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2412 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2413 else
2414 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2416 /* Don't try if size wraps around 0. */
2417 if ((unsigned long) (size) <= (unsigned long) (nb))
2418 return MAP_FAILED;
2420 char *mm = (char *) MMAP (0, size,
2421 mtag_mmap_flags | PROT_READ | PROT_WRITE,
2422 extra_flags);
2423 if (mm == MAP_FAILED)
2424 return mm;
2426 #ifdef MAP_HUGETLB
2427 if (!(extra_flags & MAP_HUGETLB))
2428 madvise_thp (mm, size);
2429 #endif
2432 The offset to the start of the mmapped region is stored in the prev_size
2433 field of the chunk. This allows us to adjust returned start address to
2434 meet alignment requirements here and in memalign(), and still be able to
2435 compute proper address argument for later munmap in free() and realloc().
2438 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2440 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2442 /* For glibc, chunk2mem increases the address by CHUNK_HDR_SZ and
2443 MALLOC_ALIGN_MASK is CHUNK_HDR_SZ-1. Each mmap'ed area is page
2444 aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
2445 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2446 front_misalign = 0;
2448 else
2449 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2451 mchunkptr p; /* the allocated/returned chunk */
2453 if (front_misalign > 0)
2455 ptrdiff_t correction = MALLOC_ALIGNMENT - front_misalign;
2456 p = (mchunkptr) (mm + correction);
2457 set_prev_size (p, correction);
2458 set_head (p, (size - correction) | IS_MMAPPED);
2460 else
2462 p = (mchunkptr) mm;
2463 set_prev_size (p, 0);
2464 set_head (p, size | IS_MMAPPED);
2467 /* update statistics */
2468 int new = atomic_fetch_add_relaxed (&mp_.n_mmaps, 1) + 1;
2469 atomic_max (&mp_.max_n_mmaps, new);
2471 unsigned long sum;
2472 sum = atomic_fetch_add_relaxed (&mp_.mmapped_mem, size) + size;
2473 atomic_max (&mp_.max_mmapped_mem, sum);
2475 check_chunk (av, p);
2477 return chunk2mem (p);
2481 Allocate memory using mmap() based on S and NB requested size, aligning to
2482 PAGESIZE if required. The EXTRA_FLAGS is used on mmap() call. If the call
2483 succeeds S is updated with the allocated size. This is used as a fallback
2484 if MORECORE fails.
2486 static void *
2487 sysmalloc_mmap_fallback (long int *s, INTERNAL_SIZE_T nb,
2488 INTERNAL_SIZE_T old_size, size_t minsize,
2489 size_t pagesize, int extra_flags, mstate av)
2491 long int size = *s;
2493 /* Cannot merge with old top, so add its size back in */
2494 if (contiguous (av))
2495 size = ALIGN_UP (size + old_size, pagesize);
2497 /* If we are relying on mmap as backup, then use larger units */
2498 if ((unsigned long) (size) < minsize)
2499 size = minsize;
2501 /* Don't try if size wraps around 0 */
2502 if ((unsigned long) (size) <= (unsigned long) (nb))
2503 return MORECORE_FAILURE;
2505 char *mbrk = (char *) (MMAP (0, size,
2506 mtag_mmap_flags | PROT_READ | PROT_WRITE,
2507 extra_flags));
2508 if (mbrk == MAP_FAILED)
2509 return MAP_FAILED;
2511 #ifdef MAP_HUGETLB
2512 if (!(extra_flags & MAP_HUGETLB))
2513 madvise_thp (mbrk, size);
2514 #endif
2516 /* Record that we no longer have a contiguous sbrk region. After the first
2517 time mmap is used as backup, we do not ever rely on contiguous space
2518 since this could incorrectly bridge regions. */
2519 set_noncontiguous (av);
2521 *s = size;
2522 return mbrk;
2525 static void *
2526 sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2528 mchunkptr old_top; /* incoming value of av->top */
2529 INTERNAL_SIZE_T old_size; /* its size */
2530 char *old_end; /* its end address */
2532 long size; /* arg to first MORECORE or mmap call */
2533 char *brk; /* return value from MORECORE */
2535 long correction; /* arg to 2nd MORECORE call */
2536 char *snd_brk; /* 2nd return val */
2538 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2539 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2540 char *aligned_brk; /* aligned offset into brk */
2542 mchunkptr p; /* the allocated/returned chunk */
2543 mchunkptr remainder; /* remainder from allocation */
2544 unsigned long remainder_size; /* its size */
2547 size_t pagesize = GLRO (dl_pagesize);
2548 bool tried_mmap = false;
2552 If have mmap, and the request size meets the mmap threshold, and
2553 the system supports mmap, and there are few enough currently
2554 allocated mmapped regions, try to directly map this request
2555 rather than expanding top.
2558 if (av == NULL
2559 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2560 && (mp_.n_mmaps < mp_.n_mmaps_max)))
2562 char *mm;
2563 if (mp_.hp_pagesize > 0 && nb >= mp_.hp_pagesize)
2565 /* There is no need to issue the THP madvise call if Huge Pages are
2566 used directly. */
2567 mm = sysmalloc_mmap (nb, mp_.hp_pagesize, mp_.hp_flags, av);
2568 if (mm != MAP_FAILED)
2569 return mm;
2571 mm = sysmalloc_mmap (nb, pagesize, 0, av);
2572 if (mm != MAP_FAILED)
2573 return mm;
2574 tried_mmap = true;
2577 /* There are no usable arenas and mmap also failed. */
2578 if (av == NULL)
2579 return 0;
2581 /* Record incoming configuration of top */
2583 old_top = av->top;
2584 old_size = chunksize (old_top);
2585 old_end = (char *) (chunk_at_offset (old_top, old_size));
2587 brk = snd_brk = (char *) (MORECORE_FAILURE);
2590 If not the first time through, we require old_size to be
2591 at least MINSIZE and to have prev_inuse set.
2594 assert ((old_top == initial_top (av) && old_size == 0) ||
2595 ((unsigned long) (old_size) >= MINSIZE &&
2596 prev_inuse (old_top) &&
2597 ((unsigned long) old_end & (pagesize - 1)) == 0));
2599 /* Precondition: not enough current space to satisfy nb request */
2600 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2603 if (av != &main_arena)
2605 heap_info *old_heap, *heap;
2606 size_t old_heap_size;
2608 /* First try to extend the current heap. */
2609 old_heap = heap_for_ptr (old_top);
2610 old_heap_size = old_heap->size;
2611 if ((long) (MINSIZE + nb - old_size) > 0
2612 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2614 av->system_mem += old_heap->size - old_heap_size;
2615 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2616 | PREV_INUSE);
2618 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2620 /* Use a newly allocated heap. */
2621 heap->ar_ptr = av;
2622 heap->prev = old_heap;
2623 av->system_mem += heap->size;
2624 /* Set up the new top. */
2625 top (av) = chunk_at_offset (heap, sizeof (*heap));
2626 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2628 /* Setup fencepost and free the old top chunk with a multiple of
2629 MALLOC_ALIGNMENT in size. */
2630 /* The fencepost takes at least MINSIZE bytes, because it might
2631 become the top chunk again later. Note that a footer is set
2632 up, too, although the chunk is marked in use. */
2633 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2634 set_head (chunk_at_offset (old_top, old_size + CHUNK_HDR_SZ),
2635 0 | PREV_INUSE);
2636 if (old_size >= MINSIZE)
2638 set_head (chunk_at_offset (old_top, old_size),
2639 CHUNK_HDR_SZ | PREV_INUSE);
2640 set_foot (chunk_at_offset (old_top, old_size), CHUNK_HDR_SZ);
2641 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2642 _int_free (av, old_top, 1);
2644 else
2646 set_head (old_top, (old_size + CHUNK_HDR_SZ) | PREV_INUSE);
2647 set_foot (old_top, (old_size + CHUNK_HDR_SZ));
2650 else if (!tried_mmap)
2652 /* We can at least try to use to mmap memory. If new_heap fails
2653 it is unlikely that trying to allocate huge pages will
2654 succeed. */
2655 char *mm = sysmalloc_mmap (nb, pagesize, 0, av);
2656 if (mm != MAP_FAILED)
2657 return mm;
2660 else /* av == main_arena */
2663 { /* Request enough space for nb + pad + overhead */
2664 size = nb + mp_.top_pad + MINSIZE;
2667 If contiguous, we can subtract out existing space that we hope to
2668 combine with new space. We add it back later only if
2669 we don't actually get contiguous space.
2672 if (contiguous (av))
2673 size -= old_size;
2676 Round to a multiple of page size or huge page size.
2677 If MORECORE is not contiguous, this ensures that we only call it
2678 with whole-page arguments. And if MORECORE is contiguous and
2679 this is not first time through, this preserves page-alignment of
2680 previous calls. Otherwise, we correct to page-align below.
2683 #ifdef MADV_HUGEPAGE
2684 /* Defined in brk.c. */
2685 extern void *__curbrk;
2686 if (__glibc_unlikely (mp_.thp_pagesize != 0))
2688 uintptr_t top = ALIGN_UP ((uintptr_t) __curbrk + size,
2689 mp_.thp_pagesize);
2690 size = top - (uintptr_t) __curbrk;
2692 else
2693 #endif
2694 size = ALIGN_UP (size, GLRO(dl_pagesize));
2697 Don't try to call MORECORE if argument is so big as to appear
2698 negative. Note that since mmap takes size_t arg, it may succeed
2699 below even if we cannot call MORECORE.
2702 if (size > 0)
2704 brk = (char *) (MORECORE (size));
2705 if (brk != (char *) (MORECORE_FAILURE))
2706 madvise_thp (brk, size);
2707 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2710 if (brk == (char *) (MORECORE_FAILURE))
2713 If have mmap, try using it as a backup when MORECORE fails or
2714 cannot be used. This is worth doing on systems that have "holes" in
2715 address space, so sbrk cannot extend to give contiguous space, but
2716 space is available elsewhere. Note that we ignore mmap max count
2717 and threshold limits, since the space will not be used as a
2718 segregated mmap region.
2721 char *mbrk = MAP_FAILED;
2722 if (mp_.hp_pagesize > 0)
2723 mbrk = sysmalloc_mmap_fallback (&size, nb, old_size,
2724 mp_.hp_pagesize, mp_.hp_pagesize,
2725 mp_.hp_flags, av);
2726 if (mbrk == MAP_FAILED)
2727 mbrk = sysmalloc_mmap_fallback (&size, nb, old_size, MMAP_AS_MORECORE_SIZE,
2728 pagesize, 0, av);
2729 if (mbrk != MAP_FAILED)
2731 /* We do not need, and cannot use, another sbrk call to find end */
2732 brk = mbrk;
2733 snd_brk = brk + size;
2737 if (brk != (char *) (MORECORE_FAILURE))
2739 if (mp_.sbrk_base == 0)
2740 mp_.sbrk_base = brk;
2741 av->system_mem += size;
2744 If MORECORE extends previous space, we can likewise extend top size.
2747 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2748 set_head (old_top, (size + old_size) | PREV_INUSE);
2750 else if (contiguous (av) && old_size && brk < old_end)
2751 /* Oops! Someone else killed our space.. Can't touch anything. */
2752 malloc_printerr ("break adjusted to free malloc space");
2755 Otherwise, make adjustments:
2757 * If the first time through or noncontiguous, we need to call sbrk
2758 just to find out where the end of memory lies.
2760 * We need to ensure that all returned chunks from malloc will meet
2761 MALLOC_ALIGNMENT
2763 * If there was an intervening foreign sbrk, we need to adjust sbrk
2764 request size to account for fact that we will not be able to
2765 combine new space with existing space in old_top.
2767 * Almost all systems internally allocate whole pages at a time, in
2768 which case we might as well use the whole last page of request.
2769 So we allocate enough more memory to hit a page boundary now,
2770 which in turn causes future contiguous calls to page-align.
2773 else
2775 front_misalign = 0;
2776 end_misalign = 0;
2777 correction = 0;
2778 aligned_brk = brk;
2780 /* handle contiguous cases */
2781 if (contiguous (av))
2783 /* Count foreign sbrk as system_mem. */
2784 if (old_size)
2785 av->system_mem += brk - old_end;
2787 /* Guarantee alignment of first new chunk made from this space */
2789 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2790 if (front_misalign > 0)
2793 Skip over some bytes to arrive at an aligned position.
2794 We don't need to specially mark these wasted front bytes.
2795 They will never be accessed anyway because
2796 prev_inuse of av->top (and any chunk created from its start)
2797 is always true after initialization.
2800 correction = MALLOC_ALIGNMENT - front_misalign;
2801 aligned_brk += correction;
2805 If this isn't adjacent to existing space, then we will not
2806 be able to merge with old_top space, so must add to 2nd request.
2809 correction += old_size;
2811 /* Extend the end address to hit a page boundary */
2812 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2813 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2815 assert (correction >= 0);
2816 snd_brk = (char *) (MORECORE (correction));
2819 If can't allocate correction, try to at least find out current
2820 brk. It might be enough to proceed without failing.
2822 Note that if second sbrk did NOT fail, we assume that space
2823 is contiguous with first sbrk. This is a safe assumption unless
2824 program is multithreaded but doesn't use locks and a foreign sbrk
2825 occurred between our first and second calls.
2828 if (snd_brk == (char *) (MORECORE_FAILURE))
2830 correction = 0;
2831 snd_brk = (char *) (MORECORE (0));
2833 else
2834 madvise_thp (snd_brk, correction);
2837 /* handle non-contiguous cases */
2838 else
2840 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2841 /* MORECORE/mmap must correctly align */
2842 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2843 else
2845 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2846 if (front_misalign > 0)
2849 Skip over some bytes to arrive at an aligned position.
2850 We don't need to specially mark these wasted front bytes.
2851 They will never be accessed anyway because
2852 prev_inuse of av->top (and any chunk created from its start)
2853 is always true after initialization.
2856 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2860 /* Find out current end of memory */
2861 if (snd_brk == (char *) (MORECORE_FAILURE))
2863 snd_brk = (char *) (MORECORE (0));
2867 /* Adjust top based on results of second sbrk */
2868 if (snd_brk != (char *) (MORECORE_FAILURE))
2870 av->top = (mchunkptr) aligned_brk;
2871 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2872 av->system_mem += correction;
2875 If not the first time through, we either have a
2876 gap due to foreign sbrk or a non-contiguous region. Insert a
2877 double fencepost at old_top to prevent consolidation with space
2878 we don't own. These fenceposts are artificial chunks that are
2879 marked as inuse and are in any case too small to use. We need
2880 two to make sizes and alignments work out.
2883 if (old_size != 0)
2886 Shrink old_top to insert fenceposts, keeping size a
2887 multiple of MALLOC_ALIGNMENT. We know there is at least
2888 enough space in old_top to do this.
2890 old_size = (old_size - 2 * CHUNK_HDR_SZ) & ~MALLOC_ALIGN_MASK;
2891 set_head (old_top, old_size | PREV_INUSE);
2894 Note that the following assignments completely overwrite
2895 old_top when old_size was previously MINSIZE. This is
2896 intentional. We need the fencepost, even if old_top otherwise gets
2897 lost.
2899 set_head (chunk_at_offset (old_top, old_size),
2900 CHUNK_HDR_SZ | PREV_INUSE);
2901 set_head (chunk_at_offset (old_top,
2902 old_size + CHUNK_HDR_SZ),
2903 CHUNK_HDR_SZ | PREV_INUSE);
2905 /* If possible, release the rest. */
2906 if (old_size >= MINSIZE)
2908 _int_free (av, old_top, 1);
2914 } /* if (av != &main_arena) */
2916 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2917 av->max_system_mem = av->system_mem;
2918 check_malloc_state (av);
2920 /* finally, do the allocation */
2921 p = av->top;
2922 size = chunksize (p);
2924 /* check that one of the above allocation paths succeeded */
2925 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2927 remainder_size = size - nb;
2928 remainder = chunk_at_offset (p, nb);
2929 av->top = remainder;
2930 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2931 set_head (remainder, remainder_size | PREV_INUSE);
2932 check_malloced_chunk (av, p, nb);
2933 return chunk2mem (p);
2936 /* catch all failure paths */
2937 __set_errno (ENOMEM);
2938 return 0;
2943 systrim is an inverse of sorts to sysmalloc. It gives memory back
2944 to the system (via negative arguments to sbrk) if there is unused
2945 memory at the `high' end of the malloc pool. It is called
2946 automatically by free() when top space exceeds the trim
2947 threshold. It is also called by the public malloc_trim routine. It
2948 returns 1 if it actually released any memory, else 0.
2951 static int
2952 systrim (size_t pad, mstate av)
2954 long top_size; /* Amount of top-most memory */
2955 long extra; /* Amount to release */
2956 long released; /* Amount actually released */
2957 char *current_brk; /* address returned by pre-check sbrk call */
2958 char *new_brk; /* address returned by post-check sbrk call */
2959 long top_area;
2961 top_size = chunksize (av->top);
2963 top_area = top_size - MINSIZE - 1;
2964 if (top_area <= pad)
2965 return 0;
2967 /* Release in pagesize units and round down to the nearest page. */
2968 #ifdef MADV_HUGEPAGE
2969 if (__glibc_unlikely (mp_.thp_pagesize != 0))
2970 extra = ALIGN_DOWN (top_area - pad, mp_.thp_pagesize);
2971 else
2972 #endif
2973 extra = ALIGN_DOWN (top_area - pad, GLRO(dl_pagesize));
2975 if (extra == 0)
2976 return 0;
2979 Only proceed if end of memory is where we last set it.
2980 This avoids problems if there were foreign sbrk calls.
2982 current_brk = (char *) (MORECORE (0));
2983 if (current_brk == (char *) (av->top) + top_size)
2986 Attempt to release memory. We ignore MORECORE return value,
2987 and instead call again to find out where new end of memory is.
2988 This avoids problems if first call releases less than we asked,
2989 of if failure somehow altered brk value. (We could still
2990 encounter problems if it altered brk in some very bad way,
2991 but the only thing we can do is adjust anyway, which will cause
2992 some downstream failure.)
2995 MORECORE (-extra);
2996 new_brk = (char *) (MORECORE (0));
2998 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
3000 if (new_brk != (char *) MORECORE_FAILURE)
3002 released = (long) (current_brk - new_brk);
3004 if (released != 0)
3006 /* Success. Adjust top. */
3007 av->system_mem -= released;
3008 set_head (av->top, (top_size - released) | PREV_INUSE);
3009 check_malloc_state (av);
3010 return 1;
3014 return 0;
3017 static void
3018 munmap_chunk (mchunkptr p)
3020 size_t pagesize = GLRO (dl_pagesize);
3021 INTERNAL_SIZE_T size = chunksize (p);
3023 assert (chunk_is_mmapped (p));
3025 uintptr_t mem = (uintptr_t) chunk2mem (p);
3026 uintptr_t block = (uintptr_t) p - prev_size (p);
3027 size_t total_size = prev_size (p) + size;
3028 /* Unfortunately we have to do the compilers job by hand here. Normally
3029 we would test BLOCK and TOTAL-SIZE separately for compliance with the
3030 page size. But gcc does not recognize the optimization possibility
3031 (in the moment at least) so we combine the two values into one before
3032 the bit test. */
3033 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
3034 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
3035 malloc_printerr ("munmap_chunk(): invalid pointer");
3037 atomic_fetch_add_relaxed (&mp_.n_mmaps, -1);
3038 atomic_fetch_add_relaxed (&mp_.mmapped_mem, -total_size);
3040 /* If munmap failed the process virtual memory address space is in a
3041 bad shape. Just leave the block hanging around, the process will
3042 terminate shortly anyway since not much can be done. */
3043 __munmap ((char *) block, total_size);
3046 #if HAVE_MREMAP
3048 static mchunkptr
3049 mremap_chunk (mchunkptr p, size_t new_size)
3051 size_t pagesize = GLRO (dl_pagesize);
3052 INTERNAL_SIZE_T offset = prev_size (p);
3053 INTERNAL_SIZE_T size = chunksize (p);
3054 char *cp;
3056 assert (chunk_is_mmapped (p));
3058 uintptr_t block = (uintptr_t) p - offset;
3059 uintptr_t mem = (uintptr_t) chunk2mem(p);
3060 size_t total_size = offset + size;
3061 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
3062 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
3063 malloc_printerr("mremap_chunk(): invalid pointer");
3065 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
3066 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
3068 /* No need to remap if the number of pages does not change. */
3069 if (total_size == new_size)
3070 return p;
3072 cp = (char *) __mremap ((char *) block, total_size, new_size,
3073 MREMAP_MAYMOVE);
3075 if (cp == MAP_FAILED)
3076 return 0;
3078 madvise_thp (cp, new_size);
3080 p = (mchunkptr) (cp + offset);
3082 assert (aligned_OK (chunk2mem (p)));
3084 assert (prev_size (p) == offset);
3085 set_head (p, (new_size - offset) | IS_MMAPPED);
3087 INTERNAL_SIZE_T new;
3088 new = atomic_fetch_add_relaxed (&mp_.mmapped_mem, new_size - size - offset)
3089 + new_size - size - offset;
3090 atomic_max (&mp_.max_mmapped_mem, new);
3091 return p;
3093 #endif /* HAVE_MREMAP */
3095 /*------------------------ Public wrappers. --------------------------------*/
3097 #if USE_TCACHE
3099 /* We overlay this structure on the user-data portion of a chunk when
3100 the chunk is stored in the per-thread cache. */
3101 typedef struct tcache_entry
3103 struct tcache_entry *next;
3104 /* This field exists to detect double frees. */
3105 uintptr_t key;
3106 } tcache_entry;
3108 /* There is one of these for each thread, which contains the
3109 per-thread cache (hence "tcache_perthread_struct"). Keeping
3110 overall size low is mildly important. Note that COUNTS and ENTRIES
3111 are redundant (we could have just counted the linked list each
3112 time), this is for performance reasons. */
3113 typedef struct tcache_perthread_struct
3115 uint16_t counts[TCACHE_MAX_BINS];
3116 tcache_entry *entries[TCACHE_MAX_BINS];
3117 } tcache_perthread_struct;
3119 static __thread bool tcache_shutting_down = false;
3120 static __thread tcache_perthread_struct *tcache = NULL;
3122 /* Process-wide key to try and catch a double-free in the same thread. */
3123 static uintptr_t tcache_key;
3125 /* The value of tcache_key does not really have to be a cryptographically
3126 secure random number. It only needs to be arbitrary enough so that it does
3127 not collide with values present in applications. If a collision does happen
3128 consistently enough, it could cause a degradation in performance since the
3129 entire list is checked to check if the block indeed has been freed the
3130 second time. The odds of this happening are exceedingly low though, about 1
3131 in 2^wordsize. There is probably a higher chance of the performance
3132 degradation being due to a double free where the first free happened in a
3133 different thread; that's a case this check does not cover. */
3134 static void
3135 tcache_key_initialize (void)
3137 if (__getrandom_nocancel (&tcache_key, sizeof(tcache_key), GRND_NONBLOCK)
3138 != sizeof (tcache_key))
3140 tcache_key = random_bits ();
3141 #if __WORDSIZE == 64
3142 tcache_key = (tcache_key << 32) | random_bits ();
3143 #endif
3147 /* Caller must ensure that we know tc_idx is valid and there's room
3148 for more chunks. */
3149 static __always_inline void
3150 tcache_put (mchunkptr chunk, size_t tc_idx)
3152 tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
3154 /* Mark this chunk as "in the tcache" so the test in _int_free will
3155 detect a double free. */
3156 e->key = tcache_key;
3158 e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]);
3159 tcache->entries[tc_idx] = e;
3160 ++(tcache->counts[tc_idx]);
3163 /* Caller must ensure that we know tc_idx is valid and there's
3164 available chunks to remove. Removes chunk from the middle of the
3165 list. */
3166 static __always_inline void *
3167 tcache_get_n (size_t tc_idx, tcache_entry **ep)
3169 tcache_entry *e;
3170 if (ep == &(tcache->entries[tc_idx]))
3171 e = *ep;
3172 else
3173 e = REVEAL_PTR (*ep);
3175 if (__glibc_unlikely (!aligned_OK (e)))
3176 malloc_printerr ("malloc(): unaligned tcache chunk detected");
3178 if (ep == &(tcache->entries[tc_idx]))
3179 *ep = REVEAL_PTR (e->next);
3180 else
3181 *ep = PROTECT_PTR (ep, REVEAL_PTR (e->next));
3183 --(tcache->counts[tc_idx]);
3184 e->key = 0;
3185 return (void *) e;
3188 /* Like the above, but removes from the head of the list. */
3189 static __always_inline void *
3190 tcache_get (size_t tc_idx)
3192 return tcache_get_n (tc_idx, & tcache->entries[tc_idx]);
3195 /* Iterates through the tcache linked list. */
3196 static __always_inline tcache_entry *
3197 tcache_next (tcache_entry *e)
3199 return (tcache_entry *) REVEAL_PTR (e->next);
3202 static void
3203 tcache_thread_shutdown (void)
3205 int i;
3206 tcache_perthread_struct *tcache_tmp = tcache;
3208 tcache_shutting_down = true;
3210 if (!tcache)
3211 return;
3213 /* Disable the tcache and prevent it from being reinitialized. */
3214 tcache = NULL;
3216 /* Free all of the entries and the tcache itself back to the arena
3217 heap for coalescing. */
3218 for (i = 0; i < TCACHE_MAX_BINS; ++i)
3220 while (tcache_tmp->entries[i])
3222 tcache_entry *e = tcache_tmp->entries[i];
3223 if (__glibc_unlikely (!aligned_OK (e)))
3224 malloc_printerr ("tcache_thread_shutdown(): "
3225 "unaligned tcache chunk detected");
3226 tcache_tmp->entries[i] = REVEAL_PTR (e->next);
3227 __libc_free (e);
3231 __libc_free (tcache_tmp);
3234 static void
3235 tcache_init(void)
3237 mstate ar_ptr;
3238 void *victim = 0;
3239 const size_t bytes = sizeof (tcache_perthread_struct);
3241 if (tcache_shutting_down)
3242 return;
3244 arena_get (ar_ptr, bytes);
3245 victim = _int_malloc (ar_ptr, bytes);
3246 if (!victim && ar_ptr != NULL)
3248 ar_ptr = arena_get_retry (ar_ptr, bytes);
3249 victim = _int_malloc (ar_ptr, bytes);
3253 if (ar_ptr != NULL)
3254 __libc_lock_unlock (ar_ptr->mutex);
3256 /* In a low memory situation, we may not be able to allocate memory
3257 - in which case, we just keep trying later. However, we
3258 typically do this very early, so either there is sufficient
3259 memory, or there isn't enough memory to do non-trivial
3260 allocations anyway. */
3261 if (victim)
3263 tcache = (tcache_perthread_struct *) victim;
3264 memset (tcache, 0, sizeof (tcache_perthread_struct));
3269 # define MAYBE_INIT_TCACHE() \
3270 if (__glibc_unlikely (tcache == NULL)) \
3271 tcache_init();
3273 #else /* !USE_TCACHE */
3274 # define MAYBE_INIT_TCACHE()
3276 static void
3277 tcache_thread_shutdown (void)
3279 /* Nothing to do if there is no thread cache. */
3282 #endif /* !USE_TCACHE */
3284 #if IS_IN (libc)
3285 void *
3286 __libc_malloc (size_t bytes)
3288 mstate ar_ptr;
3289 void *victim;
3291 _Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2,
3292 "PTRDIFF_MAX is not more than half of SIZE_MAX");
3294 if (!__malloc_initialized)
3295 ptmalloc_init ();
3296 #if USE_TCACHE
3297 /* int_free also calls request2size, be careful to not pad twice. */
3298 size_t tbytes = checked_request2size (bytes);
3299 if (tbytes == 0)
3301 __set_errno (ENOMEM);
3302 return NULL;
3304 size_t tc_idx = csize2tidx (tbytes);
3306 MAYBE_INIT_TCACHE ();
3308 DIAG_PUSH_NEEDS_COMMENT;
3309 if (tc_idx < mp_.tcache_bins
3310 && tcache != NULL
3311 && tcache->counts[tc_idx] > 0)
3313 victim = tcache_get (tc_idx);
3314 return tag_new_usable (victim);
3316 DIAG_POP_NEEDS_COMMENT;
3317 #endif
3319 if (SINGLE_THREAD_P)
3321 victim = tag_new_usable (_int_malloc (&main_arena, bytes));
3322 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3323 &main_arena == arena_for_chunk (mem2chunk (victim)));
3324 return victim;
3327 arena_get (ar_ptr, bytes);
3329 victim = _int_malloc (ar_ptr, bytes);
3330 /* Retry with another arena only if we were able to find a usable arena
3331 before. */
3332 if (!victim && ar_ptr != NULL)
3334 LIBC_PROBE (memory_malloc_retry, 1, bytes);
3335 ar_ptr = arena_get_retry (ar_ptr, bytes);
3336 victim = _int_malloc (ar_ptr, bytes);
3339 if (ar_ptr != NULL)
3340 __libc_lock_unlock (ar_ptr->mutex);
3342 victim = tag_new_usable (victim);
3344 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3345 ar_ptr == arena_for_chunk (mem2chunk (victim)));
3346 return victim;
3348 libc_hidden_def (__libc_malloc)
3350 void
3351 __libc_free (void *mem)
3353 mstate ar_ptr;
3354 mchunkptr p; /* chunk corresponding to mem */
3356 if (mem == 0) /* free(0) has no effect */
3357 return;
3359 /* Quickly check that the freed pointer matches the tag for the memory.
3360 This gives a useful double-free detection. */
3361 if (__glibc_unlikely (mtag_enabled))
3362 *(volatile char *)mem;
3364 int err = errno;
3366 p = mem2chunk (mem);
3368 if (chunk_is_mmapped (p)) /* release mmapped memory. */
3370 /* See if the dynamic brk/mmap threshold needs adjusting.
3371 Dumped fake mmapped chunks do not affect the threshold. */
3372 if (!mp_.no_dyn_threshold
3373 && chunksize_nomask (p) > mp_.mmap_threshold
3374 && chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX)
3376 mp_.mmap_threshold = chunksize (p);
3377 mp_.trim_threshold = 2 * mp_.mmap_threshold;
3378 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
3379 mp_.mmap_threshold, mp_.trim_threshold);
3381 munmap_chunk (p);
3383 else
3385 MAYBE_INIT_TCACHE ();
3387 /* Mark the chunk as belonging to the library again. */
3388 (void)tag_region (chunk2mem (p), memsize (p));
3390 ar_ptr = arena_for_chunk (p);
3391 _int_free (ar_ptr, p, 0);
3394 __set_errno (err);
3396 libc_hidden_def (__libc_free)
3398 void *
3399 __libc_realloc (void *oldmem, size_t bytes)
3401 mstate ar_ptr;
3402 INTERNAL_SIZE_T nb; /* padded request size */
3404 void *newp; /* chunk to return */
3406 if (!__malloc_initialized)
3407 ptmalloc_init ();
3409 #if REALLOC_ZERO_BYTES_FREES
3410 if (bytes == 0 && oldmem != NULL)
3412 __libc_free (oldmem); return 0;
3414 #endif
3416 /* realloc of null is supposed to be same as malloc */
3417 if (oldmem == 0)
3418 return __libc_malloc (bytes);
3420 /* Perform a quick check to ensure that the pointer's tag matches the
3421 memory's tag. */
3422 if (__glibc_unlikely (mtag_enabled))
3423 *(volatile char*) oldmem;
3425 /* chunk corresponding to oldmem */
3426 const mchunkptr oldp = mem2chunk (oldmem);
3428 /* Return the chunk as is if the request grows within usable bytes, typically
3429 into the alignment padding. We want to avoid reusing the block for
3430 shrinkages because it ends up unnecessarily fragmenting the address space.
3431 This is also why the heuristic misses alignment padding for THP for
3432 now. */
3433 size_t usable = musable (oldmem);
3434 if (bytes <= usable)
3436 size_t difference = usable - bytes;
3437 if ((unsigned long) difference < 2 * sizeof (INTERNAL_SIZE_T)
3438 || (chunk_is_mmapped (oldp) && difference <= GLRO (dl_pagesize)))
3439 return oldmem;
3442 /* its size */
3443 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
3445 if (chunk_is_mmapped (oldp))
3446 ar_ptr = NULL;
3447 else
3449 MAYBE_INIT_TCACHE ();
3450 ar_ptr = arena_for_chunk (oldp);
3453 /* Little security check which won't hurt performance: the allocator
3454 never wraps around at the end of the address space. Therefore
3455 we can exclude some size values which might appear here by
3456 accident or by "design" from some intruder. */
3457 if ((__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
3458 || __builtin_expect (misaligned_chunk (oldp), 0)))
3459 malloc_printerr ("realloc(): invalid pointer");
3461 nb = checked_request2size (bytes);
3462 if (nb == 0)
3464 __set_errno (ENOMEM);
3465 return NULL;
3468 if (chunk_is_mmapped (oldp))
3470 void *newmem;
3472 #if HAVE_MREMAP
3473 newp = mremap_chunk (oldp, nb);
3474 if (newp)
3476 void *newmem = chunk2mem_tag (newp);
3477 /* Give the new block a different tag. This helps to ensure
3478 that stale handles to the previous mapping are not
3479 reused. There's a performance hit for both us and the
3480 caller for doing this, so we might want to
3481 reconsider. */
3482 return tag_new_usable (newmem);
3484 #endif
3485 /* Note the extra SIZE_SZ overhead. */
3486 if (oldsize - SIZE_SZ >= nb)
3487 return oldmem; /* do nothing */
3489 /* Must alloc, copy, free. */
3490 newmem = __libc_malloc (bytes);
3491 if (newmem == 0)
3492 return 0; /* propagate failure */
3494 memcpy (newmem, oldmem, oldsize - CHUNK_HDR_SZ);
3495 munmap_chunk (oldp);
3496 return newmem;
3499 if (SINGLE_THREAD_P)
3501 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3502 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3503 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3505 return newp;
3508 __libc_lock_lock (ar_ptr->mutex);
3510 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3512 __libc_lock_unlock (ar_ptr->mutex);
3513 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3514 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3516 if (newp == NULL)
3518 /* Try harder to allocate memory in other arenas. */
3519 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3520 newp = __libc_malloc (bytes);
3521 if (newp != NULL)
3523 size_t sz = memsize (oldp);
3524 memcpy (newp, oldmem, sz);
3525 (void) tag_region (chunk2mem (oldp), sz);
3526 _int_free (ar_ptr, oldp, 0);
3530 return newp;
3532 libc_hidden_def (__libc_realloc)
3534 void *
3535 __libc_memalign (size_t alignment, size_t bytes)
3537 if (!__malloc_initialized)
3538 ptmalloc_init ();
3540 void *address = RETURN_ADDRESS (0);
3541 return _mid_memalign (alignment, bytes, address);
3543 libc_hidden_def (__libc_memalign)
3545 /* For ISO C17. */
3546 void *
3547 weak_function
3548 aligned_alloc (size_t alignment, size_t bytes)
3550 if (!__malloc_initialized)
3551 ptmalloc_init ();
3553 /* Similar to memalign, but starting with ISO C17 the standard
3554 requires an error for alignments that are not supported by the
3555 implementation. Valid alignments for the current implementation
3556 are non-negative powers of two. */
3557 if (!powerof2 (alignment) || alignment == 0)
3559 __set_errno (EINVAL);
3560 return 0;
3563 void *address = RETURN_ADDRESS (0);
3564 return _mid_memalign (alignment, bytes, address);
3567 static void *
3568 _mid_memalign (size_t alignment, size_t bytes, void *address)
3570 mstate ar_ptr;
3571 void *p;
3573 /* If we need less alignment than we give anyway, just relay to malloc. */
3574 if (alignment <= MALLOC_ALIGNMENT)
3575 return __libc_malloc (bytes);
3577 /* Otherwise, ensure that it is at least a minimum chunk size */
3578 if (alignment < MINSIZE)
3579 alignment = MINSIZE;
3581 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3582 power of 2 and will cause overflow in the check below. */
3583 if (alignment > SIZE_MAX / 2 + 1)
3585 __set_errno (EINVAL);
3586 return 0;
3590 /* Make sure alignment is power of 2. */
3591 if (!powerof2 (alignment))
3593 size_t a = MALLOC_ALIGNMENT * 2;
3594 while (a < alignment)
3595 a <<= 1;
3596 alignment = a;
3599 #if USE_TCACHE
3601 size_t tbytes;
3602 tbytes = checked_request2size (bytes);
3603 if (tbytes == 0)
3605 __set_errno (ENOMEM);
3606 return NULL;
3608 size_t tc_idx = csize2tidx (tbytes);
3610 if (tc_idx < mp_.tcache_bins
3611 && tcache != NULL
3612 && tcache->counts[tc_idx] > 0)
3614 /* The tcache itself isn't encoded, but the chain is. */
3615 tcache_entry **tep = & tcache->entries[tc_idx];
3616 tcache_entry *te = *tep;
3617 while (te != NULL && !PTR_IS_ALIGNED (te, alignment))
3619 tep = & (te->next);
3620 te = tcache_next (te);
3622 if (te != NULL)
3624 void *victim = tcache_get_n (tc_idx, tep);
3625 return tag_new_usable (victim);
3629 #endif
3631 if (SINGLE_THREAD_P)
3633 p = _int_memalign (&main_arena, alignment, bytes);
3634 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3635 &main_arena == arena_for_chunk (mem2chunk (p)));
3636 return tag_new_usable (p);
3639 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3641 p = _int_memalign (ar_ptr, alignment, bytes);
3642 if (!p && ar_ptr != NULL)
3644 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3645 ar_ptr = arena_get_retry (ar_ptr, bytes);
3646 p = _int_memalign (ar_ptr, alignment, bytes);
3649 if (ar_ptr != NULL)
3650 __libc_lock_unlock (ar_ptr->mutex);
3652 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3653 ar_ptr == arena_for_chunk (mem2chunk (p)));
3654 return tag_new_usable (p);
3657 void *
3658 __libc_valloc (size_t bytes)
3660 if (!__malloc_initialized)
3661 ptmalloc_init ();
3663 void *address = RETURN_ADDRESS (0);
3664 size_t pagesize = GLRO (dl_pagesize);
3665 return _mid_memalign (pagesize, bytes, address);
3668 void *
3669 __libc_pvalloc (size_t bytes)
3671 if (!__malloc_initialized)
3672 ptmalloc_init ();
3674 void *address = RETURN_ADDRESS (0);
3675 size_t pagesize = GLRO (dl_pagesize);
3676 size_t rounded_bytes;
3677 /* ALIGN_UP with overflow check. */
3678 if (__glibc_unlikely (__builtin_add_overflow (bytes,
3679 pagesize - 1,
3680 &rounded_bytes)))
3682 __set_errno (ENOMEM);
3683 return 0;
3685 rounded_bytes = rounded_bytes & -(pagesize - 1);
3687 return _mid_memalign (pagesize, rounded_bytes, address);
3690 void *
3691 __libc_calloc (size_t n, size_t elem_size)
3693 mstate av;
3694 mchunkptr oldtop;
3695 INTERNAL_SIZE_T sz, oldtopsize;
3696 void *mem;
3697 unsigned long clearsize;
3698 unsigned long nclears;
3699 INTERNAL_SIZE_T *d;
3700 ptrdiff_t bytes;
3702 if (__glibc_unlikely (__builtin_mul_overflow (n, elem_size, &bytes)))
3704 __set_errno (ENOMEM);
3705 return NULL;
3708 sz = bytes;
3710 if (!__malloc_initialized)
3711 ptmalloc_init ();
3713 MAYBE_INIT_TCACHE ();
3715 if (SINGLE_THREAD_P)
3716 av = &main_arena;
3717 else
3718 arena_get (av, sz);
3720 if (av)
3722 /* Check if we hand out the top chunk, in which case there may be no
3723 need to clear. */
3724 #if MORECORE_CLEARS
3725 oldtop = top (av);
3726 oldtopsize = chunksize (top (av));
3727 # if MORECORE_CLEARS < 2
3728 /* Only newly allocated memory is guaranteed to be cleared. */
3729 if (av == &main_arena &&
3730 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3731 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3732 # endif
3733 if (av != &main_arena)
3735 heap_info *heap = heap_for_ptr (oldtop);
3736 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3737 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3739 #endif
3741 else
3743 /* No usable arenas. */
3744 oldtop = 0;
3745 oldtopsize = 0;
3747 mem = _int_malloc (av, sz);
3749 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3750 av == arena_for_chunk (mem2chunk (mem)));
3752 if (!SINGLE_THREAD_P)
3754 if (mem == 0 && av != NULL)
3756 LIBC_PROBE (memory_calloc_retry, 1, sz);
3757 av = arena_get_retry (av, sz);
3758 mem = _int_malloc (av, sz);
3761 if (av != NULL)
3762 __libc_lock_unlock (av->mutex);
3765 /* Allocation failed even after a retry. */
3766 if (mem == 0)
3767 return 0;
3769 mchunkptr p = mem2chunk (mem);
3771 /* If we are using memory tagging, then we need to set the tags
3772 regardless of MORECORE_CLEARS, so we zero the whole block while
3773 doing so. */
3774 if (__glibc_unlikely (mtag_enabled))
3775 return tag_new_zero_region (mem, memsize (p));
3777 INTERNAL_SIZE_T csz = chunksize (p);
3779 /* Two optional cases in which clearing not necessary */
3780 if (chunk_is_mmapped (p))
3782 if (__builtin_expect (perturb_byte, 0))
3783 return memset (mem, 0, sz);
3785 return mem;
3788 #if MORECORE_CLEARS
3789 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3791 /* clear only the bytes from non-freshly-sbrked memory */
3792 csz = oldtopsize;
3794 #endif
3796 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3797 contents have an odd number of INTERNAL_SIZE_T-sized words;
3798 minimally 3. */
3799 d = (INTERNAL_SIZE_T *) mem;
3800 clearsize = csz - SIZE_SZ;
3801 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3802 assert (nclears >= 3);
3804 if (nclears > 9)
3805 return memset (d, 0, clearsize);
3807 else
3809 *(d + 0) = 0;
3810 *(d + 1) = 0;
3811 *(d + 2) = 0;
3812 if (nclears > 4)
3814 *(d + 3) = 0;
3815 *(d + 4) = 0;
3816 if (nclears > 6)
3818 *(d + 5) = 0;
3819 *(d + 6) = 0;
3820 if (nclears > 8)
3822 *(d + 7) = 0;
3823 *(d + 8) = 0;
3829 return mem;
3831 #endif /* IS_IN (libc) */
3834 ------------------------------ malloc ------------------------------
3837 static void *
3838 _int_malloc (mstate av, size_t bytes)
3840 INTERNAL_SIZE_T nb; /* normalized request size */
3841 unsigned int idx; /* associated bin index */
3842 mbinptr bin; /* associated bin */
3844 mchunkptr victim; /* inspected/selected chunk */
3845 INTERNAL_SIZE_T size; /* its size */
3846 int victim_index; /* its bin index */
3848 mchunkptr remainder; /* remainder from a split */
3849 unsigned long remainder_size; /* its size */
3851 unsigned int block; /* bit map traverser */
3852 unsigned int bit; /* bit map traverser */
3853 unsigned int map; /* current word of binmap */
3855 mchunkptr fwd; /* misc temp for linking */
3856 mchunkptr bck; /* misc temp for linking */
3858 #if USE_TCACHE
3859 size_t tcache_unsorted_count; /* count of unsorted chunks processed */
3860 #endif
3863 Convert request size to internal form by adding SIZE_SZ bytes
3864 overhead plus possibly more to obtain necessary alignment and/or
3865 to obtain a size of at least MINSIZE, the smallest allocatable
3866 size. Also, checked_request2size returns false for request sizes
3867 that are so large that they wrap around zero when padded and
3868 aligned.
3871 nb = checked_request2size (bytes);
3872 if (nb == 0)
3874 __set_errno (ENOMEM);
3875 return NULL;
3878 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3879 mmap. */
3880 if (__glibc_unlikely (av == NULL))
3882 void *p = sysmalloc (nb, av);
3883 if (p != NULL)
3884 alloc_perturb (p, bytes);
3885 return p;
3889 If the size qualifies as a fastbin, first check corresponding bin.
3890 This code is safe to execute even if av is not yet initialized, so we
3891 can try it without checking, which saves some time on this fast path.
3894 #define REMOVE_FB(fb, victim, pp) \
3895 do \
3897 victim = pp; \
3898 if (victim == NULL) \
3899 break; \
3900 pp = REVEAL_PTR (victim->fd); \
3901 if (__glibc_unlikely (pp != NULL && misaligned_chunk (pp))) \
3902 malloc_printerr ("malloc(): unaligned fastbin chunk detected"); \
3904 while ((pp = catomic_compare_and_exchange_val_acq (fb, pp, victim)) \
3905 != victim); \
3907 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3909 idx = fastbin_index (nb);
3910 mfastbinptr *fb = &fastbin (av, idx);
3911 mchunkptr pp;
3912 victim = *fb;
3914 if (victim != NULL)
3916 if (__glibc_unlikely (misaligned_chunk (victim)))
3917 malloc_printerr ("malloc(): unaligned fastbin chunk detected 2");
3919 if (SINGLE_THREAD_P)
3920 *fb = REVEAL_PTR (victim->fd);
3921 else
3922 REMOVE_FB (fb, pp, victim);
3923 if (__glibc_likely (victim != NULL))
3925 size_t victim_idx = fastbin_index (chunksize (victim));
3926 if (__builtin_expect (victim_idx != idx, 0))
3927 malloc_printerr ("malloc(): memory corruption (fast)");
3928 check_remalloced_chunk (av, victim, nb);
3929 #if USE_TCACHE
3930 /* While we're here, if we see other chunks of the same size,
3931 stash them in the tcache. */
3932 size_t tc_idx = csize2tidx (nb);
3933 if (tcache != NULL && tc_idx < mp_.tcache_bins)
3935 mchunkptr tc_victim;
3937 /* While bin not empty and tcache not full, copy chunks. */
3938 while (tcache->counts[tc_idx] < mp_.tcache_count
3939 && (tc_victim = *fb) != NULL)
3941 if (__glibc_unlikely (misaligned_chunk (tc_victim)))
3942 malloc_printerr ("malloc(): unaligned fastbin chunk detected 3");
3943 if (SINGLE_THREAD_P)
3944 *fb = REVEAL_PTR (tc_victim->fd);
3945 else
3947 REMOVE_FB (fb, pp, tc_victim);
3948 if (__glibc_unlikely (tc_victim == NULL))
3949 break;
3951 tcache_put (tc_victim, tc_idx);
3954 #endif
3955 void *p = chunk2mem (victim);
3956 alloc_perturb (p, bytes);
3957 return p;
3963 If a small request, check regular bin. Since these "smallbins"
3964 hold one size each, no searching within bins is necessary.
3965 (For a large request, we need to wait until unsorted chunks are
3966 processed to find best fit. But for small ones, fits are exact
3967 anyway, so we can check now, which is faster.)
3970 if (in_smallbin_range (nb))
3972 idx = smallbin_index (nb);
3973 bin = bin_at (av, idx);
3975 if ((victim = last (bin)) != bin)
3977 bck = victim->bk;
3978 if (__glibc_unlikely (bck->fd != victim))
3979 malloc_printerr ("malloc(): smallbin double linked list corrupted");
3980 set_inuse_bit_at_offset (victim, nb);
3981 bin->bk = bck;
3982 bck->fd = bin;
3984 if (av != &main_arena)
3985 set_non_main_arena (victim);
3986 check_malloced_chunk (av, victim, nb);
3987 #if USE_TCACHE
3988 /* While we're here, if we see other chunks of the same size,
3989 stash them in the tcache. */
3990 size_t tc_idx = csize2tidx (nb);
3991 if (tcache != NULL && tc_idx < mp_.tcache_bins)
3993 mchunkptr tc_victim;
3995 /* While bin not empty and tcache not full, copy chunks over. */
3996 while (tcache->counts[tc_idx] < mp_.tcache_count
3997 && (tc_victim = last (bin)) != bin)
3999 if (tc_victim != 0)
4001 bck = tc_victim->bk;
4002 set_inuse_bit_at_offset (tc_victim, nb);
4003 if (av != &main_arena)
4004 set_non_main_arena (tc_victim);
4005 bin->bk = bck;
4006 bck->fd = bin;
4008 tcache_put (tc_victim, tc_idx);
4012 #endif
4013 void *p = chunk2mem (victim);
4014 alloc_perturb (p, bytes);
4015 return p;
4020 If this is a large request, consolidate fastbins before continuing.
4021 While it might look excessive to kill all fastbins before
4022 even seeing if there is space available, this avoids
4023 fragmentation problems normally associated with fastbins.
4024 Also, in practice, programs tend to have runs of either small or
4025 large requests, but less often mixtures, so consolidation is not
4026 invoked all that often in most programs. And the programs that
4027 it is called frequently in otherwise tend to fragment.
4030 else
4032 idx = largebin_index (nb);
4033 if (atomic_load_relaxed (&av->have_fastchunks))
4034 malloc_consolidate (av);
4038 Process recently freed or remaindered chunks, taking one only if
4039 it is exact fit, or, if this a small request, the chunk is remainder from
4040 the most recent non-exact fit. Place other traversed chunks in
4041 bins. Note that this step is the only place in any routine where
4042 chunks are placed in bins.
4044 The outer loop here is needed because we might not realize until
4045 near the end of malloc that we should have consolidated, so must
4046 do so and retry. This happens at most once, and only when we would
4047 otherwise need to expand memory to service a "small" request.
4050 #if USE_TCACHE
4051 INTERNAL_SIZE_T tcache_nb = 0;
4052 size_t tc_idx = csize2tidx (nb);
4053 if (tcache != NULL && tc_idx < mp_.tcache_bins)
4054 tcache_nb = nb;
4055 int return_cached = 0;
4057 tcache_unsorted_count = 0;
4058 #endif
4060 for (;; )
4062 int iters = 0;
4063 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
4065 bck = victim->bk;
4066 size = chunksize (victim);
4067 mchunkptr next = chunk_at_offset (victim, size);
4069 if (__glibc_unlikely (size <= CHUNK_HDR_SZ)
4070 || __glibc_unlikely (size > av->system_mem))
4071 malloc_printerr ("malloc(): invalid size (unsorted)");
4072 if (__glibc_unlikely (chunksize_nomask (next) < CHUNK_HDR_SZ)
4073 || __glibc_unlikely (chunksize_nomask (next) > av->system_mem))
4074 malloc_printerr ("malloc(): invalid next size (unsorted)");
4075 if (__glibc_unlikely ((prev_size (next) & ~(SIZE_BITS)) != size))
4076 malloc_printerr ("malloc(): mismatching next->prev_size (unsorted)");
4077 if (__glibc_unlikely (bck->fd != victim)
4078 || __glibc_unlikely (victim->fd != unsorted_chunks (av)))
4079 malloc_printerr ("malloc(): unsorted double linked list corrupted");
4080 if (__glibc_unlikely (prev_inuse (next)))
4081 malloc_printerr ("malloc(): invalid next->prev_inuse (unsorted)");
4084 If a small request, try to use last remainder if it is the
4085 only chunk in unsorted bin. This helps promote locality for
4086 runs of consecutive small requests. This is the only
4087 exception to best-fit, and applies only when there is
4088 no exact fit for a small chunk.
4091 if (in_smallbin_range (nb) &&
4092 bck == unsorted_chunks (av) &&
4093 victim == av->last_remainder &&
4094 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4096 /* split and reattach remainder */
4097 remainder_size = size - nb;
4098 remainder = chunk_at_offset (victim, nb);
4099 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
4100 av->last_remainder = remainder;
4101 remainder->bk = remainder->fd = unsorted_chunks (av);
4102 if (!in_smallbin_range (remainder_size))
4104 remainder->fd_nextsize = NULL;
4105 remainder->bk_nextsize = NULL;
4108 set_head (victim, nb | PREV_INUSE |
4109 (av != &main_arena ? NON_MAIN_ARENA : 0));
4110 set_head (remainder, remainder_size | PREV_INUSE);
4111 set_foot (remainder, remainder_size);
4113 check_malloced_chunk (av, victim, nb);
4114 void *p = chunk2mem (victim);
4115 alloc_perturb (p, bytes);
4116 return p;
4119 /* remove from unsorted list */
4120 unsorted_chunks (av)->bk = bck;
4121 bck->fd = unsorted_chunks (av);
4123 /* Take now instead of binning if exact fit */
4125 if (size == nb)
4127 set_inuse_bit_at_offset (victim, size);
4128 if (av != &main_arena)
4129 set_non_main_arena (victim);
4130 #if USE_TCACHE
4131 /* Fill cache first, return to user only if cache fills.
4132 We may return one of these chunks later. */
4133 if (tcache_nb > 0
4134 && tcache->counts[tc_idx] < mp_.tcache_count)
4136 tcache_put (victim, tc_idx);
4137 return_cached = 1;
4138 continue;
4140 else
4142 #endif
4143 check_malloced_chunk (av, victim, nb);
4144 void *p = chunk2mem (victim);
4145 alloc_perturb (p, bytes);
4146 return p;
4147 #if USE_TCACHE
4149 #endif
4152 /* place chunk in bin */
4154 if (in_smallbin_range (size))
4156 victim_index = smallbin_index (size);
4157 bck = bin_at (av, victim_index);
4158 fwd = bck->fd;
4160 else
4162 victim_index = largebin_index (size);
4163 bck = bin_at (av, victim_index);
4164 fwd = bck->fd;
4166 /* maintain large bins in sorted order */
4167 if (fwd != bck)
4169 /* Or with inuse bit to speed comparisons */
4170 size |= PREV_INUSE;
4171 /* if smaller than smallest, bypass loop below */
4172 assert (chunk_main_arena (bck->bk));
4173 if ((unsigned long) (size)
4174 < (unsigned long) chunksize_nomask (bck->bk))
4176 fwd = bck;
4177 bck = bck->bk;
4179 victim->fd_nextsize = fwd->fd;
4180 victim->bk_nextsize = fwd->fd->bk_nextsize;
4181 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
4183 else
4185 assert (chunk_main_arena (fwd));
4186 while ((unsigned long) size < chunksize_nomask (fwd))
4188 fwd = fwd->fd_nextsize;
4189 assert (chunk_main_arena (fwd));
4192 if ((unsigned long) size
4193 == (unsigned long) chunksize_nomask (fwd))
4194 /* Always insert in the second position. */
4195 fwd = fwd->fd;
4196 else
4198 victim->fd_nextsize = fwd;
4199 victim->bk_nextsize = fwd->bk_nextsize;
4200 if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd))
4201 malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)");
4202 fwd->bk_nextsize = victim;
4203 victim->bk_nextsize->fd_nextsize = victim;
4205 bck = fwd->bk;
4206 if (bck->fd != fwd)
4207 malloc_printerr ("malloc(): largebin double linked list corrupted (bk)");
4210 else
4211 victim->fd_nextsize = victim->bk_nextsize = victim;
4214 mark_bin (av, victim_index);
4215 victim->bk = bck;
4216 victim->fd = fwd;
4217 fwd->bk = victim;
4218 bck->fd = victim;
4220 #if USE_TCACHE
4221 /* If we've processed as many chunks as we're allowed while
4222 filling the cache, return one of the cached ones. */
4223 ++tcache_unsorted_count;
4224 if (return_cached
4225 && mp_.tcache_unsorted_limit > 0
4226 && tcache_unsorted_count > mp_.tcache_unsorted_limit)
4228 return tcache_get (tc_idx);
4230 #endif
4232 #define MAX_ITERS 10000
4233 if (++iters >= MAX_ITERS)
4234 break;
4237 #if USE_TCACHE
4238 /* If all the small chunks we found ended up cached, return one now. */
4239 if (return_cached)
4241 return tcache_get (tc_idx);
4243 #endif
4246 If a large request, scan through the chunks of current bin in
4247 sorted order to find smallest that fits. Use the skip list for this.
4250 if (!in_smallbin_range (nb))
4252 bin = bin_at (av, idx);
4254 /* skip scan if empty or largest chunk is too small */
4255 if ((victim = first (bin)) != bin
4256 && (unsigned long) chunksize_nomask (victim)
4257 >= (unsigned long) (nb))
4259 victim = victim->bk_nextsize;
4260 while (((unsigned long) (size = chunksize (victim)) <
4261 (unsigned long) (nb)))
4262 victim = victim->bk_nextsize;
4264 /* Avoid removing the first entry for a size so that the skip
4265 list does not have to be rerouted. */
4266 if (victim != last (bin)
4267 && chunksize_nomask (victim)
4268 == chunksize_nomask (victim->fd))
4269 victim = victim->fd;
4271 remainder_size = size - nb;
4272 unlink_chunk (av, victim);
4274 /* Exhaust */
4275 if (remainder_size < MINSIZE)
4277 set_inuse_bit_at_offset (victim, size);
4278 if (av != &main_arena)
4279 set_non_main_arena (victim);
4281 /* Split */
4282 else
4284 remainder = chunk_at_offset (victim, nb);
4285 /* We cannot assume the unsorted list is empty and therefore
4286 have to perform a complete insert here. */
4287 bck = unsorted_chunks (av);
4288 fwd = bck->fd;
4289 if (__glibc_unlikely (fwd->bk != bck))
4290 malloc_printerr ("malloc(): corrupted unsorted chunks");
4291 remainder->bk = bck;
4292 remainder->fd = fwd;
4293 bck->fd = remainder;
4294 fwd->bk = remainder;
4295 if (!in_smallbin_range (remainder_size))
4297 remainder->fd_nextsize = NULL;
4298 remainder->bk_nextsize = NULL;
4300 set_head (victim, nb | PREV_INUSE |
4301 (av != &main_arena ? NON_MAIN_ARENA : 0));
4302 set_head (remainder, remainder_size | PREV_INUSE);
4303 set_foot (remainder, remainder_size);
4305 check_malloced_chunk (av, victim, nb);
4306 void *p = chunk2mem (victim);
4307 alloc_perturb (p, bytes);
4308 return p;
4313 Search for a chunk by scanning bins, starting with next largest
4314 bin. This search is strictly by best-fit; i.e., the smallest
4315 (with ties going to approximately the least recently used) chunk
4316 that fits is selected.
4318 The bitmap avoids needing to check that most blocks are nonempty.
4319 The particular case of skipping all bins during warm-up phases
4320 when no chunks have been returned yet is faster than it might look.
4323 ++idx;
4324 bin = bin_at (av, idx);
4325 block = idx2block (idx);
4326 map = av->binmap[block];
4327 bit = idx2bit (idx);
4329 for (;; )
4331 /* Skip rest of block if there are no more set bits in this block. */
4332 if (bit > map || bit == 0)
4336 if (++block >= BINMAPSIZE) /* out of bins */
4337 goto use_top;
4339 while ((map = av->binmap[block]) == 0);
4341 bin = bin_at (av, (block << BINMAPSHIFT));
4342 bit = 1;
4345 /* Advance to bin with set bit. There must be one. */
4346 while ((bit & map) == 0)
4348 bin = next_bin (bin);
4349 bit <<= 1;
4350 assert (bit != 0);
4353 /* Inspect the bin. It is likely to be non-empty */
4354 victim = last (bin);
4356 /* If a false alarm (empty bin), clear the bit. */
4357 if (victim == bin)
4359 av->binmap[block] = map &= ~bit; /* Write through */
4360 bin = next_bin (bin);
4361 bit <<= 1;
4364 else
4366 size = chunksize (victim);
4368 /* We know the first chunk in this bin is big enough to use. */
4369 assert ((unsigned long) (size) >= (unsigned long) (nb));
4371 remainder_size = size - nb;
4373 /* unlink */
4374 unlink_chunk (av, victim);
4376 /* Exhaust */
4377 if (remainder_size < MINSIZE)
4379 set_inuse_bit_at_offset (victim, size);
4380 if (av != &main_arena)
4381 set_non_main_arena (victim);
4384 /* Split */
4385 else
4387 remainder = chunk_at_offset (victim, nb);
4389 /* We cannot assume the unsorted list is empty and therefore
4390 have to perform a complete insert here. */
4391 bck = unsorted_chunks (av);
4392 fwd = bck->fd;
4393 if (__glibc_unlikely (fwd->bk != bck))
4394 malloc_printerr ("malloc(): corrupted unsorted chunks 2");
4395 remainder->bk = bck;
4396 remainder->fd = fwd;
4397 bck->fd = remainder;
4398 fwd->bk = remainder;
4400 /* advertise as last remainder */
4401 if (in_smallbin_range (nb))
4402 av->last_remainder = remainder;
4403 if (!in_smallbin_range (remainder_size))
4405 remainder->fd_nextsize = NULL;
4406 remainder->bk_nextsize = NULL;
4408 set_head (victim, nb | PREV_INUSE |
4409 (av != &main_arena ? NON_MAIN_ARENA : 0));
4410 set_head (remainder, remainder_size | PREV_INUSE);
4411 set_foot (remainder, remainder_size);
4413 check_malloced_chunk (av, victim, nb);
4414 void *p = chunk2mem (victim);
4415 alloc_perturb (p, bytes);
4416 return p;
4420 use_top:
4422 If large enough, split off the chunk bordering the end of memory
4423 (held in av->top). Note that this is in accord with the best-fit
4424 search rule. In effect, av->top is treated as larger (and thus
4425 less well fitting) than any other available chunk since it can
4426 be extended to be as large as necessary (up to system
4427 limitations).
4429 We require that av->top always exists (i.e., has size >=
4430 MINSIZE) after initialization, so if it would otherwise be
4431 exhausted by current request, it is replenished. (The main
4432 reason for ensuring it exists is that we may need MINSIZE space
4433 to put in fenceposts in sysmalloc.)
4436 victim = av->top;
4437 size = chunksize (victim);
4439 if (__glibc_unlikely (size > av->system_mem))
4440 malloc_printerr ("malloc(): corrupted top size");
4442 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
4444 remainder_size = size - nb;
4445 remainder = chunk_at_offset (victim, nb);
4446 av->top = remainder;
4447 set_head (victim, nb | PREV_INUSE |
4448 (av != &main_arena ? NON_MAIN_ARENA : 0));
4449 set_head (remainder, remainder_size | PREV_INUSE);
4451 check_malloced_chunk (av, victim, nb);
4452 void *p = chunk2mem (victim);
4453 alloc_perturb (p, bytes);
4454 return p;
4457 /* When we are using atomic ops to free fast chunks we can get
4458 here for all block sizes. */
4459 else if (atomic_load_relaxed (&av->have_fastchunks))
4461 malloc_consolidate (av);
4462 /* restore original bin index */
4463 if (in_smallbin_range (nb))
4464 idx = smallbin_index (nb);
4465 else
4466 idx = largebin_index (nb);
4470 Otherwise, relay to handle system-dependent cases
4472 else
4474 void *p = sysmalloc (nb, av);
4475 if (p != NULL)
4476 alloc_perturb (p, bytes);
4477 return p;
4483 ------------------------------ free ------------------------------
4486 static void
4487 _int_free (mstate av, mchunkptr p, int have_lock)
4489 INTERNAL_SIZE_T size; /* its size */
4490 mfastbinptr *fb; /* associated fastbin */
4492 size = chunksize (p);
4494 /* Little security check which won't hurt performance: the
4495 allocator never wraps around at the end of the address space.
4496 Therefore we can exclude some size values which might appear
4497 here by accident or by "design" from some intruder. */
4498 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
4499 || __builtin_expect (misaligned_chunk (p), 0))
4500 malloc_printerr ("free(): invalid pointer");
4501 /* We know that each chunk is at least MINSIZE bytes in size or a
4502 multiple of MALLOC_ALIGNMENT. */
4503 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
4504 malloc_printerr ("free(): invalid size");
4506 check_inuse_chunk(av, p);
4508 #if USE_TCACHE
4510 size_t tc_idx = csize2tidx (size);
4511 if (tcache != NULL && tc_idx < mp_.tcache_bins)
4513 /* Check to see if it's already in the tcache. */
4514 tcache_entry *e = (tcache_entry *) chunk2mem (p);
4516 /* This test succeeds on double free. However, we don't 100%
4517 trust it (it also matches random payload data at a 1 in
4518 2^<size_t> chance), so verify it's not an unlikely
4519 coincidence before aborting. */
4520 if (__glibc_unlikely (e->key == tcache_key))
4522 tcache_entry *tmp;
4523 size_t cnt = 0;
4524 LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
4525 for (tmp = tcache->entries[tc_idx];
4526 tmp;
4527 tmp = REVEAL_PTR (tmp->next), ++cnt)
4529 if (cnt >= mp_.tcache_count)
4530 malloc_printerr ("free(): too many chunks detected in tcache");
4531 if (__glibc_unlikely (!aligned_OK (tmp)))
4532 malloc_printerr ("free(): unaligned chunk detected in tcache 2");
4533 if (tmp == e)
4534 malloc_printerr ("free(): double free detected in tcache 2");
4535 /* If we get here, it was a coincidence. We've wasted a
4536 few cycles, but don't abort. */
4540 if (tcache->counts[tc_idx] < mp_.tcache_count)
4542 tcache_put (p, tc_idx);
4543 return;
4547 #endif
4550 If eligible, place chunk on a fastbin so it can be found
4551 and used quickly in malloc.
4554 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
4556 #if TRIM_FASTBINS
4558 If TRIM_FASTBINS set, don't place chunks
4559 bordering top into fastbins
4561 && (chunk_at_offset(p, size) != av->top)
4562 #endif
4565 if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
4566 <= CHUNK_HDR_SZ, 0)
4567 || __builtin_expect (chunksize (chunk_at_offset (p, size))
4568 >= av->system_mem, 0))
4570 bool fail = true;
4571 /* We might not have a lock at this point and concurrent modifications
4572 of system_mem might result in a false positive. Redo the test after
4573 getting the lock. */
4574 if (!have_lock)
4576 __libc_lock_lock (av->mutex);
4577 fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ
4578 || chunksize (chunk_at_offset (p, size)) >= av->system_mem);
4579 __libc_lock_unlock (av->mutex);
4582 if (fail)
4583 malloc_printerr ("free(): invalid next size (fast)");
4586 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4588 atomic_store_relaxed (&av->have_fastchunks, true);
4589 unsigned int idx = fastbin_index(size);
4590 fb = &fastbin (av, idx);
4592 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
4593 mchunkptr old = *fb, old2;
4595 if (SINGLE_THREAD_P)
4597 /* Check that the top of the bin is not the record we are going to
4598 add (i.e., double free). */
4599 if (__builtin_expect (old == p, 0))
4600 malloc_printerr ("double free or corruption (fasttop)");
4601 p->fd = PROTECT_PTR (&p->fd, old);
4602 *fb = p;
4604 else
4607 /* Check that the top of the bin is not the record we are going to
4608 add (i.e., double free). */
4609 if (__builtin_expect (old == p, 0))
4610 malloc_printerr ("double free or corruption (fasttop)");
4611 old2 = old;
4612 p->fd = PROTECT_PTR (&p->fd, old);
4614 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2))
4615 != old2);
4617 /* Check that size of fastbin chunk at the top is the same as
4618 size of the chunk that we are adding. We can dereference OLD
4619 only if we have the lock, otherwise it might have already been
4620 allocated again. */
4621 if (have_lock && old != NULL
4622 && __builtin_expect (fastbin_index (chunksize (old)) != idx, 0))
4623 malloc_printerr ("invalid fastbin entry (free)");
4627 Consolidate other non-mmapped chunks as they arrive.
4630 else if (!chunk_is_mmapped(p)) {
4632 /* If we're single-threaded, don't lock the arena. */
4633 if (SINGLE_THREAD_P)
4634 have_lock = true;
4636 if (!have_lock)
4637 __libc_lock_lock (av->mutex);
4639 _int_free_merge_chunk (av, p, size);
4641 if (!have_lock)
4642 __libc_lock_unlock (av->mutex);
4645 If the chunk was allocated via mmap, release via munmap().
4648 else {
4649 munmap_chunk (p);
4653 /* Try to merge chunk P of SIZE bytes with its neighbors. Put the
4654 resulting chunk on the appropriate bin list. P must not be on a
4655 bin list yet, and it can be in use. */
4656 static void
4657 _int_free_merge_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T size)
4659 mchunkptr nextchunk = chunk_at_offset(p, size);
4661 /* Lightweight tests: check whether the block is already the
4662 top block. */
4663 if (__glibc_unlikely (p == av->top))
4664 malloc_printerr ("double free or corruption (top)");
4665 /* Or whether the next chunk is beyond the boundaries of the arena. */
4666 if (__builtin_expect (contiguous (av)
4667 && (char *) nextchunk
4668 >= ((char *) av->top + chunksize(av->top)), 0))
4669 malloc_printerr ("double free or corruption (out)");
4670 /* Or whether the block is actually not marked used. */
4671 if (__glibc_unlikely (!prev_inuse(nextchunk)))
4672 malloc_printerr ("double free or corruption (!prev)");
4674 INTERNAL_SIZE_T nextsize = chunksize(nextchunk);
4675 if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0)
4676 || __builtin_expect (nextsize >= av->system_mem, 0))
4677 malloc_printerr ("free(): invalid next size (normal)");
4679 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4681 /* Consolidate backward. */
4682 if (!prev_inuse(p))
4684 INTERNAL_SIZE_T prevsize = prev_size (p);
4685 size += prevsize;
4686 p = chunk_at_offset(p, -((long) prevsize));
4687 if (__glibc_unlikely (chunksize(p) != prevsize))
4688 malloc_printerr ("corrupted size vs. prev_size while consolidating");
4689 unlink_chunk (av, p);
4692 /* Write the chunk header, maybe after merging with the following chunk. */
4693 size = _int_free_create_chunk (av, p, size, nextchunk, nextsize);
4694 _int_free_maybe_consolidate (av, size);
4697 /* Create a chunk at P of SIZE bytes, with SIZE potentially increased
4698 to cover the immediately following chunk NEXTCHUNK of NEXTSIZE
4699 bytes (if NEXTCHUNK is unused). The chunk at P is not actually
4700 read and does not have to be initialized. After creation, it is
4701 placed on the appropriate bin list. The function returns the size
4702 of the new chunk. */
4703 static INTERNAL_SIZE_T
4704 _int_free_create_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T size,
4705 mchunkptr nextchunk, INTERNAL_SIZE_T nextsize)
4707 if (nextchunk != av->top)
4709 /* get and clear inuse bit */
4710 bool nextinuse = inuse_bit_at_offset (nextchunk, nextsize);
4712 /* consolidate forward */
4713 if (!nextinuse) {
4714 unlink_chunk (av, nextchunk);
4715 size += nextsize;
4716 } else
4717 clear_inuse_bit_at_offset(nextchunk, 0);
4720 Place the chunk in unsorted chunk list. Chunks are
4721 not placed into regular bins until after they have
4722 been given one chance to be used in malloc.
4725 mchunkptr bck = unsorted_chunks (av);
4726 mchunkptr fwd = bck->fd;
4727 if (__glibc_unlikely (fwd->bk != bck))
4728 malloc_printerr ("free(): corrupted unsorted chunks");
4729 p->fd = fwd;
4730 p->bk = bck;
4731 if (!in_smallbin_range(size))
4733 p->fd_nextsize = NULL;
4734 p->bk_nextsize = NULL;
4736 bck->fd = p;
4737 fwd->bk = p;
4739 set_head(p, size | PREV_INUSE);
4740 set_foot(p, size);
4742 check_free_chunk(av, p);
4745 else
4747 /* If the chunk borders the current high end of memory,
4748 consolidate into top. */
4749 size += nextsize;
4750 set_head(p, size | PREV_INUSE);
4751 av->top = p;
4752 check_chunk(av, p);
4755 return size;
4758 /* If freeing a large space, consolidate possibly-surrounding
4759 chunks. Then, if the total unused topmost memory exceeds trim
4760 threshold, ask malloc_trim to reduce top. */
4761 static void
4762 _int_free_maybe_consolidate (mstate av, INTERNAL_SIZE_T size)
4764 /* Unless max_fast is 0, we don't know if there are fastbins
4765 bordering top, so we cannot tell for sure whether threshold has
4766 been reached unless fastbins are consolidated. But we don't want
4767 to consolidate on each free. As a compromise, consolidation is
4768 performed if FASTBIN_CONSOLIDATION_THRESHOLD is reached. */
4769 if (size >= FASTBIN_CONSOLIDATION_THRESHOLD)
4771 if (atomic_load_relaxed (&av->have_fastchunks))
4772 malloc_consolidate(av);
4774 if (av == &main_arena)
4776 #ifndef MORECORE_CANNOT_TRIM
4777 if (chunksize (av->top) >= mp_.trim_threshold)
4778 systrim (mp_.top_pad, av);
4779 #endif
4781 else
4783 /* Always try heap_trim, even if the top chunk is not large,
4784 because the corresponding heap might go away. */
4785 heap_info *heap = heap_for_ptr (top (av));
4787 assert (heap->ar_ptr == av);
4788 heap_trim (heap, mp_.top_pad);
4794 ------------------------- malloc_consolidate -------------------------
4796 malloc_consolidate is a specialized version of free() that tears
4797 down chunks held in fastbins. Free itself cannot be used for this
4798 purpose since, among other things, it might place chunks back onto
4799 fastbins. So, instead, we need to use a minor variant of the same
4800 code.
4803 static void malloc_consolidate(mstate av)
4805 mfastbinptr* fb; /* current fastbin being consolidated */
4806 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4807 mchunkptr p; /* current chunk being consolidated */
4808 mchunkptr nextp; /* next chunk to consolidate */
4809 mchunkptr unsorted_bin; /* bin header */
4810 mchunkptr first_unsorted; /* chunk to link to */
4812 /* These have same use as in free() */
4813 mchunkptr nextchunk;
4814 INTERNAL_SIZE_T size;
4815 INTERNAL_SIZE_T nextsize;
4816 INTERNAL_SIZE_T prevsize;
4817 int nextinuse;
4819 atomic_store_relaxed (&av->have_fastchunks, false);
4821 unsorted_bin = unsorted_chunks(av);
4824 Remove each chunk from fast bin and consolidate it, placing it
4825 then in unsorted bin. Among other reasons for doing this,
4826 placing in unsorted bin avoids needing to calculate actual bins
4827 until malloc is sure that chunks aren't immediately going to be
4828 reused anyway.
4831 maxfb = &fastbin (av, NFASTBINS - 1);
4832 fb = &fastbin (av, 0);
4833 do {
4834 p = atomic_exchange_acquire (fb, NULL);
4835 if (p != 0) {
4836 do {
4838 if (__glibc_unlikely (misaligned_chunk (p)))
4839 malloc_printerr ("malloc_consolidate(): "
4840 "unaligned fastbin chunk detected");
4842 unsigned int idx = fastbin_index (chunksize (p));
4843 if ((&fastbin (av, idx)) != fb)
4844 malloc_printerr ("malloc_consolidate(): invalid chunk size");
4847 check_inuse_chunk(av, p);
4848 nextp = REVEAL_PTR (p->fd);
4850 /* Slightly streamlined version of consolidation code in free() */
4851 size = chunksize (p);
4852 nextchunk = chunk_at_offset(p, size);
4853 nextsize = chunksize(nextchunk);
4855 if (!prev_inuse(p)) {
4856 prevsize = prev_size (p);
4857 size += prevsize;
4858 p = chunk_at_offset(p, -((long) prevsize));
4859 if (__glibc_unlikely (chunksize(p) != prevsize))
4860 malloc_printerr ("corrupted size vs. prev_size in fastbins");
4861 unlink_chunk (av, p);
4864 if (nextchunk != av->top) {
4865 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4867 if (!nextinuse) {
4868 size += nextsize;
4869 unlink_chunk (av, nextchunk);
4870 } else
4871 clear_inuse_bit_at_offset(nextchunk, 0);
4873 first_unsorted = unsorted_bin->fd;
4874 unsorted_bin->fd = p;
4875 first_unsorted->bk = p;
4877 if (!in_smallbin_range (size)) {
4878 p->fd_nextsize = NULL;
4879 p->bk_nextsize = NULL;
4882 set_head(p, size | PREV_INUSE);
4883 p->bk = unsorted_bin;
4884 p->fd = first_unsorted;
4885 set_foot(p, size);
4888 else {
4889 size += nextsize;
4890 set_head(p, size | PREV_INUSE);
4891 av->top = p;
4894 } while ( (p = nextp) != 0);
4897 } while (fb++ != maxfb);
4901 ------------------------------ realloc ------------------------------
4904 static void *
4905 _int_realloc (mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4906 INTERNAL_SIZE_T nb)
4908 mchunkptr newp; /* chunk to return */
4909 INTERNAL_SIZE_T newsize; /* its size */
4910 void* newmem; /* corresponding user mem */
4912 mchunkptr next; /* next contiguous chunk after oldp */
4914 mchunkptr remainder; /* extra space at end of newp */
4915 unsigned long remainder_size; /* its size */
4917 /* oldmem size */
4918 if (__builtin_expect (chunksize_nomask (oldp) <= CHUNK_HDR_SZ, 0)
4919 || __builtin_expect (oldsize >= av->system_mem, 0)
4920 || __builtin_expect (oldsize != chunksize (oldp), 0))
4921 malloc_printerr ("realloc(): invalid old size");
4923 check_inuse_chunk (av, oldp);
4925 /* All callers already filter out mmap'ed chunks. */
4926 assert (!chunk_is_mmapped (oldp));
4928 next = chunk_at_offset (oldp, oldsize);
4929 INTERNAL_SIZE_T nextsize = chunksize (next);
4930 if (__builtin_expect (chunksize_nomask (next) <= CHUNK_HDR_SZ, 0)
4931 || __builtin_expect (nextsize >= av->system_mem, 0))
4932 malloc_printerr ("realloc(): invalid next size");
4934 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4936 /* already big enough; split below */
4937 newp = oldp;
4938 newsize = oldsize;
4941 else
4943 /* Try to expand forward into top */
4944 if (next == av->top &&
4945 (unsigned long) (newsize = oldsize + nextsize) >=
4946 (unsigned long) (nb + MINSIZE))
4948 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4949 av->top = chunk_at_offset (oldp, nb);
4950 set_head (av->top, (newsize - nb) | PREV_INUSE);
4951 check_inuse_chunk (av, oldp);
4952 return tag_new_usable (chunk2mem (oldp));
4955 /* Try to expand forward into next chunk; split off remainder below */
4956 else if (next != av->top &&
4957 !inuse (next) &&
4958 (unsigned long) (newsize = oldsize + nextsize) >=
4959 (unsigned long) (nb))
4961 newp = oldp;
4962 unlink_chunk (av, next);
4965 /* allocate, copy, free */
4966 else
4968 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4969 if (newmem == 0)
4970 return 0; /* propagate failure */
4972 newp = mem2chunk (newmem);
4973 newsize = chunksize (newp);
4976 Avoid copy if newp is next chunk after oldp.
4978 if (newp == next)
4980 newsize += oldsize;
4981 newp = oldp;
4983 else
4985 void *oldmem = chunk2mem (oldp);
4986 size_t sz = memsize (oldp);
4987 (void) tag_region (oldmem, sz);
4988 newmem = tag_new_usable (newmem);
4989 memcpy (newmem, oldmem, sz);
4990 _int_free (av, oldp, 1);
4991 check_inuse_chunk (av, newp);
4992 return newmem;
4997 /* If possible, free extra space in old or extended chunk */
4999 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
5001 remainder_size = newsize - nb;
5003 if (remainder_size < MINSIZE) /* not enough extra to split off */
5005 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
5006 set_inuse_bit_at_offset (newp, newsize);
5008 else /* split remainder */
5010 remainder = chunk_at_offset (newp, nb);
5011 /* Clear any user-space tags before writing the header. */
5012 remainder = tag_region (remainder, remainder_size);
5013 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
5014 set_head (remainder, remainder_size | PREV_INUSE |
5015 (av != &main_arena ? NON_MAIN_ARENA : 0));
5016 /* Mark remainder as inuse so free() won't complain */
5017 set_inuse_bit_at_offset (remainder, remainder_size);
5018 _int_free (av, remainder, 1);
5021 check_inuse_chunk (av, newp);
5022 return tag_new_usable (chunk2mem (newp));
5026 ------------------------------ memalign ------------------------------
5029 /* BYTES is user requested bytes, not requested chunksize bytes. */
5030 static void *
5031 _int_memalign (mstate av, size_t alignment, size_t bytes)
5033 INTERNAL_SIZE_T nb; /* padded request size */
5034 char *m; /* memory returned by malloc call */
5035 mchunkptr p; /* corresponding chunk */
5036 char *brk; /* alignment point within p */
5037 mchunkptr newp; /* chunk to return */
5038 INTERNAL_SIZE_T newsize; /* its size */
5039 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
5040 mchunkptr remainder; /* spare room at end to split off */
5041 unsigned long remainder_size; /* its size */
5042 INTERNAL_SIZE_T size;
5044 nb = checked_request2size (bytes);
5045 if (nb == 0)
5047 __set_errno (ENOMEM);
5048 return NULL;
5051 /* We can't check tcache here because we hold the arena lock, which
5052 tcache doesn't expect. We expect it has been checked
5053 earlier. */
5055 /* Strategy: search the bins looking for an existing block that
5056 meets our needs. We scan a range of bins from "exact size" to
5057 "just under 2x", spanning the small/large barrier if needed. If
5058 we don't find anything in those bins, the common malloc code will
5059 scan starting at 2x. */
5061 /* Call malloc with worst case padding to hit alignment. */
5062 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
5064 if (m == 0)
5065 return 0; /* propagate failure */
5067 p = mem2chunk (m);
5069 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
5071 /* Find an aligned spot inside chunk. Since we need to give back
5072 leading space in a chunk of at least MINSIZE, if the first
5073 calculation places us at a spot with less than MINSIZE leader,
5074 we can move to the next aligned spot -- we've allocated enough
5075 total room so that this is always possible. */
5076 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
5077 - ((signed long) alignment));
5078 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
5079 brk += alignment;
5081 newp = (mchunkptr) brk;
5082 leadsize = brk - (char *) (p);
5083 newsize = chunksize (p) - leadsize;
5085 /* For mmapped chunks, just adjust offset */
5086 if (chunk_is_mmapped (p))
5088 set_prev_size (newp, prev_size (p) + leadsize);
5089 set_head (newp, newsize | IS_MMAPPED);
5090 return chunk2mem (newp);
5093 /* Otherwise, give back leader, use the rest */
5094 set_head (newp, newsize | PREV_INUSE |
5095 (av != &main_arena ? NON_MAIN_ARENA : 0));
5096 set_inuse_bit_at_offset (newp, newsize);
5097 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
5098 _int_free_merge_chunk (av, p, leadsize);
5099 p = newp;
5101 assert (newsize >= nb &&
5102 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
5105 /* Also give back spare room at the end */
5106 if (!chunk_is_mmapped (p))
5108 size = chunksize (p);
5109 mchunkptr nextchunk = chunk_at_offset(p, size);
5110 INTERNAL_SIZE_T nextsize = chunksize(nextchunk);
5111 if (size > nb)
5113 remainder_size = size - nb;
5114 if (remainder_size >= MINSIZE
5115 || nextchunk == av->top
5116 || !inuse_bit_at_offset (nextchunk, nextsize))
5118 /* We can only give back the tail if it is larger than
5119 MINSIZE, or if the following chunk is unused (top
5120 chunk or unused in-heap chunk). Otherwise we would
5121 create a chunk that is smaller than MINSIZE. */
5122 remainder = chunk_at_offset (p, nb);
5123 set_head_size (p, nb);
5124 remainder_size = _int_free_create_chunk (av, remainder,
5125 remainder_size,
5126 nextchunk, nextsize);
5127 _int_free_maybe_consolidate (av, remainder_size);
5132 check_inuse_chunk (av, p);
5133 return chunk2mem (p);
5138 ------------------------------ malloc_trim ------------------------------
5141 static int
5142 mtrim (mstate av, size_t pad)
5144 /* Ensure all blocks are consolidated. */
5145 malloc_consolidate (av);
5147 const size_t ps = GLRO (dl_pagesize);
5148 int psindex = bin_index (ps);
5149 const size_t psm1 = ps - 1;
5151 int result = 0;
5152 for (int i = 1; i < NBINS; ++i)
5153 if (i == 1 || i >= psindex)
5155 mbinptr bin = bin_at (av, i);
5157 for (mchunkptr p = last (bin); p != bin; p = p->bk)
5159 INTERNAL_SIZE_T size = chunksize (p);
5161 if (size > psm1 + sizeof (struct malloc_chunk))
5163 /* See whether the chunk contains at least one unused page. */
5164 char *paligned_mem = (char *) (((uintptr_t) p
5165 + sizeof (struct malloc_chunk)
5166 + psm1) & ~psm1);
5168 assert ((char *) chunk2mem (p) + 2 * CHUNK_HDR_SZ
5169 <= paligned_mem);
5170 assert ((char *) p + size > paligned_mem);
5172 /* This is the size we could potentially free. */
5173 size -= paligned_mem - (char *) p;
5175 if (size > psm1)
5177 #if MALLOC_DEBUG
5178 /* When debugging we simulate destroying the memory
5179 content. */
5180 memset (paligned_mem, 0x89, size & ~psm1);
5181 #endif
5182 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
5184 result = 1;
5190 #ifndef MORECORE_CANNOT_TRIM
5191 return result | (av == &main_arena ? systrim (pad, av) : 0);
5193 #else
5194 return result;
5195 #endif
5200 __malloc_trim (size_t s)
5202 int result = 0;
5204 if (!__malloc_initialized)
5205 ptmalloc_init ();
5207 mstate ar_ptr = &main_arena;
5210 __libc_lock_lock (ar_ptr->mutex);
5211 result |= mtrim (ar_ptr, s);
5212 __libc_lock_unlock (ar_ptr->mutex);
5214 ar_ptr = ar_ptr->next;
5216 while (ar_ptr != &main_arena);
5218 return result;
5223 ------------------------- malloc_usable_size -------------------------
5226 static size_t
5227 musable (void *mem)
5229 mchunkptr p = mem2chunk (mem);
5231 if (chunk_is_mmapped (p))
5232 return chunksize (p) - CHUNK_HDR_SZ;
5233 else if (inuse (p))
5234 return memsize (p);
5236 return 0;
5239 #if IS_IN (libc)
5240 size_t
5241 __malloc_usable_size (void *m)
5243 if (m == NULL)
5244 return 0;
5245 return musable (m);
5247 #endif
5250 ------------------------------ mallinfo ------------------------------
5251 Accumulate malloc statistics for arena AV into M.
5253 static void
5254 int_mallinfo (mstate av, struct mallinfo2 *m)
5256 size_t i;
5257 mbinptr b;
5258 mchunkptr p;
5259 INTERNAL_SIZE_T avail;
5260 INTERNAL_SIZE_T fastavail;
5261 int nblocks;
5262 int nfastblocks;
5264 check_malloc_state (av);
5266 /* Account for top */
5267 avail = chunksize (av->top);
5268 nblocks = 1; /* top always exists */
5270 /* traverse fastbins */
5271 nfastblocks = 0;
5272 fastavail = 0;
5274 for (i = 0; i < NFASTBINS; ++i)
5276 for (p = fastbin (av, i);
5277 p != 0;
5278 p = REVEAL_PTR (p->fd))
5280 if (__glibc_unlikely (misaligned_chunk (p)))
5281 malloc_printerr ("int_mallinfo(): "
5282 "unaligned fastbin chunk detected");
5283 ++nfastblocks;
5284 fastavail += chunksize (p);
5288 avail += fastavail;
5290 /* traverse regular bins */
5291 for (i = 1; i < NBINS; ++i)
5293 b = bin_at (av, i);
5294 for (p = last (b); p != b; p = p->bk)
5296 ++nblocks;
5297 avail += chunksize (p);
5301 m->smblks += nfastblocks;
5302 m->ordblks += nblocks;
5303 m->fordblks += avail;
5304 m->uordblks += av->system_mem - avail;
5305 m->arena += av->system_mem;
5306 m->fsmblks += fastavail;
5307 if (av == &main_arena)
5309 m->hblks = mp_.n_mmaps;
5310 m->hblkhd = mp_.mmapped_mem;
5311 m->usmblks = 0;
5312 m->keepcost = chunksize (av->top);
5317 struct mallinfo2
5318 __libc_mallinfo2 (void)
5320 struct mallinfo2 m;
5321 mstate ar_ptr;
5323 if (!__malloc_initialized)
5324 ptmalloc_init ();
5326 memset (&m, 0, sizeof (m));
5327 ar_ptr = &main_arena;
5330 __libc_lock_lock (ar_ptr->mutex);
5331 int_mallinfo (ar_ptr, &m);
5332 __libc_lock_unlock (ar_ptr->mutex);
5334 ar_ptr = ar_ptr->next;
5336 while (ar_ptr != &main_arena);
5338 return m;
5340 libc_hidden_def (__libc_mallinfo2)
5342 struct mallinfo
5343 __libc_mallinfo (void)
5345 struct mallinfo m;
5346 struct mallinfo2 m2 = __libc_mallinfo2 ();
5348 m.arena = m2.arena;
5349 m.ordblks = m2.ordblks;
5350 m.smblks = m2.smblks;
5351 m.hblks = m2.hblks;
5352 m.hblkhd = m2.hblkhd;
5353 m.usmblks = m2.usmblks;
5354 m.fsmblks = m2.fsmblks;
5355 m.uordblks = m2.uordblks;
5356 m.fordblks = m2.fordblks;
5357 m.keepcost = m2.keepcost;
5359 return m;
5364 ------------------------------ malloc_stats ------------------------------
5367 void
5368 __malloc_stats (void)
5370 int i;
5371 mstate ar_ptr;
5372 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
5374 if (!__malloc_initialized)
5375 ptmalloc_init ();
5376 _IO_flockfile (stderr);
5377 int old_flags2 = stderr->_flags2;
5378 stderr->_flags2 |= _IO_FLAGS2_NOTCANCEL;
5379 for (i = 0, ar_ptr = &main_arena;; i++)
5381 struct mallinfo2 mi;
5383 memset (&mi, 0, sizeof (mi));
5384 __libc_lock_lock (ar_ptr->mutex);
5385 int_mallinfo (ar_ptr, &mi);
5386 fprintf (stderr, "Arena %d:\n", i);
5387 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
5388 fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
5389 #if MALLOC_DEBUG > 1
5390 if (i > 0)
5391 dump_heap (heap_for_ptr (top (ar_ptr)));
5392 #endif
5393 system_b += mi.arena;
5394 in_use_b += mi.uordblks;
5395 __libc_lock_unlock (ar_ptr->mutex);
5396 ar_ptr = ar_ptr->next;
5397 if (ar_ptr == &main_arena)
5398 break;
5400 fprintf (stderr, "Total (incl. mmap):\n");
5401 fprintf (stderr, "system bytes = %10u\n", system_b);
5402 fprintf (stderr, "in use bytes = %10u\n", in_use_b);
5403 fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
5404 fprintf (stderr, "max mmap bytes = %10lu\n",
5405 (unsigned long) mp_.max_mmapped_mem);
5406 stderr->_flags2 = old_flags2;
5407 _IO_funlockfile (stderr);
5412 ------------------------------ mallopt ------------------------------
5414 static __always_inline int
5415 do_set_trim_threshold (size_t value)
5417 LIBC_PROBE (memory_mallopt_trim_threshold, 3, value, mp_.trim_threshold,
5418 mp_.no_dyn_threshold);
5419 mp_.trim_threshold = value;
5420 mp_.no_dyn_threshold = 1;
5421 return 1;
5424 static __always_inline int
5425 do_set_top_pad (size_t value)
5427 LIBC_PROBE (memory_mallopt_top_pad, 3, value, mp_.top_pad,
5428 mp_.no_dyn_threshold);
5429 mp_.top_pad = value;
5430 mp_.no_dyn_threshold = 1;
5431 return 1;
5434 static __always_inline int
5435 do_set_mmap_threshold (size_t value)
5437 LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value, mp_.mmap_threshold,
5438 mp_.no_dyn_threshold);
5439 mp_.mmap_threshold = value;
5440 mp_.no_dyn_threshold = 1;
5441 return 1;
5444 static __always_inline int
5445 do_set_mmaps_max (int32_t value)
5447 LIBC_PROBE (memory_mallopt_mmap_max, 3, value, mp_.n_mmaps_max,
5448 mp_.no_dyn_threshold);
5449 mp_.n_mmaps_max = value;
5450 mp_.no_dyn_threshold = 1;
5451 return 1;
5454 static __always_inline int
5455 do_set_mallopt_check (int32_t value)
5457 return 1;
5460 static __always_inline int
5461 do_set_perturb_byte (int32_t value)
5463 LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
5464 perturb_byte = value;
5465 return 1;
5468 static __always_inline int
5469 do_set_arena_test (size_t value)
5471 LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
5472 mp_.arena_test = value;
5473 return 1;
5476 static __always_inline int
5477 do_set_arena_max (size_t value)
5479 LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
5480 mp_.arena_max = value;
5481 return 1;
5484 #if USE_TCACHE
5485 static __always_inline int
5486 do_set_tcache_max (size_t value)
5488 if (value <= MAX_TCACHE_SIZE)
5490 LIBC_PROBE (memory_tunable_tcache_max_bytes, 2, value, mp_.tcache_max_bytes);
5491 mp_.tcache_max_bytes = value;
5492 mp_.tcache_bins = csize2tidx (request2size(value)) + 1;
5493 return 1;
5495 return 0;
5498 static __always_inline int
5499 do_set_tcache_count (size_t value)
5501 if (value <= MAX_TCACHE_COUNT)
5503 LIBC_PROBE (memory_tunable_tcache_count, 2, value, mp_.tcache_count);
5504 mp_.tcache_count = value;
5505 return 1;
5507 return 0;
5510 static __always_inline int
5511 do_set_tcache_unsorted_limit (size_t value)
5513 LIBC_PROBE (memory_tunable_tcache_unsorted_limit, 2, value, mp_.tcache_unsorted_limit);
5514 mp_.tcache_unsorted_limit = value;
5515 return 1;
5517 #endif
5519 static __always_inline int
5520 do_set_mxfast (size_t value)
5522 if (value <= MAX_FAST_SIZE)
5524 LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
5525 set_max_fast (value);
5526 return 1;
5528 return 0;
5531 static __always_inline int
5532 do_set_hugetlb (size_t value)
5534 if (value == 1)
5536 enum malloc_thp_mode_t thp_mode = __malloc_thp_mode ();
5538 Only enable THP madvise usage if system does support it and
5539 has 'madvise' mode. Otherwise the madvise() call is wasteful.
5541 if (thp_mode == malloc_thp_mode_madvise)
5542 mp_.thp_pagesize = __malloc_default_thp_pagesize ();
5544 else if (value >= 2)
5545 __malloc_hugepage_config (value == 2 ? 0 : value, &mp_.hp_pagesize,
5546 &mp_.hp_flags);
5547 return 0;
5551 __libc_mallopt (int param_number, int value)
5553 mstate av = &main_arena;
5554 int res = 1;
5556 if (!__malloc_initialized)
5557 ptmalloc_init ();
5558 __libc_lock_lock (av->mutex);
5560 LIBC_PROBE (memory_mallopt, 2, param_number, value);
5562 /* We must consolidate main arena before changing max_fast
5563 (see definition of set_max_fast). */
5564 malloc_consolidate (av);
5566 /* Many of these helper functions take a size_t. We do not worry
5567 about overflow here, because negative int values will wrap to
5568 very large size_t values and the helpers have sufficient range
5569 checking for such conversions. Many of these helpers are also
5570 used by the tunables macros in arena.c. */
5572 switch (param_number)
5574 case M_MXFAST:
5575 res = do_set_mxfast (value);
5576 break;
5578 case M_TRIM_THRESHOLD:
5579 res = do_set_trim_threshold (value);
5580 break;
5582 case M_TOP_PAD:
5583 res = do_set_top_pad (value);
5584 break;
5586 case M_MMAP_THRESHOLD:
5587 res = do_set_mmap_threshold (value);
5588 break;
5590 case M_MMAP_MAX:
5591 res = do_set_mmaps_max (value);
5592 break;
5594 case M_CHECK_ACTION:
5595 res = do_set_mallopt_check (value);
5596 break;
5598 case M_PERTURB:
5599 res = do_set_perturb_byte (value);
5600 break;
5602 case M_ARENA_TEST:
5603 if (value > 0)
5604 res = do_set_arena_test (value);
5605 break;
5607 case M_ARENA_MAX:
5608 if (value > 0)
5609 res = do_set_arena_max (value);
5610 break;
5612 __libc_lock_unlock (av->mutex);
5613 return res;
5615 libc_hidden_def (__libc_mallopt)
5619 -------------------- Alternative MORECORE functions --------------------
5624 General Requirements for MORECORE.
5626 The MORECORE function must have the following properties:
5628 If MORECORE_CONTIGUOUS is false:
5630 * MORECORE must allocate in multiples of pagesize. It will
5631 only be called with arguments that are multiples of pagesize.
5633 * MORECORE(0) must return an address that is at least
5634 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
5636 else (i.e. If MORECORE_CONTIGUOUS is true):
5638 * Consecutive calls to MORECORE with positive arguments
5639 return increasing addresses, indicating that space has been
5640 contiguously extended.
5642 * MORECORE need not allocate in multiples of pagesize.
5643 Calls to MORECORE need not have args of multiples of pagesize.
5645 * MORECORE need not page-align.
5647 In either case:
5649 * MORECORE may allocate more memory than requested. (Or even less,
5650 but this will generally result in a malloc failure.)
5652 * MORECORE must not allocate memory when given argument zero, but
5653 instead return one past the end address of memory from previous
5654 nonzero call. This malloc does NOT call MORECORE(0)
5655 until at least one call with positive arguments is made, so
5656 the initial value returned is not important.
5658 * Even though consecutive calls to MORECORE need not return contiguous
5659 addresses, it must be OK for malloc'ed chunks to span multiple
5660 regions in those cases where they do happen to be contiguous.
5662 * MORECORE need not handle negative arguments -- it may instead
5663 just return MORECORE_FAILURE when given negative arguments.
5664 Negative arguments are always multiples of pagesize. MORECORE
5665 must not misinterpret negative args as large positive unsigned
5666 args. You can suppress all such calls from even occurring by defining
5667 MORECORE_CANNOT_TRIM,
5669 There is some variation across systems about the type of the
5670 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
5671 actually be size_t, because sbrk supports negative args, so it is
5672 normally the signed type of the same width as size_t (sometimes
5673 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
5674 matter though. Internally, we use "long" as arguments, which should
5675 work across all reasonable possibilities.
5677 Additionally, if MORECORE ever returns failure for a positive
5678 request, then mmap is used as a noncontiguous system allocator. This
5679 is a useful backup strategy for systems with holes in address spaces
5680 -- in this case sbrk cannot contiguously expand the heap, but mmap
5681 may be able to map noncontiguous space.
5683 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
5684 a function that always returns MORECORE_FAILURE.
5686 If you are using this malloc with something other than sbrk (or its
5687 emulation) to supply memory regions, you probably want to set
5688 MORECORE_CONTIGUOUS as false. As an example, here is a custom
5689 allocator kindly contributed for pre-OSX macOS. It uses virtually
5690 but not necessarily physically contiguous non-paged memory (locked
5691 in, present and won't get swapped out). You can use it by
5692 uncommenting this section, adding some #includes, and setting up the
5693 appropriate defines above:
5695 *#define MORECORE osMoreCore
5696 *#define MORECORE_CONTIGUOUS 0
5698 There is also a shutdown routine that should somehow be called for
5699 cleanup upon program exit.
5701 *#define MAX_POOL_ENTRIES 100
5702 *#define MINIMUM_MORECORE_SIZE (64 * 1024)
5703 static int next_os_pool;
5704 void *our_os_pools[MAX_POOL_ENTRIES];
5706 void *osMoreCore(int size)
5708 void *ptr = 0;
5709 static void *sbrk_top = 0;
5711 if (size > 0)
5713 if (size < MINIMUM_MORECORE_SIZE)
5714 size = MINIMUM_MORECORE_SIZE;
5715 if (CurrentExecutionLevel() == kTaskLevel)
5716 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
5717 if (ptr == 0)
5719 return (void *) MORECORE_FAILURE;
5721 // save ptrs so they can be freed during cleanup
5722 our_os_pools[next_os_pool] = ptr;
5723 next_os_pool++;
5724 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
5725 sbrk_top = (char *) ptr + size;
5726 return ptr;
5728 else if (size < 0)
5730 // we don't currently support shrink behavior
5731 return (void *) MORECORE_FAILURE;
5733 else
5735 return sbrk_top;
5739 // cleanup any allocated memory pools
5740 // called as last thing before shutting down driver
5742 void osCleanupMem(void)
5744 void **ptr;
5746 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
5747 if (*ptr)
5749 PoolDeallocate(*ptr);
5750 * ptr = 0;
5757 /* Helper code. */
5759 extern char **__libc_argv attribute_hidden;
5761 static void
5762 malloc_printerr (const char *str)
5764 #if IS_IN (libc)
5765 __libc_message ("%s\n", str);
5766 #else
5767 __libc_fatal (str);
5768 #endif
5769 __builtin_unreachable ();
5772 #if IS_IN (libc)
5773 /* We need a wrapper function for one of the additions of POSIX. */
5775 __posix_memalign (void **memptr, size_t alignment, size_t size)
5777 void *mem;
5779 if (!__malloc_initialized)
5780 ptmalloc_init ();
5782 /* Test whether the SIZE argument is valid. It must be a power of
5783 two multiple of sizeof (void *). */
5784 if (alignment % sizeof (void *) != 0
5785 || !powerof2 (alignment / sizeof (void *))
5786 || alignment == 0)
5787 return EINVAL;
5790 void *address = RETURN_ADDRESS (0);
5791 mem = _mid_memalign (alignment, size, address);
5793 if (mem != NULL)
5795 *memptr = mem;
5796 return 0;
5799 return ENOMEM;
5801 weak_alias (__posix_memalign, posix_memalign)
5802 #endif
5806 __malloc_info (int options, FILE *fp)
5808 /* For now, at least. */
5809 if (options != 0)
5810 return EINVAL;
5812 int n = 0;
5813 size_t total_nblocks = 0;
5814 size_t total_nfastblocks = 0;
5815 size_t total_avail = 0;
5816 size_t total_fastavail = 0;
5817 size_t total_system = 0;
5818 size_t total_max_system = 0;
5819 size_t total_aspace = 0;
5820 size_t total_aspace_mprotect = 0;
5824 if (!__malloc_initialized)
5825 ptmalloc_init ();
5827 fputs ("<malloc version=\"1\">\n", fp);
5829 /* Iterate over all arenas currently in use. */
5830 mstate ar_ptr = &main_arena;
5833 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
5835 size_t nblocks = 0;
5836 size_t nfastblocks = 0;
5837 size_t avail = 0;
5838 size_t fastavail = 0;
5839 struct
5841 size_t from;
5842 size_t to;
5843 size_t total;
5844 size_t count;
5845 } sizes[NFASTBINS + NBINS - 1];
5846 #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
5848 __libc_lock_lock (ar_ptr->mutex);
5850 /* Account for top chunk. The top-most available chunk is
5851 treated specially and is never in any bin. See "initial_top"
5852 comments. */
5853 avail = chunksize (ar_ptr->top);
5854 nblocks = 1; /* Top always exists. */
5856 for (size_t i = 0; i < NFASTBINS; ++i)
5858 mchunkptr p = fastbin (ar_ptr, i);
5859 if (p != NULL)
5861 size_t nthissize = 0;
5862 size_t thissize = chunksize (p);
5864 while (p != NULL)
5866 if (__glibc_unlikely (misaligned_chunk (p)))
5867 malloc_printerr ("__malloc_info(): "
5868 "unaligned fastbin chunk detected");
5869 ++nthissize;
5870 p = REVEAL_PTR (p->fd);
5873 fastavail += nthissize * thissize;
5874 nfastblocks += nthissize;
5875 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
5876 sizes[i].to = thissize;
5877 sizes[i].count = nthissize;
5879 else
5880 sizes[i].from = sizes[i].to = sizes[i].count = 0;
5882 sizes[i].total = sizes[i].count * sizes[i].to;
5886 mbinptr bin;
5887 struct malloc_chunk *r;
5889 for (size_t i = 1; i < NBINS; ++i)
5891 bin = bin_at (ar_ptr, i);
5892 r = bin->fd;
5893 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5894 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5895 = sizes[NFASTBINS - 1 + i].count = 0;
5897 if (r != NULL)
5898 while (r != bin)
5900 size_t r_size = chunksize_nomask (r);
5901 ++sizes[NFASTBINS - 1 + i].count;
5902 sizes[NFASTBINS - 1 + i].total += r_size;
5903 sizes[NFASTBINS - 1 + i].from
5904 = MIN (sizes[NFASTBINS - 1 + i].from, r_size);
5905 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5906 r_size);
5908 r = r->fd;
5911 if (sizes[NFASTBINS - 1 + i].count == 0)
5912 sizes[NFASTBINS - 1 + i].from = 0;
5913 nblocks += sizes[NFASTBINS - 1 + i].count;
5914 avail += sizes[NFASTBINS - 1 + i].total;
5917 size_t heap_size = 0;
5918 size_t heap_mprotect_size = 0;
5919 size_t heap_count = 0;
5920 if (ar_ptr != &main_arena)
5922 /* Iterate over the arena heaps from back to front. */
5923 heap_info *heap = heap_for_ptr (top (ar_ptr));
5926 heap_size += heap->size;
5927 heap_mprotect_size += heap->mprotect_size;
5928 heap = heap->prev;
5929 ++heap_count;
5931 while (heap != NULL);
5934 __libc_lock_unlock (ar_ptr->mutex);
5936 total_nfastblocks += nfastblocks;
5937 total_fastavail += fastavail;
5939 total_nblocks += nblocks;
5940 total_avail += avail;
5942 for (size_t i = 0; i < nsizes; ++i)
5943 if (sizes[i].count != 0 && i != NFASTBINS)
5944 fprintf (fp, "\
5945 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5946 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
5948 if (sizes[NFASTBINS].count != 0)
5949 fprintf (fp, "\
5950 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5951 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5952 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
5954 total_system += ar_ptr->system_mem;
5955 total_max_system += ar_ptr->max_system_mem;
5957 fprintf (fp,
5958 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5959 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5960 "<system type=\"current\" size=\"%zu\"/>\n"
5961 "<system type=\"max\" size=\"%zu\"/>\n",
5962 nfastblocks, fastavail, nblocks, avail,
5963 ar_ptr->system_mem, ar_ptr->max_system_mem);
5965 if (ar_ptr != &main_arena)
5967 fprintf (fp,
5968 "<aspace type=\"total\" size=\"%zu\"/>\n"
5969 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5970 "<aspace type=\"subheaps\" size=\"%zu\"/>\n",
5971 heap_size, heap_mprotect_size, heap_count);
5972 total_aspace += heap_size;
5973 total_aspace_mprotect += heap_mprotect_size;
5975 else
5977 fprintf (fp,
5978 "<aspace type=\"total\" size=\"%zu\"/>\n"
5979 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5980 ar_ptr->system_mem, ar_ptr->system_mem);
5981 total_aspace += ar_ptr->system_mem;
5982 total_aspace_mprotect += ar_ptr->system_mem;
5985 fputs ("</heap>\n", fp);
5986 ar_ptr = ar_ptr->next;
5988 while (ar_ptr != &main_arena);
5990 fprintf (fp,
5991 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5992 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5993 "<total type=\"mmap\" count=\"%d\" size=\"%zu\"/>\n"
5994 "<system type=\"current\" size=\"%zu\"/>\n"
5995 "<system type=\"max\" size=\"%zu\"/>\n"
5996 "<aspace type=\"total\" size=\"%zu\"/>\n"
5997 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5998 "</malloc>\n",
5999 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
6000 mp_.n_mmaps, mp_.mmapped_mem,
6001 total_system, total_max_system,
6002 total_aspace, total_aspace_mprotect);
6004 return 0;
6006 #if IS_IN (libc)
6007 weak_alias (__malloc_info, malloc_info)
6009 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
6010 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
6011 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
6012 strong_alias (__libc_memalign, __memalign)
6013 weak_alias (__libc_memalign, memalign)
6014 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
6015 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
6016 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
6017 strong_alias (__libc_mallinfo, __mallinfo)
6018 weak_alias (__libc_mallinfo, mallinfo)
6019 strong_alias (__libc_mallinfo2, __mallinfo2)
6020 weak_alias (__libc_mallinfo2, mallinfo2)
6021 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
6023 weak_alias (__malloc_stats, malloc_stats)
6024 weak_alias (__malloc_usable_size, malloc_usable_size)
6025 weak_alias (__malloc_trim, malloc_trim)
6026 #endif
6028 #if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_26)
6029 compat_symbol (libc, __libc_free, cfree, GLIBC_2_0);
6030 #endif
6032 /* ------------------------------------------------------------
6033 History:
6035 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
6039 * Local variables:
6040 * c-basic-offset: 2
6041 * End: