x86: Optimize strlen-avx2.S
[glibc.git] / malloc / malloc.c
blobe2d7b1b58396906375ba0e953a20ac57f0904378
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2021 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Wolfram Gloger <wg@malloc.de>
5 and Doug Lea <dl@cs.oswego.edu>, 2001.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If
19 not, see <https://www.gnu.org/licenses/>. */
22 This is a version (aka ptmalloc2) of malloc/free/realloc written by
23 Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
25 There have been substantial changes made after the integration into
26 glibc in all parts of the code. Do not look for much commonality
27 with the ptmalloc2 version.
29 * Version ptmalloc2-20011215
30 based on:
31 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
33 * Quickstart
35 In order to compile this implementation, a Makefile is provided with
36 the ptmalloc2 distribution, which has pre-defined targets for some
37 popular systems (e.g. "make posix" for Posix threads). All that is
38 typically required with regard to compiler flags is the selection of
39 the thread package via defining one out of USE_PTHREADS, USE_THR or
40 USE_SPROC. Check the thread-m.h file for what effects this has.
41 Many/most systems will additionally require USE_TSD_DATA_HACK to be
42 defined, so this is the default for "make posix".
44 * Why use this malloc?
46 This is not the fastest, most space-conserving, most portable, or
47 most tunable malloc ever written. However it is among the fastest
48 while also being among the most space-conserving, portable and tunable.
49 Consistent balance across these factors results in a good general-purpose
50 allocator for malloc-intensive programs.
52 The main properties of the algorithms are:
53 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
54 with ties normally decided via FIFO (i.e. least recently used).
55 * For small (<= 64 bytes by default) requests, it is a caching
56 allocator, that maintains pools of quickly recycled chunks.
57 * In between, and for combinations of large and small requests, it does
58 the best it can trying to meet both goals at once.
59 * For very large requests (>= 128KB by default), it relies on system
60 memory mapping facilities, if supported.
62 For a longer but slightly out of date high-level description, see
63 http://gee.cs.oswego.edu/dl/html/malloc.html
65 You may already by default be using a C library containing a malloc
66 that is based on some version of this malloc (for example in
67 linux). You might still want to use the one in this file in order to
68 customize settings or to avoid overheads associated with library
69 versions.
71 * Contents, described in more detail in "description of public routines" below.
73 Standard (ANSI/SVID/...) functions:
74 malloc(size_t n);
75 calloc(size_t n_elements, size_t element_size);
76 free(void* p);
77 realloc(void* p, size_t n);
78 memalign(size_t alignment, size_t n);
79 valloc(size_t n);
80 mallinfo()
81 mallopt(int parameter_number, int parameter_value)
83 Additional functions:
84 independent_calloc(size_t n_elements, size_t size, void* chunks[]);
85 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
86 pvalloc(size_t n);
87 malloc_trim(size_t pad);
88 malloc_usable_size(void* p);
89 malloc_stats();
91 * Vital statistics:
93 Supported pointer representation: 4 or 8 bytes
94 Supported size_t representation: 4 or 8 bytes
95 Note that size_t is allowed to be 4 bytes even if pointers are 8.
96 You can adjust this by defining INTERNAL_SIZE_T
98 Alignment: 2 * sizeof(size_t) (default)
99 (i.e., 8 byte alignment with 4byte size_t). This suffices for
100 nearly all current machines and C compilers. However, you can
101 define MALLOC_ALIGNMENT to be wider than this if necessary.
103 Minimum overhead per allocated chunk: 4 or 8 bytes
104 Each malloced chunk has a hidden word of overhead holding size
105 and status information.
107 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
108 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
110 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
111 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
112 needed; 4 (8) for a trailing size field and 8 (16) bytes for
113 free list pointers. Thus, the minimum allocatable size is
114 16/24/32 bytes.
116 Even a request for zero bytes (i.e., malloc(0)) returns a
117 pointer to something of the minimum allocatable size.
119 The maximum overhead wastage (i.e., number of extra bytes
120 allocated than were requested in malloc) is less than or equal
121 to the minimum size, except for requests >= mmap_threshold that
122 are serviced via mmap(), where the worst case wastage is 2 *
123 sizeof(size_t) bytes plus the remainder from a system page (the
124 minimal mmap unit); typically 4096 or 8192 bytes.
126 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
127 8-byte size_t: 2^64 minus about two pages
129 It is assumed that (possibly signed) size_t values suffice to
130 represent chunk sizes. `Possibly signed' is due to the fact
131 that `size_t' may be defined on a system as either a signed or
132 an unsigned type. The ISO C standard says that it must be
133 unsigned, but a few systems are known not to adhere to this.
134 Additionally, even when size_t is unsigned, sbrk (which is by
135 default used to obtain memory from system) accepts signed
136 arguments, and may not be able to handle size_t-wide arguments
137 with negative sign bit. Generally, values that would
138 appear as negative after accounting for overhead and alignment
139 are supported only via mmap(), which does not have this
140 limitation.
142 Requests for sizes outside the allowed range will perform an optional
143 failure action and then return null. (Requests may also
144 also fail because a system is out of memory.)
146 Thread-safety: thread-safe
148 Compliance: I believe it is compliant with the 1997 Single Unix Specification
149 Also SVID/XPG, ANSI C, and probably others as well.
151 * Synopsis of compile-time options:
153 People have reported using previous versions of this malloc on all
154 versions of Unix, sometimes by tweaking some of the defines
155 below. It has been tested most extensively on Solaris and Linux.
156 People also report using it in stand-alone embedded systems.
158 The implementation is in straight, hand-tuned ANSI C. It is not
159 at all modular. (Sorry!) It uses a lot of macros. To be at all
160 usable, this code should be compiled using an optimizing compiler
161 (for example gcc -O3) that can simplify expressions and control
162 paths. (FAQ: some macros import variables as arguments rather than
163 declare locals because people reported that some debuggers
164 otherwise get confused.)
166 OPTION DEFAULT VALUE
168 Compilation Environment options:
170 HAVE_MREMAP 0
172 Changing default word sizes:
174 INTERNAL_SIZE_T size_t
176 Configuration and functionality options:
178 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
179 USE_MALLOC_LOCK NOT defined
180 MALLOC_DEBUG NOT defined
181 REALLOC_ZERO_BYTES_FREES 1
182 TRIM_FASTBINS 0
184 Options for customizing MORECORE:
186 MORECORE sbrk
187 MORECORE_FAILURE -1
188 MORECORE_CONTIGUOUS 1
189 MORECORE_CANNOT_TRIM NOT defined
190 MORECORE_CLEARS 1
191 MMAP_AS_MORECORE_SIZE (1024 * 1024)
193 Tuning options that are also dynamically changeable via mallopt:
195 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
196 DEFAULT_TRIM_THRESHOLD 128 * 1024
197 DEFAULT_TOP_PAD 0
198 DEFAULT_MMAP_THRESHOLD 128 * 1024
199 DEFAULT_MMAP_MAX 65536
201 There are several other #defined constants and macros that you
202 probably don't want to touch unless you are extending or adapting malloc. */
205 void* is the pointer type that malloc should say it returns
208 #ifndef void
209 #define void void
210 #endif /*void*/
212 #include <stddef.h> /* for size_t */
213 #include <stdlib.h> /* for getenv(), abort() */
214 #include <unistd.h> /* for __libc_enable_secure */
216 #include <atomic.h>
217 #include <_itoa.h>
218 #include <bits/wordsize.h>
219 #include <sys/sysinfo.h>
221 #include <ldsodefs.h>
223 #include <unistd.h>
224 #include <stdio.h> /* needed for malloc_stats */
225 #include <errno.h>
226 #include <assert.h>
228 #include <shlib-compat.h>
230 /* For uintptr_t. */
231 #include <stdint.h>
233 /* For va_arg, va_start, va_end. */
234 #include <stdarg.h>
236 /* For MIN, MAX, powerof2. */
237 #include <sys/param.h>
239 /* For ALIGN_UP et. al. */
240 #include <libc-pointer-arith.h>
242 /* For DIAG_PUSH/POP_NEEDS_COMMENT et al. */
243 #include <libc-diag.h>
245 /* For memory tagging. */
246 #include <libc-mtag.h>
248 #include <malloc/malloc-internal.h>
250 /* For SINGLE_THREAD_P. */
251 #include <sysdep-cancel.h>
253 #include <libc-internal.h>
256 Debugging:
258 Because freed chunks may be overwritten with bookkeeping fields, this
259 malloc will often die when freed memory is overwritten by user
260 programs. This can be very effective (albeit in an annoying way)
261 in helping track down dangling pointers.
263 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
264 enabled that will catch more memory errors. You probably won't be
265 able to make much sense of the actual assertion errors, but they
266 should help you locate incorrectly overwritten memory. The checking
267 is fairly extensive, and will slow down execution
268 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
269 will attempt to check every non-mmapped allocated and free chunk in
270 the course of computing the summmaries. (By nature, mmapped regions
271 cannot be checked very much automatically.)
273 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
274 this code. The assertions in the check routines spell out in more
275 detail the assumptions and invariants underlying the algorithms.
277 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
278 checking that all accesses to malloced memory stay within their
279 bounds. However, there are several add-ons and adaptations of this
280 or other mallocs available that do this.
283 #ifndef MALLOC_DEBUG
284 #define MALLOC_DEBUG 0
285 #endif
287 #ifndef NDEBUG
288 # define __assert_fail(assertion, file, line, function) \
289 __malloc_assert(assertion, file, line, function)
291 extern const char *__progname;
293 static void
294 __malloc_assert (const char *assertion, const char *file, unsigned int line,
295 const char *function)
297 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
298 __progname, __progname[0] ? ": " : "",
299 file, line,
300 function ? function : "", function ? ": " : "",
301 assertion);
302 fflush (stderr);
303 abort ();
305 #endif
307 #if USE_TCACHE
308 /* We want 64 entries. This is an arbitrary limit, which tunables can reduce. */
309 # define TCACHE_MAX_BINS 64
310 # define MAX_TCACHE_SIZE tidx2usize (TCACHE_MAX_BINS-1)
312 /* Only used to pre-fill the tunables. */
313 # define tidx2usize(idx) (((size_t) idx) * MALLOC_ALIGNMENT + MINSIZE - SIZE_SZ)
315 /* When "x" is from chunksize(). */
316 # define csize2tidx(x) (((x) - MINSIZE + MALLOC_ALIGNMENT - 1) / MALLOC_ALIGNMENT)
317 /* When "x" is a user-provided size. */
318 # define usize2tidx(x) csize2tidx (request2size (x))
320 /* With rounding and alignment, the bins are...
321 idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit)
322 idx 1 bytes 25..40 or 13..20
323 idx 2 bytes 41..56 or 21..28
324 etc. */
326 /* This is another arbitrary limit, which tunables can change. Each
327 tcache bin will hold at most this number of chunks. */
328 # define TCACHE_FILL_COUNT 7
330 /* Maximum chunks in tcache bins for tunables. This value must fit the range
331 of tcache->counts[] entries, else they may overflow. */
332 # define MAX_TCACHE_COUNT UINT16_MAX
333 #endif
335 /* Safe-Linking:
336 Use randomness from ASLR (mmap_base) to protect single-linked lists
337 of Fast-Bins and TCache. That is, mask the "next" pointers of the
338 lists' chunks, and also perform allocation alignment checks on them.
339 This mechanism reduces the risk of pointer hijacking, as was done with
340 Safe-Unlinking in the double-linked lists of Small-Bins.
341 It assumes a minimum page size of 4096 bytes (12 bits). Systems with
342 larger pages provide less entropy, although the pointer mangling
343 still works. */
344 #define PROTECT_PTR(pos, ptr) \
345 ((__typeof (ptr)) ((((size_t) pos) >> 12) ^ ((size_t) ptr)))
346 #define REVEAL_PTR(ptr) PROTECT_PTR (&ptr, ptr)
349 The REALLOC_ZERO_BYTES_FREES macro controls the behavior of realloc (p, 0)
350 when p is nonnull. If the macro is nonzero, the realloc call returns NULL;
351 otherwise, the call returns what malloc (0) would. In either case,
352 p is freed. Glibc uses a nonzero REALLOC_ZERO_BYTES_FREES, which
353 implements common historical practice.
355 ISO C17 says the realloc call has implementation-defined behavior,
356 and it might not even free p.
359 #ifndef REALLOC_ZERO_BYTES_FREES
360 #define REALLOC_ZERO_BYTES_FREES 1
361 #endif
364 TRIM_FASTBINS controls whether free() of a very small chunk can
365 immediately lead to trimming. Setting to true (1) can reduce memory
366 footprint, but will almost always slow down programs that use a lot
367 of small chunks.
369 Define this only if you are willing to give up some speed to more
370 aggressively reduce system-level memory footprint when releasing
371 memory in programs that use many small chunks. You can get
372 essentially the same effect by setting MXFAST to 0, but this can
373 lead to even greater slowdowns in programs using many small chunks.
374 TRIM_FASTBINS is an in-between compile-time option, that disables
375 only those chunks bordering topmost memory from being placed in
376 fastbins.
379 #ifndef TRIM_FASTBINS
380 #define TRIM_FASTBINS 0
381 #endif
384 /* Definition for getting more memory from the OS. */
385 #define MORECORE (*__morecore)
386 #define MORECORE_FAILURE 0
387 void * __default_morecore (ptrdiff_t);
388 void *(*__morecore)(ptrdiff_t) = __default_morecore;
390 /* Memory tagging. */
392 /* Some systems support the concept of tagging (sometimes known as
393 coloring) memory locations on a fine grained basis. Each memory
394 location is given a color (normally allocated randomly) and
395 pointers are also colored. When the pointer is dereferenced, the
396 pointer's color is checked against the memory's color and if they
397 differ the access is faulted (sometimes lazily).
399 We use this in glibc by maintaining a single color for the malloc
400 data structures that are interleaved with the user data and then
401 assigning separate colors for each block allocation handed out. In
402 this way simple buffer overruns will be rapidly detected. When
403 memory is freed, the memory is recolored back to the glibc default
404 so that simple use-after-free errors can also be detected.
406 If memory is reallocated the buffer is recolored even if the
407 address remains the same. This has a performance impact, but
408 guarantees that the old pointer cannot mistakenly be reused (code
409 that compares old against new will see a mismatch and will then
410 need to behave as though realloc moved the data to a new location).
412 Internal API for memory tagging support.
414 The aim is to keep the code for memory tagging support as close to
415 the normal APIs in glibc as possible, so that if tagging is not
416 enabled in the library, or is disabled at runtime then standard
417 operations can continue to be used. Support macros are used to do
418 this:
420 void *tag_new_zero_region (void *ptr, size_t size)
422 Allocates a new tag, colors the memory with that tag, zeros the
423 memory and returns a pointer that is correctly colored for that
424 location. The non-tagging version will simply call memset with 0.
426 void *tag_region (void *ptr, size_t size)
428 Color the region of memory pointed to by PTR and size SIZE with
429 the color of PTR. Returns the original pointer.
431 void *tag_new_usable (void *ptr)
433 Allocate a new random color and use it to color the user region of
434 a chunk; this may include data from the subsequent chunk's header
435 if tagging is sufficiently fine grained. Returns PTR suitably
436 recolored for accessing the memory there.
438 void *tag_at (void *ptr)
440 Read the current color of the memory at the address pointed to by
441 PTR (ignoring it's current color) and return PTR recolored to that
442 color. PTR must be valid address in all other respects. When
443 tagging is not enabled, it simply returns the original pointer.
446 #ifdef USE_MTAG
447 static bool mtag_enabled = false;
448 static int mtag_mmap_flags = 0;
449 #else
450 # define mtag_enabled false
451 # define mtag_mmap_flags 0
452 #endif
454 static __always_inline void *
455 tag_region (void *ptr, size_t size)
457 if (__glibc_unlikely (mtag_enabled))
458 return __libc_mtag_tag_region (ptr, size);
459 return ptr;
462 static __always_inline void *
463 tag_new_zero_region (void *ptr, size_t size)
465 if (__glibc_unlikely (mtag_enabled))
466 return __libc_mtag_tag_zero_region (__libc_mtag_new_tag (ptr), size);
467 return memset (ptr, 0, size);
470 /* Defined later. */
471 static void *
472 tag_new_usable (void *ptr);
474 static __always_inline void *
475 tag_at (void *ptr)
477 if (__glibc_unlikely (mtag_enabled))
478 return __libc_mtag_address_get_tag (ptr);
479 return ptr;
482 #include <string.h>
485 MORECORE-related declarations. By default, rely on sbrk
490 MORECORE is the name of the routine to call to obtain more memory
491 from the system. See below for general guidance on writing
492 alternative MORECORE functions, as well as a version for WIN32 and a
493 sample version for pre-OSX macos.
496 #ifndef MORECORE
497 #define MORECORE sbrk
498 #endif
501 MORECORE_FAILURE is the value returned upon failure of MORECORE
502 as well as mmap. Since it cannot be an otherwise valid memory address,
503 and must reflect values of standard sys calls, you probably ought not
504 try to redefine it.
507 #ifndef MORECORE_FAILURE
508 #define MORECORE_FAILURE (-1)
509 #endif
512 If MORECORE_CONTIGUOUS is true, take advantage of fact that
513 consecutive calls to MORECORE with positive arguments always return
514 contiguous increasing addresses. This is true of unix sbrk. Even
515 if not defined, when regions happen to be contiguous, malloc will
516 permit allocations spanning regions obtained from different
517 calls. But defining this when applicable enables some stronger
518 consistency checks and space efficiencies.
521 #ifndef MORECORE_CONTIGUOUS
522 #define MORECORE_CONTIGUOUS 1
523 #endif
526 Define MORECORE_CANNOT_TRIM if your version of MORECORE
527 cannot release space back to the system when given negative
528 arguments. This is generally necessary only if you are using
529 a hand-crafted MORECORE function that cannot handle negative arguments.
532 /* #define MORECORE_CANNOT_TRIM */
534 /* MORECORE_CLEARS (default 1)
535 The degree to which the routine mapped to MORECORE zeroes out
536 memory: never (0), only for newly allocated space (1) or always
537 (2). The distinction between (1) and (2) is necessary because on
538 some systems, if the application first decrements and then
539 increments the break value, the contents of the reallocated space
540 are unspecified.
543 #ifndef MORECORE_CLEARS
544 # define MORECORE_CLEARS 1
545 #endif
549 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
550 sbrk fails, and mmap is used as a backup. The value must be a
551 multiple of page size. This backup strategy generally applies only
552 when systems have "holes" in address space, so sbrk cannot perform
553 contiguous expansion, but there is still space available on system.
554 On systems for which this is known to be useful (i.e. most linux
555 kernels), this occurs only when programs allocate huge amounts of
556 memory. Between this, and the fact that mmap regions tend to be
557 limited, the size should be large, to avoid too many mmap calls and
558 thus avoid running out of kernel resources. */
560 #ifndef MMAP_AS_MORECORE_SIZE
561 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
562 #endif
565 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
566 large blocks.
569 #ifndef HAVE_MREMAP
570 #define HAVE_MREMAP 0
571 #endif
573 /* We may need to support __malloc_initialize_hook for backwards
574 compatibility. */
576 #if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_24)
577 # define HAVE_MALLOC_INIT_HOOK 1
578 #else
579 # define HAVE_MALLOC_INIT_HOOK 0
580 #endif
584 This version of malloc supports the standard SVID/XPG mallinfo
585 routine that returns a struct containing usage properties and
586 statistics. It should work on any SVID/XPG compliant system that has
587 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
588 install such a thing yourself, cut out the preliminary declarations
589 as described above and below and save them in a malloc.h file. But
590 there's no compelling reason to bother to do this.)
592 The main declaration needed is the mallinfo struct that is returned
593 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
594 bunch of fields that are not even meaningful in this version of
595 malloc. These fields are are instead filled by mallinfo() with
596 other numbers that might be of interest.
600 /* ---------- description of public routines ------------ */
603 malloc(size_t n)
604 Returns a pointer to a newly allocated chunk of at least n bytes, or null
605 if no space is available. Additionally, on failure, errno is
606 set to ENOMEM on ANSI C systems.
608 If n is zero, malloc returns a minimum-sized chunk. (The minimum
609 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
610 systems.) On most systems, size_t is an unsigned type, so calls
611 with negative arguments are interpreted as requests for huge amounts
612 of space, which will often fail. The maximum supported value of n
613 differs across systems, but is in all cases less than the maximum
614 representable value of a size_t.
616 void* __libc_malloc(size_t);
617 libc_hidden_proto (__libc_malloc)
620 free(void* p)
621 Releases the chunk of memory pointed to by p, that had been previously
622 allocated using malloc or a related routine such as realloc.
623 It has no effect if p is null. It can have arbitrary (i.e., bad!)
624 effects if p has already been freed.
626 Unless disabled (using mallopt), freeing very large spaces will
627 when possible, automatically trigger operations that give
628 back unused memory to the system, thus reducing program footprint.
630 void __libc_free(void*);
631 libc_hidden_proto (__libc_free)
634 calloc(size_t n_elements, size_t element_size);
635 Returns a pointer to n_elements * element_size bytes, with all locations
636 set to zero.
638 void* __libc_calloc(size_t, size_t);
641 realloc(void* p, size_t n)
642 Returns a pointer to a chunk of size n that contains the same data
643 as does chunk p up to the minimum of (n, p's size) bytes, or null
644 if no space is available.
646 The returned pointer may or may not be the same as p. The algorithm
647 prefers extending p when possible, otherwise it employs the
648 equivalent of a malloc-copy-free sequence.
650 If p is null, realloc is equivalent to malloc.
652 If space is not available, realloc returns null, errno is set (if on
653 ANSI) and p is NOT freed.
655 if n is for fewer bytes than already held by p, the newly unused
656 space is lopped off and freed if possible. Unless the #define
657 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
658 zero (re)allocates a minimum-sized chunk.
660 Large chunks that were internally obtained via mmap will always be
661 grown using malloc-copy-free sequences unless the system supports
662 MREMAP (currently only linux).
664 The old unix realloc convention of allowing the last-free'd chunk
665 to be used as an argument to realloc is not supported.
667 void* __libc_realloc(void*, size_t);
668 libc_hidden_proto (__libc_realloc)
671 memalign(size_t alignment, size_t n);
672 Returns a pointer to a newly allocated chunk of n bytes, aligned
673 in accord with the alignment argument.
675 The alignment argument should be a power of two. If the argument is
676 not a power of two, the nearest greater power is used.
677 8-byte alignment is guaranteed by normal malloc calls, so don't
678 bother calling memalign with an argument of 8 or less.
680 Overreliance on memalign is a sure way to fragment space.
682 void* __libc_memalign(size_t, size_t);
683 libc_hidden_proto (__libc_memalign)
686 valloc(size_t n);
687 Equivalent to memalign(pagesize, n), where pagesize is the page
688 size of the system. If the pagesize is unknown, 4096 is used.
690 void* __libc_valloc(size_t);
695 mallopt(int parameter_number, int parameter_value)
696 Sets tunable parameters The format is to provide a
697 (parameter-number, parameter-value) pair. mallopt then sets the
698 corresponding parameter to the argument value if it can (i.e., so
699 long as the value is meaningful), and returns 1 if successful else
700 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
701 normally defined in malloc.h. Only one of these (M_MXFAST) is used
702 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
703 so setting them has no effect. But this malloc also supports four
704 other options in mallopt. See below for details. Briefly, supported
705 parameters are as follows (listed defaults are for "typical"
706 configurations).
708 Symbol param # default allowed param values
709 M_MXFAST 1 64 0-80 (0 disables fastbins)
710 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
711 M_TOP_PAD -2 0 any
712 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
713 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
715 int __libc_mallopt(int, int);
716 libc_hidden_proto (__libc_mallopt)
720 mallinfo()
721 Returns (by copy) a struct containing various summary statistics:
723 arena: current total non-mmapped bytes allocated from system
724 ordblks: the number of free chunks
725 smblks: the number of fastbin blocks (i.e., small chunks that
726 have been freed but not use resused or consolidated)
727 hblks: current number of mmapped regions
728 hblkhd: total bytes held in mmapped regions
729 usmblks: always 0
730 fsmblks: total bytes held in fastbin blocks
731 uordblks: current total allocated space (normal or mmapped)
732 fordblks: total free space
733 keepcost: the maximum number of bytes that could ideally be released
734 back to system via malloc_trim. ("ideally" means that
735 it ignores page restrictions etc.)
737 Because these fields are ints, but internal bookkeeping may
738 be kept as longs, the reported values may wrap around zero and
739 thus be inaccurate.
741 struct mallinfo2 __libc_mallinfo2(void);
742 libc_hidden_proto (__libc_mallinfo2)
744 struct mallinfo __libc_mallinfo(void);
748 pvalloc(size_t n);
749 Equivalent to valloc(minimum-page-that-holds(n)), that is,
750 round up n to nearest pagesize.
752 void* __libc_pvalloc(size_t);
755 malloc_trim(size_t pad);
757 If possible, gives memory back to the system (via negative
758 arguments to sbrk) if there is unused memory at the `high' end of
759 the malloc pool. You can call this after freeing large blocks of
760 memory to potentially reduce the system-level memory requirements
761 of a program. However, it cannot guarantee to reduce memory. Under
762 some allocation patterns, some large free blocks of memory will be
763 locked between two used chunks, so they cannot be given back to
764 the system.
766 The `pad' argument to malloc_trim represents the amount of free
767 trailing space to leave untrimmed. If this argument is zero,
768 only the minimum amount of memory to maintain internal data
769 structures will be left (one page or less). Non-zero arguments
770 can be supplied to maintain enough trailing space to service
771 future expected allocations without having to re-obtain memory
772 from the system.
774 Malloc_trim returns 1 if it actually released any memory, else 0.
775 On systems that do not support "negative sbrks", it will always
776 return 0.
778 int __malloc_trim(size_t);
781 malloc_usable_size(void* p);
783 Returns the number of bytes you can actually use in
784 an allocated chunk, which may be more than you requested (although
785 often not) due to alignment and minimum size constraints.
786 You can use this many bytes without worrying about
787 overwriting other allocated objects. This is not a particularly great
788 programming practice. malloc_usable_size can be more useful in
789 debugging and assertions, for example:
791 p = malloc(n);
792 assert(malloc_usable_size(p) >= 256);
795 size_t __malloc_usable_size(void*);
798 malloc_stats();
799 Prints on stderr the amount of space obtained from the system (both
800 via sbrk and mmap), the maximum amount (which may be more than
801 current if malloc_trim and/or munmap got called), and the current
802 number of bytes allocated via malloc (or realloc, etc) but not yet
803 freed. Note that this is the number of bytes allocated, not the
804 number requested. It will be larger than the number requested
805 because of alignment and bookkeeping overhead. Because it includes
806 alignment wastage as being in use, this figure may be greater than
807 zero even when no user-level chunks are allocated.
809 The reported current and maximum system memory can be inaccurate if
810 a program makes other calls to system memory allocation functions
811 (normally sbrk) outside of malloc.
813 malloc_stats prints only the most commonly interesting statistics.
814 More information can be obtained by calling mallinfo.
817 void __malloc_stats(void);
820 posix_memalign(void **memptr, size_t alignment, size_t size);
822 POSIX wrapper like memalign(), checking for validity of size.
824 int __posix_memalign(void **, size_t, size_t);
826 /* mallopt tuning options */
829 M_MXFAST is the maximum request size used for "fastbins", special bins
830 that hold returned chunks without consolidating their spaces. This
831 enables future requests for chunks of the same size to be handled
832 very quickly, but can increase fragmentation, and thus increase the
833 overall memory footprint of a program.
835 This malloc manages fastbins very conservatively yet still
836 efficiently, so fragmentation is rarely a problem for values less
837 than or equal to the default. The maximum supported value of MXFAST
838 is 80. You wouldn't want it any higher than this anyway. Fastbins
839 are designed especially for use with many small structs, objects or
840 strings -- the default handles structs/objects/arrays with sizes up
841 to 8 4byte fields, or small strings representing words, tokens,
842 etc. Using fastbins for larger objects normally worsens
843 fragmentation without improving speed.
845 M_MXFAST is set in REQUEST size units. It is internally used in
846 chunksize units, which adds padding and alignment. You can reduce
847 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
848 algorithm to be a closer approximation of fifo-best-fit in all cases,
849 not just for larger requests, but will generally cause it to be
850 slower.
854 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
855 #ifndef M_MXFAST
856 #define M_MXFAST 1
857 #endif
859 #ifndef DEFAULT_MXFAST
860 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
861 #endif
865 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
866 to keep before releasing via malloc_trim in free().
868 Automatic trimming is mainly useful in long-lived programs.
869 Because trimming via sbrk can be slow on some systems, and can
870 sometimes be wasteful (in cases where programs immediately
871 afterward allocate more large chunks) the value should be high
872 enough so that your overall system performance would improve by
873 releasing this much memory.
875 The trim threshold and the mmap control parameters (see below)
876 can be traded off with one another. Trimming and mmapping are
877 two different ways of releasing unused memory back to the
878 system. Between these two, it is often possible to keep
879 system-level demands of a long-lived program down to a bare
880 minimum. For example, in one test suite of sessions measuring
881 the XF86 X server on Linux, using a trim threshold of 128K and a
882 mmap threshold of 192K led to near-minimal long term resource
883 consumption.
885 If you are using this malloc in a long-lived program, it should
886 pay to experiment with these values. As a rough guide, you
887 might set to a value close to the average size of a process
888 (program) running on your system. Releasing this much memory
889 would allow such a process to run in memory. Generally, it's
890 worth it to tune for trimming rather tham memory mapping when a
891 program undergoes phases where several large chunks are
892 allocated and released in ways that can reuse each other's
893 storage, perhaps mixed with phases where there are no such
894 chunks at all. And in well-behaved long-lived programs,
895 controlling release of large blocks via trimming versus mapping
896 is usually faster.
898 However, in most programs, these parameters serve mainly as
899 protection against the system-level effects of carrying around
900 massive amounts of unneeded memory. Since frequent calls to
901 sbrk, mmap, and munmap otherwise degrade performance, the default
902 parameters are set to relatively high values that serve only as
903 safeguards.
905 The trim value It must be greater than page size to have any useful
906 effect. To disable trimming completely, you can set to
907 (unsigned long)(-1)
909 Trim settings interact with fastbin (MXFAST) settings: Unless
910 TRIM_FASTBINS is defined, automatic trimming never takes place upon
911 freeing a chunk with size less than or equal to MXFAST. Trimming is
912 instead delayed until subsequent freeing of larger chunks. However,
913 you can still force an attempted trim by calling malloc_trim.
915 Also, trimming is not generally possible in cases where
916 the main arena is obtained via mmap.
918 Note that the trick some people use of mallocing a huge space and
919 then freeing it at program startup, in an attempt to reserve system
920 memory, doesn't have the intended effect under automatic trimming,
921 since that memory will immediately be returned to the system.
924 #define M_TRIM_THRESHOLD -1
926 #ifndef DEFAULT_TRIM_THRESHOLD
927 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
928 #endif
931 M_TOP_PAD is the amount of extra `padding' space to allocate or
932 retain whenever sbrk is called. It is used in two ways internally:
934 * When sbrk is called to extend the top of the arena to satisfy
935 a new malloc request, this much padding is added to the sbrk
936 request.
938 * When malloc_trim is called automatically from free(),
939 it is used as the `pad' argument.
941 In both cases, the actual amount of padding is rounded
942 so that the end of the arena is always a system page boundary.
944 The main reason for using padding is to avoid calling sbrk so
945 often. Having even a small pad greatly reduces the likelihood
946 that nearly every malloc request during program start-up (or
947 after trimming) will invoke sbrk, which needlessly wastes
948 time.
950 Automatic rounding-up to page-size units is normally sufficient
951 to avoid measurable overhead, so the default is 0. However, in
952 systems where sbrk is relatively slow, it can pay to increase
953 this value, at the expense of carrying around more memory than
954 the program needs.
957 #define M_TOP_PAD -2
959 #ifndef DEFAULT_TOP_PAD
960 #define DEFAULT_TOP_PAD (0)
961 #endif
964 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
965 adjusted MMAP_THRESHOLD.
968 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
969 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
970 #endif
972 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
973 /* For 32-bit platforms we cannot increase the maximum mmap
974 threshold much because it is also the minimum value for the
975 maximum heap size and its alignment. Going above 512k (i.e., 1M
976 for new heaps) wastes too much address space. */
977 # if __WORDSIZE == 32
978 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
979 # else
980 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
981 # endif
982 #endif
985 M_MMAP_THRESHOLD is the request size threshold for using mmap()
986 to service a request. Requests of at least this size that cannot
987 be allocated using already-existing space will be serviced via mmap.
988 (If enough normal freed space already exists it is used instead.)
990 Using mmap segregates relatively large chunks of memory so that
991 they can be individually obtained and released from the host
992 system. A request serviced through mmap is never reused by any
993 other request (at least not directly; the system may just so
994 happen to remap successive requests to the same locations).
996 Segregating space in this way has the benefits that:
998 1. Mmapped space can ALWAYS be individually released back
999 to the system, which helps keep the system level memory
1000 demands of a long-lived program low.
1001 2. Mapped memory can never become `locked' between
1002 other chunks, as can happen with normally allocated chunks, which
1003 means that even trimming via malloc_trim would not release them.
1004 3. On some systems with "holes" in address spaces, mmap can obtain
1005 memory that sbrk cannot.
1007 However, it has the disadvantages that:
1009 1. The space cannot be reclaimed, consolidated, and then
1010 used to service later requests, as happens with normal chunks.
1011 2. It can lead to more wastage because of mmap page alignment
1012 requirements
1013 3. It causes malloc performance to be more dependent on host
1014 system memory management support routines which may vary in
1015 implementation quality and may impose arbitrary
1016 limitations. Generally, servicing a request via normal
1017 malloc steps is faster than going through a system's mmap.
1019 The advantages of mmap nearly always outweigh disadvantages for
1020 "large" chunks, but the value of "large" varies across systems. The
1021 default is an empirically derived value that works well in most
1022 systems.
1025 Update in 2006:
1026 The above was written in 2001. Since then the world has changed a lot.
1027 Memory got bigger. Applications got bigger. The virtual address space
1028 layout in 32 bit linux changed.
1030 In the new situation, brk() and mmap space is shared and there are no
1031 artificial limits on brk size imposed by the kernel. What is more,
1032 applications have started using transient allocations larger than the
1033 128Kb as was imagined in 2001.
1035 The price for mmap is also high now; each time glibc mmaps from the
1036 kernel, the kernel is forced to zero out the memory it gives to the
1037 application. Zeroing memory is expensive and eats a lot of cache and
1038 memory bandwidth. This has nothing to do with the efficiency of the
1039 virtual memory system, by doing mmap the kernel just has no choice but
1040 to zero.
1042 In 2001, the kernel had a maximum size for brk() which was about 800
1043 megabytes on 32 bit x86, at that point brk() would hit the first
1044 mmaped shared libaries and couldn't expand anymore. With current 2.6
1045 kernels, the VA space layout is different and brk() and mmap
1046 both can span the entire heap at will.
1048 Rather than using a static threshold for the brk/mmap tradeoff,
1049 we are now using a simple dynamic one. The goal is still to avoid
1050 fragmentation. The old goals we kept are
1051 1) try to get the long lived large allocations to use mmap()
1052 2) really large allocations should always use mmap()
1053 and we're adding now:
1054 3) transient allocations should use brk() to avoid forcing the kernel
1055 having to zero memory over and over again
1057 The implementation works with a sliding threshold, which is by default
1058 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
1059 out at 128Kb as per the 2001 default.
1061 This allows us to satisfy requirement 1) under the assumption that long
1062 lived allocations are made early in the process' lifespan, before it has
1063 started doing dynamic allocations of the same size (which will
1064 increase the threshold).
1066 The upperbound on the threshold satisfies requirement 2)
1068 The threshold goes up in value when the application frees memory that was
1069 allocated with the mmap allocator. The idea is that once the application
1070 starts freeing memory of a certain size, it's highly probable that this is
1071 a size the application uses for transient allocations. This estimator
1072 is there to satisfy the new third requirement.
1076 #define M_MMAP_THRESHOLD -3
1078 #ifndef DEFAULT_MMAP_THRESHOLD
1079 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1080 #endif
1083 M_MMAP_MAX is the maximum number of requests to simultaneously
1084 service using mmap. This parameter exists because
1085 some systems have a limited number of internal tables for
1086 use by mmap, and using more than a few of them may degrade
1087 performance.
1089 The default is set to a value that serves only as a safeguard.
1090 Setting to 0 disables use of mmap for servicing large requests.
1093 #define M_MMAP_MAX -4
1095 #ifndef DEFAULT_MMAP_MAX
1096 #define DEFAULT_MMAP_MAX (65536)
1097 #endif
1099 #include <malloc.h>
1101 #ifndef RETURN_ADDRESS
1102 #define RETURN_ADDRESS(X_) (NULL)
1103 #endif
1105 /* Forward declarations. */
1106 struct malloc_chunk;
1107 typedef struct malloc_chunk* mchunkptr;
1109 /* Internal routines. */
1111 static void* _int_malloc(mstate, size_t);
1112 static void _int_free(mstate, mchunkptr, int);
1113 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1114 INTERNAL_SIZE_T);
1115 static void* _int_memalign(mstate, size_t, size_t);
1116 static void* _mid_memalign(size_t, size_t, void *);
1118 static void malloc_printerr(const char *str) __attribute__ ((noreturn));
1120 static void* mem2mem_check(void *p, size_t sz);
1121 static void top_check(void);
1122 static void munmap_chunk(mchunkptr p);
1123 #if HAVE_MREMAP
1124 static mchunkptr mremap_chunk(mchunkptr p, size_t new_size);
1125 #endif
1127 static void* malloc_check(size_t sz, const void *caller);
1128 static void free_check(void* mem, const void *caller);
1129 static void* realloc_check(void* oldmem, size_t bytes,
1130 const void *caller);
1131 static void* memalign_check(size_t alignment, size_t bytes,
1132 const void *caller);
1134 /* ------------------ MMAP support ------------------ */
1137 #include <fcntl.h>
1138 #include <sys/mman.h>
1140 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1141 # define MAP_ANONYMOUS MAP_ANON
1142 #endif
1144 #ifndef MAP_NORESERVE
1145 # define MAP_NORESERVE 0
1146 #endif
1148 #define MMAP(addr, size, prot, flags) \
1149 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1153 ----------------------- Chunk representations -----------------------
1158 This struct declaration is misleading (but accurate and necessary).
1159 It declares a "view" into memory allowing access to necessary
1160 fields at known offsets from a given base. See explanation below.
1163 struct malloc_chunk {
1165 INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk (if free). */
1166 INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
1168 struct malloc_chunk* fd; /* double links -- used only if free. */
1169 struct malloc_chunk* bk;
1171 /* Only used for large blocks: pointer to next larger size. */
1172 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1173 struct malloc_chunk* bk_nextsize;
1178 malloc_chunk details:
1180 (The following includes lightly edited explanations by Colin Plumb.)
1182 Chunks of memory are maintained using a `boundary tag' method as
1183 described in e.g., Knuth or Standish. (See the paper by Paul
1184 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1185 survey of such techniques.) Sizes of free chunks are stored both
1186 in the front of each chunk and at the end. This makes
1187 consolidating fragmented chunks into bigger chunks very fast. The
1188 size fields also hold bits representing whether chunks are free or
1189 in use.
1191 An allocated chunk looks like this:
1194 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1195 | Size of previous chunk, if unallocated (P clear) |
1196 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1197 | Size of chunk, in bytes |A|M|P|
1198 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1199 | User data starts here... .
1201 . (malloc_usable_size() bytes) .
1203 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1204 | (size of chunk, but used for application data) |
1205 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1206 | Size of next chunk, in bytes |A|0|1|
1207 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1209 Where "chunk" is the front of the chunk for the purpose of most of
1210 the malloc code, but "mem" is the pointer that is returned to the
1211 user. "Nextchunk" is the beginning of the next contiguous chunk.
1213 Chunks always begin on even word boundaries, so the mem portion
1214 (which is returned to the user) is also on an even word boundary, and
1215 thus at least double-word aligned.
1217 Free chunks are stored in circular doubly-linked lists, and look like this:
1219 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1220 | Size of previous chunk, if unallocated (P clear) |
1221 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1222 `head:' | Size of chunk, in bytes |A|0|P|
1223 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1224 | Forward pointer to next chunk in list |
1225 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1226 | Back pointer to previous chunk in list |
1227 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1228 | Unused space (may be 0 bytes long) .
1231 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1232 `foot:' | Size of chunk, in bytes |
1233 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1234 | Size of next chunk, in bytes |A|0|0|
1235 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1237 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1238 chunk size (which is always a multiple of two words), is an in-use
1239 bit for the *previous* chunk. If that bit is *clear*, then the
1240 word before the current chunk size contains the previous chunk
1241 size, and can be used to find the front of the previous chunk.
1242 The very first chunk allocated always has this bit set,
1243 preventing access to non-existent (or non-owned) memory. If
1244 prev_inuse is set for any given chunk, then you CANNOT determine
1245 the size of the previous chunk, and might even get a memory
1246 addressing fault when trying to do so.
1248 The A (NON_MAIN_ARENA) bit is cleared for chunks on the initial,
1249 main arena, described by the main_arena variable. When additional
1250 threads are spawned, each thread receives its own arena (up to a
1251 configurable limit, after which arenas are reused for multiple
1252 threads), and the chunks in these arenas have the A bit set. To
1253 find the arena for a chunk on such a non-main arena, heap_for_ptr
1254 performs a bit mask operation and indirection through the ar_ptr
1255 member of the per-heap header heap_info (see arena.c).
1257 Note that the `foot' of the current chunk is actually represented
1258 as the prev_size of the NEXT chunk. This makes it easier to
1259 deal with alignments etc but can be very confusing when trying
1260 to extend or adapt this code.
1262 The three exceptions to all this are:
1264 1. The special chunk `top' doesn't bother using the
1265 trailing size field since there is no next contiguous chunk
1266 that would have to index off it. After initialization, `top'
1267 is forced to always exist. If it would become less than
1268 MINSIZE bytes long, it is replenished.
1270 2. Chunks allocated via mmap, which have the second-lowest-order
1271 bit M (IS_MMAPPED) set in their size fields. Because they are
1272 allocated one-by-one, each must contain its own trailing size
1273 field. If the M bit is set, the other bits are ignored
1274 (because mmapped chunks are neither in an arena, nor adjacent
1275 to a freed chunk). The M bit is also used for chunks which
1276 originally came from a dumped heap via malloc_set_state in
1277 hooks.c.
1279 3. Chunks in fastbins are treated as allocated chunks from the
1280 point of view of the chunk allocator. They are consolidated
1281 with their neighbors only in bulk, in malloc_consolidate.
1285 ---------- Size and alignment checks and conversions ----------
1288 /* Conversion from malloc headers to user pointers, and back. When
1289 using memory tagging the user data and the malloc data structure
1290 headers have distinct tags. Converting fully from one to the other
1291 involves extracting the tag at the other address and creating a
1292 suitable pointer using it. That can be quite expensive. There are
1293 cases when the pointers are not dereferenced (for example only used
1294 for alignment check) so the tags are not relevant, and there are
1295 cases when user data is not tagged distinctly from malloc headers
1296 (user data is untagged because tagging is done late in malloc and
1297 early in free). User memory tagging across internal interfaces:
1299 sysmalloc: Returns untagged memory.
1300 _int_malloc: Returns untagged memory.
1301 _int_free: Takes untagged memory.
1302 _int_memalign: Returns untagged memory.
1303 _int_memalign: Returns untagged memory.
1304 _mid_memalign: Returns tagged memory.
1305 _int_realloc: Takes and returns tagged memory.
1308 /* The chunk header is two SIZE_SZ elements, but this is used widely, so
1309 we define it here for clarity later. */
1310 #define CHUNK_HDR_SZ (2 * SIZE_SZ)
1312 /* Convert a chunk address to a user mem pointer without correcting
1313 the tag. */
1314 #define chunk2mem(p) ((void*)((char*)(p) + CHUNK_HDR_SZ))
1316 /* Convert a chunk address to a user mem pointer and extract the right tag. */
1317 #define chunk2mem_tag(p) ((void*)tag_at ((char*)(p) + CHUNK_HDR_SZ))
1319 /* Convert a user mem pointer to a chunk address and extract the right tag. */
1320 #define mem2chunk(mem) ((mchunkptr)tag_at (((char*)(mem) - CHUNK_HDR_SZ)))
1322 /* The smallest possible chunk */
1323 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1325 /* The smallest size we can malloc is an aligned minimal chunk */
1327 #define MINSIZE \
1328 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1330 /* Check if m has acceptable alignment */
1332 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1334 #define misaligned_chunk(p) \
1335 ((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \
1336 & MALLOC_ALIGN_MASK)
1338 /* pad request bytes into a usable size -- internal version */
1339 /* Note: This must be a macro that evaluates to a compile time constant
1340 if passed a literal constant. */
1341 #define request2size(req) \
1342 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1343 MINSIZE : \
1344 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1346 /* Check if REQ overflows when padded and aligned and if the resulting value
1347 is less than PTRDIFF_T. Returns TRUE and the requested size or MINSIZE in
1348 case the value is less than MINSIZE on SZ or false if any of the previous
1349 check fail. */
1350 static inline bool
1351 checked_request2size (size_t req, size_t *sz) __nonnull (1)
1353 if (__glibc_unlikely (req > PTRDIFF_MAX))
1354 return false;
1356 /* When using tagged memory, we cannot share the end of the user
1357 block with the header for the next chunk, so ensure that we
1358 allocate blocks that are rounded up to the granule size. Take
1359 care not to overflow from close to MAX_SIZE_T to a small
1360 number. Ideally, this would be part of request2size(), but that
1361 must be a macro that produces a compile time constant if passed
1362 a constant literal. */
1363 if (__glibc_unlikely (mtag_enabled))
1365 /* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551. */
1366 asm ("");
1368 req = (req + (__MTAG_GRANULE_SIZE - 1)) &
1369 ~(size_t)(__MTAG_GRANULE_SIZE - 1);
1372 *sz = request2size (req);
1373 return true;
1377 --------------- Physical chunk operations ---------------
1381 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1382 #define PREV_INUSE 0x1
1384 /* extract inuse bit of previous chunk */
1385 #define prev_inuse(p) ((p)->mchunk_size & PREV_INUSE)
1388 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1389 #define IS_MMAPPED 0x2
1391 /* check for mmap()'ed chunk */
1392 #define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)
1395 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1396 from a non-main arena. This is only set immediately before handing
1397 the chunk to the user, if necessary. */
1398 #define NON_MAIN_ARENA 0x4
1400 /* Check for chunk from main arena. */
1401 #define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)
1403 /* Mark a chunk as not being on the main arena. */
1404 #define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
1408 Bits to mask off when extracting size
1410 Note: IS_MMAPPED is intentionally not masked off from size field in
1411 macros for which mmapped chunks should never be seen. This should
1412 cause helpful core dumps to occur if it is tried by accident by
1413 people extending or adapting this malloc.
1415 #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1417 /* Get size, ignoring use bits */
1418 #define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))
1420 /* Like chunksize, but do not mask SIZE_BITS. */
1421 #define chunksize_nomask(p) ((p)->mchunk_size)
1423 /* Ptr to next physical malloc_chunk. */
1424 #define next_chunk(p) ((mchunkptr) (((char *) (p)) + chunksize (p)))
1426 /* Size of the chunk below P. Only valid if !prev_inuse (P). */
1427 #define prev_size(p) ((p)->mchunk_prev_size)
1429 /* Set the size of the chunk below P. Only valid if !prev_inuse (P). */
1430 #define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))
1432 /* Ptr to previous physical malloc_chunk. Only valid if !prev_inuse (P). */
1433 #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - prev_size (p)))
1435 /* Treat space at ptr + offset as a chunk */
1436 #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1438 /* extract p's inuse bit */
1439 #define inuse(p) \
1440 ((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
1442 /* set/clear chunk as being inuse without otherwise disturbing */
1443 #define set_inuse(p) \
1444 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
1446 #define clear_inuse(p) \
1447 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
1450 /* check/set/clear inuse bits in known places */
1451 #define inuse_bit_at_offset(p, s) \
1452 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
1454 #define set_inuse_bit_at_offset(p, s) \
1455 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
1457 #define clear_inuse_bit_at_offset(p, s) \
1458 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
1461 /* Set size at head, without disturbing its use bit */
1462 #define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
1464 /* Set size/use field */
1465 #define set_head(p, s) ((p)->mchunk_size = (s))
1467 /* Set size at footer (only when chunk is not in use) */
1468 #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
1470 #pragma GCC poison mchunk_size
1471 #pragma GCC poison mchunk_prev_size
1473 /* This is the size of the real usable data in the chunk. Not valid for
1474 dumped heap chunks. */
1475 #define memsize(p) \
1476 (__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \
1477 chunksize (p) - CHUNK_HDR_SZ : \
1478 chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ))
1480 /* If memory tagging is enabled the layout changes to accomodate the granule
1481 size, this is wasteful for small allocations so not done by default.
1482 Both the chunk header and user data has to be granule aligned. */
1483 _Static_assert (__MTAG_GRANULE_SIZE <= CHUNK_HDR_SZ,
1484 "memory tagging is not supported with large granule.");
1486 static __always_inline void *
1487 tag_new_usable (void *ptr)
1489 if (__glibc_unlikely (mtag_enabled) && ptr)
1491 mchunkptr cp = mem2chunk(ptr);
1492 ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp));
1494 return ptr;
1498 -------------------- Internal data structures --------------------
1500 All internal state is held in an instance of malloc_state defined
1501 below. There are no other static variables, except in two optional
1502 cases:
1503 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1504 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1505 for mmap.
1507 Beware of lots of tricks that minimize the total bookkeeping space
1508 requirements. The result is a little over 1K bytes (for 4byte
1509 pointers and size_t.)
1513 Bins
1515 An array of bin headers for free chunks. Each bin is doubly
1516 linked. The bins are approximately proportionally (log) spaced.
1517 There are a lot of these bins (128). This may look excessive, but
1518 works very well in practice. Most bins hold sizes that are
1519 unusual as malloc request sizes, but are more usual for fragments
1520 and consolidated sets of chunks, which is what these bins hold, so
1521 they can be found quickly. All procedures maintain the invariant
1522 that no consolidated chunk physically borders another one, so each
1523 chunk in a list is known to be preceeded and followed by either
1524 inuse chunks or the ends of memory.
1526 Chunks in bins are kept in size order, with ties going to the
1527 approximately least recently used chunk. Ordering isn't needed
1528 for the small bins, which all contain the same-sized chunks, but
1529 facilitates best-fit allocation for larger chunks. These lists
1530 are just sequential. Keeping them in order almost never requires
1531 enough traversal to warrant using fancier ordered data
1532 structures.
1534 Chunks of the same size are linked with the most
1535 recently freed at the front, and allocations are taken from the
1536 back. This results in LRU (FIFO) allocation order, which tends
1537 to give each chunk an equal opportunity to be consolidated with
1538 adjacent freed chunks, resulting in larger free chunks and less
1539 fragmentation.
1541 To simplify use in double-linked lists, each bin header acts
1542 as a malloc_chunk. This avoids special-casing for headers.
1543 But to conserve space and improve locality, we allocate
1544 only the fd/bk pointers of bins, and then use repositioning tricks
1545 to treat these as the fields of a malloc_chunk*.
1548 typedef struct malloc_chunk *mbinptr;
1550 /* addressing -- note that bin_at(0) does not exist */
1551 #define bin_at(m, i) \
1552 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1553 - offsetof (struct malloc_chunk, fd))
1555 /* analog of ++bin */
1556 #define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
1558 /* Reminders about list directionality within bins */
1559 #define first(b) ((b)->fd)
1560 #define last(b) ((b)->bk)
1563 Indexing
1565 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1566 8 bytes apart. Larger bins are approximately logarithmically spaced:
1568 64 bins of size 8
1569 32 bins of size 64
1570 16 bins of size 512
1571 8 bins of size 4096
1572 4 bins of size 32768
1573 2 bins of size 262144
1574 1 bin of size what's left
1576 There is actually a little bit of slop in the numbers in bin_index
1577 for the sake of speed. This makes no difference elsewhere.
1579 The bins top out around 1MB because we expect to service large
1580 requests via mmap.
1582 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1583 a valid chunk size the small bins are bumped up one.
1586 #define NBINS 128
1587 #define NSMALLBINS 64
1588 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1589 #define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > CHUNK_HDR_SZ)
1590 #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
1592 #define in_smallbin_range(sz) \
1593 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
1595 #define smallbin_index(sz) \
1596 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
1597 + SMALLBIN_CORRECTION)
1599 #define largebin_index_32(sz) \
1600 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1601 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1602 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1603 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1604 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1605 126)
1607 #define largebin_index_32_big(sz) \
1608 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1609 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1610 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1611 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1612 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1613 126)
1615 // XXX It remains to be seen whether it is good to keep the widths of
1616 // XXX the buckets the same or whether it should be scaled by a factor
1617 // XXX of two as well.
1618 #define largebin_index_64(sz) \
1619 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1620 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1621 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1622 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1623 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1624 126)
1626 #define largebin_index(sz) \
1627 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1628 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1629 : largebin_index_32 (sz))
1631 #define bin_index(sz) \
1632 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
1634 /* Take a chunk off a bin list. */
1635 static void
1636 unlink_chunk (mstate av, mchunkptr p)
1638 if (chunksize (p) != prev_size (next_chunk (p)))
1639 malloc_printerr ("corrupted size vs. prev_size");
1641 mchunkptr fd = p->fd;
1642 mchunkptr bk = p->bk;
1644 if (__builtin_expect (fd->bk != p || bk->fd != p, 0))
1645 malloc_printerr ("corrupted double-linked list");
1647 fd->bk = bk;
1648 bk->fd = fd;
1649 if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL)
1651 if (p->fd_nextsize->bk_nextsize != p
1652 || p->bk_nextsize->fd_nextsize != p)
1653 malloc_printerr ("corrupted double-linked list (not small)");
1655 if (fd->fd_nextsize == NULL)
1657 if (p->fd_nextsize == p)
1658 fd->fd_nextsize = fd->bk_nextsize = fd;
1659 else
1661 fd->fd_nextsize = p->fd_nextsize;
1662 fd->bk_nextsize = p->bk_nextsize;
1663 p->fd_nextsize->bk_nextsize = fd;
1664 p->bk_nextsize->fd_nextsize = fd;
1667 else
1669 p->fd_nextsize->bk_nextsize = p->bk_nextsize;
1670 p->bk_nextsize->fd_nextsize = p->fd_nextsize;
1676 Unsorted chunks
1678 All remainders from chunk splits, as well as all returned chunks,
1679 are first placed in the "unsorted" bin. They are then placed
1680 in regular bins after malloc gives them ONE chance to be used before
1681 binning. So, basically, the unsorted_chunks list acts as a queue,
1682 with chunks being placed on it in free (and malloc_consolidate),
1683 and taken off (to be either used or placed in bins) in malloc.
1685 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1686 does not have to be taken into account in size comparisons.
1689 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1690 #define unsorted_chunks(M) (bin_at (M, 1))
1695 The top-most available chunk (i.e., the one bordering the end of
1696 available memory) is treated specially. It is never included in
1697 any bin, is used only if no other chunk is available, and is
1698 released back to the system if it is very large (see
1699 M_TRIM_THRESHOLD). Because top initially
1700 points to its own bin with initial zero size, thus forcing
1701 extension on the first malloc request, we avoid having any special
1702 code in malloc to check whether it even exists yet. But we still
1703 need to do so when getting memory from system, so we make
1704 initial_top treat the bin as a legal but unusable chunk during the
1705 interval between initialization and the first call to
1706 sysmalloc. (This is somewhat delicate, since it relies on
1707 the 2 preceding words to be zero during this interval as well.)
1710 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1711 #define initial_top(M) (unsorted_chunks (M))
1714 Binmap
1716 To help compensate for the large number of bins, a one-level index
1717 structure is used for bin-by-bin searching. `binmap' is a
1718 bitvector recording whether bins are definitely empty so they can
1719 be skipped over during during traversals. The bits are NOT always
1720 cleared as soon as bins are empty, but instead only
1721 when they are noticed to be empty during traversal in malloc.
1724 /* Conservatively use 32 bits per map word, even if on 64bit system */
1725 #define BINMAPSHIFT 5
1726 #define BITSPERMAP (1U << BINMAPSHIFT)
1727 #define BINMAPSIZE (NBINS / BITSPERMAP)
1729 #define idx2block(i) ((i) >> BINMAPSHIFT)
1730 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
1732 #define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1733 #define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1734 #define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
1737 Fastbins
1739 An array of lists holding recently freed small chunks. Fastbins
1740 are not doubly linked. It is faster to single-link them, and
1741 since chunks are never removed from the middles of these lists,
1742 double linking is not necessary. Also, unlike regular bins, they
1743 are not even processed in FIFO order (they use faster LIFO) since
1744 ordering doesn't much matter in the transient contexts in which
1745 fastbins are normally used.
1747 Chunks in fastbins keep their inuse bit set, so they cannot
1748 be consolidated with other free chunks. malloc_consolidate
1749 releases all chunks in fastbins and consolidates them with
1750 other free chunks.
1753 typedef struct malloc_chunk *mfastbinptr;
1754 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1756 /* offset 2 to use otherwise unindexable first 2 bins */
1757 #define fastbin_index(sz) \
1758 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1761 /* The maximum fastbin request size we support */
1762 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1764 #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
1767 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1768 that triggers automatic consolidation of possibly-surrounding
1769 fastbin chunks. This is a heuristic, so the exact value should not
1770 matter too much. It is defined at half the default trim threshold as a
1771 compromise heuristic to only attempt consolidation if it is likely
1772 to lead to trimming. However, it is not dynamically tunable, since
1773 consolidation reduces fragmentation surrounding large chunks even
1774 if trimming is not used.
1777 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1780 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1781 regions. Otherwise, contiguity is exploited in merging together,
1782 when possible, results from consecutive MORECORE calls.
1784 The initial value comes from MORECORE_CONTIGUOUS, but is
1785 changed dynamically if mmap is ever used as an sbrk substitute.
1788 #define NONCONTIGUOUS_BIT (2U)
1790 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1791 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1792 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1793 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1795 /* Maximum size of memory handled in fastbins. */
1796 static INTERNAL_SIZE_T global_max_fast;
1799 Set value of max_fast.
1800 Use impossibly small value if 0.
1801 Precondition: there are no existing fastbin chunks in the main arena.
1802 Since do_check_malloc_state () checks this, we call malloc_consolidate ()
1803 before changing max_fast. Note other arenas will leak their fast bin
1804 entries if max_fast is reduced.
1807 #define set_max_fast(s) \
1808 global_max_fast = (((size_t) (s) <= MALLOC_ALIGN_MASK - SIZE_SZ) \
1809 ? MIN_CHUNK_SIZE / 2 : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1811 static inline INTERNAL_SIZE_T
1812 get_max_fast (void)
1814 /* Tell the GCC optimizers that global_max_fast is never larger
1815 than MAX_FAST_SIZE. This avoids out-of-bounds array accesses in
1816 _int_malloc after constant propagation of the size parameter.
1817 (The code never executes because malloc preserves the
1818 global_max_fast invariant, but the optimizers may not recognize
1819 this.) */
1820 if (global_max_fast > MAX_FAST_SIZE)
1821 __builtin_unreachable ();
1822 return global_max_fast;
1826 ----------- Internal state representation and initialization -----------
1830 have_fastchunks indicates that there are probably some fastbin chunks.
1831 It is set true on entering a chunk into any fastbin, and cleared early in
1832 malloc_consolidate. The value is approximate since it may be set when there
1833 are no fastbin chunks, or it may be clear even if there are fastbin chunks
1834 available. Given it's sole purpose is to reduce number of redundant calls to
1835 malloc_consolidate, it does not affect correctness. As a result we can safely
1836 use relaxed atomic accesses.
1840 struct malloc_state
1842 /* Serialize access. */
1843 __libc_lock_define (, mutex);
1845 /* Flags (formerly in max_fast). */
1846 int flags;
1848 /* Set if the fastbin chunks contain recently inserted free blocks. */
1849 /* Note this is a bool but not all targets support atomics on booleans. */
1850 int have_fastchunks;
1852 /* Fastbins */
1853 mfastbinptr fastbinsY[NFASTBINS];
1855 /* Base of the topmost chunk -- not otherwise kept in a bin */
1856 mchunkptr top;
1858 /* The remainder from the most recent split of a small request */
1859 mchunkptr last_remainder;
1861 /* Normal bins packed as described above */
1862 mchunkptr bins[NBINS * 2 - 2];
1864 /* Bitmap of bins */
1865 unsigned int binmap[BINMAPSIZE];
1867 /* Linked list */
1868 struct malloc_state *next;
1870 /* Linked list for free arenas. Access to this field is serialized
1871 by free_list_lock in arena.c. */
1872 struct malloc_state *next_free;
1874 /* Number of threads attached to this arena. 0 if the arena is on
1875 the free list. Access to this field is serialized by
1876 free_list_lock in arena.c. */
1877 INTERNAL_SIZE_T attached_threads;
1879 /* Memory allocated from the system in this arena. */
1880 INTERNAL_SIZE_T system_mem;
1881 INTERNAL_SIZE_T max_system_mem;
1884 struct malloc_par
1886 /* Tunable parameters */
1887 unsigned long trim_threshold;
1888 INTERNAL_SIZE_T top_pad;
1889 INTERNAL_SIZE_T mmap_threshold;
1890 INTERNAL_SIZE_T arena_test;
1891 INTERNAL_SIZE_T arena_max;
1893 /* Memory map support */
1894 int n_mmaps;
1895 int n_mmaps_max;
1896 int max_n_mmaps;
1897 /* the mmap_threshold is dynamic, until the user sets
1898 it manually, at which point we need to disable any
1899 dynamic behavior. */
1900 int no_dyn_threshold;
1902 /* Statistics */
1903 INTERNAL_SIZE_T mmapped_mem;
1904 INTERNAL_SIZE_T max_mmapped_mem;
1906 /* First address handed out by MORECORE/sbrk. */
1907 char *sbrk_base;
1909 #if USE_TCACHE
1910 /* Maximum number of buckets to use. */
1911 size_t tcache_bins;
1912 size_t tcache_max_bytes;
1913 /* Maximum number of chunks in each bucket. */
1914 size_t tcache_count;
1915 /* Maximum number of chunks to remove from the unsorted list, which
1916 aren't used to prefill the cache. */
1917 size_t tcache_unsorted_limit;
1918 #endif
1921 /* There are several instances of this struct ("arenas") in this
1922 malloc. If you are adapting this malloc in a way that does NOT use
1923 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1924 before using. This malloc relies on the property that malloc_state
1925 is initialized to all zeroes (as is true of C statics). */
1927 static struct malloc_state main_arena =
1929 .mutex = _LIBC_LOCK_INITIALIZER,
1930 .next = &main_arena,
1931 .attached_threads = 1
1934 /* These variables are used for undumping support. Chunked are marked
1935 as using mmap, but we leave them alone if they fall into this
1936 range. NB: The chunk size for these chunks only includes the
1937 initial size field (of SIZE_SZ bytes), there is no trailing size
1938 field (unlike with regular mmapped chunks). */
1939 static mchunkptr dumped_main_arena_start; /* Inclusive. */
1940 static mchunkptr dumped_main_arena_end; /* Exclusive. */
1942 /* True if the pointer falls into the dumped arena. Use this after
1943 chunk_is_mmapped indicates a chunk is mmapped. */
1944 #define DUMPED_MAIN_ARENA_CHUNK(p) \
1945 ((p) >= dumped_main_arena_start && (p) < dumped_main_arena_end)
1947 /* There is only one instance of the malloc parameters. */
1949 static struct malloc_par mp_ =
1951 .top_pad = DEFAULT_TOP_PAD,
1952 .n_mmaps_max = DEFAULT_MMAP_MAX,
1953 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1954 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1955 #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1956 .arena_test = NARENAS_FROM_NCORES (1)
1957 #if USE_TCACHE
1959 .tcache_count = TCACHE_FILL_COUNT,
1960 .tcache_bins = TCACHE_MAX_BINS,
1961 .tcache_max_bytes = tidx2usize (TCACHE_MAX_BINS-1),
1962 .tcache_unsorted_limit = 0 /* No limit. */
1963 #endif
1967 Initialize a malloc_state struct.
1969 This is called from ptmalloc_init () or from _int_new_arena ()
1970 when creating a new arena.
1973 static void
1974 malloc_init_state (mstate av)
1976 int i;
1977 mbinptr bin;
1979 /* Establish circular links for normal bins */
1980 for (i = 1; i < NBINS; ++i)
1982 bin = bin_at (av, i);
1983 bin->fd = bin->bk = bin;
1986 #if MORECORE_CONTIGUOUS
1987 if (av != &main_arena)
1988 #endif
1989 set_noncontiguous (av);
1990 if (av == &main_arena)
1991 set_max_fast (DEFAULT_MXFAST);
1992 atomic_store_relaxed (&av->have_fastchunks, false);
1994 av->top = initial_top (av);
1998 Other internal utilities operating on mstates
2001 static void *sysmalloc (INTERNAL_SIZE_T, mstate);
2002 static int systrim (size_t, mstate);
2003 static void malloc_consolidate (mstate);
2006 /* -------------- Early definitions for debugging hooks ---------------- */
2008 /* Define and initialize the hook variables. These weak definitions must
2009 appear before any use of the variables in a function (arena.c uses one). */
2010 #ifndef weak_variable
2011 /* In GNU libc we want the hook variables to be weak definitions to
2012 avoid a problem with Emacs. */
2013 # define weak_variable weak_function
2014 #endif
2016 /* Forward declarations. */
2017 static void *malloc_hook_ini (size_t sz,
2018 const void *caller) __THROW;
2019 static void *realloc_hook_ini (void *ptr, size_t sz,
2020 const void *caller) __THROW;
2021 static void *memalign_hook_ini (size_t alignment, size_t sz,
2022 const void *caller) __THROW;
2024 #if HAVE_MALLOC_INIT_HOOK
2025 void (*__malloc_initialize_hook) (void) __attribute__ ((nocommon));
2026 compat_symbol (libc, __malloc_initialize_hook,
2027 __malloc_initialize_hook, GLIBC_2_0);
2028 #endif
2030 void weak_variable (*__free_hook) (void *__ptr,
2031 const void *) = NULL;
2032 void *weak_variable (*__malloc_hook)
2033 (size_t __size, const void *) = malloc_hook_ini;
2034 void *weak_variable (*__realloc_hook)
2035 (void *__ptr, size_t __size, const void *)
2036 = realloc_hook_ini;
2037 void *weak_variable (*__memalign_hook)
2038 (size_t __alignment, size_t __size, const void *)
2039 = memalign_hook_ini;
2040 void weak_variable (*__after_morecore_hook) (void) = NULL;
2042 /* This function is called from the arena shutdown hook, to free the
2043 thread cache (if it exists). */
2044 static void tcache_thread_shutdown (void);
2046 /* ------------------ Testing support ----------------------------------*/
2048 static int perturb_byte;
2050 static void
2051 alloc_perturb (char *p, size_t n)
2053 if (__glibc_unlikely (perturb_byte))
2054 memset (p, perturb_byte ^ 0xff, n);
2057 static void
2058 free_perturb (char *p, size_t n)
2060 if (__glibc_unlikely (perturb_byte))
2061 memset (p, perturb_byte, n);
2066 #include <stap-probe.h>
2068 /* ------------------- Support for multiple arenas -------------------- */
2069 #include "arena.c"
2072 Debugging support
2074 These routines make a number of assertions about the states
2075 of data structures that should be true at all times. If any
2076 are not true, it's very likely that a user program has somehow
2077 trashed memory. (It's also possible that there is a coding error
2078 in malloc. In which case, please report it!)
2081 #if !MALLOC_DEBUG
2083 # define check_chunk(A, P)
2084 # define check_free_chunk(A, P)
2085 # define check_inuse_chunk(A, P)
2086 # define check_remalloced_chunk(A, P, N)
2087 # define check_malloced_chunk(A, P, N)
2088 # define check_malloc_state(A)
2090 #else
2092 # define check_chunk(A, P) do_check_chunk (A, P)
2093 # define check_free_chunk(A, P) do_check_free_chunk (A, P)
2094 # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
2095 # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
2096 # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
2097 # define check_malloc_state(A) do_check_malloc_state (A)
2100 Properties of all chunks
2103 static void
2104 do_check_chunk (mstate av, mchunkptr p)
2106 unsigned long sz = chunksize (p);
2107 /* min and max possible addresses assuming contiguous allocation */
2108 char *max_address = (char *) (av->top) + chunksize (av->top);
2109 char *min_address = max_address - av->system_mem;
2111 if (!chunk_is_mmapped (p))
2113 /* Has legal address ... */
2114 if (p != av->top)
2116 if (contiguous (av))
2118 assert (((char *) p) >= min_address);
2119 assert (((char *) p + sz) <= ((char *) (av->top)));
2122 else
2124 /* top size is always at least MINSIZE */
2125 assert ((unsigned long) (sz) >= MINSIZE);
2126 /* top predecessor always marked inuse */
2127 assert (prev_inuse (p));
2130 else if (!DUMPED_MAIN_ARENA_CHUNK (p))
2132 /* address is outside main heap */
2133 if (contiguous (av) && av->top != initial_top (av))
2135 assert (((char *) p) < min_address || ((char *) p) >= max_address);
2137 /* chunk is page-aligned */
2138 assert (((prev_size (p) + sz) & (GLRO (dl_pagesize) - 1)) == 0);
2139 /* mem is aligned */
2140 assert (aligned_OK (chunk2mem (p)));
2145 Properties of free chunks
2148 static void
2149 do_check_free_chunk (mstate av, mchunkptr p)
2151 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2152 mchunkptr next = chunk_at_offset (p, sz);
2154 do_check_chunk (av, p);
2156 /* Chunk must claim to be free ... */
2157 assert (!inuse (p));
2158 assert (!chunk_is_mmapped (p));
2160 /* Unless a special marker, must have OK fields */
2161 if ((unsigned long) (sz) >= MINSIZE)
2163 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2164 assert (aligned_OK (chunk2mem (p)));
2165 /* ... matching footer field */
2166 assert (prev_size (next_chunk (p)) == sz);
2167 /* ... and is fully consolidated */
2168 assert (prev_inuse (p));
2169 assert (next == av->top || inuse (next));
2171 /* ... and has minimally sane links */
2172 assert (p->fd->bk == p);
2173 assert (p->bk->fd == p);
2175 else /* markers are always of size SIZE_SZ */
2176 assert (sz == SIZE_SZ);
2180 Properties of inuse chunks
2183 static void
2184 do_check_inuse_chunk (mstate av, mchunkptr p)
2186 mchunkptr next;
2188 do_check_chunk (av, p);
2190 if (chunk_is_mmapped (p))
2191 return; /* mmapped chunks have no next/prev */
2193 /* Check whether it claims to be in use ... */
2194 assert (inuse (p));
2196 next = next_chunk (p);
2198 /* ... and is surrounded by OK chunks.
2199 Since more things can be checked with free chunks than inuse ones,
2200 if an inuse chunk borders them and debug is on, it's worth doing them.
2202 if (!prev_inuse (p))
2204 /* Note that we cannot even look at prev unless it is not inuse */
2205 mchunkptr prv = prev_chunk (p);
2206 assert (next_chunk (prv) == p);
2207 do_check_free_chunk (av, prv);
2210 if (next == av->top)
2212 assert (prev_inuse (next));
2213 assert (chunksize (next) >= MINSIZE);
2215 else if (!inuse (next))
2216 do_check_free_chunk (av, next);
2220 Properties of chunks recycled from fastbins
2223 static void
2224 do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2226 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2228 if (!chunk_is_mmapped (p))
2230 assert (av == arena_for_chunk (p));
2231 if (chunk_main_arena (p))
2232 assert (av == &main_arena);
2233 else
2234 assert (av != &main_arena);
2237 do_check_inuse_chunk (av, p);
2239 /* Legal size ... */
2240 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2241 assert ((unsigned long) (sz) >= MINSIZE);
2242 /* ... and alignment */
2243 assert (aligned_OK (chunk2mem (p)));
2244 /* chunk is less than MINSIZE more than request */
2245 assert ((long) (sz) - (long) (s) >= 0);
2246 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2250 Properties of nonrecycled chunks at the point they are malloced
2253 static void
2254 do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2256 /* same as recycled case ... */
2257 do_check_remalloced_chunk (av, p, s);
2260 ... plus, must obey implementation invariant that prev_inuse is
2261 always true of any allocated chunk; i.e., that each allocated
2262 chunk borders either a previously allocated and still in-use
2263 chunk, or the base of its memory arena. This is ensured
2264 by making all allocations from the `lowest' part of any found
2265 chunk. This does not necessarily hold however for chunks
2266 recycled via fastbins.
2269 assert (prev_inuse (p));
2274 Properties of malloc_state.
2276 This may be useful for debugging malloc, as well as detecting user
2277 programmer errors that somehow write into malloc_state.
2279 If you are extending or experimenting with this malloc, you can
2280 probably figure out how to hack this routine to print out or
2281 display chunk addresses, sizes, bins, and other instrumentation.
2284 static void
2285 do_check_malloc_state (mstate av)
2287 int i;
2288 mchunkptr p;
2289 mchunkptr q;
2290 mbinptr b;
2291 unsigned int idx;
2292 INTERNAL_SIZE_T size;
2293 unsigned long total = 0;
2294 int max_fast_bin;
2296 /* internal size_t must be no wider than pointer type */
2297 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2299 /* alignment is a power of 2 */
2300 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2302 /* Check the arena is initialized. */
2303 assert (av->top != 0);
2305 /* No memory has been allocated yet, so doing more tests is not possible. */
2306 if (av->top == initial_top (av))
2307 return;
2309 /* pagesize is a power of 2 */
2310 assert (powerof2(GLRO (dl_pagesize)));
2312 /* A contiguous main_arena is consistent with sbrk_base. */
2313 if (av == &main_arena && contiguous (av))
2314 assert ((char *) mp_.sbrk_base + av->system_mem ==
2315 (char *) av->top + chunksize (av->top));
2317 /* properties of fastbins */
2319 /* max_fast is in allowed range */
2320 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2322 max_fast_bin = fastbin_index (get_max_fast ());
2324 for (i = 0; i < NFASTBINS; ++i)
2326 p = fastbin (av, i);
2328 /* The following test can only be performed for the main arena.
2329 While mallopt calls malloc_consolidate to get rid of all fast
2330 bins (especially those larger than the new maximum) this does
2331 only happen for the main arena. Trying to do this for any
2332 other arena would mean those arenas have to be locked and
2333 malloc_consolidate be called for them. This is excessive. And
2334 even if this is acceptable to somebody it still cannot solve
2335 the problem completely since if the arena is locked a
2336 concurrent malloc call might create a new arena which then
2337 could use the newly invalid fast bins. */
2339 /* all bins past max_fast are empty */
2340 if (av == &main_arena && i > max_fast_bin)
2341 assert (p == 0);
2343 while (p != 0)
2345 if (__glibc_unlikely (misaligned_chunk (p)))
2346 malloc_printerr ("do_check_malloc_state(): "
2347 "unaligned fastbin chunk detected");
2348 /* each chunk claims to be inuse */
2349 do_check_inuse_chunk (av, p);
2350 total += chunksize (p);
2351 /* chunk belongs in this bin */
2352 assert (fastbin_index (chunksize (p)) == i);
2353 p = REVEAL_PTR (p->fd);
2357 /* check normal bins */
2358 for (i = 1; i < NBINS; ++i)
2360 b = bin_at (av, i);
2362 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2363 if (i >= 2)
2365 unsigned int binbit = get_binmap (av, i);
2366 int empty = last (b) == b;
2367 if (!binbit)
2368 assert (empty);
2369 else if (!empty)
2370 assert (binbit);
2373 for (p = last (b); p != b; p = p->bk)
2375 /* each chunk claims to be free */
2376 do_check_free_chunk (av, p);
2377 size = chunksize (p);
2378 total += size;
2379 if (i >= 2)
2381 /* chunk belongs in bin */
2382 idx = bin_index (size);
2383 assert (idx == i);
2384 /* lists are sorted */
2385 assert (p->bk == b ||
2386 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2388 if (!in_smallbin_range (size))
2390 if (p->fd_nextsize != NULL)
2392 if (p->fd_nextsize == p)
2393 assert (p->bk_nextsize == p);
2394 else
2396 if (p->fd_nextsize == first (b))
2397 assert (chunksize (p) < chunksize (p->fd_nextsize));
2398 else
2399 assert (chunksize (p) > chunksize (p->fd_nextsize));
2401 if (p == first (b))
2402 assert (chunksize (p) > chunksize (p->bk_nextsize));
2403 else
2404 assert (chunksize (p) < chunksize (p->bk_nextsize));
2407 else
2408 assert (p->bk_nextsize == NULL);
2411 else if (!in_smallbin_range (size))
2412 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2413 /* chunk is followed by a legal chain of inuse chunks */
2414 for (q = next_chunk (p);
2415 (q != av->top && inuse (q) &&
2416 (unsigned long) (chunksize (q)) >= MINSIZE);
2417 q = next_chunk (q))
2418 do_check_inuse_chunk (av, q);
2422 /* top chunk is OK */
2423 check_chunk (av, av->top);
2425 #endif
2428 /* ----------------- Support for debugging hooks -------------------- */
2429 #include "hooks.c"
2432 /* ----------- Routines dealing with system allocation -------------- */
2435 sysmalloc handles malloc cases requiring more memory from the system.
2436 On entry, it is assumed that av->top does not have enough
2437 space to service request for nb bytes, thus requiring that av->top
2438 be extended or replaced.
2441 static void *
2442 sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2444 mchunkptr old_top; /* incoming value of av->top */
2445 INTERNAL_SIZE_T old_size; /* its size */
2446 char *old_end; /* its end address */
2448 long size; /* arg to first MORECORE or mmap call */
2449 char *brk; /* return value from MORECORE */
2451 long correction; /* arg to 2nd MORECORE call */
2452 char *snd_brk; /* 2nd return val */
2454 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2455 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2456 char *aligned_brk; /* aligned offset into brk */
2458 mchunkptr p; /* the allocated/returned chunk */
2459 mchunkptr remainder; /* remainder from allocation */
2460 unsigned long remainder_size; /* its size */
2463 size_t pagesize = GLRO (dl_pagesize);
2464 bool tried_mmap = false;
2468 If have mmap, and the request size meets the mmap threshold, and
2469 the system supports mmap, and there are few enough currently
2470 allocated mmapped regions, try to directly map this request
2471 rather than expanding top.
2474 if (av == NULL
2475 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2476 && (mp_.n_mmaps < mp_.n_mmaps_max)))
2478 char *mm; /* return value from mmap call*/
2480 try_mmap:
2482 Round up size to nearest page. For mmapped chunks, the overhead
2483 is one SIZE_SZ unit larger than for normal chunks, because there
2484 is no following chunk whose prev_size field could be used.
2486 See the front_misalign handling below, for glibc there is no
2487 need for further alignments unless we have have high alignment.
2489 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2490 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2491 else
2492 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2493 tried_mmap = true;
2495 /* Don't try if size wraps around 0 */
2496 if ((unsigned long) (size) > (unsigned long) (nb))
2498 mm = (char *) (MMAP (0, size,
2499 mtag_mmap_flags | PROT_READ | PROT_WRITE, 0));
2501 if (mm != MAP_FAILED)
2504 The offset to the start of the mmapped region is stored
2505 in the prev_size field of the chunk. This allows us to adjust
2506 returned start address to meet alignment requirements here
2507 and in memalign(), and still be able to compute proper
2508 address argument for later munmap in free() and realloc().
2511 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2513 /* For glibc, chunk2mem increases the address by
2514 CHUNK_HDR_SZ and MALLOC_ALIGN_MASK is
2515 CHUNK_HDR_SZ-1. Each mmap'ed area is page
2516 aligned and therefore definitely
2517 MALLOC_ALIGN_MASK-aligned. */
2518 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2519 front_misalign = 0;
2521 else
2522 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2523 if (front_misalign > 0)
2525 correction = MALLOC_ALIGNMENT - front_misalign;
2526 p = (mchunkptr) (mm + correction);
2527 set_prev_size (p, correction);
2528 set_head (p, (size - correction) | IS_MMAPPED);
2530 else
2532 p = (mchunkptr) mm;
2533 set_prev_size (p, 0);
2534 set_head (p, size | IS_MMAPPED);
2537 /* update statistics */
2539 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2540 atomic_max (&mp_.max_n_mmaps, new);
2542 unsigned long sum;
2543 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2544 atomic_max (&mp_.max_mmapped_mem, sum);
2546 check_chunk (av, p);
2548 return chunk2mem (p);
2553 /* There are no usable arenas and mmap also failed. */
2554 if (av == NULL)
2555 return 0;
2557 /* Record incoming configuration of top */
2559 old_top = av->top;
2560 old_size = chunksize (old_top);
2561 old_end = (char *) (chunk_at_offset (old_top, old_size));
2563 brk = snd_brk = (char *) (MORECORE_FAILURE);
2566 If not the first time through, we require old_size to be
2567 at least MINSIZE and to have prev_inuse set.
2570 assert ((old_top == initial_top (av) && old_size == 0) ||
2571 ((unsigned long) (old_size) >= MINSIZE &&
2572 prev_inuse (old_top) &&
2573 ((unsigned long) old_end & (pagesize - 1)) == 0));
2575 /* Precondition: not enough current space to satisfy nb request */
2576 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2579 if (av != &main_arena)
2581 heap_info *old_heap, *heap;
2582 size_t old_heap_size;
2584 /* First try to extend the current heap. */
2585 old_heap = heap_for_ptr (old_top);
2586 old_heap_size = old_heap->size;
2587 if ((long) (MINSIZE + nb - old_size) > 0
2588 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2590 av->system_mem += old_heap->size - old_heap_size;
2591 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2592 | PREV_INUSE);
2594 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2596 /* Use a newly allocated heap. */
2597 heap->ar_ptr = av;
2598 heap->prev = old_heap;
2599 av->system_mem += heap->size;
2600 /* Set up the new top. */
2601 top (av) = chunk_at_offset (heap, sizeof (*heap));
2602 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2604 /* Setup fencepost and free the old top chunk with a multiple of
2605 MALLOC_ALIGNMENT in size. */
2606 /* The fencepost takes at least MINSIZE bytes, because it might
2607 become the top chunk again later. Note that a footer is set
2608 up, too, although the chunk is marked in use. */
2609 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2610 set_head (chunk_at_offset (old_top, old_size + CHUNK_HDR_SZ),
2611 0 | PREV_INUSE);
2612 if (old_size >= MINSIZE)
2614 set_head (chunk_at_offset (old_top, old_size),
2615 CHUNK_HDR_SZ | PREV_INUSE);
2616 set_foot (chunk_at_offset (old_top, old_size), CHUNK_HDR_SZ);
2617 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2618 _int_free (av, old_top, 1);
2620 else
2622 set_head (old_top, (old_size + CHUNK_HDR_SZ) | PREV_INUSE);
2623 set_foot (old_top, (old_size + CHUNK_HDR_SZ));
2626 else if (!tried_mmap)
2627 /* We can at least try to use to mmap memory. */
2628 goto try_mmap;
2630 else /* av == main_arena */
2633 { /* Request enough space for nb + pad + overhead */
2634 size = nb + mp_.top_pad + MINSIZE;
2637 If contiguous, we can subtract out existing space that we hope to
2638 combine with new space. We add it back later only if
2639 we don't actually get contiguous space.
2642 if (contiguous (av))
2643 size -= old_size;
2646 Round to a multiple of page size.
2647 If MORECORE is not contiguous, this ensures that we only call it
2648 with whole-page arguments. And if MORECORE is contiguous and
2649 this is not first time through, this preserves page-alignment of
2650 previous calls. Otherwise, we correct to page-align below.
2653 size = ALIGN_UP (size, pagesize);
2656 Don't try to call MORECORE if argument is so big as to appear
2657 negative. Note that since mmap takes size_t arg, it may succeed
2658 below even if we cannot call MORECORE.
2661 if (size > 0)
2663 brk = (char *) (MORECORE (size));
2664 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2667 if (brk != (char *) (MORECORE_FAILURE))
2669 /* Call the `morecore' hook if necessary. */
2670 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2671 if (__builtin_expect (hook != NULL, 0))
2672 (*hook)();
2674 else
2677 If have mmap, try using it as a backup when MORECORE fails or
2678 cannot be used. This is worth doing on systems that have "holes" in
2679 address space, so sbrk cannot extend to give contiguous space, but
2680 space is available elsewhere. Note that we ignore mmap max count
2681 and threshold limits, since the space will not be used as a
2682 segregated mmap region.
2685 /* Cannot merge with old top, so add its size back in */
2686 if (contiguous (av))
2687 size = ALIGN_UP (size + old_size, pagesize);
2689 /* If we are relying on mmap as backup, then use larger units */
2690 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2691 size = MMAP_AS_MORECORE_SIZE;
2693 /* Don't try if size wraps around 0 */
2694 if ((unsigned long) (size) > (unsigned long) (nb))
2696 char *mbrk = (char *) (MMAP (0, size,
2697 mtag_mmap_flags | PROT_READ | PROT_WRITE,
2698 0));
2700 if (mbrk != MAP_FAILED)
2702 /* We do not need, and cannot use, another sbrk call to find end */
2703 brk = mbrk;
2704 snd_brk = brk + size;
2707 Record that we no longer have a contiguous sbrk region.
2708 After the first time mmap is used as backup, we do not
2709 ever rely on contiguous space since this could incorrectly
2710 bridge regions.
2712 set_noncontiguous (av);
2717 if (brk != (char *) (MORECORE_FAILURE))
2719 if (mp_.sbrk_base == 0)
2720 mp_.sbrk_base = brk;
2721 av->system_mem += size;
2724 If MORECORE extends previous space, we can likewise extend top size.
2727 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2728 set_head (old_top, (size + old_size) | PREV_INUSE);
2730 else if (contiguous (av) && old_size && brk < old_end)
2731 /* Oops! Someone else killed our space.. Can't touch anything. */
2732 malloc_printerr ("break adjusted to free malloc space");
2735 Otherwise, make adjustments:
2737 * If the first time through or noncontiguous, we need to call sbrk
2738 just to find out where the end of memory lies.
2740 * We need to ensure that all returned chunks from malloc will meet
2741 MALLOC_ALIGNMENT
2743 * If there was an intervening foreign sbrk, we need to adjust sbrk
2744 request size to account for fact that we will not be able to
2745 combine new space with existing space in old_top.
2747 * Almost all systems internally allocate whole pages at a time, in
2748 which case we might as well use the whole last page of request.
2749 So we allocate enough more memory to hit a page boundary now,
2750 which in turn causes future contiguous calls to page-align.
2753 else
2755 front_misalign = 0;
2756 end_misalign = 0;
2757 correction = 0;
2758 aligned_brk = brk;
2760 /* handle contiguous cases */
2761 if (contiguous (av))
2763 /* Count foreign sbrk as system_mem. */
2764 if (old_size)
2765 av->system_mem += brk - old_end;
2767 /* Guarantee alignment of first new chunk made from this space */
2769 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2770 if (front_misalign > 0)
2773 Skip over some bytes to arrive at an aligned position.
2774 We don't need to specially mark these wasted front bytes.
2775 They will never be accessed anyway because
2776 prev_inuse of av->top (and any chunk created from its start)
2777 is always true after initialization.
2780 correction = MALLOC_ALIGNMENT - front_misalign;
2781 aligned_brk += correction;
2785 If this isn't adjacent to existing space, then we will not
2786 be able to merge with old_top space, so must add to 2nd request.
2789 correction += old_size;
2791 /* Extend the end address to hit a page boundary */
2792 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2793 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2795 assert (correction >= 0);
2796 snd_brk = (char *) (MORECORE (correction));
2799 If can't allocate correction, try to at least find out current
2800 brk. It might be enough to proceed without failing.
2802 Note that if second sbrk did NOT fail, we assume that space
2803 is contiguous with first sbrk. This is a safe assumption unless
2804 program is multithreaded but doesn't use locks and a foreign sbrk
2805 occurred between our first and second calls.
2808 if (snd_brk == (char *) (MORECORE_FAILURE))
2810 correction = 0;
2811 snd_brk = (char *) (MORECORE (0));
2813 else
2815 /* Call the `morecore' hook if necessary. */
2816 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2817 if (__builtin_expect (hook != NULL, 0))
2818 (*hook)();
2822 /* handle non-contiguous cases */
2823 else
2825 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2826 /* MORECORE/mmap must correctly align */
2827 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2828 else
2830 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2831 if (front_misalign > 0)
2834 Skip over some bytes to arrive at an aligned position.
2835 We don't need to specially mark these wasted front bytes.
2836 They will never be accessed anyway because
2837 prev_inuse of av->top (and any chunk created from its start)
2838 is always true after initialization.
2841 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2845 /* Find out current end of memory */
2846 if (snd_brk == (char *) (MORECORE_FAILURE))
2848 snd_brk = (char *) (MORECORE (0));
2852 /* Adjust top based on results of second sbrk */
2853 if (snd_brk != (char *) (MORECORE_FAILURE))
2855 av->top = (mchunkptr) aligned_brk;
2856 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2857 av->system_mem += correction;
2860 If not the first time through, we either have a
2861 gap due to foreign sbrk or a non-contiguous region. Insert a
2862 double fencepost at old_top to prevent consolidation with space
2863 we don't own. These fenceposts are artificial chunks that are
2864 marked as inuse and are in any case too small to use. We need
2865 two to make sizes and alignments work out.
2868 if (old_size != 0)
2871 Shrink old_top to insert fenceposts, keeping size a
2872 multiple of MALLOC_ALIGNMENT. We know there is at least
2873 enough space in old_top to do this.
2875 old_size = (old_size - 2 * CHUNK_HDR_SZ) & ~MALLOC_ALIGN_MASK;
2876 set_head (old_top, old_size | PREV_INUSE);
2879 Note that the following assignments completely overwrite
2880 old_top when old_size was previously MINSIZE. This is
2881 intentional. We need the fencepost, even if old_top otherwise gets
2882 lost.
2884 set_head (chunk_at_offset (old_top, old_size),
2885 CHUNK_HDR_SZ | PREV_INUSE);
2886 set_head (chunk_at_offset (old_top,
2887 old_size + CHUNK_HDR_SZ),
2888 CHUNK_HDR_SZ | PREV_INUSE);
2890 /* If possible, release the rest. */
2891 if (old_size >= MINSIZE)
2893 _int_free (av, old_top, 1);
2899 } /* if (av != &main_arena) */
2901 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2902 av->max_system_mem = av->system_mem;
2903 check_malloc_state (av);
2905 /* finally, do the allocation */
2906 p = av->top;
2907 size = chunksize (p);
2909 /* check that one of the above allocation paths succeeded */
2910 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2912 remainder_size = size - nb;
2913 remainder = chunk_at_offset (p, nb);
2914 av->top = remainder;
2915 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2916 set_head (remainder, remainder_size | PREV_INUSE);
2917 check_malloced_chunk (av, p, nb);
2918 return chunk2mem (p);
2921 /* catch all failure paths */
2922 __set_errno (ENOMEM);
2923 return 0;
2928 systrim is an inverse of sorts to sysmalloc. It gives memory back
2929 to the system (via negative arguments to sbrk) if there is unused
2930 memory at the `high' end of the malloc pool. It is called
2931 automatically by free() when top space exceeds the trim
2932 threshold. It is also called by the public malloc_trim routine. It
2933 returns 1 if it actually released any memory, else 0.
2936 static int
2937 systrim (size_t pad, mstate av)
2939 long top_size; /* Amount of top-most memory */
2940 long extra; /* Amount to release */
2941 long released; /* Amount actually released */
2942 char *current_brk; /* address returned by pre-check sbrk call */
2943 char *new_brk; /* address returned by post-check sbrk call */
2944 size_t pagesize;
2945 long top_area;
2947 pagesize = GLRO (dl_pagesize);
2948 top_size = chunksize (av->top);
2950 top_area = top_size - MINSIZE - 1;
2951 if (top_area <= pad)
2952 return 0;
2954 /* Release in pagesize units and round down to the nearest page. */
2955 extra = ALIGN_DOWN(top_area - pad, pagesize);
2957 if (extra == 0)
2958 return 0;
2961 Only proceed if end of memory is where we last set it.
2962 This avoids problems if there were foreign sbrk calls.
2964 current_brk = (char *) (MORECORE (0));
2965 if (current_brk == (char *) (av->top) + top_size)
2968 Attempt to release memory. We ignore MORECORE return value,
2969 and instead call again to find out where new end of memory is.
2970 This avoids problems if first call releases less than we asked,
2971 of if failure somehow altered brk value. (We could still
2972 encounter problems if it altered brk in some very bad way,
2973 but the only thing we can do is adjust anyway, which will cause
2974 some downstream failure.)
2977 MORECORE (-extra);
2978 /* Call the `morecore' hook if necessary. */
2979 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2980 if (__builtin_expect (hook != NULL, 0))
2981 (*hook)();
2982 new_brk = (char *) (MORECORE (0));
2984 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2986 if (new_brk != (char *) MORECORE_FAILURE)
2988 released = (long) (current_brk - new_brk);
2990 if (released != 0)
2992 /* Success. Adjust top. */
2993 av->system_mem -= released;
2994 set_head (av->top, (top_size - released) | PREV_INUSE);
2995 check_malloc_state (av);
2996 return 1;
3000 return 0;
3003 static void
3004 munmap_chunk (mchunkptr p)
3006 size_t pagesize = GLRO (dl_pagesize);
3007 INTERNAL_SIZE_T size = chunksize (p);
3009 assert (chunk_is_mmapped (p));
3011 /* Do nothing if the chunk is a faked mmapped chunk in the dumped
3012 main arena. We never free this memory. */
3013 if (DUMPED_MAIN_ARENA_CHUNK (p))
3014 return;
3016 uintptr_t mem = (uintptr_t) chunk2mem (p);
3017 uintptr_t block = (uintptr_t) p - prev_size (p);
3018 size_t total_size = prev_size (p) + size;
3019 /* Unfortunately we have to do the compilers job by hand here. Normally
3020 we would test BLOCK and TOTAL-SIZE separately for compliance with the
3021 page size. But gcc does not recognize the optimization possibility
3022 (in the moment at least) so we combine the two values into one before
3023 the bit test. */
3024 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
3025 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
3026 malloc_printerr ("munmap_chunk(): invalid pointer");
3028 atomic_decrement (&mp_.n_mmaps);
3029 atomic_add (&mp_.mmapped_mem, -total_size);
3031 /* If munmap failed the process virtual memory address space is in a
3032 bad shape. Just leave the block hanging around, the process will
3033 terminate shortly anyway since not much can be done. */
3034 __munmap ((char *) block, total_size);
3037 #if HAVE_MREMAP
3039 static mchunkptr
3040 mremap_chunk (mchunkptr p, size_t new_size)
3042 size_t pagesize = GLRO (dl_pagesize);
3043 INTERNAL_SIZE_T offset = prev_size (p);
3044 INTERNAL_SIZE_T size = chunksize (p);
3045 char *cp;
3047 assert (chunk_is_mmapped (p));
3049 uintptr_t block = (uintptr_t) p - offset;
3050 uintptr_t mem = (uintptr_t) chunk2mem(p);
3051 size_t total_size = offset + size;
3052 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
3053 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
3054 malloc_printerr("mremap_chunk(): invalid pointer");
3056 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
3057 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
3059 /* No need to remap if the number of pages does not change. */
3060 if (total_size == new_size)
3061 return p;
3063 cp = (char *) __mremap ((char *) block, total_size, new_size,
3064 MREMAP_MAYMOVE);
3066 if (cp == MAP_FAILED)
3067 return 0;
3069 p = (mchunkptr) (cp + offset);
3071 assert (aligned_OK (chunk2mem (p)));
3073 assert (prev_size (p) == offset);
3074 set_head (p, (new_size - offset) | IS_MMAPPED);
3076 INTERNAL_SIZE_T new;
3077 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
3078 + new_size - size - offset;
3079 atomic_max (&mp_.max_mmapped_mem, new);
3080 return p;
3082 #endif /* HAVE_MREMAP */
3084 /*------------------------ Public wrappers. --------------------------------*/
3086 #if USE_TCACHE
3088 /* We overlay this structure on the user-data portion of a chunk when
3089 the chunk is stored in the per-thread cache. */
3090 typedef struct tcache_entry
3092 struct tcache_entry *next;
3093 /* This field exists to detect double frees. */
3094 struct tcache_perthread_struct *key;
3095 } tcache_entry;
3097 /* There is one of these for each thread, which contains the
3098 per-thread cache (hence "tcache_perthread_struct"). Keeping
3099 overall size low is mildly important. Note that COUNTS and ENTRIES
3100 are redundant (we could have just counted the linked list each
3101 time), this is for performance reasons. */
3102 typedef struct tcache_perthread_struct
3104 uint16_t counts[TCACHE_MAX_BINS];
3105 tcache_entry *entries[TCACHE_MAX_BINS];
3106 } tcache_perthread_struct;
3108 static __thread bool tcache_shutting_down = false;
3109 static __thread tcache_perthread_struct *tcache = NULL;
3111 /* Caller must ensure that we know tc_idx is valid and there's room
3112 for more chunks. */
3113 static __always_inline void
3114 tcache_put (mchunkptr chunk, size_t tc_idx)
3116 tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
3118 /* Mark this chunk as "in the tcache" so the test in _int_free will
3119 detect a double free. */
3120 e->key = tcache;
3122 e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]);
3123 tcache->entries[tc_idx] = e;
3124 ++(tcache->counts[tc_idx]);
3127 /* Caller must ensure that we know tc_idx is valid and there's
3128 available chunks to remove. */
3129 static __always_inline void *
3130 tcache_get (size_t tc_idx)
3132 tcache_entry *e = tcache->entries[tc_idx];
3133 if (__glibc_unlikely (!aligned_OK (e)))
3134 malloc_printerr ("malloc(): unaligned tcache chunk detected");
3135 tcache->entries[tc_idx] = REVEAL_PTR (e->next);
3136 --(tcache->counts[tc_idx]);
3137 e->key = NULL;
3138 return (void *) e;
3141 static void
3142 tcache_thread_shutdown (void)
3144 int i;
3145 tcache_perthread_struct *tcache_tmp = tcache;
3147 if (!tcache)
3148 return;
3150 /* Disable the tcache and prevent it from being reinitialized. */
3151 tcache = NULL;
3152 tcache_shutting_down = true;
3154 /* Free all of the entries and the tcache itself back to the arena
3155 heap for coalescing. */
3156 for (i = 0; i < TCACHE_MAX_BINS; ++i)
3158 while (tcache_tmp->entries[i])
3160 tcache_entry *e = tcache_tmp->entries[i];
3161 if (__glibc_unlikely (!aligned_OK (e)))
3162 malloc_printerr ("tcache_thread_shutdown(): "
3163 "unaligned tcache chunk detected");
3164 tcache_tmp->entries[i] = REVEAL_PTR (e->next);
3165 __libc_free (e);
3169 __libc_free (tcache_tmp);
3172 static void
3173 tcache_init(void)
3175 mstate ar_ptr;
3176 void *victim = 0;
3177 const size_t bytes = sizeof (tcache_perthread_struct);
3179 if (tcache_shutting_down)
3180 return;
3182 arena_get (ar_ptr, bytes);
3183 victim = _int_malloc (ar_ptr, bytes);
3184 if (!victim && ar_ptr != NULL)
3186 ar_ptr = arena_get_retry (ar_ptr, bytes);
3187 victim = _int_malloc (ar_ptr, bytes);
3191 if (ar_ptr != NULL)
3192 __libc_lock_unlock (ar_ptr->mutex);
3194 /* In a low memory situation, we may not be able to allocate memory
3195 - in which case, we just keep trying later. However, we
3196 typically do this very early, so either there is sufficient
3197 memory, or there isn't enough memory to do non-trivial
3198 allocations anyway. */
3199 if (victim)
3201 tcache = (tcache_perthread_struct *) victim;
3202 memset (tcache, 0, sizeof (tcache_perthread_struct));
3207 # define MAYBE_INIT_TCACHE() \
3208 if (__glibc_unlikely (tcache == NULL)) \
3209 tcache_init();
3211 #else /* !USE_TCACHE */
3212 # define MAYBE_INIT_TCACHE()
3214 static void
3215 tcache_thread_shutdown (void)
3217 /* Nothing to do if there is no thread cache. */
3220 #endif /* !USE_TCACHE */
3222 void *
3223 __libc_malloc (size_t bytes)
3225 mstate ar_ptr;
3226 void *victim;
3228 _Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2,
3229 "PTRDIFF_MAX is not more than half of SIZE_MAX");
3231 void *(*hook) (size_t, const void *)
3232 = atomic_forced_read (__malloc_hook);
3233 if (__builtin_expect (hook != NULL, 0))
3234 return (*hook)(bytes, RETURN_ADDRESS (0));
3235 #if USE_TCACHE
3236 /* int_free also calls request2size, be careful to not pad twice. */
3237 size_t tbytes;
3238 if (!checked_request2size (bytes, &tbytes))
3240 __set_errno (ENOMEM);
3241 return NULL;
3243 size_t tc_idx = csize2tidx (tbytes);
3245 MAYBE_INIT_TCACHE ();
3247 DIAG_PUSH_NEEDS_COMMENT;
3248 if (tc_idx < mp_.tcache_bins
3249 && tcache
3250 && tcache->counts[tc_idx] > 0)
3252 victim = tcache_get (tc_idx);
3253 return tag_new_usable (victim);
3255 DIAG_POP_NEEDS_COMMENT;
3256 #endif
3258 if (SINGLE_THREAD_P)
3260 victim = tag_new_usable (_int_malloc (&main_arena, bytes));
3261 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3262 &main_arena == arena_for_chunk (mem2chunk (victim)));
3263 return victim;
3266 arena_get (ar_ptr, bytes);
3268 victim = _int_malloc (ar_ptr, bytes);
3269 /* Retry with another arena only if we were able to find a usable arena
3270 before. */
3271 if (!victim && ar_ptr != NULL)
3273 LIBC_PROBE (memory_malloc_retry, 1, bytes);
3274 ar_ptr = arena_get_retry (ar_ptr, bytes);
3275 victim = _int_malloc (ar_ptr, bytes);
3278 if (ar_ptr != NULL)
3279 __libc_lock_unlock (ar_ptr->mutex);
3281 victim = tag_new_usable (victim);
3283 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3284 ar_ptr == arena_for_chunk (mem2chunk (victim)));
3285 return victim;
3287 libc_hidden_def (__libc_malloc)
3289 void
3290 __libc_free (void *mem)
3292 mstate ar_ptr;
3293 mchunkptr p; /* chunk corresponding to mem */
3295 void (*hook) (void *, const void *)
3296 = atomic_forced_read (__free_hook);
3297 if (__builtin_expect (hook != NULL, 0))
3299 (*hook)(mem, RETURN_ADDRESS (0));
3300 return;
3303 if (mem == 0) /* free(0) has no effect */
3304 return;
3306 /* Quickly check that the freed pointer matches the tag for the memory.
3307 This gives a useful double-free detection. */
3308 if (__glibc_unlikely (mtag_enabled))
3309 *(volatile char *)mem;
3311 int err = errno;
3313 p = mem2chunk (mem);
3315 if (chunk_is_mmapped (p)) /* release mmapped memory. */
3317 /* See if the dynamic brk/mmap threshold needs adjusting.
3318 Dumped fake mmapped chunks do not affect the threshold. */
3319 if (!mp_.no_dyn_threshold
3320 && chunksize_nomask (p) > mp_.mmap_threshold
3321 && chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX
3322 && !DUMPED_MAIN_ARENA_CHUNK (p))
3324 mp_.mmap_threshold = chunksize (p);
3325 mp_.trim_threshold = 2 * mp_.mmap_threshold;
3326 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
3327 mp_.mmap_threshold, mp_.trim_threshold);
3329 munmap_chunk (p);
3331 else
3333 MAYBE_INIT_TCACHE ();
3335 /* Mark the chunk as belonging to the library again. */
3336 (void)tag_region (chunk2mem (p), memsize (p));
3338 ar_ptr = arena_for_chunk (p);
3339 _int_free (ar_ptr, p, 0);
3342 __set_errno (err);
3344 libc_hidden_def (__libc_free)
3346 void *
3347 __libc_realloc (void *oldmem, size_t bytes)
3349 mstate ar_ptr;
3350 INTERNAL_SIZE_T nb; /* padded request size */
3352 void *newp; /* chunk to return */
3354 void *(*hook) (void *, size_t, const void *) =
3355 atomic_forced_read (__realloc_hook);
3356 if (__builtin_expect (hook != NULL, 0))
3357 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
3359 #if REALLOC_ZERO_BYTES_FREES
3360 if (bytes == 0 && oldmem != NULL)
3362 __libc_free (oldmem); return 0;
3364 #endif
3366 /* realloc of null is supposed to be same as malloc */
3367 if (oldmem == 0)
3368 return __libc_malloc (bytes);
3370 /* Perform a quick check to ensure that the pointer's tag matches the
3371 memory's tag. */
3372 if (__glibc_unlikely (mtag_enabled))
3373 *(volatile char*) oldmem;
3375 /* chunk corresponding to oldmem */
3376 const mchunkptr oldp = mem2chunk (oldmem);
3377 /* its size */
3378 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
3380 if (chunk_is_mmapped (oldp))
3381 ar_ptr = NULL;
3382 else
3384 MAYBE_INIT_TCACHE ();
3385 ar_ptr = arena_for_chunk (oldp);
3388 /* Little security check which won't hurt performance: the allocator
3389 never wrapps around at the end of the address space. Therefore
3390 we can exclude some size values which might appear here by
3391 accident or by "design" from some intruder. We need to bypass
3392 this check for dumped fake mmap chunks from the old main arena
3393 because the new malloc may provide additional alignment. */
3394 if ((__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
3395 || __builtin_expect (misaligned_chunk (oldp), 0))
3396 && !DUMPED_MAIN_ARENA_CHUNK (oldp))
3397 malloc_printerr ("realloc(): invalid pointer");
3399 if (!checked_request2size (bytes, &nb))
3401 __set_errno (ENOMEM);
3402 return NULL;
3405 if (chunk_is_mmapped (oldp))
3407 /* If this is a faked mmapped chunk from the dumped main arena,
3408 always make a copy (and do not free the old chunk). */
3409 if (DUMPED_MAIN_ARENA_CHUNK (oldp))
3411 /* Must alloc, copy, free. */
3412 void *newmem = __libc_malloc (bytes);
3413 if (newmem == 0)
3414 return NULL;
3415 /* Copy as many bytes as are available from the old chunk
3416 and fit into the new size. NB: The overhead for faked
3417 mmapped chunks is only SIZE_SZ, not CHUNK_HDR_SZ as for
3418 regular mmapped chunks. */
3419 if (bytes > oldsize - SIZE_SZ)
3420 bytes = oldsize - SIZE_SZ;
3421 memcpy (newmem, oldmem, bytes);
3422 return newmem;
3425 void *newmem;
3427 #if HAVE_MREMAP
3428 newp = mremap_chunk (oldp, nb);
3429 if (newp)
3431 void *newmem = chunk2mem_tag (newp);
3432 /* Give the new block a different tag. This helps to ensure
3433 that stale handles to the previous mapping are not
3434 reused. There's a performance hit for both us and the
3435 caller for doing this, so we might want to
3436 reconsider. */
3437 return tag_new_usable (newmem);
3439 #endif
3440 /* Note the extra SIZE_SZ overhead. */
3441 if (oldsize - SIZE_SZ >= nb)
3442 return oldmem; /* do nothing */
3444 /* Must alloc, copy, free. */
3445 newmem = __libc_malloc (bytes);
3446 if (newmem == 0)
3447 return 0; /* propagate failure */
3449 memcpy (newmem, oldmem, oldsize - CHUNK_HDR_SZ);
3450 munmap_chunk (oldp);
3451 return newmem;
3454 if (SINGLE_THREAD_P)
3456 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3457 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3458 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3460 return newp;
3463 __libc_lock_lock (ar_ptr->mutex);
3465 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3467 __libc_lock_unlock (ar_ptr->mutex);
3468 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3469 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3471 if (newp == NULL)
3473 /* Try harder to allocate memory in other arenas. */
3474 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3475 newp = __libc_malloc (bytes);
3476 if (newp != NULL)
3478 size_t sz = memsize (oldp);
3479 memcpy (newp, oldmem, sz);
3480 (void) tag_region (chunk2mem (oldp), sz);
3481 _int_free (ar_ptr, oldp, 0);
3485 return newp;
3487 libc_hidden_def (__libc_realloc)
3489 void *
3490 __libc_memalign (size_t alignment, size_t bytes)
3492 void *address = RETURN_ADDRESS (0);
3493 return _mid_memalign (alignment, bytes, address);
3496 static void *
3497 _mid_memalign (size_t alignment, size_t bytes, void *address)
3499 mstate ar_ptr;
3500 void *p;
3502 void *(*hook) (size_t, size_t, const void *) =
3503 atomic_forced_read (__memalign_hook);
3504 if (__builtin_expect (hook != NULL, 0))
3505 return (*hook)(alignment, bytes, address);
3507 /* If we need less alignment than we give anyway, just relay to malloc. */
3508 if (alignment <= MALLOC_ALIGNMENT)
3509 return __libc_malloc (bytes);
3511 /* Otherwise, ensure that it is at least a minimum chunk size */
3512 if (alignment < MINSIZE)
3513 alignment = MINSIZE;
3515 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3516 power of 2 and will cause overflow in the check below. */
3517 if (alignment > SIZE_MAX / 2 + 1)
3519 __set_errno (EINVAL);
3520 return 0;
3524 /* Make sure alignment is power of 2. */
3525 if (!powerof2 (alignment))
3527 size_t a = MALLOC_ALIGNMENT * 2;
3528 while (a < alignment)
3529 a <<= 1;
3530 alignment = a;
3533 if (SINGLE_THREAD_P)
3535 p = _int_memalign (&main_arena, alignment, bytes);
3536 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3537 &main_arena == arena_for_chunk (mem2chunk (p)));
3538 return tag_new_usable (p);
3541 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3543 p = _int_memalign (ar_ptr, alignment, bytes);
3544 if (!p && ar_ptr != NULL)
3546 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3547 ar_ptr = arena_get_retry (ar_ptr, bytes);
3548 p = _int_memalign (ar_ptr, alignment, bytes);
3551 if (ar_ptr != NULL)
3552 __libc_lock_unlock (ar_ptr->mutex);
3554 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3555 ar_ptr == arena_for_chunk (mem2chunk (p)));
3556 return tag_new_usable (p);
3558 /* For ISO C11. */
3559 weak_alias (__libc_memalign, aligned_alloc)
3560 libc_hidden_def (__libc_memalign)
3562 void *
3563 __libc_valloc (size_t bytes)
3565 if (__malloc_initialized < 0)
3566 ptmalloc_init ();
3568 void *address = RETURN_ADDRESS (0);
3569 size_t pagesize = GLRO (dl_pagesize);
3570 return _mid_memalign (pagesize, bytes, address);
3573 void *
3574 __libc_pvalloc (size_t bytes)
3576 if (__malloc_initialized < 0)
3577 ptmalloc_init ();
3579 void *address = RETURN_ADDRESS (0);
3580 size_t pagesize = GLRO (dl_pagesize);
3581 size_t rounded_bytes;
3582 /* ALIGN_UP with overflow check. */
3583 if (__glibc_unlikely (__builtin_add_overflow (bytes,
3584 pagesize - 1,
3585 &rounded_bytes)))
3587 __set_errno (ENOMEM);
3588 return 0;
3590 rounded_bytes = rounded_bytes & -(pagesize - 1);
3592 return _mid_memalign (pagesize, rounded_bytes, address);
3595 void *
3596 __libc_calloc (size_t n, size_t elem_size)
3598 mstate av;
3599 mchunkptr oldtop;
3600 INTERNAL_SIZE_T sz, oldtopsize;
3601 void *mem;
3602 unsigned long clearsize;
3603 unsigned long nclears;
3604 INTERNAL_SIZE_T *d;
3605 ptrdiff_t bytes;
3607 if (__glibc_unlikely (__builtin_mul_overflow (n, elem_size, &bytes)))
3609 __set_errno (ENOMEM);
3610 return NULL;
3613 sz = bytes;
3615 void *(*hook) (size_t, const void *) =
3616 atomic_forced_read (__malloc_hook);
3617 if (__builtin_expect (hook != NULL, 0))
3619 mem = (*hook)(sz, RETURN_ADDRESS (0));
3620 if (mem == 0)
3621 return 0;
3623 return memset (mem, 0, sz);
3626 MAYBE_INIT_TCACHE ();
3628 if (SINGLE_THREAD_P)
3629 av = &main_arena;
3630 else
3631 arena_get (av, sz);
3633 if (av)
3635 /* Check if we hand out the top chunk, in which case there may be no
3636 need to clear. */
3637 #if MORECORE_CLEARS
3638 oldtop = top (av);
3639 oldtopsize = chunksize (top (av));
3640 # if MORECORE_CLEARS < 2
3641 /* Only newly allocated memory is guaranteed to be cleared. */
3642 if (av == &main_arena &&
3643 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3644 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3645 # endif
3646 if (av != &main_arena)
3648 heap_info *heap = heap_for_ptr (oldtop);
3649 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3650 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3652 #endif
3654 else
3656 /* No usable arenas. */
3657 oldtop = 0;
3658 oldtopsize = 0;
3660 mem = _int_malloc (av, sz);
3662 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3663 av == arena_for_chunk (mem2chunk (mem)));
3665 if (!SINGLE_THREAD_P)
3667 if (mem == 0 && av != NULL)
3669 LIBC_PROBE (memory_calloc_retry, 1, sz);
3670 av = arena_get_retry (av, sz);
3671 mem = _int_malloc (av, sz);
3674 if (av != NULL)
3675 __libc_lock_unlock (av->mutex);
3678 /* Allocation failed even after a retry. */
3679 if (mem == 0)
3680 return 0;
3682 mchunkptr p = mem2chunk (mem);
3684 /* If we are using memory tagging, then we need to set the tags
3685 regardless of MORECORE_CLEARS, so we zero the whole block while
3686 doing so. */
3687 if (__glibc_unlikely (mtag_enabled))
3688 return tag_new_zero_region (mem, memsize (p));
3690 INTERNAL_SIZE_T csz = chunksize (p);
3692 /* Two optional cases in which clearing not necessary */
3693 if (chunk_is_mmapped (p))
3695 if (__builtin_expect (perturb_byte, 0))
3696 return memset (mem, 0, sz);
3698 return mem;
3701 #if MORECORE_CLEARS
3702 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3704 /* clear only the bytes from non-freshly-sbrked memory */
3705 csz = oldtopsize;
3707 #endif
3709 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3710 contents have an odd number of INTERNAL_SIZE_T-sized words;
3711 minimally 3. */
3712 d = (INTERNAL_SIZE_T *) mem;
3713 clearsize = csz - SIZE_SZ;
3714 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3715 assert (nclears >= 3);
3717 if (nclears > 9)
3718 return memset (d, 0, clearsize);
3720 else
3722 *(d + 0) = 0;
3723 *(d + 1) = 0;
3724 *(d + 2) = 0;
3725 if (nclears > 4)
3727 *(d + 3) = 0;
3728 *(d + 4) = 0;
3729 if (nclears > 6)
3731 *(d + 5) = 0;
3732 *(d + 6) = 0;
3733 if (nclears > 8)
3735 *(d + 7) = 0;
3736 *(d + 8) = 0;
3742 return mem;
3746 ------------------------------ malloc ------------------------------
3749 static void *
3750 _int_malloc (mstate av, size_t bytes)
3752 INTERNAL_SIZE_T nb; /* normalized request size */
3753 unsigned int idx; /* associated bin index */
3754 mbinptr bin; /* associated bin */
3756 mchunkptr victim; /* inspected/selected chunk */
3757 INTERNAL_SIZE_T size; /* its size */
3758 int victim_index; /* its bin index */
3760 mchunkptr remainder; /* remainder from a split */
3761 unsigned long remainder_size; /* its size */
3763 unsigned int block; /* bit map traverser */
3764 unsigned int bit; /* bit map traverser */
3765 unsigned int map; /* current word of binmap */
3767 mchunkptr fwd; /* misc temp for linking */
3768 mchunkptr bck; /* misc temp for linking */
3770 #if USE_TCACHE
3771 size_t tcache_unsorted_count; /* count of unsorted chunks processed */
3772 #endif
3775 Convert request size to internal form by adding SIZE_SZ bytes
3776 overhead plus possibly more to obtain necessary alignment and/or
3777 to obtain a size of at least MINSIZE, the smallest allocatable
3778 size. Also, checked_request2size returns false for request sizes
3779 that are so large that they wrap around zero when padded and
3780 aligned.
3783 if (!checked_request2size (bytes, &nb))
3785 __set_errno (ENOMEM);
3786 return NULL;
3789 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3790 mmap. */
3791 if (__glibc_unlikely (av == NULL))
3793 void *p = sysmalloc (nb, av);
3794 if (p != NULL)
3795 alloc_perturb (p, bytes);
3796 return p;
3800 If the size qualifies as a fastbin, first check corresponding bin.
3801 This code is safe to execute even if av is not yet initialized, so we
3802 can try it without checking, which saves some time on this fast path.
3805 #define REMOVE_FB(fb, victim, pp) \
3806 do \
3808 victim = pp; \
3809 if (victim == NULL) \
3810 break; \
3811 pp = REVEAL_PTR (victim->fd); \
3812 if (__glibc_unlikely (pp != NULL && misaligned_chunk (pp))) \
3813 malloc_printerr ("malloc(): unaligned fastbin chunk detected"); \
3815 while ((pp = catomic_compare_and_exchange_val_acq (fb, pp, victim)) \
3816 != victim); \
3818 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3820 idx = fastbin_index (nb);
3821 mfastbinptr *fb = &fastbin (av, idx);
3822 mchunkptr pp;
3823 victim = *fb;
3825 if (victim != NULL)
3827 if (__glibc_unlikely (misaligned_chunk (victim)))
3828 malloc_printerr ("malloc(): unaligned fastbin chunk detected 2");
3830 if (SINGLE_THREAD_P)
3831 *fb = REVEAL_PTR (victim->fd);
3832 else
3833 REMOVE_FB (fb, pp, victim);
3834 if (__glibc_likely (victim != NULL))
3836 size_t victim_idx = fastbin_index (chunksize (victim));
3837 if (__builtin_expect (victim_idx != idx, 0))
3838 malloc_printerr ("malloc(): memory corruption (fast)");
3839 check_remalloced_chunk (av, victim, nb);
3840 #if USE_TCACHE
3841 /* While we're here, if we see other chunks of the same size,
3842 stash them in the tcache. */
3843 size_t tc_idx = csize2tidx (nb);
3844 if (tcache && tc_idx < mp_.tcache_bins)
3846 mchunkptr tc_victim;
3848 /* While bin not empty and tcache not full, copy chunks. */
3849 while (tcache->counts[tc_idx] < mp_.tcache_count
3850 && (tc_victim = *fb) != NULL)
3852 if (__glibc_unlikely (misaligned_chunk (tc_victim)))
3853 malloc_printerr ("malloc(): unaligned fastbin chunk detected 3");
3854 if (SINGLE_THREAD_P)
3855 *fb = REVEAL_PTR (tc_victim->fd);
3856 else
3858 REMOVE_FB (fb, pp, tc_victim);
3859 if (__glibc_unlikely (tc_victim == NULL))
3860 break;
3862 tcache_put (tc_victim, tc_idx);
3865 #endif
3866 void *p = chunk2mem (victim);
3867 alloc_perturb (p, bytes);
3868 return p;
3874 If a small request, check regular bin. Since these "smallbins"
3875 hold one size each, no searching within bins is necessary.
3876 (For a large request, we need to wait until unsorted chunks are
3877 processed to find best fit. But for small ones, fits are exact
3878 anyway, so we can check now, which is faster.)
3881 if (in_smallbin_range (nb))
3883 idx = smallbin_index (nb);
3884 bin = bin_at (av, idx);
3886 if ((victim = last (bin)) != bin)
3888 bck = victim->bk;
3889 if (__glibc_unlikely (bck->fd != victim))
3890 malloc_printerr ("malloc(): smallbin double linked list corrupted");
3891 set_inuse_bit_at_offset (victim, nb);
3892 bin->bk = bck;
3893 bck->fd = bin;
3895 if (av != &main_arena)
3896 set_non_main_arena (victim);
3897 check_malloced_chunk (av, victim, nb);
3898 #if USE_TCACHE
3899 /* While we're here, if we see other chunks of the same size,
3900 stash them in the tcache. */
3901 size_t tc_idx = csize2tidx (nb);
3902 if (tcache && tc_idx < mp_.tcache_bins)
3904 mchunkptr tc_victim;
3906 /* While bin not empty and tcache not full, copy chunks over. */
3907 while (tcache->counts[tc_idx] < mp_.tcache_count
3908 && (tc_victim = last (bin)) != bin)
3910 if (tc_victim != 0)
3912 bck = tc_victim->bk;
3913 set_inuse_bit_at_offset (tc_victim, nb);
3914 if (av != &main_arena)
3915 set_non_main_arena (tc_victim);
3916 bin->bk = bck;
3917 bck->fd = bin;
3919 tcache_put (tc_victim, tc_idx);
3923 #endif
3924 void *p = chunk2mem (victim);
3925 alloc_perturb (p, bytes);
3926 return p;
3931 If this is a large request, consolidate fastbins before continuing.
3932 While it might look excessive to kill all fastbins before
3933 even seeing if there is space available, this avoids
3934 fragmentation problems normally associated with fastbins.
3935 Also, in practice, programs tend to have runs of either small or
3936 large requests, but less often mixtures, so consolidation is not
3937 invoked all that often in most programs. And the programs that
3938 it is called frequently in otherwise tend to fragment.
3941 else
3943 idx = largebin_index (nb);
3944 if (atomic_load_relaxed (&av->have_fastchunks))
3945 malloc_consolidate (av);
3949 Process recently freed or remaindered chunks, taking one only if
3950 it is exact fit, or, if this a small request, the chunk is remainder from
3951 the most recent non-exact fit. Place other traversed chunks in
3952 bins. Note that this step is the only place in any routine where
3953 chunks are placed in bins.
3955 The outer loop here is needed because we might not realize until
3956 near the end of malloc that we should have consolidated, so must
3957 do so and retry. This happens at most once, and only when we would
3958 otherwise need to expand memory to service a "small" request.
3961 #if USE_TCACHE
3962 INTERNAL_SIZE_T tcache_nb = 0;
3963 size_t tc_idx = csize2tidx (nb);
3964 if (tcache && tc_idx < mp_.tcache_bins)
3965 tcache_nb = nb;
3966 int return_cached = 0;
3968 tcache_unsorted_count = 0;
3969 #endif
3971 for (;; )
3973 int iters = 0;
3974 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3976 bck = victim->bk;
3977 size = chunksize (victim);
3978 mchunkptr next = chunk_at_offset (victim, size);
3980 if (__glibc_unlikely (size <= CHUNK_HDR_SZ)
3981 || __glibc_unlikely (size > av->system_mem))
3982 malloc_printerr ("malloc(): invalid size (unsorted)");
3983 if (__glibc_unlikely (chunksize_nomask (next) < CHUNK_HDR_SZ)
3984 || __glibc_unlikely (chunksize_nomask (next) > av->system_mem))
3985 malloc_printerr ("malloc(): invalid next size (unsorted)");
3986 if (__glibc_unlikely ((prev_size (next) & ~(SIZE_BITS)) != size))
3987 malloc_printerr ("malloc(): mismatching next->prev_size (unsorted)");
3988 if (__glibc_unlikely (bck->fd != victim)
3989 || __glibc_unlikely (victim->fd != unsorted_chunks (av)))
3990 malloc_printerr ("malloc(): unsorted double linked list corrupted");
3991 if (__glibc_unlikely (prev_inuse (next)))
3992 malloc_printerr ("malloc(): invalid next->prev_inuse (unsorted)");
3995 If a small request, try to use last remainder if it is the
3996 only chunk in unsorted bin. This helps promote locality for
3997 runs of consecutive small requests. This is the only
3998 exception to best-fit, and applies only when there is
3999 no exact fit for a small chunk.
4002 if (in_smallbin_range (nb) &&
4003 bck == unsorted_chunks (av) &&
4004 victim == av->last_remainder &&
4005 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4007 /* split and reattach remainder */
4008 remainder_size = size - nb;
4009 remainder = chunk_at_offset (victim, nb);
4010 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
4011 av->last_remainder = remainder;
4012 remainder->bk = remainder->fd = unsorted_chunks (av);
4013 if (!in_smallbin_range (remainder_size))
4015 remainder->fd_nextsize = NULL;
4016 remainder->bk_nextsize = NULL;
4019 set_head (victim, nb | PREV_INUSE |
4020 (av != &main_arena ? NON_MAIN_ARENA : 0));
4021 set_head (remainder, remainder_size | PREV_INUSE);
4022 set_foot (remainder, remainder_size);
4024 check_malloced_chunk (av, victim, nb);
4025 void *p = chunk2mem (victim);
4026 alloc_perturb (p, bytes);
4027 return p;
4030 /* remove from unsorted list */
4031 if (__glibc_unlikely (bck->fd != victim))
4032 malloc_printerr ("malloc(): corrupted unsorted chunks 3");
4033 unsorted_chunks (av)->bk = bck;
4034 bck->fd = unsorted_chunks (av);
4036 /* Take now instead of binning if exact fit */
4038 if (size == nb)
4040 set_inuse_bit_at_offset (victim, size);
4041 if (av != &main_arena)
4042 set_non_main_arena (victim);
4043 #if USE_TCACHE
4044 /* Fill cache first, return to user only if cache fills.
4045 We may return one of these chunks later. */
4046 if (tcache_nb
4047 && tcache->counts[tc_idx] < mp_.tcache_count)
4049 tcache_put (victim, tc_idx);
4050 return_cached = 1;
4051 continue;
4053 else
4055 #endif
4056 check_malloced_chunk (av, victim, nb);
4057 void *p = chunk2mem (victim);
4058 alloc_perturb (p, bytes);
4059 return p;
4060 #if USE_TCACHE
4062 #endif
4065 /* place chunk in bin */
4067 if (in_smallbin_range (size))
4069 victim_index = smallbin_index (size);
4070 bck = bin_at (av, victim_index);
4071 fwd = bck->fd;
4073 else
4075 victim_index = largebin_index (size);
4076 bck = bin_at (av, victim_index);
4077 fwd = bck->fd;
4079 /* maintain large bins in sorted order */
4080 if (fwd != bck)
4082 /* Or with inuse bit to speed comparisons */
4083 size |= PREV_INUSE;
4084 /* if smaller than smallest, bypass loop below */
4085 assert (chunk_main_arena (bck->bk));
4086 if ((unsigned long) (size)
4087 < (unsigned long) chunksize_nomask (bck->bk))
4089 fwd = bck;
4090 bck = bck->bk;
4092 victim->fd_nextsize = fwd->fd;
4093 victim->bk_nextsize = fwd->fd->bk_nextsize;
4094 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
4096 else
4098 assert (chunk_main_arena (fwd));
4099 while ((unsigned long) size < chunksize_nomask (fwd))
4101 fwd = fwd->fd_nextsize;
4102 assert (chunk_main_arena (fwd));
4105 if ((unsigned long) size
4106 == (unsigned long) chunksize_nomask (fwd))
4107 /* Always insert in the second position. */
4108 fwd = fwd->fd;
4109 else
4111 victim->fd_nextsize = fwd;
4112 victim->bk_nextsize = fwd->bk_nextsize;
4113 if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd))
4114 malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)");
4115 fwd->bk_nextsize = victim;
4116 victim->bk_nextsize->fd_nextsize = victim;
4118 bck = fwd->bk;
4119 if (bck->fd != fwd)
4120 malloc_printerr ("malloc(): largebin double linked list corrupted (bk)");
4123 else
4124 victim->fd_nextsize = victim->bk_nextsize = victim;
4127 mark_bin (av, victim_index);
4128 victim->bk = bck;
4129 victim->fd = fwd;
4130 fwd->bk = victim;
4131 bck->fd = victim;
4133 #if USE_TCACHE
4134 /* If we've processed as many chunks as we're allowed while
4135 filling the cache, return one of the cached ones. */
4136 ++tcache_unsorted_count;
4137 if (return_cached
4138 && mp_.tcache_unsorted_limit > 0
4139 && tcache_unsorted_count > mp_.tcache_unsorted_limit)
4141 return tcache_get (tc_idx);
4143 #endif
4145 #define MAX_ITERS 10000
4146 if (++iters >= MAX_ITERS)
4147 break;
4150 #if USE_TCACHE
4151 /* If all the small chunks we found ended up cached, return one now. */
4152 if (return_cached)
4154 return tcache_get (tc_idx);
4156 #endif
4159 If a large request, scan through the chunks of current bin in
4160 sorted order to find smallest that fits. Use the skip list for this.
4163 if (!in_smallbin_range (nb))
4165 bin = bin_at (av, idx);
4167 /* skip scan if empty or largest chunk is too small */
4168 if ((victim = first (bin)) != bin
4169 && (unsigned long) chunksize_nomask (victim)
4170 >= (unsigned long) (nb))
4172 victim = victim->bk_nextsize;
4173 while (((unsigned long) (size = chunksize (victim)) <
4174 (unsigned long) (nb)))
4175 victim = victim->bk_nextsize;
4177 /* Avoid removing the first entry for a size so that the skip
4178 list does not have to be rerouted. */
4179 if (victim != last (bin)
4180 && chunksize_nomask (victim)
4181 == chunksize_nomask (victim->fd))
4182 victim = victim->fd;
4184 remainder_size = size - nb;
4185 unlink_chunk (av, victim);
4187 /* Exhaust */
4188 if (remainder_size < MINSIZE)
4190 set_inuse_bit_at_offset (victim, size);
4191 if (av != &main_arena)
4192 set_non_main_arena (victim);
4194 /* Split */
4195 else
4197 remainder = chunk_at_offset (victim, nb);
4198 /* We cannot assume the unsorted list is empty and therefore
4199 have to perform a complete insert here. */
4200 bck = unsorted_chunks (av);
4201 fwd = bck->fd;
4202 if (__glibc_unlikely (fwd->bk != bck))
4203 malloc_printerr ("malloc(): corrupted unsorted chunks");
4204 remainder->bk = bck;
4205 remainder->fd = fwd;
4206 bck->fd = remainder;
4207 fwd->bk = remainder;
4208 if (!in_smallbin_range (remainder_size))
4210 remainder->fd_nextsize = NULL;
4211 remainder->bk_nextsize = NULL;
4213 set_head (victim, nb | PREV_INUSE |
4214 (av != &main_arena ? NON_MAIN_ARENA : 0));
4215 set_head (remainder, remainder_size | PREV_INUSE);
4216 set_foot (remainder, remainder_size);
4218 check_malloced_chunk (av, victim, nb);
4219 void *p = chunk2mem (victim);
4220 alloc_perturb (p, bytes);
4221 return p;
4226 Search for a chunk by scanning bins, starting with next largest
4227 bin. This search is strictly by best-fit; i.e., the smallest
4228 (with ties going to approximately the least recently used) chunk
4229 that fits is selected.
4231 The bitmap avoids needing to check that most blocks are nonempty.
4232 The particular case of skipping all bins during warm-up phases
4233 when no chunks have been returned yet is faster than it might look.
4236 ++idx;
4237 bin = bin_at (av, idx);
4238 block = idx2block (idx);
4239 map = av->binmap[block];
4240 bit = idx2bit (idx);
4242 for (;; )
4244 /* Skip rest of block if there are no more set bits in this block. */
4245 if (bit > map || bit == 0)
4249 if (++block >= BINMAPSIZE) /* out of bins */
4250 goto use_top;
4252 while ((map = av->binmap[block]) == 0);
4254 bin = bin_at (av, (block << BINMAPSHIFT));
4255 bit = 1;
4258 /* Advance to bin with set bit. There must be one. */
4259 while ((bit & map) == 0)
4261 bin = next_bin (bin);
4262 bit <<= 1;
4263 assert (bit != 0);
4266 /* Inspect the bin. It is likely to be non-empty */
4267 victim = last (bin);
4269 /* If a false alarm (empty bin), clear the bit. */
4270 if (victim == bin)
4272 av->binmap[block] = map &= ~bit; /* Write through */
4273 bin = next_bin (bin);
4274 bit <<= 1;
4277 else
4279 size = chunksize (victim);
4281 /* We know the first chunk in this bin is big enough to use. */
4282 assert ((unsigned long) (size) >= (unsigned long) (nb));
4284 remainder_size = size - nb;
4286 /* unlink */
4287 unlink_chunk (av, victim);
4289 /* Exhaust */
4290 if (remainder_size < MINSIZE)
4292 set_inuse_bit_at_offset (victim, size);
4293 if (av != &main_arena)
4294 set_non_main_arena (victim);
4297 /* Split */
4298 else
4300 remainder = chunk_at_offset (victim, nb);
4302 /* We cannot assume the unsorted list is empty and therefore
4303 have to perform a complete insert here. */
4304 bck = unsorted_chunks (av);
4305 fwd = bck->fd;
4306 if (__glibc_unlikely (fwd->bk != bck))
4307 malloc_printerr ("malloc(): corrupted unsorted chunks 2");
4308 remainder->bk = bck;
4309 remainder->fd = fwd;
4310 bck->fd = remainder;
4311 fwd->bk = remainder;
4313 /* advertise as last remainder */
4314 if (in_smallbin_range (nb))
4315 av->last_remainder = remainder;
4316 if (!in_smallbin_range (remainder_size))
4318 remainder->fd_nextsize = NULL;
4319 remainder->bk_nextsize = NULL;
4321 set_head (victim, nb | PREV_INUSE |
4322 (av != &main_arena ? NON_MAIN_ARENA : 0));
4323 set_head (remainder, remainder_size | PREV_INUSE);
4324 set_foot (remainder, remainder_size);
4326 check_malloced_chunk (av, victim, nb);
4327 void *p = chunk2mem (victim);
4328 alloc_perturb (p, bytes);
4329 return p;
4333 use_top:
4335 If large enough, split off the chunk bordering the end of memory
4336 (held in av->top). Note that this is in accord with the best-fit
4337 search rule. In effect, av->top is treated as larger (and thus
4338 less well fitting) than any other available chunk since it can
4339 be extended to be as large as necessary (up to system
4340 limitations).
4342 We require that av->top always exists (i.e., has size >=
4343 MINSIZE) after initialization, so if it would otherwise be
4344 exhausted by current request, it is replenished. (The main
4345 reason for ensuring it exists is that we may need MINSIZE space
4346 to put in fenceposts in sysmalloc.)
4349 victim = av->top;
4350 size = chunksize (victim);
4352 if (__glibc_unlikely (size > av->system_mem))
4353 malloc_printerr ("malloc(): corrupted top size");
4355 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
4357 remainder_size = size - nb;
4358 remainder = chunk_at_offset (victim, nb);
4359 av->top = remainder;
4360 set_head (victim, nb | PREV_INUSE |
4361 (av != &main_arena ? NON_MAIN_ARENA : 0));
4362 set_head (remainder, remainder_size | PREV_INUSE);
4364 check_malloced_chunk (av, victim, nb);
4365 void *p = chunk2mem (victim);
4366 alloc_perturb (p, bytes);
4367 return p;
4370 /* When we are using atomic ops to free fast chunks we can get
4371 here for all block sizes. */
4372 else if (atomic_load_relaxed (&av->have_fastchunks))
4374 malloc_consolidate (av);
4375 /* restore original bin index */
4376 if (in_smallbin_range (nb))
4377 idx = smallbin_index (nb);
4378 else
4379 idx = largebin_index (nb);
4383 Otherwise, relay to handle system-dependent cases
4385 else
4387 void *p = sysmalloc (nb, av);
4388 if (p != NULL)
4389 alloc_perturb (p, bytes);
4390 return p;
4396 ------------------------------ free ------------------------------
4399 static void
4400 _int_free (mstate av, mchunkptr p, int have_lock)
4402 INTERNAL_SIZE_T size; /* its size */
4403 mfastbinptr *fb; /* associated fastbin */
4404 mchunkptr nextchunk; /* next contiguous chunk */
4405 INTERNAL_SIZE_T nextsize; /* its size */
4406 int nextinuse; /* true if nextchunk is used */
4407 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
4408 mchunkptr bck; /* misc temp for linking */
4409 mchunkptr fwd; /* misc temp for linking */
4411 size = chunksize (p);
4413 /* Little security check which won't hurt performance: the
4414 allocator never wrapps around at the end of the address space.
4415 Therefore we can exclude some size values which might appear
4416 here by accident or by "design" from some intruder. */
4417 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
4418 || __builtin_expect (misaligned_chunk (p), 0))
4419 malloc_printerr ("free(): invalid pointer");
4420 /* We know that each chunk is at least MINSIZE bytes in size or a
4421 multiple of MALLOC_ALIGNMENT. */
4422 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
4423 malloc_printerr ("free(): invalid size");
4425 check_inuse_chunk(av, p);
4427 #if USE_TCACHE
4429 size_t tc_idx = csize2tidx (size);
4430 if (tcache != NULL && tc_idx < mp_.tcache_bins)
4432 /* Check to see if it's already in the tcache. */
4433 tcache_entry *e = (tcache_entry *) chunk2mem (p);
4435 /* This test succeeds on double free. However, we don't 100%
4436 trust it (it also matches random payload data at a 1 in
4437 2^<size_t> chance), so verify it's not an unlikely
4438 coincidence before aborting. */
4439 if (__glibc_unlikely (e->key == tcache))
4441 tcache_entry *tmp;
4442 size_t cnt = 0;
4443 LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
4444 for (tmp = tcache->entries[tc_idx];
4445 tmp;
4446 tmp = REVEAL_PTR (tmp->next), ++cnt)
4448 if (cnt >= mp_.tcache_count)
4449 malloc_printerr ("free(): too many chunks detected in tcache");
4450 if (__glibc_unlikely (!aligned_OK (tmp)))
4451 malloc_printerr ("free(): unaligned chunk detected in tcache 2");
4452 if (tmp == e)
4453 malloc_printerr ("free(): double free detected in tcache 2");
4454 /* If we get here, it was a coincidence. We've wasted a
4455 few cycles, but don't abort. */
4459 if (tcache->counts[tc_idx] < mp_.tcache_count)
4461 tcache_put (p, tc_idx);
4462 return;
4466 #endif
4469 If eligible, place chunk on a fastbin so it can be found
4470 and used quickly in malloc.
4473 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
4475 #if TRIM_FASTBINS
4477 If TRIM_FASTBINS set, don't place chunks
4478 bordering top into fastbins
4480 && (chunk_at_offset(p, size) != av->top)
4481 #endif
4484 if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
4485 <= CHUNK_HDR_SZ, 0)
4486 || __builtin_expect (chunksize (chunk_at_offset (p, size))
4487 >= av->system_mem, 0))
4489 bool fail = true;
4490 /* We might not have a lock at this point and concurrent modifications
4491 of system_mem might result in a false positive. Redo the test after
4492 getting the lock. */
4493 if (!have_lock)
4495 __libc_lock_lock (av->mutex);
4496 fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ
4497 || chunksize (chunk_at_offset (p, size)) >= av->system_mem);
4498 __libc_lock_unlock (av->mutex);
4501 if (fail)
4502 malloc_printerr ("free(): invalid next size (fast)");
4505 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4507 atomic_store_relaxed (&av->have_fastchunks, true);
4508 unsigned int idx = fastbin_index(size);
4509 fb = &fastbin (av, idx);
4511 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
4512 mchunkptr old = *fb, old2;
4514 if (SINGLE_THREAD_P)
4516 /* Check that the top of the bin is not the record we are going to
4517 add (i.e., double free). */
4518 if (__builtin_expect (old == p, 0))
4519 malloc_printerr ("double free or corruption (fasttop)");
4520 p->fd = PROTECT_PTR (&p->fd, old);
4521 *fb = p;
4523 else
4526 /* Check that the top of the bin is not the record we are going to
4527 add (i.e., double free). */
4528 if (__builtin_expect (old == p, 0))
4529 malloc_printerr ("double free or corruption (fasttop)");
4530 old2 = old;
4531 p->fd = PROTECT_PTR (&p->fd, old);
4533 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2))
4534 != old2);
4536 /* Check that size of fastbin chunk at the top is the same as
4537 size of the chunk that we are adding. We can dereference OLD
4538 only if we have the lock, otherwise it might have already been
4539 allocated again. */
4540 if (have_lock && old != NULL
4541 && __builtin_expect (fastbin_index (chunksize (old)) != idx, 0))
4542 malloc_printerr ("invalid fastbin entry (free)");
4546 Consolidate other non-mmapped chunks as they arrive.
4549 else if (!chunk_is_mmapped(p)) {
4551 /* If we're single-threaded, don't lock the arena. */
4552 if (SINGLE_THREAD_P)
4553 have_lock = true;
4555 if (!have_lock)
4556 __libc_lock_lock (av->mutex);
4558 nextchunk = chunk_at_offset(p, size);
4560 /* Lightweight tests: check whether the block is already the
4561 top block. */
4562 if (__glibc_unlikely (p == av->top))
4563 malloc_printerr ("double free or corruption (top)");
4564 /* Or whether the next chunk is beyond the boundaries of the arena. */
4565 if (__builtin_expect (contiguous (av)
4566 && (char *) nextchunk
4567 >= ((char *) av->top + chunksize(av->top)), 0))
4568 malloc_printerr ("double free or corruption (out)");
4569 /* Or whether the block is actually not marked used. */
4570 if (__glibc_unlikely (!prev_inuse(nextchunk)))
4571 malloc_printerr ("double free or corruption (!prev)");
4573 nextsize = chunksize(nextchunk);
4574 if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0)
4575 || __builtin_expect (nextsize >= av->system_mem, 0))
4576 malloc_printerr ("free(): invalid next size (normal)");
4578 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4580 /* consolidate backward */
4581 if (!prev_inuse(p)) {
4582 prevsize = prev_size (p);
4583 size += prevsize;
4584 p = chunk_at_offset(p, -((long) prevsize));
4585 if (__glibc_unlikely (chunksize(p) != prevsize))
4586 malloc_printerr ("corrupted size vs. prev_size while consolidating");
4587 unlink_chunk (av, p);
4590 if (nextchunk != av->top) {
4591 /* get and clear inuse bit */
4592 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4594 /* consolidate forward */
4595 if (!nextinuse) {
4596 unlink_chunk (av, nextchunk);
4597 size += nextsize;
4598 } else
4599 clear_inuse_bit_at_offset(nextchunk, 0);
4602 Place the chunk in unsorted chunk list. Chunks are
4603 not placed into regular bins until after they have
4604 been given one chance to be used in malloc.
4607 bck = unsorted_chunks(av);
4608 fwd = bck->fd;
4609 if (__glibc_unlikely (fwd->bk != bck))
4610 malloc_printerr ("free(): corrupted unsorted chunks");
4611 p->fd = fwd;
4612 p->bk = bck;
4613 if (!in_smallbin_range(size))
4615 p->fd_nextsize = NULL;
4616 p->bk_nextsize = NULL;
4618 bck->fd = p;
4619 fwd->bk = p;
4621 set_head(p, size | PREV_INUSE);
4622 set_foot(p, size);
4624 check_free_chunk(av, p);
4628 If the chunk borders the current high end of memory,
4629 consolidate into top
4632 else {
4633 size += nextsize;
4634 set_head(p, size | PREV_INUSE);
4635 av->top = p;
4636 check_chunk(av, p);
4640 If freeing a large space, consolidate possibly-surrounding
4641 chunks. Then, if the total unused topmost memory exceeds trim
4642 threshold, ask malloc_trim to reduce top.
4644 Unless max_fast is 0, we don't know if there are fastbins
4645 bordering top, so we cannot tell for sure whether threshold
4646 has been reached unless fastbins are consolidated. But we
4647 don't want to consolidate on each free. As a compromise,
4648 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4649 is reached.
4652 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4653 if (atomic_load_relaxed (&av->have_fastchunks))
4654 malloc_consolidate(av);
4656 if (av == &main_arena) {
4657 #ifndef MORECORE_CANNOT_TRIM
4658 if ((unsigned long)(chunksize(av->top)) >=
4659 (unsigned long)(mp_.trim_threshold))
4660 systrim(mp_.top_pad, av);
4661 #endif
4662 } else {
4663 /* Always try heap_trim(), even if the top chunk is not
4664 large, because the corresponding heap might go away. */
4665 heap_info *heap = heap_for_ptr(top(av));
4667 assert(heap->ar_ptr == av);
4668 heap_trim(heap, mp_.top_pad);
4672 if (!have_lock)
4673 __libc_lock_unlock (av->mutex);
4676 If the chunk was allocated via mmap, release via munmap().
4679 else {
4680 munmap_chunk (p);
4685 ------------------------- malloc_consolidate -------------------------
4687 malloc_consolidate is a specialized version of free() that tears
4688 down chunks held in fastbins. Free itself cannot be used for this
4689 purpose since, among other things, it might place chunks back onto
4690 fastbins. So, instead, we need to use a minor variant of the same
4691 code.
4694 static void malloc_consolidate(mstate av)
4696 mfastbinptr* fb; /* current fastbin being consolidated */
4697 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4698 mchunkptr p; /* current chunk being consolidated */
4699 mchunkptr nextp; /* next chunk to consolidate */
4700 mchunkptr unsorted_bin; /* bin header */
4701 mchunkptr first_unsorted; /* chunk to link to */
4703 /* These have same use as in free() */
4704 mchunkptr nextchunk;
4705 INTERNAL_SIZE_T size;
4706 INTERNAL_SIZE_T nextsize;
4707 INTERNAL_SIZE_T prevsize;
4708 int nextinuse;
4710 atomic_store_relaxed (&av->have_fastchunks, false);
4712 unsorted_bin = unsorted_chunks(av);
4715 Remove each chunk from fast bin and consolidate it, placing it
4716 then in unsorted bin. Among other reasons for doing this,
4717 placing in unsorted bin avoids needing to calculate actual bins
4718 until malloc is sure that chunks aren't immediately going to be
4719 reused anyway.
4722 maxfb = &fastbin (av, NFASTBINS - 1);
4723 fb = &fastbin (av, 0);
4724 do {
4725 p = atomic_exchange_acq (fb, NULL);
4726 if (p != 0) {
4727 do {
4729 if (__glibc_unlikely (misaligned_chunk (p)))
4730 malloc_printerr ("malloc_consolidate(): "
4731 "unaligned fastbin chunk detected");
4733 unsigned int idx = fastbin_index (chunksize (p));
4734 if ((&fastbin (av, idx)) != fb)
4735 malloc_printerr ("malloc_consolidate(): invalid chunk size");
4738 check_inuse_chunk(av, p);
4739 nextp = REVEAL_PTR (p->fd);
4741 /* Slightly streamlined version of consolidation code in free() */
4742 size = chunksize (p);
4743 nextchunk = chunk_at_offset(p, size);
4744 nextsize = chunksize(nextchunk);
4746 if (!prev_inuse(p)) {
4747 prevsize = prev_size (p);
4748 size += prevsize;
4749 p = chunk_at_offset(p, -((long) prevsize));
4750 if (__glibc_unlikely (chunksize(p) != prevsize))
4751 malloc_printerr ("corrupted size vs. prev_size in fastbins");
4752 unlink_chunk (av, p);
4755 if (nextchunk != av->top) {
4756 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4758 if (!nextinuse) {
4759 size += nextsize;
4760 unlink_chunk (av, nextchunk);
4761 } else
4762 clear_inuse_bit_at_offset(nextchunk, 0);
4764 first_unsorted = unsorted_bin->fd;
4765 unsorted_bin->fd = p;
4766 first_unsorted->bk = p;
4768 if (!in_smallbin_range (size)) {
4769 p->fd_nextsize = NULL;
4770 p->bk_nextsize = NULL;
4773 set_head(p, size | PREV_INUSE);
4774 p->bk = unsorted_bin;
4775 p->fd = first_unsorted;
4776 set_foot(p, size);
4779 else {
4780 size += nextsize;
4781 set_head(p, size | PREV_INUSE);
4782 av->top = p;
4785 } while ( (p = nextp) != 0);
4788 } while (fb++ != maxfb);
4792 ------------------------------ realloc ------------------------------
4795 void*
4796 _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4797 INTERNAL_SIZE_T nb)
4799 mchunkptr newp; /* chunk to return */
4800 INTERNAL_SIZE_T newsize; /* its size */
4801 void* newmem; /* corresponding user mem */
4803 mchunkptr next; /* next contiguous chunk after oldp */
4805 mchunkptr remainder; /* extra space at end of newp */
4806 unsigned long remainder_size; /* its size */
4808 /* oldmem size */
4809 if (__builtin_expect (chunksize_nomask (oldp) <= CHUNK_HDR_SZ, 0)
4810 || __builtin_expect (oldsize >= av->system_mem, 0))
4811 malloc_printerr ("realloc(): invalid old size");
4813 check_inuse_chunk (av, oldp);
4815 /* All callers already filter out mmap'ed chunks. */
4816 assert (!chunk_is_mmapped (oldp));
4818 next = chunk_at_offset (oldp, oldsize);
4819 INTERNAL_SIZE_T nextsize = chunksize (next);
4820 if (__builtin_expect (chunksize_nomask (next) <= CHUNK_HDR_SZ, 0)
4821 || __builtin_expect (nextsize >= av->system_mem, 0))
4822 malloc_printerr ("realloc(): invalid next size");
4824 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4826 /* already big enough; split below */
4827 newp = oldp;
4828 newsize = oldsize;
4831 else
4833 /* Try to expand forward into top */
4834 if (next == av->top &&
4835 (unsigned long) (newsize = oldsize + nextsize) >=
4836 (unsigned long) (nb + MINSIZE))
4838 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4839 av->top = chunk_at_offset (oldp, nb);
4840 set_head (av->top, (newsize - nb) | PREV_INUSE);
4841 check_inuse_chunk (av, oldp);
4842 return tag_new_usable (chunk2mem (oldp));
4845 /* Try to expand forward into next chunk; split off remainder below */
4846 else if (next != av->top &&
4847 !inuse (next) &&
4848 (unsigned long) (newsize = oldsize + nextsize) >=
4849 (unsigned long) (nb))
4851 newp = oldp;
4852 unlink_chunk (av, next);
4855 /* allocate, copy, free */
4856 else
4858 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4859 if (newmem == 0)
4860 return 0; /* propagate failure */
4862 newp = mem2chunk (newmem);
4863 newsize = chunksize (newp);
4866 Avoid copy if newp is next chunk after oldp.
4868 if (newp == next)
4870 newsize += oldsize;
4871 newp = oldp;
4873 else
4875 void *oldmem = chunk2mem (oldp);
4876 size_t sz = memsize (oldp);
4877 (void) tag_region (oldmem, sz);
4878 newmem = tag_new_usable (newmem);
4879 memcpy (newmem, oldmem, sz);
4880 _int_free (av, oldp, 1);
4881 check_inuse_chunk (av, newp);
4882 return newmem;
4887 /* If possible, free extra space in old or extended chunk */
4889 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
4891 remainder_size = newsize - nb;
4893 if (remainder_size < MINSIZE) /* not enough extra to split off */
4895 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4896 set_inuse_bit_at_offset (newp, newsize);
4898 else /* split remainder */
4900 remainder = chunk_at_offset (newp, nb);
4901 /* Clear any user-space tags before writing the header. */
4902 remainder = tag_region (remainder, remainder_size);
4903 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4904 set_head (remainder, remainder_size | PREV_INUSE |
4905 (av != &main_arena ? NON_MAIN_ARENA : 0));
4906 /* Mark remainder as inuse so free() won't complain */
4907 set_inuse_bit_at_offset (remainder, remainder_size);
4908 _int_free (av, remainder, 1);
4911 check_inuse_chunk (av, newp);
4912 return tag_new_usable (chunk2mem (newp));
4916 ------------------------------ memalign ------------------------------
4919 static void *
4920 _int_memalign (mstate av, size_t alignment, size_t bytes)
4922 INTERNAL_SIZE_T nb; /* padded request size */
4923 char *m; /* memory returned by malloc call */
4924 mchunkptr p; /* corresponding chunk */
4925 char *brk; /* alignment point within p */
4926 mchunkptr newp; /* chunk to return */
4927 INTERNAL_SIZE_T newsize; /* its size */
4928 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4929 mchunkptr remainder; /* spare room at end to split off */
4930 unsigned long remainder_size; /* its size */
4931 INTERNAL_SIZE_T size;
4935 if (!checked_request2size (bytes, &nb))
4937 __set_errno (ENOMEM);
4938 return NULL;
4942 Strategy: find a spot within that chunk that meets the alignment
4943 request, and then possibly free the leading and trailing space.
4946 /* Call malloc with worst case padding to hit alignment. */
4948 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4950 if (m == 0)
4951 return 0; /* propagate failure */
4953 p = mem2chunk (m);
4955 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4957 { /*
4958 Find an aligned spot inside chunk. Since we need to give back
4959 leading space in a chunk of at least MINSIZE, if the first
4960 calculation places us at a spot with less than MINSIZE leader,
4961 we can move to the next aligned spot -- we've allocated enough
4962 total room so that this is always possible.
4964 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4965 - ((signed long) alignment));
4966 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4967 brk += alignment;
4969 newp = (mchunkptr) brk;
4970 leadsize = brk - (char *) (p);
4971 newsize = chunksize (p) - leadsize;
4973 /* For mmapped chunks, just adjust offset */
4974 if (chunk_is_mmapped (p))
4976 set_prev_size (newp, prev_size (p) + leadsize);
4977 set_head (newp, newsize | IS_MMAPPED);
4978 return chunk2mem (newp);
4981 /* Otherwise, give back leader, use the rest */
4982 set_head (newp, newsize | PREV_INUSE |
4983 (av != &main_arena ? NON_MAIN_ARENA : 0));
4984 set_inuse_bit_at_offset (newp, newsize);
4985 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4986 _int_free (av, p, 1);
4987 p = newp;
4989 assert (newsize >= nb &&
4990 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
4993 /* Also give back spare room at the end */
4994 if (!chunk_is_mmapped (p))
4996 size = chunksize (p);
4997 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4999 remainder_size = size - nb;
5000 remainder = chunk_at_offset (p, nb);
5001 set_head (remainder, remainder_size | PREV_INUSE |
5002 (av != &main_arena ? NON_MAIN_ARENA : 0));
5003 set_head_size (p, nb);
5004 _int_free (av, remainder, 1);
5008 check_inuse_chunk (av, p);
5009 return chunk2mem (p);
5014 ------------------------------ malloc_trim ------------------------------
5017 static int
5018 mtrim (mstate av, size_t pad)
5020 /* Ensure all blocks are consolidated. */
5021 malloc_consolidate (av);
5023 const size_t ps = GLRO (dl_pagesize);
5024 int psindex = bin_index (ps);
5025 const size_t psm1 = ps - 1;
5027 int result = 0;
5028 for (int i = 1; i < NBINS; ++i)
5029 if (i == 1 || i >= psindex)
5031 mbinptr bin = bin_at (av, i);
5033 for (mchunkptr p = last (bin); p != bin; p = p->bk)
5035 INTERNAL_SIZE_T size = chunksize (p);
5037 if (size > psm1 + sizeof (struct malloc_chunk))
5039 /* See whether the chunk contains at least one unused page. */
5040 char *paligned_mem = (char *) (((uintptr_t) p
5041 + sizeof (struct malloc_chunk)
5042 + psm1) & ~psm1);
5044 assert ((char *) chunk2mem (p) + 2 * CHUNK_HDR_SZ
5045 <= paligned_mem);
5046 assert ((char *) p + size > paligned_mem);
5048 /* This is the size we could potentially free. */
5049 size -= paligned_mem - (char *) p;
5051 if (size > psm1)
5053 #if MALLOC_DEBUG
5054 /* When debugging we simulate destroying the memory
5055 content. */
5056 memset (paligned_mem, 0x89, size & ~psm1);
5057 #endif
5058 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
5060 result = 1;
5066 #ifndef MORECORE_CANNOT_TRIM
5067 return result | (av == &main_arena ? systrim (pad, av) : 0);
5069 #else
5070 return result;
5071 #endif
5076 __malloc_trim (size_t s)
5078 int result = 0;
5080 if (__malloc_initialized < 0)
5081 ptmalloc_init ();
5083 mstate ar_ptr = &main_arena;
5086 __libc_lock_lock (ar_ptr->mutex);
5087 result |= mtrim (ar_ptr, s);
5088 __libc_lock_unlock (ar_ptr->mutex);
5090 ar_ptr = ar_ptr->next;
5092 while (ar_ptr != &main_arena);
5094 return result;
5099 ------------------------- malloc_usable_size -------------------------
5102 static size_t
5103 musable (void *mem)
5105 mchunkptr p;
5106 if (mem != 0)
5108 size_t result = 0;
5110 p = mem2chunk (mem);
5112 if (__builtin_expect (using_malloc_checking == 1, 0))
5113 return malloc_check_get_size (p);
5115 if (chunk_is_mmapped (p))
5117 if (DUMPED_MAIN_ARENA_CHUNK (p))
5118 result = chunksize (p) - SIZE_SZ;
5119 else
5120 result = chunksize (p) - CHUNK_HDR_SZ;
5122 else if (inuse (p))
5123 result = memsize (p);
5125 return result;
5127 return 0;
5131 size_t
5132 __malloc_usable_size (void *m)
5134 size_t result;
5136 result = musable (m);
5137 return result;