x86-64: Use notl in EVEX strcmp [BZ #28646]
[glibc.git] / malloc / malloc.c
blob095d97a3bee75bf47a562190cf8ab7b589e96d08
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2021 Free Software Foundation, Inc.
3 Copyright The GNU Toolchain Authors.
4 This file is part of the GNU C Library.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If
18 not, see <https://www.gnu.org/licenses/>. */
21 This is a version (aka ptmalloc2) of malloc/free/realloc written by
22 Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
24 There have been substantial changes made after the integration into
25 glibc in all parts of the code. Do not look for much commonality
26 with the ptmalloc2 version.
28 * Version ptmalloc2-20011215
29 based on:
30 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
32 * Quickstart
34 In order to compile this implementation, a Makefile is provided with
35 the ptmalloc2 distribution, which has pre-defined targets for some
36 popular systems (e.g. "make posix" for Posix threads). All that is
37 typically required with regard to compiler flags is the selection of
38 the thread package via defining one out of USE_PTHREADS, USE_THR or
39 USE_SPROC. Check the thread-m.h file for what effects this has.
40 Many/most systems will additionally require USE_TSD_DATA_HACK to be
41 defined, so this is the default for "make posix".
43 * Why use this malloc?
45 This is not the fastest, most space-conserving, most portable, or
46 most tunable malloc ever written. However it is among the fastest
47 while also being among the most space-conserving, portable and tunable.
48 Consistent balance across these factors results in a good general-purpose
49 allocator for malloc-intensive programs.
51 The main properties of the algorithms are:
52 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
53 with ties normally decided via FIFO (i.e. least recently used).
54 * For small (<= 64 bytes by default) requests, it is a caching
55 allocator, that maintains pools of quickly recycled chunks.
56 * In between, and for combinations of large and small requests, it does
57 the best it can trying to meet both goals at once.
58 * For very large requests (>= 128KB by default), it relies on system
59 memory mapping facilities, if supported.
61 For a longer but slightly out of date high-level description, see
62 http://gee.cs.oswego.edu/dl/html/malloc.html
64 You may already by default be using a C library containing a malloc
65 that is based on some version of this malloc (for example in
66 linux). You might still want to use the one in this file in order to
67 customize settings or to avoid overheads associated with library
68 versions.
70 * Contents, described in more detail in "description of public routines" below.
72 Standard (ANSI/SVID/...) functions:
73 malloc(size_t n);
74 calloc(size_t n_elements, size_t element_size);
75 free(void* p);
76 realloc(void* p, size_t n);
77 memalign(size_t alignment, size_t n);
78 valloc(size_t n);
79 mallinfo()
80 mallopt(int parameter_number, int parameter_value)
82 Additional functions:
83 independent_calloc(size_t n_elements, size_t size, void* chunks[]);
84 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
85 pvalloc(size_t n);
86 malloc_trim(size_t pad);
87 malloc_usable_size(void* p);
88 malloc_stats();
90 * Vital statistics:
92 Supported pointer representation: 4 or 8 bytes
93 Supported size_t representation: 4 or 8 bytes
94 Note that size_t is allowed to be 4 bytes even if pointers are 8.
95 You can adjust this by defining INTERNAL_SIZE_T
97 Alignment: 2 * sizeof(size_t) (default)
98 (i.e., 8 byte alignment with 4byte size_t). This suffices for
99 nearly all current machines and C compilers. However, you can
100 define MALLOC_ALIGNMENT to be wider than this if necessary.
102 Minimum overhead per allocated chunk: 4 or 8 bytes
103 Each malloced chunk has a hidden word of overhead holding size
104 and status information.
106 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
107 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
109 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
110 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
111 needed; 4 (8) for a trailing size field and 8 (16) bytes for
112 free list pointers. Thus, the minimum allocatable size is
113 16/24/32 bytes.
115 Even a request for zero bytes (i.e., malloc(0)) returns a
116 pointer to something of the minimum allocatable size.
118 The maximum overhead wastage (i.e., number of extra bytes
119 allocated than were requested in malloc) is less than or equal
120 to the minimum size, except for requests >= mmap_threshold that
121 are serviced via mmap(), where the worst case wastage is 2 *
122 sizeof(size_t) bytes plus the remainder from a system page (the
123 minimal mmap unit); typically 4096 or 8192 bytes.
125 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
126 8-byte size_t: 2^64 minus about two pages
128 It is assumed that (possibly signed) size_t values suffice to
129 represent chunk sizes. `Possibly signed' is due to the fact
130 that `size_t' may be defined on a system as either a signed or
131 an unsigned type. The ISO C standard says that it must be
132 unsigned, but a few systems are known not to adhere to this.
133 Additionally, even when size_t is unsigned, sbrk (which is by
134 default used to obtain memory from system) accepts signed
135 arguments, and may not be able to handle size_t-wide arguments
136 with negative sign bit. Generally, values that would
137 appear as negative after accounting for overhead and alignment
138 are supported only via mmap(), which does not have this
139 limitation.
141 Requests for sizes outside the allowed range will perform an optional
142 failure action and then return null. (Requests may also
143 also fail because a system is out of memory.)
145 Thread-safety: thread-safe
147 Compliance: I believe it is compliant with the 1997 Single Unix Specification
148 Also SVID/XPG, ANSI C, and probably others as well.
150 * Synopsis of compile-time options:
152 People have reported using previous versions of this malloc on all
153 versions of Unix, sometimes by tweaking some of the defines
154 below. It has been tested most extensively on Solaris and Linux.
155 People also report using it in stand-alone embedded systems.
157 The implementation is in straight, hand-tuned ANSI C. It is not
158 at all modular. (Sorry!) It uses a lot of macros. To be at all
159 usable, this code should be compiled using an optimizing compiler
160 (for example gcc -O3) that can simplify expressions and control
161 paths. (FAQ: some macros import variables as arguments rather than
162 declare locals because people reported that some debuggers
163 otherwise get confused.)
165 OPTION DEFAULT VALUE
167 Compilation Environment options:
169 HAVE_MREMAP 0
171 Changing default word sizes:
173 INTERNAL_SIZE_T size_t
175 Configuration and functionality options:
177 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
178 USE_MALLOC_LOCK NOT defined
179 MALLOC_DEBUG NOT defined
180 REALLOC_ZERO_BYTES_FREES 1
181 TRIM_FASTBINS 0
183 Options for customizing MORECORE:
185 MORECORE sbrk
186 MORECORE_FAILURE -1
187 MORECORE_CONTIGUOUS 1
188 MORECORE_CANNOT_TRIM NOT defined
189 MORECORE_CLEARS 1
190 MMAP_AS_MORECORE_SIZE (1024 * 1024)
192 Tuning options that are also dynamically changeable via mallopt:
194 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
195 DEFAULT_TRIM_THRESHOLD 128 * 1024
196 DEFAULT_TOP_PAD 0
197 DEFAULT_MMAP_THRESHOLD 128 * 1024
198 DEFAULT_MMAP_MAX 65536
200 There are several other #defined constants and macros that you
201 probably don't want to touch unless you are extending or adapting malloc. */
204 void* is the pointer type that malloc should say it returns
207 #ifndef void
208 #define void void
209 #endif /*void*/
211 #include <stddef.h> /* for size_t */
212 #include <stdlib.h> /* for getenv(), abort() */
213 #include <unistd.h> /* for __libc_enable_secure */
215 #include <atomic.h>
216 #include <_itoa.h>
217 #include <bits/wordsize.h>
218 #include <sys/sysinfo.h>
220 #include <ldsodefs.h>
222 #include <unistd.h>
223 #include <stdio.h> /* needed for malloc_stats */
224 #include <errno.h>
225 #include <assert.h>
227 #include <shlib-compat.h>
229 /* For uintptr_t. */
230 #include <stdint.h>
232 /* For va_arg, va_start, va_end. */
233 #include <stdarg.h>
235 /* For MIN, MAX, powerof2. */
236 #include <sys/param.h>
238 /* For ALIGN_UP et. al. */
239 #include <libc-pointer-arith.h>
241 /* For DIAG_PUSH/POP_NEEDS_COMMENT et al. */
242 #include <libc-diag.h>
244 /* For memory tagging. */
245 #include <libc-mtag.h>
247 #include <malloc/malloc-internal.h>
249 /* For SINGLE_THREAD_P. */
250 #include <sysdep-cancel.h>
252 #include <libc-internal.h>
254 /* For tcache double-free check. */
255 #include <random-bits.h>
256 #include <sys/random.h>
259 Debugging:
261 Because freed chunks may be overwritten with bookkeeping fields, this
262 malloc will often die when freed memory is overwritten by user
263 programs. This can be very effective (albeit in an annoying way)
264 in helping track down dangling pointers.
266 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
267 enabled that will catch more memory errors. You probably won't be
268 able to make much sense of the actual assertion errors, but they
269 should help you locate incorrectly overwritten memory. The checking
270 is fairly extensive, and will slow down execution
271 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
272 will attempt to check every non-mmapped allocated and free chunk in
273 the course of computing the summmaries. (By nature, mmapped regions
274 cannot be checked very much automatically.)
276 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
277 this code. The assertions in the check routines spell out in more
278 detail the assumptions and invariants underlying the algorithms.
280 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
281 checking that all accesses to malloced memory stay within their
282 bounds. However, there are several add-ons and adaptations of this
283 or other mallocs available that do this.
286 #ifndef MALLOC_DEBUG
287 #define MALLOC_DEBUG 0
288 #endif
290 #if IS_IN (libc)
291 #ifndef NDEBUG
292 # define __assert_fail(assertion, file, line, function) \
293 __malloc_assert(assertion, file, line, function)
295 extern const char *__progname;
297 static void
298 __malloc_assert (const char *assertion, const char *file, unsigned int line,
299 const char *function)
301 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
302 __progname, __progname[0] ? ": " : "",
303 file, line,
304 function ? function : "", function ? ": " : "",
305 assertion);
306 fflush (stderr);
307 abort ();
309 #endif
310 #endif
312 #if USE_TCACHE
313 /* We want 64 entries. This is an arbitrary limit, which tunables can reduce. */
314 # define TCACHE_MAX_BINS 64
315 # define MAX_TCACHE_SIZE tidx2usize (TCACHE_MAX_BINS-1)
317 /* Only used to pre-fill the tunables. */
318 # define tidx2usize(idx) (((size_t) idx) * MALLOC_ALIGNMENT + MINSIZE - SIZE_SZ)
320 /* When "x" is from chunksize(). */
321 # define csize2tidx(x) (((x) - MINSIZE + MALLOC_ALIGNMENT - 1) / MALLOC_ALIGNMENT)
322 /* When "x" is a user-provided size. */
323 # define usize2tidx(x) csize2tidx (request2size (x))
325 /* With rounding and alignment, the bins are...
326 idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit)
327 idx 1 bytes 25..40 or 13..20
328 idx 2 bytes 41..56 or 21..28
329 etc. */
331 /* This is another arbitrary limit, which tunables can change. Each
332 tcache bin will hold at most this number of chunks. */
333 # define TCACHE_FILL_COUNT 7
335 /* Maximum chunks in tcache bins for tunables. This value must fit the range
336 of tcache->counts[] entries, else they may overflow. */
337 # define MAX_TCACHE_COUNT UINT16_MAX
338 #endif
340 /* Safe-Linking:
341 Use randomness from ASLR (mmap_base) to protect single-linked lists
342 of Fast-Bins and TCache. That is, mask the "next" pointers of the
343 lists' chunks, and also perform allocation alignment checks on them.
344 This mechanism reduces the risk of pointer hijacking, as was done with
345 Safe-Unlinking in the double-linked lists of Small-Bins.
346 It assumes a minimum page size of 4096 bytes (12 bits). Systems with
347 larger pages provide less entropy, although the pointer mangling
348 still works. */
349 #define PROTECT_PTR(pos, ptr) \
350 ((__typeof (ptr)) ((((size_t) pos) >> 12) ^ ((size_t) ptr)))
351 #define REVEAL_PTR(ptr) PROTECT_PTR (&ptr, ptr)
354 The REALLOC_ZERO_BYTES_FREES macro controls the behavior of realloc (p, 0)
355 when p is nonnull. If the macro is nonzero, the realloc call returns NULL;
356 otherwise, the call returns what malloc (0) would. In either case,
357 p is freed. Glibc uses a nonzero REALLOC_ZERO_BYTES_FREES, which
358 implements common historical practice.
360 ISO C17 says the realloc call has implementation-defined behavior,
361 and it might not even free p.
364 #ifndef REALLOC_ZERO_BYTES_FREES
365 #define REALLOC_ZERO_BYTES_FREES 1
366 #endif
369 TRIM_FASTBINS controls whether free() of a very small chunk can
370 immediately lead to trimming. Setting to true (1) can reduce memory
371 footprint, but will almost always slow down programs that use a lot
372 of small chunks.
374 Define this only if you are willing to give up some speed to more
375 aggressively reduce system-level memory footprint when releasing
376 memory in programs that use many small chunks. You can get
377 essentially the same effect by setting MXFAST to 0, but this can
378 lead to even greater slowdowns in programs using many small chunks.
379 TRIM_FASTBINS is an in-between compile-time option, that disables
380 only those chunks bordering topmost memory from being placed in
381 fastbins.
384 #ifndef TRIM_FASTBINS
385 #define TRIM_FASTBINS 0
386 #endif
388 /* Definition for getting more memory from the OS. */
389 #include "morecore.c"
391 #define MORECORE (*__glibc_morecore)
392 #define MORECORE_FAILURE 0
394 /* Memory tagging. */
396 /* Some systems support the concept of tagging (sometimes known as
397 coloring) memory locations on a fine grained basis. Each memory
398 location is given a color (normally allocated randomly) and
399 pointers are also colored. When the pointer is dereferenced, the
400 pointer's color is checked against the memory's color and if they
401 differ the access is faulted (sometimes lazily).
403 We use this in glibc by maintaining a single color for the malloc
404 data structures that are interleaved with the user data and then
405 assigning separate colors for each block allocation handed out. In
406 this way simple buffer overruns will be rapidly detected. When
407 memory is freed, the memory is recolored back to the glibc default
408 so that simple use-after-free errors can also be detected.
410 If memory is reallocated the buffer is recolored even if the
411 address remains the same. This has a performance impact, but
412 guarantees that the old pointer cannot mistakenly be reused (code
413 that compares old against new will see a mismatch and will then
414 need to behave as though realloc moved the data to a new location).
416 Internal API for memory tagging support.
418 The aim is to keep the code for memory tagging support as close to
419 the normal APIs in glibc as possible, so that if tagging is not
420 enabled in the library, or is disabled at runtime then standard
421 operations can continue to be used. Support macros are used to do
422 this:
424 void *tag_new_zero_region (void *ptr, size_t size)
426 Allocates a new tag, colors the memory with that tag, zeros the
427 memory and returns a pointer that is correctly colored for that
428 location. The non-tagging version will simply call memset with 0.
430 void *tag_region (void *ptr, size_t size)
432 Color the region of memory pointed to by PTR and size SIZE with
433 the color of PTR. Returns the original pointer.
435 void *tag_new_usable (void *ptr)
437 Allocate a new random color and use it to color the user region of
438 a chunk; this may include data from the subsequent chunk's header
439 if tagging is sufficiently fine grained. Returns PTR suitably
440 recolored for accessing the memory there.
442 void *tag_at (void *ptr)
444 Read the current color of the memory at the address pointed to by
445 PTR (ignoring it's current color) and return PTR recolored to that
446 color. PTR must be valid address in all other respects. When
447 tagging is not enabled, it simply returns the original pointer.
450 #ifdef USE_MTAG
451 static bool mtag_enabled = false;
452 static int mtag_mmap_flags = 0;
453 #else
454 # define mtag_enabled false
455 # define mtag_mmap_flags 0
456 #endif
458 static __always_inline void *
459 tag_region (void *ptr, size_t size)
461 if (__glibc_unlikely (mtag_enabled))
462 return __libc_mtag_tag_region (ptr, size);
463 return ptr;
466 static __always_inline void *
467 tag_new_zero_region (void *ptr, size_t size)
469 if (__glibc_unlikely (mtag_enabled))
470 return __libc_mtag_tag_zero_region (__libc_mtag_new_tag (ptr), size);
471 return memset (ptr, 0, size);
474 /* Defined later. */
475 static void *
476 tag_new_usable (void *ptr);
478 static __always_inline void *
479 tag_at (void *ptr)
481 if (__glibc_unlikely (mtag_enabled))
482 return __libc_mtag_address_get_tag (ptr);
483 return ptr;
486 #include <string.h>
489 MORECORE-related declarations. By default, rely on sbrk
494 MORECORE is the name of the routine to call to obtain more memory
495 from the system. See below for general guidance on writing
496 alternative MORECORE functions, as well as a version for WIN32 and a
497 sample version for pre-OSX macos.
500 #ifndef MORECORE
501 #define MORECORE sbrk
502 #endif
505 MORECORE_FAILURE is the value returned upon failure of MORECORE
506 as well as mmap. Since it cannot be an otherwise valid memory address,
507 and must reflect values of standard sys calls, you probably ought not
508 try to redefine it.
511 #ifndef MORECORE_FAILURE
512 #define MORECORE_FAILURE (-1)
513 #endif
516 If MORECORE_CONTIGUOUS is true, take advantage of fact that
517 consecutive calls to MORECORE with positive arguments always return
518 contiguous increasing addresses. This is true of unix sbrk. Even
519 if not defined, when regions happen to be contiguous, malloc will
520 permit allocations spanning regions obtained from different
521 calls. But defining this when applicable enables some stronger
522 consistency checks and space efficiencies.
525 #ifndef MORECORE_CONTIGUOUS
526 #define MORECORE_CONTIGUOUS 1
527 #endif
530 Define MORECORE_CANNOT_TRIM if your version of MORECORE
531 cannot release space back to the system when given negative
532 arguments. This is generally necessary only if you are using
533 a hand-crafted MORECORE function that cannot handle negative arguments.
536 /* #define MORECORE_CANNOT_TRIM */
538 /* MORECORE_CLEARS (default 1)
539 The degree to which the routine mapped to MORECORE zeroes out
540 memory: never (0), only for newly allocated space (1) or always
541 (2). The distinction between (1) and (2) is necessary because on
542 some systems, if the application first decrements and then
543 increments the break value, the contents of the reallocated space
544 are unspecified.
547 #ifndef MORECORE_CLEARS
548 # define MORECORE_CLEARS 1
549 #endif
553 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
554 sbrk fails, and mmap is used as a backup. The value must be a
555 multiple of page size. This backup strategy generally applies only
556 when systems have "holes" in address space, so sbrk cannot perform
557 contiguous expansion, but there is still space available on system.
558 On systems for which this is known to be useful (i.e. most linux
559 kernels), this occurs only when programs allocate huge amounts of
560 memory. Between this, and the fact that mmap regions tend to be
561 limited, the size should be large, to avoid too many mmap calls and
562 thus avoid running out of kernel resources. */
564 #ifndef MMAP_AS_MORECORE_SIZE
565 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
566 #endif
569 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
570 large blocks.
573 #ifndef HAVE_MREMAP
574 #define HAVE_MREMAP 0
575 #endif
578 This version of malloc supports the standard SVID/XPG mallinfo
579 routine that returns a struct containing usage properties and
580 statistics. It should work on any SVID/XPG compliant system that has
581 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
582 install such a thing yourself, cut out the preliminary declarations
583 as described above and below and save them in a malloc.h file. But
584 there's no compelling reason to bother to do this.)
586 The main declaration needed is the mallinfo struct that is returned
587 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
588 bunch of fields that are not even meaningful in this version of
589 malloc. These fields are are instead filled by mallinfo() with
590 other numbers that might be of interest.
594 /* ---------- description of public routines ------------ */
596 #if IS_IN (libc)
598 malloc(size_t n)
599 Returns a pointer to a newly allocated chunk of at least n bytes, or null
600 if no space is available. Additionally, on failure, errno is
601 set to ENOMEM on ANSI C systems.
603 If n is zero, malloc returns a minimum-sized chunk. (The minimum
604 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
605 systems.) On most systems, size_t is an unsigned type, so calls
606 with negative arguments are interpreted as requests for huge amounts
607 of space, which will often fail. The maximum supported value of n
608 differs across systems, but is in all cases less than the maximum
609 representable value of a size_t.
611 void* __libc_malloc(size_t);
612 libc_hidden_proto (__libc_malloc)
615 free(void* p)
616 Releases the chunk of memory pointed to by p, that had been previously
617 allocated using malloc or a related routine such as realloc.
618 It has no effect if p is null. It can have arbitrary (i.e., bad!)
619 effects if p has already been freed.
621 Unless disabled (using mallopt), freeing very large spaces will
622 when possible, automatically trigger operations that give
623 back unused memory to the system, thus reducing program footprint.
625 void __libc_free(void*);
626 libc_hidden_proto (__libc_free)
629 calloc(size_t n_elements, size_t element_size);
630 Returns a pointer to n_elements * element_size bytes, with all locations
631 set to zero.
633 void* __libc_calloc(size_t, size_t);
636 realloc(void* p, size_t n)
637 Returns a pointer to a chunk of size n that contains the same data
638 as does chunk p up to the minimum of (n, p's size) bytes, or null
639 if no space is available.
641 The returned pointer may or may not be the same as p. The algorithm
642 prefers extending p when possible, otherwise it employs the
643 equivalent of a malloc-copy-free sequence.
645 If p is null, realloc is equivalent to malloc.
647 If space is not available, realloc returns null, errno is set (if on
648 ANSI) and p is NOT freed.
650 if n is for fewer bytes than already held by p, the newly unused
651 space is lopped off and freed if possible. Unless the #define
652 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
653 zero (re)allocates a minimum-sized chunk.
655 Large chunks that were internally obtained via mmap will always be
656 grown using malloc-copy-free sequences unless the system supports
657 MREMAP (currently only linux).
659 The old unix realloc convention of allowing the last-free'd chunk
660 to be used as an argument to realloc is not supported.
662 void* __libc_realloc(void*, size_t);
663 libc_hidden_proto (__libc_realloc)
666 memalign(size_t alignment, size_t n);
667 Returns a pointer to a newly allocated chunk of n bytes, aligned
668 in accord with the alignment argument.
670 The alignment argument should be a power of two. If the argument is
671 not a power of two, the nearest greater power is used.
672 8-byte alignment is guaranteed by normal malloc calls, so don't
673 bother calling memalign with an argument of 8 or less.
675 Overreliance on memalign is a sure way to fragment space.
677 void* __libc_memalign(size_t, size_t);
678 libc_hidden_proto (__libc_memalign)
681 valloc(size_t n);
682 Equivalent to memalign(pagesize, n), where pagesize is the page
683 size of the system. If the pagesize is unknown, 4096 is used.
685 void* __libc_valloc(size_t);
690 mallinfo()
691 Returns (by copy) a struct containing various summary statistics:
693 arena: current total non-mmapped bytes allocated from system
694 ordblks: the number of free chunks
695 smblks: the number of fastbin blocks (i.e., small chunks that
696 have been freed but not use resused or consolidated)
697 hblks: current number of mmapped regions
698 hblkhd: total bytes held in mmapped regions
699 usmblks: always 0
700 fsmblks: total bytes held in fastbin blocks
701 uordblks: current total allocated space (normal or mmapped)
702 fordblks: total free space
703 keepcost: the maximum number of bytes that could ideally be released
704 back to system via malloc_trim. ("ideally" means that
705 it ignores page restrictions etc.)
707 Because these fields are ints, but internal bookkeeping may
708 be kept as longs, the reported values may wrap around zero and
709 thus be inaccurate.
711 struct mallinfo2 __libc_mallinfo2(void);
712 libc_hidden_proto (__libc_mallinfo2)
714 struct mallinfo __libc_mallinfo(void);
718 pvalloc(size_t n);
719 Equivalent to valloc(minimum-page-that-holds(n)), that is,
720 round up n to nearest pagesize.
722 void* __libc_pvalloc(size_t);
725 malloc_trim(size_t pad);
727 If possible, gives memory back to the system (via negative
728 arguments to sbrk) if there is unused memory at the `high' end of
729 the malloc pool. You can call this after freeing large blocks of
730 memory to potentially reduce the system-level memory requirements
731 of a program. However, it cannot guarantee to reduce memory. Under
732 some allocation patterns, some large free blocks of memory will be
733 locked between two used chunks, so they cannot be given back to
734 the system.
736 The `pad' argument to malloc_trim represents the amount of free
737 trailing space to leave untrimmed. If this argument is zero,
738 only the minimum amount of memory to maintain internal data
739 structures will be left (one page or less). Non-zero arguments
740 can be supplied to maintain enough trailing space to service
741 future expected allocations without having to re-obtain memory
742 from the system.
744 Malloc_trim returns 1 if it actually released any memory, else 0.
745 On systems that do not support "negative sbrks", it will always
746 return 0.
748 int __malloc_trim(size_t);
751 malloc_usable_size(void* p);
753 Returns the number of bytes you can actually use in
754 an allocated chunk, which may be more than you requested (although
755 often not) due to alignment and minimum size constraints.
756 You can use this many bytes without worrying about
757 overwriting other allocated objects. This is not a particularly great
758 programming practice. malloc_usable_size can be more useful in
759 debugging and assertions, for example:
761 p = malloc(n);
762 assert(malloc_usable_size(p) >= 256);
765 size_t __malloc_usable_size(void*);
768 malloc_stats();
769 Prints on stderr the amount of space obtained from the system (both
770 via sbrk and mmap), the maximum amount (which may be more than
771 current if malloc_trim and/or munmap got called), and the current
772 number of bytes allocated via malloc (or realloc, etc) but not yet
773 freed. Note that this is the number of bytes allocated, not the
774 number requested. It will be larger than the number requested
775 because of alignment and bookkeeping overhead. Because it includes
776 alignment wastage as being in use, this figure may be greater than
777 zero even when no user-level chunks are allocated.
779 The reported current and maximum system memory can be inaccurate if
780 a program makes other calls to system memory allocation functions
781 (normally sbrk) outside of malloc.
783 malloc_stats prints only the most commonly interesting statistics.
784 More information can be obtained by calling mallinfo.
787 void __malloc_stats(void);
790 posix_memalign(void **memptr, size_t alignment, size_t size);
792 POSIX wrapper like memalign(), checking for validity of size.
794 int __posix_memalign(void **, size_t, size_t);
795 #endif /* IS_IN (libc) */
798 mallopt(int parameter_number, int parameter_value)
799 Sets tunable parameters The format is to provide a
800 (parameter-number, parameter-value) pair. mallopt then sets the
801 corresponding parameter to the argument value if it can (i.e., so
802 long as the value is meaningful), and returns 1 if successful else
803 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
804 normally defined in malloc.h. Only one of these (M_MXFAST) is used
805 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
806 so setting them has no effect. But this malloc also supports four
807 other options in mallopt. See below for details. Briefly, supported
808 parameters are as follows (listed defaults are for "typical"
809 configurations).
811 Symbol param # default allowed param values
812 M_MXFAST 1 64 0-80 (0 disables fastbins)
813 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
814 M_TOP_PAD -2 0 any
815 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
816 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
818 int __libc_mallopt(int, int);
819 #if IS_IN (libc)
820 libc_hidden_proto (__libc_mallopt)
821 #endif
823 /* mallopt tuning options */
826 M_MXFAST is the maximum request size used for "fastbins", special bins
827 that hold returned chunks without consolidating their spaces. This
828 enables future requests for chunks of the same size to be handled
829 very quickly, but can increase fragmentation, and thus increase the
830 overall memory footprint of a program.
832 This malloc manages fastbins very conservatively yet still
833 efficiently, so fragmentation is rarely a problem for values less
834 than or equal to the default. The maximum supported value of MXFAST
835 is 80. You wouldn't want it any higher than this anyway. Fastbins
836 are designed especially for use with many small structs, objects or
837 strings -- the default handles structs/objects/arrays with sizes up
838 to 8 4byte fields, or small strings representing words, tokens,
839 etc. Using fastbins for larger objects normally worsens
840 fragmentation without improving speed.
842 M_MXFAST is set in REQUEST size units. It is internally used in
843 chunksize units, which adds padding and alignment. You can reduce
844 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
845 algorithm to be a closer approximation of fifo-best-fit in all cases,
846 not just for larger requests, but will generally cause it to be
847 slower.
851 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
852 #ifndef M_MXFAST
853 #define M_MXFAST 1
854 #endif
856 #ifndef DEFAULT_MXFAST
857 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
858 #endif
862 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
863 to keep before releasing via malloc_trim in free().
865 Automatic trimming is mainly useful in long-lived programs.
866 Because trimming via sbrk can be slow on some systems, and can
867 sometimes be wasteful (in cases where programs immediately
868 afterward allocate more large chunks) the value should be high
869 enough so that your overall system performance would improve by
870 releasing this much memory.
872 The trim threshold and the mmap control parameters (see below)
873 can be traded off with one another. Trimming and mmapping are
874 two different ways of releasing unused memory back to the
875 system. Between these two, it is often possible to keep
876 system-level demands of a long-lived program down to a bare
877 minimum. For example, in one test suite of sessions measuring
878 the XF86 X server on Linux, using a trim threshold of 128K and a
879 mmap threshold of 192K led to near-minimal long term resource
880 consumption.
882 If you are using this malloc in a long-lived program, it should
883 pay to experiment with these values. As a rough guide, you
884 might set to a value close to the average size of a process
885 (program) running on your system. Releasing this much memory
886 would allow such a process to run in memory. Generally, it's
887 worth it to tune for trimming rather tham memory mapping when a
888 program undergoes phases where several large chunks are
889 allocated and released in ways that can reuse each other's
890 storage, perhaps mixed with phases where there are no such
891 chunks at all. And in well-behaved long-lived programs,
892 controlling release of large blocks via trimming versus mapping
893 is usually faster.
895 However, in most programs, these parameters serve mainly as
896 protection against the system-level effects of carrying around
897 massive amounts of unneeded memory. Since frequent calls to
898 sbrk, mmap, and munmap otherwise degrade performance, the default
899 parameters are set to relatively high values that serve only as
900 safeguards.
902 The trim value It must be greater than page size to have any useful
903 effect. To disable trimming completely, you can set to
904 (unsigned long)(-1)
906 Trim settings interact with fastbin (MXFAST) settings: Unless
907 TRIM_FASTBINS is defined, automatic trimming never takes place upon
908 freeing a chunk with size less than or equal to MXFAST. Trimming is
909 instead delayed until subsequent freeing of larger chunks. However,
910 you can still force an attempted trim by calling malloc_trim.
912 Also, trimming is not generally possible in cases where
913 the main arena is obtained via mmap.
915 Note that the trick some people use of mallocing a huge space and
916 then freeing it at program startup, in an attempt to reserve system
917 memory, doesn't have the intended effect under automatic trimming,
918 since that memory will immediately be returned to the system.
921 #define M_TRIM_THRESHOLD -1
923 #ifndef DEFAULT_TRIM_THRESHOLD
924 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
925 #endif
928 M_TOP_PAD is the amount of extra `padding' space to allocate or
929 retain whenever sbrk is called. It is used in two ways internally:
931 * When sbrk is called to extend the top of the arena to satisfy
932 a new malloc request, this much padding is added to the sbrk
933 request.
935 * When malloc_trim is called automatically from free(),
936 it is used as the `pad' argument.
938 In both cases, the actual amount of padding is rounded
939 so that the end of the arena is always a system page boundary.
941 The main reason for using padding is to avoid calling sbrk so
942 often. Having even a small pad greatly reduces the likelihood
943 that nearly every malloc request during program start-up (or
944 after trimming) will invoke sbrk, which needlessly wastes
945 time.
947 Automatic rounding-up to page-size units is normally sufficient
948 to avoid measurable overhead, so the default is 0. However, in
949 systems where sbrk is relatively slow, it can pay to increase
950 this value, at the expense of carrying around more memory than
951 the program needs.
954 #define M_TOP_PAD -2
956 #ifndef DEFAULT_TOP_PAD
957 #define DEFAULT_TOP_PAD (0)
958 #endif
961 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
962 adjusted MMAP_THRESHOLD.
965 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
966 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
967 #endif
969 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
970 /* For 32-bit platforms we cannot increase the maximum mmap
971 threshold much because it is also the minimum value for the
972 maximum heap size and its alignment. Going above 512k (i.e., 1M
973 for new heaps) wastes too much address space. */
974 # if __WORDSIZE == 32
975 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
976 # else
977 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
978 # endif
979 #endif
982 M_MMAP_THRESHOLD is the request size threshold for using mmap()
983 to service a request. Requests of at least this size that cannot
984 be allocated using already-existing space will be serviced via mmap.
985 (If enough normal freed space already exists it is used instead.)
987 Using mmap segregates relatively large chunks of memory so that
988 they can be individually obtained and released from the host
989 system. A request serviced through mmap is never reused by any
990 other request (at least not directly; the system may just so
991 happen to remap successive requests to the same locations).
993 Segregating space in this way has the benefits that:
995 1. Mmapped space can ALWAYS be individually released back
996 to the system, which helps keep the system level memory
997 demands of a long-lived program low.
998 2. Mapped memory can never become `locked' between
999 other chunks, as can happen with normally allocated chunks, which
1000 means that even trimming via malloc_trim would not release them.
1001 3. On some systems with "holes" in address spaces, mmap can obtain
1002 memory that sbrk cannot.
1004 However, it has the disadvantages that:
1006 1. The space cannot be reclaimed, consolidated, and then
1007 used to service later requests, as happens with normal chunks.
1008 2. It can lead to more wastage because of mmap page alignment
1009 requirements
1010 3. It causes malloc performance to be more dependent on host
1011 system memory management support routines which may vary in
1012 implementation quality and may impose arbitrary
1013 limitations. Generally, servicing a request via normal
1014 malloc steps is faster than going through a system's mmap.
1016 The advantages of mmap nearly always outweigh disadvantages for
1017 "large" chunks, but the value of "large" varies across systems. The
1018 default is an empirically derived value that works well in most
1019 systems.
1022 Update in 2006:
1023 The above was written in 2001. Since then the world has changed a lot.
1024 Memory got bigger. Applications got bigger. The virtual address space
1025 layout in 32 bit linux changed.
1027 In the new situation, brk() and mmap space is shared and there are no
1028 artificial limits on brk size imposed by the kernel. What is more,
1029 applications have started using transient allocations larger than the
1030 128Kb as was imagined in 2001.
1032 The price for mmap is also high now; each time glibc mmaps from the
1033 kernel, the kernel is forced to zero out the memory it gives to the
1034 application. Zeroing memory is expensive and eats a lot of cache and
1035 memory bandwidth. This has nothing to do with the efficiency of the
1036 virtual memory system, by doing mmap the kernel just has no choice but
1037 to zero.
1039 In 2001, the kernel had a maximum size for brk() which was about 800
1040 megabytes on 32 bit x86, at that point brk() would hit the first
1041 mmaped shared libaries and couldn't expand anymore. With current 2.6
1042 kernels, the VA space layout is different and brk() and mmap
1043 both can span the entire heap at will.
1045 Rather than using a static threshold for the brk/mmap tradeoff,
1046 we are now using a simple dynamic one. The goal is still to avoid
1047 fragmentation. The old goals we kept are
1048 1) try to get the long lived large allocations to use mmap()
1049 2) really large allocations should always use mmap()
1050 and we're adding now:
1051 3) transient allocations should use brk() to avoid forcing the kernel
1052 having to zero memory over and over again
1054 The implementation works with a sliding threshold, which is by default
1055 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
1056 out at 128Kb as per the 2001 default.
1058 This allows us to satisfy requirement 1) under the assumption that long
1059 lived allocations are made early in the process' lifespan, before it has
1060 started doing dynamic allocations of the same size (which will
1061 increase the threshold).
1063 The upperbound on the threshold satisfies requirement 2)
1065 The threshold goes up in value when the application frees memory that was
1066 allocated with the mmap allocator. The idea is that once the application
1067 starts freeing memory of a certain size, it's highly probable that this is
1068 a size the application uses for transient allocations. This estimator
1069 is there to satisfy the new third requirement.
1073 #define M_MMAP_THRESHOLD -3
1075 #ifndef DEFAULT_MMAP_THRESHOLD
1076 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1077 #endif
1080 M_MMAP_MAX is the maximum number of requests to simultaneously
1081 service using mmap. This parameter exists because
1082 some systems have a limited number of internal tables for
1083 use by mmap, and using more than a few of them may degrade
1084 performance.
1086 The default is set to a value that serves only as a safeguard.
1087 Setting to 0 disables use of mmap for servicing large requests.
1090 #define M_MMAP_MAX -4
1092 #ifndef DEFAULT_MMAP_MAX
1093 #define DEFAULT_MMAP_MAX (65536)
1094 #endif
1096 #include <malloc.h>
1098 #ifndef RETURN_ADDRESS
1099 #define RETURN_ADDRESS(X_) (NULL)
1100 #endif
1102 /* Forward declarations. */
1103 struct malloc_chunk;
1104 typedef struct malloc_chunk* mchunkptr;
1106 /* Internal routines. */
1108 static void* _int_malloc(mstate, size_t);
1109 static void _int_free(mstate, mchunkptr, int);
1110 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1111 INTERNAL_SIZE_T);
1112 static void* _int_memalign(mstate, size_t, size_t);
1113 #if IS_IN (libc)
1114 static void* _mid_memalign(size_t, size_t, void *);
1115 #endif
1117 static void malloc_printerr(const char *str) __attribute__ ((noreturn));
1119 static void munmap_chunk(mchunkptr p);
1120 #if HAVE_MREMAP
1121 static mchunkptr mremap_chunk(mchunkptr p, size_t new_size);
1122 #endif
1124 /* ------------------ MMAP support ------------------ */
1127 #include <fcntl.h>
1128 #include <sys/mman.h>
1130 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1131 # define MAP_ANONYMOUS MAP_ANON
1132 #endif
1134 #ifndef MAP_NORESERVE
1135 # define MAP_NORESERVE 0
1136 #endif
1138 #define MMAP(addr, size, prot, flags) \
1139 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1143 ----------------------- Chunk representations -----------------------
1148 This struct declaration is misleading (but accurate and necessary).
1149 It declares a "view" into memory allowing access to necessary
1150 fields at known offsets from a given base. See explanation below.
1153 struct malloc_chunk {
1155 INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk (if free). */
1156 INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
1158 struct malloc_chunk* fd; /* double links -- used only if free. */
1159 struct malloc_chunk* bk;
1161 /* Only used for large blocks: pointer to next larger size. */
1162 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1163 struct malloc_chunk* bk_nextsize;
1168 malloc_chunk details:
1170 (The following includes lightly edited explanations by Colin Plumb.)
1172 Chunks of memory are maintained using a `boundary tag' method as
1173 described in e.g., Knuth or Standish. (See the paper by Paul
1174 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1175 survey of such techniques.) Sizes of free chunks are stored both
1176 in the front of each chunk and at the end. This makes
1177 consolidating fragmented chunks into bigger chunks very fast. The
1178 size fields also hold bits representing whether chunks are free or
1179 in use.
1181 An allocated chunk looks like this:
1184 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1185 | Size of previous chunk, if unallocated (P clear) |
1186 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1187 | Size of chunk, in bytes |A|M|P|
1188 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1189 | User data starts here... .
1191 . (malloc_usable_size() bytes) .
1193 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1194 | (size of chunk, but used for application data) |
1195 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1196 | Size of next chunk, in bytes |A|0|1|
1197 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1199 Where "chunk" is the front of the chunk for the purpose of most of
1200 the malloc code, but "mem" is the pointer that is returned to the
1201 user. "Nextchunk" is the beginning of the next contiguous chunk.
1203 Chunks always begin on even word boundaries, so the mem portion
1204 (which is returned to the user) is also on an even word boundary, and
1205 thus at least double-word aligned.
1207 Free chunks are stored in circular doubly-linked lists, and look like this:
1209 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1210 | Size of previous chunk, if unallocated (P clear) |
1211 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1212 `head:' | Size of chunk, in bytes |A|0|P|
1213 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1214 | Forward pointer to next chunk in list |
1215 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1216 | Back pointer to previous chunk in list |
1217 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1218 | Unused space (may be 0 bytes long) .
1221 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1222 `foot:' | Size of chunk, in bytes |
1223 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1224 | Size of next chunk, in bytes |A|0|0|
1225 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1227 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1228 chunk size (which is always a multiple of two words), is an in-use
1229 bit for the *previous* chunk. If that bit is *clear*, then the
1230 word before the current chunk size contains the previous chunk
1231 size, and can be used to find the front of the previous chunk.
1232 The very first chunk allocated always has this bit set,
1233 preventing access to non-existent (or non-owned) memory. If
1234 prev_inuse is set for any given chunk, then you CANNOT determine
1235 the size of the previous chunk, and might even get a memory
1236 addressing fault when trying to do so.
1238 The A (NON_MAIN_ARENA) bit is cleared for chunks on the initial,
1239 main arena, described by the main_arena variable. When additional
1240 threads are spawned, each thread receives its own arena (up to a
1241 configurable limit, after which arenas are reused for multiple
1242 threads), and the chunks in these arenas have the A bit set. To
1243 find the arena for a chunk on such a non-main arena, heap_for_ptr
1244 performs a bit mask operation and indirection through the ar_ptr
1245 member of the per-heap header heap_info (see arena.c).
1247 Note that the `foot' of the current chunk is actually represented
1248 as the prev_size of the NEXT chunk. This makes it easier to
1249 deal with alignments etc but can be very confusing when trying
1250 to extend or adapt this code.
1252 The three exceptions to all this are:
1254 1. The special chunk `top' doesn't bother using the
1255 trailing size field since there is no next contiguous chunk
1256 that would have to index off it. After initialization, `top'
1257 is forced to always exist. If it would become less than
1258 MINSIZE bytes long, it is replenished.
1260 2. Chunks allocated via mmap, which have the second-lowest-order
1261 bit M (IS_MMAPPED) set in their size fields. Because they are
1262 allocated one-by-one, each must contain its own trailing size
1263 field. If the M bit is set, the other bits are ignored
1264 (because mmapped chunks are neither in an arena, nor adjacent
1265 to a freed chunk). The M bit is also used for chunks which
1266 originally came from a dumped heap via malloc_set_state in
1267 hooks.c.
1269 3. Chunks in fastbins are treated as allocated chunks from the
1270 point of view of the chunk allocator. They are consolidated
1271 with their neighbors only in bulk, in malloc_consolidate.
1275 ---------- Size and alignment checks and conversions ----------
1278 /* Conversion from malloc headers to user pointers, and back. When
1279 using memory tagging the user data and the malloc data structure
1280 headers have distinct tags. Converting fully from one to the other
1281 involves extracting the tag at the other address and creating a
1282 suitable pointer using it. That can be quite expensive. There are
1283 cases when the pointers are not dereferenced (for example only used
1284 for alignment check) so the tags are not relevant, and there are
1285 cases when user data is not tagged distinctly from malloc headers
1286 (user data is untagged because tagging is done late in malloc and
1287 early in free). User memory tagging across internal interfaces:
1289 sysmalloc: Returns untagged memory.
1290 _int_malloc: Returns untagged memory.
1291 _int_free: Takes untagged memory.
1292 _int_memalign: Returns untagged memory.
1293 _int_memalign: Returns untagged memory.
1294 _mid_memalign: Returns tagged memory.
1295 _int_realloc: Takes and returns tagged memory.
1298 /* The chunk header is two SIZE_SZ elements, but this is used widely, so
1299 we define it here for clarity later. */
1300 #define CHUNK_HDR_SZ (2 * SIZE_SZ)
1302 /* Convert a chunk address to a user mem pointer without correcting
1303 the tag. */
1304 #define chunk2mem(p) ((void*)((char*)(p) + CHUNK_HDR_SZ))
1306 /* Convert a chunk address to a user mem pointer and extract the right tag. */
1307 #define chunk2mem_tag(p) ((void*)tag_at ((char*)(p) + CHUNK_HDR_SZ))
1309 /* Convert a user mem pointer to a chunk address and extract the right tag. */
1310 #define mem2chunk(mem) ((mchunkptr)tag_at (((char*)(mem) - CHUNK_HDR_SZ)))
1312 /* The smallest possible chunk */
1313 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1315 /* The smallest size we can malloc is an aligned minimal chunk */
1317 #define MINSIZE \
1318 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1320 /* Check if m has acceptable alignment */
1322 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1324 #define misaligned_chunk(p) \
1325 ((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \
1326 & MALLOC_ALIGN_MASK)
1328 /* pad request bytes into a usable size -- internal version */
1329 /* Note: This must be a macro that evaluates to a compile time constant
1330 if passed a literal constant. */
1331 #define request2size(req) \
1332 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1333 MINSIZE : \
1334 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1336 /* Check if REQ overflows when padded and aligned and if the resulting value
1337 is less than PTRDIFF_T. Returns TRUE and the requested size or MINSIZE in
1338 case the value is less than MINSIZE on SZ or false if any of the previous
1339 check fail. */
1340 static inline bool
1341 checked_request2size (size_t req, size_t *sz) __nonnull (1)
1343 if (__glibc_unlikely (req > PTRDIFF_MAX))
1344 return false;
1346 /* When using tagged memory, we cannot share the end of the user
1347 block with the header for the next chunk, so ensure that we
1348 allocate blocks that are rounded up to the granule size. Take
1349 care not to overflow from close to MAX_SIZE_T to a small
1350 number. Ideally, this would be part of request2size(), but that
1351 must be a macro that produces a compile time constant if passed
1352 a constant literal. */
1353 if (__glibc_unlikely (mtag_enabled))
1355 /* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551. */
1356 asm ("");
1358 req = (req + (__MTAG_GRANULE_SIZE - 1)) &
1359 ~(size_t)(__MTAG_GRANULE_SIZE - 1);
1362 *sz = request2size (req);
1363 return true;
1367 --------------- Physical chunk operations ---------------
1371 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1372 #define PREV_INUSE 0x1
1374 /* extract inuse bit of previous chunk */
1375 #define prev_inuse(p) ((p)->mchunk_size & PREV_INUSE)
1378 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1379 #define IS_MMAPPED 0x2
1381 /* check for mmap()'ed chunk */
1382 #define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)
1385 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1386 from a non-main arena. This is only set immediately before handing
1387 the chunk to the user, if necessary. */
1388 #define NON_MAIN_ARENA 0x4
1390 /* Check for chunk from main arena. */
1391 #define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)
1393 /* Mark a chunk as not being on the main arena. */
1394 #define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
1398 Bits to mask off when extracting size
1400 Note: IS_MMAPPED is intentionally not masked off from size field in
1401 macros for which mmapped chunks should never be seen. This should
1402 cause helpful core dumps to occur if it is tried by accident by
1403 people extending or adapting this malloc.
1405 #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1407 /* Get size, ignoring use bits */
1408 #define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))
1410 /* Like chunksize, but do not mask SIZE_BITS. */
1411 #define chunksize_nomask(p) ((p)->mchunk_size)
1413 /* Ptr to next physical malloc_chunk. */
1414 #define next_chunk(p) ((mchunkptr) (((char *) (p)) + chunksize (p)))
1416 /* Size of the chunk below P. Only valid if !prev_inuse (P). */
1417 #define prev_size(p) ((p)->mchunk_prev_size)
1419 /* Set the size of the chunk below P. Only valid if !prev_inuse (P). */
1420 #define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))
1422 /* Ptr to previous physical malloc_chunk. Only valid if !prev_inuse (P). */
1423 #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - prev_size (p)))
1425 /* Treat space at ptr + offset as a chunk */
1426 #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1428 /* extract p's inuse bit */
1429 #define inuse(p) \
1430 ((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
1432 /* set/clear chunk as being inuse without otherwise disturbing */
1433 #define set_inuse(p) \
1434 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
1436 #define clear_inuse(p) \
1437 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
1440 /* check/set/clear inuse bits in known places */
1441 #define inuse_bit_at_offset(p, s) \
1442 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
1444 #define set_inuse_bit_at_offset(p, s) \
1445 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
1447 #define clear_inuse_bit_at_offset(p, s) \
1448 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
1451 /* Set size at head, without disturbing its use bit */
1452 #define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
1454 /* Set size/use field */
1455 #define set_head(p, s) ((p)->mchunk_size = (s))
1457 /* Set size at footer (only when chunk is not in use) */
1458 #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
1460 #pragma GCC poison mchunk_size
1461 #pragma GCC poison mchunk_prev_size
1463 /* This is the size of the real usable data in the chunk. Not valid for
1464 dumped heap chunks. */
1465 #define memsize(p) \
1466 (__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \
1467 chunksize (p) - CHUNK_HDR_SZ : \
1468 chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ))
1470 /* If memory tagging is enabled the layout changes to accommodate the granule
1471 size, this is wasteful for small allocations so not done by default.
1472 Both the chunk header and user data has to be granule aligned. */
1473 _Static_assert (__MTAG_GRANULE_SIZE <= CHUNK_HDR_SZ,
1474 "memory tagging is not supported with large granule.");
1476 static __always_inline void *
1477 tag_new_usable (void *ptr)
1479 if (__glibc_unlikely (mtag_enabled) && ptr)
1481 mchunkptr cp = mem2chunk(ptr);
1482 ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp));
1484 return ptr;
1488 -------------------- Internal data structures --------------------
1490 All internal state is held in an instance of malloc_state defined
1491 below. There are no other static variables, except in two optional
1492 cases:
1493 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1494 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1495 for mmap.
1497 Beware of lots of tricks that minimize the total bookkeeping space
1498 requirements. The result is a little over 1K bytes (for 4byte
1499 pointers and size_t.)
1503 Bins
1505 An array of bin headers for free chunks. Each bin is doubly
1506 linked. The bins are approximately proportionally (log) spaced.
1507 There are a lot of these bins (128). This may look excessive, but
1508 works very well in practice. Most bins hold sizes that are
1509 unusual as malloc request sizes, but are more usual for fragments
1510 and consolidated sets of chunks, which is what these bins hold, so
1511 they can be found quickly. All procedures maintain the invariant
1512 that no consolidated chunk physically borders another one, so each
1513 chunk in a list is known to be preceeded and followed by either
1514 inuse chunks or the ends of memory.
1516 Chunks in bins are kept in size order, with ties going to the
1517 approximately least recently used chunk. Ordering isn't needed
1518 for the small bins, which all contain the same-sized chunks, but
1519 facilitates best-fit allocation for larger chunks. These lists
1520 are just sequential. Keeping them in order almost never requires
1521 enough traversal to warrant using fancier ordered data
1522 structures.
1524 Chunks of the same size are linked with the most
1525 recently freed at the front, and allocations are taken from the
1526 back. This results in LRU (FIFO) allocation order, which tends
1527 to give each chunk an equal opportunity to be consolidated with
1528 adjacent freed chunks, resulting in larger free chunks and less
1529 fragmentation.
1531 To simplify use in double-linked lists, each bin header acts
1532 as a malloc_chunk. This avoids special-casing for headers.
1533 But to conserve space and improve locality, we allocate
1534 only the fd/bk pointers of bins, and then use repositioning tricks
1535 to treat these as the fields of a malloc_chunk*.
1538 typedef struct malloc_chunk *mbinptr;
1540 /* addressing -- note that bin_at(0) does not exist */
1541 #define bin_at(m, i) \
1542 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1543 - offsetof (struct malloc_chunk, fd))
1545 /* analog of ++bin */
1546 #define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
1548 /* Reminders about list directionality within bins */
1549 #define first(b) ((b)->fd)
1550 #define last(b) ((b)->bk)
1553 Indexing
1555 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1556 8 bytes apart. Larger bins are approximately logarithmically spaced:
1558 64 bins of size 8
1559 32 bins of size 64
1560 16 bins of size 512
1561 8 bins of size 4096
1562 4 bins of size 32768
1563 2 bins of size 262144
1564 1 bin of size what's left
1566 There is actually a little bit of slop in the numbers in bin_index
1567 for the sake of speed. This makes no difference elsewhere.
1569 The bins top out around 1MB because we expect to service large
1570 requests via mmap.
1572 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1573 a valid chunk size the small bins are bumped up one.
1576 #define NBINS 128
1577 #define NSMALLBINS 64
1578 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1579 #define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > CHUNK_HDR_SZ)
1580 #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
1582 #define in_smallbin_range(sz) \
1583 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
1585 #define smallbin_index(sz) \
1586 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
1587 + SMALLBIN_CORRECTION)
1589 #define largebin_index_32(sz) \
1590 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1591 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1592 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1593 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1594 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1595 126)
1597 #define largebin_index_32_big(sz) \
1598 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1599 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1600 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1601 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1602 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1603 126)
1605 // XXX It remains to be seen whether it is good to keep the widths of
1606 // XXX the buckets the same or whether it should be scaled by a factor
1607 // XXX of two as well.
1608 #define largebin_index_64(sz) \
1609 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1610 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1611 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1612 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1613 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1614 126)
1616 #define largebin_index(sz) \
1617 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1618 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1619 : largebin_index_32 (sz))
1621 #define bin_index(sz) \
1622 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
1624 /* Take a chunk off a bin list. */
1625 static void
1626 unlink_chunk (mstate av, mchunkptr p)
1628 if (chunksize (p) != prev_size (next_chunk (p)))
1629 malloc_printerr ("corrupted size vs. prev_size");
1631 mchunkptr fd = p->fd;
1632 mchunkptr bk = p->bk;
1634 if (__builtin_expect (fd->bk != p || bk->fd != p, 0))
1635 malloc_printerr ("corrupted double-linked list");
1637 fd->bk = bk;
1638 bk->fd = fd;
1639 if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL)
1641 if (p->fd_nextsize->bk_nextsize != p
1642 || p->bk_nextsize->fd_nextsize != p)
1643 malloc_printerr ("corrupted double-linked list (not small)");
1645 if (fd->fd_nextsize == NULL)
1647 if (p->fd_nextsize == p)
1648 fd->fd_nextsize = fd->bk_nextsize = fd;
1649 else
1651 fd->fd_nextsize = p->fd_nextsize;
1652 fd->bk_nextsize = p->bk_nextsize;
1653 p->fd_nextsize->bk_nextsize = fd;
1654 p->bk_nextsize->fd_nextsize = fd;
1657 else
1659 p->fd_nextsize->bk_nextsize = p->bk_nextsize;
1660 p->bk_nextsize->fd_nextsize = p->fd_nextsize;
1666 Unsorted chunks
1668 All remainders from chunk splits, as well as all returned chunks,
1669 are first placed in the "unsorted" bin. They are then placed
1670 in regular bins after malloc gives them ONE chance to be used before
1671 binning. So, basically, the unsorted_chunks list acts as a queue,
1672 with chunks being placed on it in free (and malloc_consolidate),
1673 and taken off (to be either used or placed in bins) in malloc.
1675 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1676 does not have to be taken into account in size comparisons.
1679 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1680 #define unsorted_chunks(M) (bin_at (M, 1))
1685 The top-most available chunk (i.e., the one bordering the end of
1686 available memory) is treated specially. It is never included in
1687 any bin, is used only if no other chunk is available, and is
1688 released back to the system if it is very large (see
1689 M_TRIM_THRESHOLD). Because top initially
1690 points to its own bin with initial zero size, thus forcing
1691 extension on the first malloc request, we avoid having any special
1692 code in malloc to check whether it even exists yet. But we still
1693 need to do so when getting memory from system, so we make
1694 initial_top treat the bin as a legal but unusable chunk during the
1695 interval between initialization and the first call to
1696 sysmalloc. (This is somewhat delicate, since it relies on
1697 the 2 preceding words to be zero during this interval as well.)
1700 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1701 #define initial_top(M) (unsorted_chunks (M))
1704 Binmap
1706 To help compensate for the large number of bins, a one-level index
1707 structure is used for bin-by-bin searching. `binmap' is a
1708 bitvector recording whether bins are definitely empty so they can
1709 be skipped over during during traversals. The bits are NOT always
1710 cleared as soon as bins are empty, but instead only
1711 when they are noticed to be empty during traversal in malloc.
1714 /* Conservatively use 32 bits per map word, even if on 64bit system */
1715 #define BINMAPSHIFT 5
1716 #define BITSPERMAP (1U << BINMAPSHIFT)
1717 #define BINMAPSIZE (NBINS / BITSPERMAP)
1719 #define idx2block(i) ((i) >> BINMAPSHIFT)
1720 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
1722 #define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1723 #define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1724 #define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
1727 Fastbins
1729 An array of lists holding recently freed small chunks. Fastbins
1730 are not doubly linked. It is faster to single-link them, and
1731 since chunks are never removed from the middles of these lists,
1732 double linking is not necessary. Also, unlike regular bins, they
1733 are not even processed in FIFO order (they use faster LIFO) since
1734 ordering doesn't much matter in the transient contexts in which
1735 fastbins are normally used.
1737 Chunks in fastbins keep their inuse bit set, so they cannot
1738 be consolidated with other free chunks. malloc_consolidate
1739 releases all chunks in fastbins and consolidates them with
1740 other free chunks.
1743 typedef struct malloc_chunk *mfastbinptr;
1744 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1746 /* offset 2 to use otherwise unindexable first 2 bins */
1747 #define fastbin_index(sz) \
1748 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1751 /* The maximum fastbin request size we support */
1752 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1754 #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
1757 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1758 that triggers automatic consolidation of possibly-surrounding
1759 fastbin chunks. This is a heuristic, so the exact value should not
1760 matter too much. It is defined at half the default trim threshold as a
1761 compromise heuristic to only attempt consolidation if it is likely
1762 to lead to trimming. However, it is not dynamically tunable, since
1763 consolidation reduces fragmentation surrounding large chunks even
1764 if trimming is not used.
1767 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1770 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1771 regions. Otherwise, contiguity is exploited in merging together,
1772 when possible, results from consecutive MORECORE calls.
1774 The initial value comes from MORECORE_CONTIGUOUS, but is
1775 changed dynamically if mmap is ever used as an sbrk substitute.
1778 #define NONCONTIGUOUS_BIT (2U)
1780 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1781 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1782 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1783 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1785 /* Maximum size of memory handled in fastbins. */
1786 static INTERNAL_SIZE_T global_max_fast;
1789 Set value of max_fast.
1790 Use impossibly small value if 0.
1791 Precondition: there are no existing fastbin chunks in the main arena.
1792 Since do_check_malloc_state () checks this, we call malloc_consolidate ()
1793 before changing max_fast. Note other arenas will leak their fast bin
1794 entries if max_fast is reduced.
1797 #define set_max_fast(s) \
1798 global_max_fast = (((size_t) (s) <= MALLOC_ALIGN_MASK - SIZE_SZ) \
1799 ? MIN_CHUNK_SIZE / 2 : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1801 static inline INTERNAL_SIZE_T
1802 get_max_fast (void)
1804 /* Tell the GCC optimizers that global_max_fast is never larger
1805 than MAX_FAST_SIZE. This avoids out-of-bounds array accesses in
1806 _int_malloc after constant propagation of the size parameter.
1807 (The code never executes because malloc preserves the
1808 global_max_fast invariant, but the optimizers may not recognize
1809 this.) */
1810 if (global_max_fast > MAX_FAST_SIZE)
1811 __builtin_unreachable ();
1812 return global_max_fast;
1816 ----------- Internal state representation and initialization -----------
1820 have_fastchunks indicates that there are probably some fastbin chunks.
1821 It is set true on entering a chunk into any fastbin, and cleared early in
1822 malloc_consolidate. The value is approximate since it may be set when there
1823 are no fastbin chunks, or it may be clear even if there are fastbin chunks
1824 available. Given it's sole purpose is to reduce number of redundant calls to
1825 malloc_consolidate, it does not affect correctness. As a result we can safely
1826 use relaxed atomic accesses.
1830 struct malloc_state
1832 /* Serialize access. */
1833 __libc_lock_define (, mutex);
1835 /* Flags (formerly in max_fast). */
1836 int flags;
1838 /* Set if the fastbin chunks contain recently inserted free blocks. */
1839 /* Note this is a bool but not all targets support atomics on booleans. */
1840 int have_fastchunks;
1842 /* Fastbins */
1843 mfastbinptr fastbinsY[NFASTBINS];
1845 /* Base of the topmost chunk -- not otherwise kept in a bin */
1846 mchunkptr top;
1848 /* The remainder from the most recent split of a small request */
1849 mchunkptr last_remainder;
1851 /* Normal bins packed as described above */
1852 mchunkptr bins[NBINS * 2 - 2];
1854 /* Bitmap of bins */
1855 unsigned int binmap[BINMAPSIZE];
1857 /* Linked list */
1858 struct malloc_state *next;
1860 /* Linked list for free arenas. Access to this field is serialized
1861 by free_list_lock in arena.c. */
1862 struct malloc_state *next_free;
1864 /* Number of threads attached to this arena. 0 if the arena is on
1865 the free list. Access to this field is serialized by
1866 free_list_lock in arena.c. */
1867 INTERNAL_SIZE_T attached_threads;
1869 /* Memory allocated from the system in this arena. */
1870 INTERNAL_SIZE_T system_mem;
1871 INTERNAL_SIZE_T max_system_mem;
1874 struct malloc_par
1876 /* Tunable parameters */
1877 unsigned long trim_threshold;
1878 INTERNAL_SIZE_T top_pad;
1879 INTERNAL_SIZE_T mmap_threshold;
1880 INTERNAL_SIZE_T arena_test;
1881 INTERNAL_SIZE_T arena_max;
1883 /* Memory map support */
1884 int n_mmaps;
1885 int n_mmaps_max;
1886 int max_n_mmaps;
1887 /* the mmap_threshold is dynamic, until the user sets
1888 it manually, at which point we need to disable any
1889 dynamic behavior. */
1890 int no_dyn_threshold;
1892 /* Statistics */
1893 INTERNAL_SIZE_T mmapped_mem;
1894 INTERNAL_SIZE_T max_mmapped_mem;
1896 /* First address handed out by MORECORE/sbrk. */
1897 char *sbrk_base;
1899 #if USE_TCACHE
1900 /* Maximum number of buckets to use. */
1901 size_t tcache_bins;
1902 size_t tcache_max_bytes;
1903 /* Maximum number of chunks in each bucket. */
1904 size_t tcache_count;
1905 /* Maximum number of chunks to remove from the unsorted list, which
1906 aren't used to prefill the cache. */
1907 size_t tcache_unsorted_limit;
1908 #endif
1911 /* There are several instances of this struct ("arenas") in this
1912 malloc. If you are adapting this malloc in a way that does NOT use
1913 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1914 before using. This malloc relies on the property that malloc_state
1915 is initialized to all zeroes (as is true of C statics). */
1917 static struct malloc_state main_arena =
1919 .mutex = _LIBC_LOCK_INITIALIZER,
1920 .next = &main_arena,
1921 .attached_threads = 1
1924 /* There is only one instance of the malloc parameters. */
1926 static struct malloc_par mp_ =
1928 .top_pad = DEFAULT_TOP_PAD,
1929 .n_mmaps_max = DEFAULT_MMAP_MAX,
1930 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1931 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1932 #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1933 .arena_test = NARENAS_FROM_NCORES (1)
1934 #if USE_TCACHE
1936 .tcache_count = TCACHE_FILL_COUNT,
1937 .tcache_bins = TCACHE_MAX_BINS,
1938 .tcache_max_bytes = tidx2usize (TCACHE_MAX_BINS-1),
1939 .tcache_unsorted_limit = 0 /* No limit. */
1940 #endif
1944 Initialize a malloc_state struct.
1946 This is called from ptmalloc_init () or from _int_new_arena ()
1947 when creating a new arena.
1950 static void
1951 malloc_init_state (mstate av)
1953 int i;
1954 mbinptr bin;
1956 /* Establish circular links for normal bins */
1957 for (i = 1; i < NBINS; ++i)
1959 bin = bin_at (av, i);
1960 bin->fd = bin->bk = bin;
1963 #if MORECORE_CONTIGUOUS
1964 if (av != &main_arena)
1965 #endif
1966 set_noncontiguous (av);
1967 if (av == &main_arena)
1968 set_max_fast (DEFAULT_MXFAST);
1969 atomic_store_relaxed (&av->have_fastchunks, false);
1971 av->top = initial_top (av);
1975 Other internal utilities operating on mstates
1978 static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1979 static int systrim (size_t, mstate);
1980 static void malloc_consolidate (mstate);
1983 /* -------------- Early definitions for debugging hooks ---------------- */
1985 /* This function is called from the arena shutdown hook, to free the
1986 thread cache (if it exists). */
1987 static void tcache_thread_shutdown (void);
1989 /* ------------------ Testing support ----------------------------------*/
1991 static int perturb_byte;
1993 static void
1994 alloc_perturb (char *p, size_t n)
1996 if (__glibc_unlikely (perturb_byte))
1997 memset (p, perturb_byte ^ 0xff, n);
2000 static void
2001 free_perturb (char *p, size_t n)
2003 if (__glibc_unlikely (perturb_byte))
2004 memset (p, perturb_byte, n);
2009 #include <stap-probe.h>
2011 /* ------------------- Support for multiple arenas -------------------- */
2012 #include "arena.c"
2015 Debugging support
2017 These routines make a number of assertions about the states
2018 of data structures that should be true at all times. If any
2019 are not true, it's very likely that a user program has somehow
2020 trashed memory. (It's also possible that there is a coding error
2021 in malloc. In which case, please report it!)
2024 #if !MALLOC_DEBUG
2026 # define check_chunk(A, P)
2027 # define check_free_chunk(A, P)
2028 # define check_inuse_chunk(A, P)
2029 # define check_remalloced_chunk(A, P, N)
2030 # define check_malloced_chunk(A, P, N)
2031 # define check_malloc_state(A)
2033 #else
2035 # define check_chunk(A, P) do_check_chunk (A, P)
2036 # define check_free_chunk(A, P) do_check_free_chunk (A, P)
2037 # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
2038 # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
2039 # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
2040 # define check_malloc_state(A) do_check_malloc_state (A)
2043 Properties of all chunks
2046 static void
2047 do_check_chunk (mstate av, mchunkptr p)
2049 unsigned long sz = chunksize (p);
2050 /* min and max possible addresses assuming contiguous allocation */
2051 char *max_address = (char *) (av->top) + chunksize (av->top);
2052 char *min_address = max_address - av->system_mem;
2054 if (!chunk_is_mmapped (p))
2056 /* Has legal address ... */
2057 if (p != av->top)
2059 if (contiguous (av))
2061 assert (((char *) p) >= min_address);
2062 assert (((char *) p + sz) <= ((char *) (av->top)));
2065 else
2067 /* top size is always at least MINSIZE */
2068 assert ((unsigned long) (sz) >= MINSIZE);
2069 /* top predecessor always marked inuse */
2070 assert (prev_inuse (p));
2073 else
2075 /* address is outside main heap */
2076 if (contiguous (av) && av->top != initial_top (av))
2078 assert (((char *) p) < min_address || ((char *) p) >= max_address);
2080 /* chunk is page-aligned */
2081 assert (((prev_size (p) + sz) & (GLRO (dl_pagesize) - 1)) == 0);
2082 /* mem is aligned */
2083 assert (aligned_OK (chunk2mem (p)));
2088 Properties of free chunks
2091 static void
2092 do_check_free_chunk (mstate av, mchunkptr p)
2094 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2095 mchunkptr next = chunk_at_offset (p, sz);
2097 do_check_chunk (av, p);
2099 /* Chunk must claim to be free ... */
2100 assert (!inuse (p));
2101 assert (!chunk_is_mmapped (p));
2103 /* Unless a special marker, must have OK fields */
2104 if ((unsigned long) (sz) >= MINSIZE)
2106 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2107 assert (aligned_OK (chunk2mem (p)));
2108 /* ... matching footer field */
2109 assert (prev_size (next_chunk (p)) == sz);
2110 /* ... and is fully consolidated */
2111 assert (prev_inuse (p));
2112 assert (next == av->top || inuse (next));
2114 /* ... and has minimally sane links */
2115 assert (p->fd->bk == p);
2116 assert (p->bk->fd == p);
2118 else /* markers are always of size SIZE_SZ */
2119 assert (sz == SIZE_SZ);
2123 Properties of inuse chunks
2126 static void
2127 do_check_inuse_chunk (mstate av, mchunkptr p)
2129 mchunkptr next;
2131 do_check_chunk (av, p);
2133 if (chunk_is_mmapped (p))
2134 return; /* mmapped chunks have no next/prev */
2136 /* Check whether it claims to be in use ... */
2137 assert (inuse (p));
2139 next = next_chunk (p);
2141 /* ... and is surrounded by OK chunks.
2142 Since more things can be checked with free chunks than inuse ones,
2143 if an inuse chunk borders them and debug is on, it's worth doing them.
2145 if (!prev_inuse (p))
2147 /* Note that we cannot even look at prev unless it is not inuse */
2148 mchunkptr prv = prev_chunk (p);
2149 assert (next_chunk (prv) == p);
2150 do_check_free_chunk (av, prv);
2153 if (next == av->top)
2155 assert (prev_inuse (next));
2156 assert (chunksize (next) >= MINSIZE);
2158 else if (!inuse (next))
2159 do_check_free_chunk (av, next);
2163 Properties of chunks recycled from fastbins
2166 static void
2167 do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2169 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2171 if (!chunk_is_mmapped (p))
2173 assert (av == arena_for_chunk (p));
2174 if (chunk_main_arena (p))
2175 assert (av == &main_arena);
2176 else
2177 assert (av != &main_arena);
2180 do_check_inuse_chunk (av, p);
2182 /* Legal size ... */
2183 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2184 assert ((unsigned long) (sz) >= MINSIZE);
2185 /* ... and alignment */
2186 assert (aligned_OK (chunk2mem (p)));
2187 /* chunk is less than MINSIZE more than request */
2188 assert ((long) (sz) - (long) (s) >= 0);
2189 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2193 Properties of nonrecycled chunks at the point they are malloced
2196 static void
2197 do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2199 /* same as recycled case ... */
2200 do_check_remalloced_chunk (av, p, s);
2203 ... plus, must obey implementation invariant that prev_inuse is
2204 always true of any allocated chunk; i.e., that each allocated
2205 chunk borders either a previously allocated and still in-use
2206 chunk, or the base of its memory arena. This is ensured
2207 by making all allocations from the `lowest' part of any found
2208 chunk. This does not necessarily hold however for chunks
2209 recycled via fastbins.
2212 assert (prev_inuse (p));
2217 Properties of malloc_state.
2219 This may be useful for debugging malloc, as well as detecting user
2220 programmer errors that somehow write into malloc_state.
2222 If you are extending or experimenting with this malloc, you can
2223 probably figure out how to hack this routine to print out or
2224 display chunk addresses, sizes, bins, and other instrumentation.
2227 static void
2228 do_check_malloc_state (mstate av)
2230 int i;
2231 mchunkptr p;
2232 mchunkptr q;
2233 mbinptr b;
2234 unsigned int idx;
2235 INTERNAL_SIZE_T size;
2236 unsigned long total = 0;
2237 int max_fast_bin;
2239 /* internal size_t must be no wider than pointer type */
2240 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2242 /* alignment is a power of 2 */
2243 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2245 /* Check the arena is initialized. */
2246 assert (av->top != 0);
2248 /* No memory has been allocated yet, so doing more tests is not possible. */
2249 if (av->top == initial_top (av))
2250 return;
2252 /* pagesize is a power of 2 */
2253 assert (powerof2(GLRO (dl_pagesize)));
2255 /* A contiguous main_arena is consistent with sbrk_base. */
2256 if (av == &main_arena && contiguous (av))
2257 assert ((char *) mp_.sbrk_base + av->system_mem ==
2258 (char *) av->top + chunksize (av->top));
2260 /* properties of fastbins */
2262 /* max_fast is in allowed range */
2263 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2265 max_fast_bin = fastbin_index (get_max_fast ());
2267 for (i = 0; i < NFASTBINS; ++i)
2269 p = fastbin (av, i);
2271 /* The following test can only be performed for the main arena.
2272 While mallopt calls malloc_consolidate to get rid of all fast
2273 bins (especially those larger than the new maximum) this does
2274 only happen for the main arena. Trying to do this for any
2275 other arena would mean those arenas have to be locked and
2276 malloc_consolidate be called for them. This is excessive. And
2277 even if this is acceptable to somebody it still cannot solve
2278 the problem completely since if the arena is locked a
2279 concurrent malloc call might create a new arena which then
2280 could use the newly invalid fast bins. */
2282 /* all bins past max_fast are empty */
2283 if (av == &main_arena && i > max_fast_bin)
2284 assert (p == 0);
2286 while (p != 0)
2288 if (__glibc_unlikely (misaligned_chunk (p)))
2289 malloc_printerr ("do_check_malloc_state(): "
2290 "unaligned fastbin chunk detected");
2291 /* each chunk claims to be inuse */
2292 do_check_inuse_chunk (av, p);
2293 total += chunksize (p);
2294 /* chunk belongs in this bin */
2295 assert (fastbin_index (chunksize (p)) == i);
2296 p = REVEAL_PTR (p->fd);
2300 /* check normal bins */
2301 for (i = 1; i < NBINS; ++i)
2303 b = bin_at (av, i);
2305 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2306 if (i >= 2)
2308 unsigned int binbit = get_binmap (av, i);
2309 int empty = last (b) == b;
2310 if (!binbit)
2311 assert (empty);
2312 else if (!empty)
2313 assert (binbit);
2316 for (p = last (b); p != b; p = p->bk)
2318 /* each chunk claims to be free */
2319 do_check_free_chunk (av, p);
2320 size = chunksize (p);
2321 total += size;
2322 if (i >= 2)
2324 /* chunk belongs in bin */
2325 idx = bin_index (size);
2326 assert (idx == i);
2327 /* lists are sorted */
2328 assert (p->bk == b ||
2329 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2331 if (!in_smallbin_range (size))
2333 if (p->fd_nextsize != NULL)
2335 if (p->fd_nextsize == p)
2336 assert (p->bk_nextsize == p);
2337 else
2339 if (p->fd_nextsize == first (b))
2340 assert (chunksize (p) < chunksize (p->fd_nextsize));
2341 else
2342 assert (chunksize (p) > chunksize (p->fd_nextsize));
2344 if (p == first (b))
2345 assert (chunksize (p) > chunksize (p->bk_nextsize));
2346 else
2347 assert (chunksize (p) < chunksize (p->bk_nextsize));
2350 else
2351 assert (p->bk_nextsize == NULL);
2354 else if (!in_smallbin_range (size))
2355 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2356 /* chunk is followed by a legal chain of inuse chunks */
2357 for (q = next_chunk (p);
2358 (q != av->top && inuse (q) &&
2359 (unsigned long) (chunksize (q)) >= MINSIZE);
2360 q = next_chunk (q))
2361 do_check_inuse_chunk (av, q);
2365 /* top chunk is OK */
2366 check_chunk (av, av->top);
2368 #endif
2371 /* ----------------- Support for debugging hooks -------------------- */
2372 #if IS_IN (libc)
2373 #include "hooks.c"
2374 #endif
2377 /* ----------- Routines dealing with system allocation -------------- */
2380 sysmalloc handles malloc cases requiring more memory from the system.
2381 On entry, it is assumed that av->top does not have enough
2382 space to service request for nb bytes, thus requiring that av->top
2383 be extended or replaced.
2386 static void *
2387 sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2389 mchunkptr old_top; /* incoming value of av->top */
2390 INTERNAL_SIZE_T old_size; /* its size */
2391 char *old_end; /* its end address */
2393 long size; /* arg to first MORECORE or mmap call */
2394 char *brk; /* return value from MORECORE */
2396 long correction; /* arg to 2nd MORECORE call */
2397 char *snd_brk; /* 2nd return val */
2399 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2400 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2401 char *aligned_brk; /* aligned offset into brk */
2403 mchunkptr p; /* the allocated/returned chunk */
2404 mchunkptr remainder; /* remainder from allocation */
2405 unsigned long remainder_size; /* its size */
2408 size_t pagesize = GLRO (dl_pagesize);
2409 bool tried_mmap = false;
2413 If have mmap, and the request size meets the mmap threshold, and
2414 the system supports mmap, and there are few enough currently
2415 allocated mmapped regions, try to directly map this request
2416 rather than expanding top.
2419 if (av == NULL
2420 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2421 && (mp_.n_mmaps < mp_.n_mmaps_max)))
2423 char *mm; /* return value from mmap call*/
2425 try_mmap:
2427 Round up size to nearest page. For mmapped chunks, the overhead
2428 is one SIZE_SZ unit larger than for normal chunks, because there
2429 is no following chunk whose prev_size field could be used.
2431 See the front_misalign handling below, for glibc there is no
2432 need for further alignments unless we have have high alignment.
2434 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2435 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2436 else
2437 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2438 tried_mmap = true;
2440 /* Don't try if size wraps around 0 */
2441 if ((unsigned long) (size) > (unsigned long) (nb))
2443 mm = (char *) (MMAP (0, size,
2444 mtag_mmap_flags | PROT_READ | PROT_WRITE, 0));
2446 if (mm != MAP_FAILED)
2449 The offset to the start of the mmapped region is stored
2450 in the prev_size field of the chunk. This allows us to adjust
2451 returned start address to meet alignment requirements here
2452 and in memalign(), and still be able to compute proper
2453 address argument for later munmap in free() and realloc().
2456 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2458 /* For glibc, chunk2mem increases the address by
2459 CHUNK_HDR_SZ and MALLOC_ALIGN_MASK is
2460 CHUNK_HDR_SZ-1. Each mmap'ed area is page
2461 aligned and therefore definitely
2462 MALLOC_ALIGN_MASK-aligned. */
2463 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2464 front_misalign = 0;
2466 else
2467 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2468 if (front_misalign > 0)
2470 correction = MALLOC_ALIGNMENT - front_misalign;
2471 p = (mchunkptr) (mm + correction);
2472 set_prev_size (p, correction);
2473 set_head (p, (size - correction) | IS_MMAPPED);
2475 else
2477 p = (mchunkptr) mm;
2478 set_prev_size (p, 0);
2479 set_head (p, size | IS_MMAPPED);
2482 /* update statistics */
2484 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2485 atomic_max (&mp_.max_n_mmaps, new);
2487 unsigned long sum;
2488 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2489 atomic_max (&mp_.max_mmapped_mem, sum);
2491 check_chunk (av, p);
2493 return chunk2mem (p);
2498 /* There are no usable arenas and mmap also failed. */
2499 if (av == NULL)
2500 return 0;
2502 /* Record incoming configuration of top */
2504 old_top = av->top;
2505 old_size = chunksize (old_top);
2506 old_end = (char *) (chunk_at_offset (old_top, old_size));
2508 brk = snd_brk = (char *) (MORECORE_FAILURE);
2511 If not the first time through, we require old_size to be
2512 at least MINSIZE and to have prev_inuse set.
2515 assert ((old_top == initial_top (av) && old_size == 0) ||
2516 ((unsigned long) (old_size) >= MINSIZE &&
2517 prev_inuse (old_top) &&
2518 ((unsigned long) old_end & (pagesize - 1)) == 0));
2520 /* Precondition: not enough current space to satisfy nb request */
2521 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2524 if (av != &main_arena)
2526 heap_info *old_heap, *heap;
2527 size_t old_heap_size;
2529 /* First try to extend the current heap. */
2530 old_heap = heap_for_ptr (old_top);
2531 old_heap_size = old_heap->size;
2532 if ((long) (MINSIZE + nb - old_size) > 0
2533 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2535 av->system_mem += old_heap->size - old_heap_size;
2536 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2537 | PREV_INUSE);
2539 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2541 /* Use a newly allocated heap. */
2542 heap->ar_ptr = av;
2543 heap->prev = old_heap;
2544 av->system_mem += heap->size;
2545 /* Set up the new top. */
2546 top (av) = chunk_at_offset (heap, sizeof (*heap));
2547 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2549 /* Setup fencepost and free the old top chunk with a multiple of
2550 MALLOC_ALIGNMENT in size. */
2551 /* The fencepost takes at least MINSIZE bytes, because it might
2552 become the top chunk again later. Note that a footer is set
2553 up, too, although the chunk is marked in use. */
2554 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2555 set_head (chunk_at_offset (old_top, old_size + CHUNK_HDR_SZ),
2556 0 | PREV_INUSE);
2557 if (old_size >= MINSIZE)
2559 set_head (chunk_at_offset (old_top, old_size),
2560 CHUNK_HDR_SZ | PREV_INUSE);
2561 set_foot (chunk_at_offset (old_top, old_size), CHUNK_HDR_SZ);
2562 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2563 _int_free (av, old_top, 1);
2565 else
2567 set_head (old_top, (old_size + CHUNK_HDR_SZ) | PREV_INUSE);
2568 set_foot (old_top, (old_size + CHUNK_HDR_SZ));
2571 else if (!tried_mmap)
2572 /* We can at least try to use to mmap memory. */
2573 goto try_mmap;
2575 else /* av == main_arena */
2578 { /* Request enough space for nb + pad + overhead */
2579 size = nb + mp_.top_pad + MINSIZE;
2582 If contiguous, we can subtract out existing space that we hope to
2583 combine with new space. We add it back later only if
2584 we don't actually get contiguous space.
2587 if (contiguous (av))
2588 size -= old_size;
2591 Round to a multiple of page size.
2592 If MORECORE is not contiguous, this ensures that we only call it
2593 with whole-page arguments. And if MORECORE is contiguous and
2594 this is not first time through, this preserves page-alignment of
2595 previous calls. Otherwise, we correct to page-align below.
2598 size = ALIGN_UP (size, pagesize);
2601 Don't try to call MORECORE if argument is so big as to appear
2602 negative. Note that since mmap takes size_t arg, it may succeed
2603 below even if we cannot call MORECORE.
2606 if (size > 0)
2608 brk = (char *) (MORECORE (size));
2609 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2612 if (brk == (char *) (MORECORE_FAILURE))
2615 If have mmap, try using it as a backup when MORECORE fails or
2616 cannot be used. This is worth doing on systems that have "holes" in
2617 address space, so sbrk cannot extend to give contiguous space, but
2618 space is available elsewhere. Note that we ignore mmap max count
2619 and threshold limits, since the space will not be used as a
2620 segregated mmap region.
2623 /* Cannot merge with old top, so add its size back in */
2624 if (contiguous (av))
2625 size = ALIGN_UP (size + old_size, pagesize);
2627 /* If we are relying on mmap as backup, then use larger units */
2628 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2629 size = MMAP_AS_MORECORE_SIZE;
2631 /* Don't try if size wraps around 0 */
2632 if ((unsigned long) (size) > (unsigned long) (nb))
2634 char *mbrk = (char *) (MMAP (0, size,
2635 mtag_mmap_flags | PROT_READ | PROT_WRITE,
2636 0));
2638 if (mbrk != MAP_FAILED)
2640 /* We do not need, and cannot use, another sbrk call to find end */
2641 brk = mbrk;
2642 snd_brk = brk + size;
2645 Record that we no longer have a contiguous sbrk region.
2646 After the first time mmap is used as backup, we do not
2647 ever rely on contiguous space since this could incorrectly
2648 bridge regions.
2650 set_noncontiguous (av);
2655 if (brk != (char *) (MORECORE_FAILURE))
2657 if (mp_.sbrk_base == 0)
2658 mp_.sbrk_base = brk;
2659 av->system_mem += size;
2662 If MORECORE extends previous space, we can likewise extend top size.
2665 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2666 set_head (old_top, (size + old_size) | PREV_INUSE);
2668 else if (contiguous (av) && old_size && brk < old_end)
2669 /* Oops! Someone else killed our space.. Can't touch anything. */
2670 malloc_printerr ("break adjusted to free malloc space");
2673 Otherwise, make adjustments:
2675 * If the first time through or noncontiguous, we need to call sbrk
2676 just to find out where the end of memory lies.
2678 * We need to ensure that all returned chunks from malloc will meet
2679 MALLOC_ALIGNMENT
2681 * If there was an intervening foreign sbrk, we need to adjust sbrk
2682 request size to account for fact that we will not be able to
2683 combine new space with existing space in old_top.
2685 * Almost all systems internally allocate whole pages at a time, in
2686 which case we might as well use the whole last page of request.
2687 So we allocate enough more memory to hit a page boundary now,
2688 which in turn causes future contiguous calls to page-align.
2691 else
2693 front_misalign = 0;
2694 end_misalign = 0;
2695 correction = 0;
2696 aligned_brk = brk;
2698 /* handle contiguous cases */
2699 if (contiguous (av))
2701 /* Count foreign sbrk as system_mem. */
2702 if (old_size)
2703 av->system_mem += brk - old_end;
2705 /* Guarantee alignment of first new chunk made from this space */
2707 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2708 if (front_misalign > 0)
2711 Skip over some bytes to arrive at an aligned position.
2712 We don't need to specially mark these wasted front bytes.
2713 They will never be accessed anyway because
2714 prev_inuse of av->top (and any chunk created from its start)
2715 is always true after initialization.
2718 correction = MALLOC_ALIGNMENT - front_misalign;
2719 aligned_brk += correction;
2723 If this isn't adjacent to existing space, then we will not
2724 be able to merge with old_top space, so must add to 2nd request.
2727 correction += old_size;
2729 /* Extend the end address to hit a page boundary */
2730 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2731 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2733 assert (correction >= 0);
2734 snd_brk = (char *) (MORECORE (correction));
2737 If can't allocate correction, try to at least find out current
2738 brk. It might be enough to proceed without failing.
2740 Note that if second sbrk did NOT fail, we assume that space
2741 is contiguous with first sbrk. This is a safe assumption unless
2742 program is multithreaded but doesn't use locks and a foreign sbrk
2743 occurred between our first and second calls.
2746 if (snd_brk == (char *) (MORECORE_FAILURE))
2748 correction = 0;
2749 snd_brk = (char *) (MORECORE (0));
2753 /* handle non-contiguous cases */
2754 else
2756 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2757 /* MORECORE/mmap must correctly align */
2758 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2759 else
2761 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2762 if (front_misalign > 0)
2765 Skip over some bytes to arrive at an aligned position.
2766 We don't need to specially mark these wasted front bytes.
2767 They will never be accessed anyway because
2768 prev_inuse of av->top (and any chunk created from its start)
2769 is always true after initialization.
2772 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2776 /* Find out current end of memory */
2777 if (snd_brk == (char *) (MORECORE_FAILURE))
2779 snd_brk = (char *) (MORECORE (0));
2783 /* Adjust top based on results of second sbrk */
2784 if (snd_brk != (char *) (MORECORE_FAILURE))
2786 av->top = (mchunkptr) aligned_brk;
2787 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2788 av->system_mem += correction;
2791 If not the first time through, we either have a
2792 gap due to foreign sbrk or a non-contiguous region. Insert a
2793 double fencepost at old_top to prevent consolidation with space
2794 we don't own. These fenceposts are artificial chunks that are
2795 marked as inuse and are in any case too small to use. We need
2796 two to make sizes and alignments work out.
2799 if (old_size != 0)
2802 Shrink old_top to insert fenceposts, keeping size a
2803 multiple of MALLOC_ALIGNMENT. We know there is at least
2804 enough space in old_top to do this.
2806 old_size = (old_size - 2 * CHUNK_HDR_SZ) & ~MALLOC_ALIGN_MASK;
2807 set_head (old_top, old_size | PREV_INUSE);
2810 Note that the following assignments completely overwrite
2811 old_top when old_size was previously MINSIZE. This is
2812 intentional. We need the fencepost, even if old_top otherwise gets
2813 lost.
2815 set_head (chunk_at_offset (old_top, old_size),
2816 CHUNK_HDR_SZ | PREV_INUSE);
2817 set_head (chunk_at_offset (old_top,
2818 old_size + CHUNK_HDR_SZ),
2819 CHUNK_HDR_SZ | PREV_INUSE);
2821 /* If possible, release the rest. */
2822 if (old_size >= MINSIZE)
2824 _int_free (av, old_top, 1);
2830 } /* if (av != &main_arena) */
2832 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2833 av->max_system_mem = av->system_mem;
2834 check_malloc_state (av);
2836 /* finally, do the allocation */
2837 p = av->top;
2838 size = chunksize (p);
2840 /* check that one of the above allocation paths succeeded */
2841 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2843 remainder_size = size - nb;
2844 remainder = chunk_at_offset (p, nb);
2845 av->top = remainder;
2846 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2847 set_head (remainder, remainder_size | PREV_INUSE);
2848 check_malloced_chunk (av, p, nb);
2849 return chunk2mem (p);
2852 /* catch all failure paths */
2853 __set_errno (ENOMEM);
2854 return 0;
2859 systrim is an inverse of sorts to sysmalloc. It gives memory back
2860 to the system (via negative arguments to sbrk) if there is unused
2861 memory at the `high' end of the malloc pool. It is called
2862 automatically by free() when top space exceeds the trim
2863 threshold. It is also called by the public malloc_trim routine. It
2864 returns 1 if it actually released any memory, else 0.
2867 static int
2868 systrim (size_t pad, mstate av)
2870 long top_size; /* Amount of top-most memory */
2871 long extra; /* Amount to release */
2872 long released; /* Amount actually released */
2873 char *current_brk; /* address returned by pre-check sbrk call */
2874 char *new_brk; /* address returned by post-check sbrk call */
2875 size_t pagesize;
2876 long top_area;
2878 pagesize = GLRO (dl_pagesize);
2879 top_size = chunksize (av->top);
2881 top_area = top_size - MINSIZE - 1;
2882 if (top_area <= pad)
2883 return 0;
2885 /* Release in pagesize units and round down to the nearest page. */
2886 extra = ALIGN_DOWN(top_area - pad, pagesize);
2888 if (extra == 0)
2889 return 0;
2892 Only proceed if end of memory is where we last set it.
2893 This avoids problems if there were foreign sbrk calls.
2895 current_brk = (char *) (MORECORE (0));
2896 if (current_brk == (char *) (av->top) + top_size)
2899 Attempt to release memory. We ignore MORECORE return value,
2900 and instead call again to find out where new end of memory is.
2901 This avoids problems if first call releases less than we asked,
2902 of if failure somehow altered brk value. (We could still
2903 encounter problems if it altered brk in some very bad way,
2904 but the only thing we can do is adjust anyway, which will cause
2905 some downstream failure.)
2908 MORECORE (-extra);
2909 new_brk = (char *) (MORECORE (0));
2911 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2913 if (new_brk != (char *) MORECORE_FAILURE)
2915 released = (long) (current_brk - new_brk);
2917 if (released != 0)
2919 /* Success. Adjust top. */
2920 av->system_mem -= released;
2921 set_head (av->top, (top_size - released) | PREV_INUSE);
2922 check_malloc_state (av);
2923 return 1;
2927 return 0;
2930 static void
2931 munmap_chunk (mchunkptr p)
2933 size_t pagesize = GLRO (dl_pagesize);
2934 INTERNAL_SIZE_T size = chunksize (p);
2936 assert (chunk_is_mmapped (p));
2938 uintptr_t mem = (uintptr_t) chunk2mem (p);
2939 uintptr_t block = (uintptr_t) p - prev_size (p);
2940 size_t total_size = prev_size (p) + size;
2941 /* Unfortunately we have to do the compilers job by hand here. Normally
2942 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2943 page size. But gcc does not recognize the optimization possibility
2944 (in the moment at least) so we combine the two values into one before
2945 the bit test. */
2946 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
2947 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
2948 malloc_printerr ("munmap_chunk(): invalid pointer");
2950 atomic_decrement (&mp_.n_mmaps);
2951 atomic_add (&mp_.mmapped_mem, -total_size);
2953 /* If munmap failed the process virtual memory address space is in a
2954 bad shape. Just leave the block hanging around, the process will
2955 terminate shortly anyway since not much can be done. */
2956 __munmap ((char *) block, total_size);
2959 #if HAVE_MREMAP
2961 static mchunkptr
2962 mremap_chunk (mchunkptr p, size_t new_size)
2964 size_t pagesize = GLRO (dl_pagesize);
2965 INTERNAL_SIZE_T offset = prev_size (p);
2966 INTERNAL_SIZE_T size = chunksize (p);
2967 char *cp;
2969 assert (chunk_is_mmapped (p));
2971 uintptr_t block = (uintptr_t) p - offset;
2972 uintptr_t mem = (uintptr_t) chunk2mem(p);
2973 size_t total_size = offset + size;
2974 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
2975 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
2976 malloc_printerr("mremap_chunk(): invalid pointer");
2978 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2979 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
2981 /* No need to remap if the number of pages does not change. */
2982 if (total_size == new_size)
2983 return p;
2985 cp = (char *) __mremap ((char *) block, total_size, new_size,
2986 MREMAP_MAYMOVE);
2988 if (cp == MAP_FAILED)
2989 return 0;
2991 p = (mchunkptr) (cp + offset);
2993 assert (aligned_OK (chunk2mem (p)));
2995 assert (prev_size (p) == offset);
2996 set_head (p, (new_size - offset) | IS_MMAPPED);
2998 INTERNAL_SIZE_T new;
2999 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
3000 + new_size - size - offset;
3001 atomic_max (&mp_.max_mmapped_mem, new);
3002 return p;
3004 #endif /* HAVE_MREMAP */
3006 /*------------------------ Public wrappers. --------------------------------*/
3008 #if USE_TCACHE
3010 /* We overlay this structure on the user-data portion of a chunk when
3011 the chunk is stored in the per-thread cache. */
3012 typedef struct tcache_entry
3014 struct tcache_entry *next;
3015 /* This field exists to detect double frees. */
3016 uintptr_t key;
3017 } tcache_entry;
3019 /* There is one of these for each thread, which contains the
3020 per-thread cache (hence "tcache_perthread_struct"). Keeping
3021 overall size low is mildly important. Note that COUNTS and ENTRIES
3022 are redundant (we could have just counted the linked list each
3023 time), this is for performance reasons. */
3024 typedef struct tcache_perthread_struct
3026 uint16_t counts[TCACHE_MAX_BINS];
3027 tcache_entry *entries[TCACHE_MAX_BINS];
3028 } tcache_perthread_struct;
3030 static __thread bool tcache_shutting_down = false;
3031 static __thread tcache_perthread_struct *tcache = NULL;
3033 /* Process-wide key to try and catch a double-free in the same thread. */
3034 static uintptr_t tcache_key;
3036 /* The value of tcache_key does not really have to be a cryptographically
3037 secure random number. It only needs to be arbitrary enough so that it does
3038 not collide with values present in applications. If a collision does happen
3039 consistently enough, it could cause a degradation in performance since the
3040 entire list is checked to check if the block indeed has been freed the
3041 second time. The odds of this happening are exceedingly low though, about 1
3042 in 2^wordsize. There is probably a higher chance of the performance
3043 degradation being due to a double free where the first free happened in a
3044 different thread; that's a case this check does not cover. */
3045 static void
3046 tcache_key_initialize (void)
3048 if (__getrandom (&tcache_key, sizeof(tcache_key), GRND_NONBLOCK)
3049 != sizeof (tcache_key))
3051 tcache_key = random_bits ();
3052 #if __WORDSIZE == 64
3053 tcache_key = (tcache_key << 32) | random_bits ();
3054 #endif
3058 /* Caller must ensure that we know tc_idx is valid and there's room
3059 for more chunks. */
3060 static __always_inline void
3061 tcache_put (mchunkptr chunk, size_t tc_idx)
3063 tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
3065 /* Mark this chunk as "in the tcache" so the test in _int_free will
3066 detect a double free. */
3067 e->key = tcache_key;
3069 e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]);
3070 tcache->entries[tc_idx] = e;
3071 ++(tcache->counts[tc_idx]);
3074 /* Caller must ensure that we know tc_idx is valid and there's
3075 available chunks to remove. */
3076 static __always_inline void *
3077 tcache_get (size_t tc_idx)
3079 tcache_entry *e = tcache->entries[tc_idx];
3080 if (__glibc_unlikely (!aligned_OK (e)))
3081 malloc_printerr ("malloc(): unaligned tcache chunk detected");
3082 tcache->entries[tc_idx] = REVEAL_PTR (e->next);
3083 --(tcache->counts[tc_idx]);
3084 e->key = 0;
3085 return (void *) e;
3088 static void
3089 tcache_thread_shutdown (void)
3091 int i;
3092 tcache_perthread_struct *tcache_tmp = tcache;
3094 tcache_shutting_down = true;
3096 if (!tcache)
3097 return;
3099 /* Disable the tcache and prevent it from being reinitialized. */
3100 tcache = NULL;
3102 /* Free all of the entries and the tcache itself back to the arena
3103 heap for coalescing. */
3104 for (i = 0; i < TCACHE_MAX_BINS; ++i)
3106 while (tcache_tmp->entries[i])
3108 tcache_entry *e = tcache_tmp->entries[i];
3109 if (__glibc_unlikely (!aligned_OK (e)))
3110 malloc_printerr ("tcache_thread_shutdown(): "
3111 "unaligned tcache chunk detected");
3112 tcache_tmp->entries[i] = REVEAL_PTR (e->next);
3113 __libc_free (e);
3117 __libc_free (tcache_tmp);
3120 static void
3121 tcache_init(void)
3123 mstate ar_ptr;
3124 void *victim = 0;
3125 const size_t bytes = sizeof (tcache_perthread_struct);
3127 if (tcache_shutting_down)
3128 return;
3130 arena_get (ar_ptr, bytes);
3131 victim = _int_malloc (ar_ptr, bytes);
3132 if (!victim && ar_ptr != NULL)
3134 ar_ptr = arena_get_retry (ar_ptr, bytes);
3135 victim = _int_malloc (ar_ptr, bytes);
3139 if (ar_ptr != NULL)
3140 __libc_lock_unlock (ar_ptr->mutex);
3142 /* In a low memory situation, we may not be able to allocate memory
3143 - in which case, we just keep trying later. However, we
3144 typically do this very early, so either there is sufficient
3145 memory, or there isn't enough memory to do non-trivial
3146 allocations anyway. */
3147 if (victim)
3149 tcache = (tcache_perthread_struct *) victim;
3150 memset (tcache, 0, sizeof (tcache_perthread_struct));
3155 # define MAYBE_INIT_TCACHE() \
3156 if (__glibc_unlikely (tcache == NULL)) \
3157 tcache_init();
3159 #else /* !USE_TCACHE */
3160 # define MAYBE_INIT_TCACHE()
3162 static void
3163 tcache_thread_shutdown (void)
3165 /* Nothing to do if there is no thread cache. */
3168 #endif /* !USE_TCACHE */
3170 #if IS_IN (libc)
3171 void *
3172 __libc_malloc (size_t bytes)
3174 mstate ar_ptr;
3175 void *victim;
3177 _Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2,
3178 "PTRDIFF_MAX is not more than half of SIZE_MAX");
3180 if (!__malloc_initialized)
3181 ptmalloc_init ();
3182 #if USE_TCACHE
3183 /* int_free also calls request2size, be careful to not pad twice. */
3184 size_t tbytes;
3185 if (!checked_request2size (bytes, &tbytes))
3187 __set_errno (ENOMEM);
3188 return NULL;
3190 size_t tc_idx = csize2tidx (tbytes);
3192 MAYBE_INIT_TCACHE ();
3194 DIAG_PUSH_NEEDS_COMMENT;
3195 if (tc_idx < mp_.tcache_bins
3196 && tcache
3197 && tcache->counts[tc_idx] > 0)
3199 victim = tcache_get (tc_idx);
3200 return tag_new_usable (victim);
3202 DIAG_POP_NEEDS_COMMENT;
3203 #endif
3205 if (SINGLE_THREAD_P)
3207 victim = tag_new_usable (_int_malloc (&main_arena, bytes));
3208 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3209 &main_arena == arena_for_chunk (mem2chunk (victim)));
3210 return victim;
3213 arena_get (ar_ptr, bytes);
3215 victim = _int_malloc (ar_ptr, bytes);
3216 /* Retry with another arena only if we were able to find a usable arena
3217 before. */
3218 if (!victim && ar_ptr != NULL)
3220 LIBC_PROBE (memory_malloc_retry, 1, bytes);
3221 ar_ptr = arena_get_retry (ar_ptr, bytes);
3222 victim = _int_malloc (ar_ptr, bytes);
3225 if (ar_ptr != NULL)
3226 __libc_lock_unlock (ar_ptr->mutex);
3228 victim = tag_new_usable (victim);
3230 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3231 ar_ptr == arena_for_chunk (mem2chunk (victim)));
3232 return victim;
3234 libc_hidden_def (__libc_malloc)
3236 void
3237 __libc_free (void *mem)
3239 mstate ar_ptr;
3240 mchunkptr p; /* chunk corresponding to mem */
3242 if (mem == 0) /* free(0) has no effect */
3243 return;
3245 /* Quickly check that the freed pointer matches the tag for the memory.
3246 This gives a useful double-free detection. */
3247 if (__glibc_unlikely (mtag_enabled))
3248 *(volatile char *)mem;
3250 int err = errno;
3252 p = mem2chunk (mem);
3254 if (chunk_is_mmapped (p)) /* release mmapped memory. */
3256 /* See if the dynamic brk/mmap threshold needs adjusting.
3257 Dumped fake mmapped chunks do not affect the threshold. */
3258 if (!mp_.no_dyn_threshold
3259 && chunksize_nomask (p) > mp_.mmap_threshold
3260 && chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX)
3262 mp_.mmap_threshold = chunksize (p);
3263 mp_.trim_threshold = 2 * mp_.mmap_threshold;
3264 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
3265 mp_.mmap_threshold, mp_.trim_threshold);
3267 munmap_chunk (p);
3269 else
3271 MAYBE_INIT_TCACHE ();
3273 /* Mark the chunk as belonging to the library again. */
3274 (void)tag_region (chunk2mem (p), memsize (p));
3276 ar_ptr = arena_for_chunk (p);
3277 _int_free (ar_ptr, p, 0);
3280 __set_errno (err);
3282 libc_hidden_def (__libc_free)
3284 void *
3285 __libc_realloc (void *oldmem, size_t bytes)
3287 mstate ar_ptr;
3288 INTERNAL_SIZE_T nb; /* padded request size */
3290 void *newp; /* chunk to return */
3292 if (!__malloc_initialized)
3293 ptmalloc_init ();
3295 #if REALLOC_ZERO_BYTES_FREES
3296 if (bytes == 0 && oldmem != NULL)
3298 __libc_free (oldmem); return 0;
3300 #endif
3302 /* realloc of null is supposed to be same as malloc */
3303 if (oldmem == 0)
3304 return __libc_malloc (bytes);
3306 /* Perform a quick check to ensure that the pointer's tag matches the
3307 memory's tag. */
3308 if (__glibc_unlikely (mtag_enabled))
3309 *(volatile char*) oldmem;
3311 /* chunk corresponding to oldmem */
3312 const mchunkptr oldp = mem2chunk (oldmem);
3313 /* its size */
3314 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
3316 if (chunk_is_mmapped (oldp))
3317 ar_ptr = NULL;
3318 else
3320 MAYBE_INIT_TCACHE ();
3321 ar_ptr = arena_for_chunk (oldp);
3324 /* Little security check which won't hurt performance: the allocator
3325 never wrapps around at the end of the address space. Therefore
3326 we can exclude some size values which might appear here by
3327 accident or by "design" from some intruder. */
3328 if ((__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
3329 || __builtin_expect (misaligned_chunk (oldp), 0)))
3330 malloc_printerr ("realloc(): invalid pointer");
3332 if (!checked_request2size (bytes, &nb))
3334 __set_errno (ENOMEM);
3335 return NULL;
3338 if (chunk_is_mmapped (oldp))
3340 void *newmem;
3342 #if HAVE_MREMAP
3343 newp = mremap_chunk (oldp, nb);
3344 if (newp)
3346 void *newmem = chunk2mem_tag (newp);
3347 /* Give the new block a different tag. This helps to ensure
3348 that stale handles to the previous mapping are not
3349 reused. There's a performance hit for both us and the
3350 caller for doing this, so we might want to
3351 reconsider. */
3352 return tag_new_usable (newmem);
3354 #endif
3355 /* Note the extra SIZE_SZ overhead. */
3356 if (oldsize - SIZE_SZ >= nb)
3357 return oldmem; /* do nothing */
3359 /* Must alloc, copy, free. */
3360 newmem = __libc_malloc (bytes);
3361 if (newmem == 0)
3362 return 0; /* propagate failure */
3364 memcpy (newmem, oldmem, oldsize - CHUNK_HDR_SZ);
3365 munmap_chunk (oldp);
3366 return newmem;
3369 if (SINGLE_THREAD_P)
3371 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3372 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3373 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3375 return newp;
3378 __libc_lock_lock (ar_ptr->mutex);
3380 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3382 __libc_lock_unlock (ar_ptr->mutex);
3383 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3384 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3386 if (newp == NULL)
3388 /* Try harder to allocate memory in other arenas. */
3389 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3390 newp = __libc_malloc (bytes);
3391 if (newp != NULL)
3393 size_t sz = memsize (oldp);
3394 memcpy (newp, oldmem, sz);
3395 (void) tag_region (chunk2mem (oldp), sz);
3396 _int_free (ar_ptr, oldp, 0);
3400 return newp;
3402 libc_hidden_def (__libc_realloc)
3404 void *
3405 __libc_memalign (size_t alignment, size_t bytes)
3407 if (!__malloc_initialized)
3408 ptmalloc_init ();
3410 void *address = RETURN_ADDRESS (0);
3411 return _mid_memalign (alignment, bytes, address);
3414 static void *
3415 _mid_memalign (size_t alignment, size_t bytes, void *address)
3417 mstate ar_ptr;
3418 void *p;
3420 /* If we need less alignment than we give anyway, just relay to malloc. */
3421 if (alignment <= MALLOC_ALIGNMENT)
3422 return __libc_malloc (bytes);
3424 /* Otherwise, ensure that it is at least a minimum chunk size */
3425 if (alignment < MINSIZE)
3426 alignment = MINSIZE;
3428 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3429 power of 2 and will cause overflow in the check below. */
3430 if (alignment > SIZE_MAX / 2 + 1)
3432 __set_errno (EINVAL);
3433 return 0;
3437 /* Make sure alignment is power of 2. */
3438 if (!powerof2 (alignment))
3440 size_t a = MALLOC_ALIGNMENT * 2;
3441 while (a < alignment)
3442 a <<= 1;
3443 alignment = a;
3446 if (SINGLE_THREAD_P)
3448 p = _int_memalign (&main_arena, alignment, bytes);
3449 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3450 &main_arena == arena_for_chunk (mem2chunk (p)));
3451 return tag_new_usable (p);
3454 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3456 p = _int_memalign (ar_ptr, alignment, bytes);
3457 if (!p && ar_ptr != NULL)
3459 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3460 ar_ptr = arena_get_retry (ar_ptr, bytes);
3461 p = _int_memalign (ar_ptr, alignment, bytes);
3464 if (ar_ptr != NULL)
3465 __libc_lock_unlock (ar_ptr->mutex);
3467 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3468 ar_ptr == arena_for_chunk (mem2chunk (p)));
3469 return tag_new_usable (p);
3471 /* For ISO C11. */
3472 weak_alias (__libc_memalign, aligned_alloc)
3473 libc_hidden_def (__libc_memalign)
3475 void *
3476 __libc_valloc (size_t bytes)
3478 if (!__malloc_initialized)
3479 ptmalloc_init ();
3481 void *address = RETURN_ADDRESS (0);
3482 size_t pagesize = GLRO (dl_pagesize);
3483 return _mid_memalign (pagesize, bytes, address);
3486 void *
3487 __libc_pvalloc (size_t bytes)
3489 if (!__malloc_initialized)
3490 ptmalloc_init ();
3492 void *address = RETURN_ADDRESS (0);
3493 size_t pagesize = GLRO (dl_pagesize);
3494 size_t rounded_bytes;
3495 /* ALIGN_UP with overflow check. */
3496 if (__glibc_unlikely (__builtin_add_overflow (bytes,
3497 pagesize - 1,
3498 &rounded_bytes)))
3500 __set_errno (ENOMEM);
3501 return 0;
3503 rounded_bytes = rounded_bytes & -(pagesize - 1);
3505 return _mid_memalign (pagesize, rounded_bytes, address);
3508 void *
3509 __libc_calloc (size_t n, size_t elem_size)
3511 mstate av;
3512 mchunkptr oldtop;
3513 INTERNAL_SIZE_T sz, oldtopsize;
3514 void *mem;
3515 unsigned long clearsize;
3516 unsigned long nclears;
3517 INTERNAL_SIZE_T *d;
3518 ptrdiff_t bytes;
3520 if (__glibc_unlikely (__builtin_mul_overflow (n, elem_size, &bytes)))
3522 __set_errno (ENOMEM);
3523 return NULL;
3526 sz = bytes;
3528 if (!__malloc_initialized)
3529 ptmalloc_init ();
3531 MAYBE_INIT_TCACHE ();
3533 if (SINGLE_THREAD_P)
3534 av = &main_arena;
3535 else
3536 arena_get (av, sz);
3538 if (av)
3540 /* Check if we hand out the top chunk, in which case there may be no
3541 need to clear. */
3542 #if MORECORE_CLEARS
3543 oldtop = top (av);
3544 oldtopsize = chunksize (top (av));
3545 # if MORECORE_CLEARS < 2
3546 /* Only newly allocated memory is guaranteed to be cleared. */
3547 if (av == &main_arena &&
3548 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3549 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3550 # endif
3551 if (av != &main_arena)
3553 heap_info *heap = heap_for_ptr (oldtop);
3554 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3555 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3557 #endif
3559 else
3561 /* No usable arenas. */
3562 oldtop = 0;
3563 oldtopsize = 0;
3565 mem = _int_malloc (av, sz);
3567 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3568 av == arena_for_chunk (mem2chunk (mem)));
3570 if (!SINGLE_THREAD_P)
3572 if (mem == 0 && av != NULL)
3574 LIBC_PROBE (memory_calloc_retry, 1, sz);
3575 av = arena_get_retry (av, sz);
3576 mem = _int_malloc (av, sz);
3579 if (av != NULL)
3580 __libc_lock_unlock (av->mutex);
3583 /* Allocation failed even after a retry. */
3584 if (mem == 0)
3585 return 0;
3587 mchunkptr p = mem2chunk (mem);
3589 /* If we are using memory tagging, then we need to set the tags
3590 regardless of MORECORE_CLEARS, so we zero the whole block while
3591 doing so. */
3592 if (__glibc_unlikely (mtag_enabled))
3593 return tag_new_zero_region (mem, memsize (p));
3595 INTERNAL_SIZE_T csz = chunksize (p);
3597 /* Two optional cases in which clearing not necessary */
3598 if (chunk_is_mmapped (p))
3600 if (__builtin_expect (perturb_byte, 0))
3601 return memset (mem, 0, sz);
3603 return mem;
3606 #if MORECORE_CLEARS
3607 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3609 /* clear only the bytes from non-freshly-sbrked memory */
3610 csz = oldtopsize;
3612 #endif
3614 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3615 contents have an odd number of INTERNAL_SIZE_T-sized words;
3616 minimally 3. */
3617 d = (INTERNAL_SIZE_T *) mem;
3618 clearsize = csz - SIZE_SZ;
3619 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3620 assert (nclears >= 3);
3622 if (nclears > 9)
3623 return memset (d, 0, clearsize);
3625 else
3627 *(d + 0) = 0;
3628 *(d + 1) = 0;
3629 *(d + 2) = 0;
3630 if (nclears > 4)
3632 *(d + 3) = 0;
3633 *(d + 4) = 0;
3634 if (nclears > 6)
3636 *(d + 5) = 0;
3637 *(d + 6) = 0;
3638 if (nclears > 8)
3640 *(d + 7) = 0;
3641 *(d + 8) = 0;
3647 return mem;
3649 #endif /* IS_IN (libc) */
3652 ------------------------------ malloc ------------------------------
3655 static void *
3656 _int_malloc (mstate av, size_t bytes)
3658 INTERNAL_SIZE_T nb; /* normalized request size */
3659 unsigned int idx; /* associated bin index */
3660 mbinptr bin; /* associated bin */
3662 mchunkptr victim; /* inspected/selected chunk */
3663 INTERNAL_SIZE_T size; /* its size */
3664 int victim_index; /* its bin index */
3666 mchunkptr remainder; /* remainder from a split */
3667 unsigned long remainder_size; /* its size */
3669 unsigned int block; /* bit map traverser */
3670 unsigned int bit; /* bit map traverser */
3671 unsigned int map; /* current word of binmap */
3673 mchunkptr fwd; /* misc temp for linking */
3674 mchunkptr bck; /* misc temp for linking */
3676 #if USE_TCACHE
3677 size_t tcache_unsorted_count; /* count of unsorted chunks processed */
3678 #endif
3681 Convert request size to internal form by adding SIZE_SZ bytes
3682 overhead plus possibly more to obtain necessary alignment and/or
3683 to obtain a size of at least MINSIZE, the smallest allocatable
3684 size. Also, checked_request2size returns false for request sizes
3685 that are so large that they wrap around zero when padded and
3686 aligned.
3689 if (!checked_request2size (bytes, &nb))
3691 __set_errno (ENOMEM);
3692 return NULL;
3695 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3696 mmap. */
3697 if (__glibc_unlikely (av == NULL))
3699 void *p = sysmalloc (nb, av);
3700 if (p != NULL)
3701 alloc_perturb (p, bytes);
3702 return p;
3706 If the size qualifies as a fastbin, first check corresponding bin.
3707 This code is safe to execute even if av is not yet initialized, so we
3708 can try it without checking, which saves some time on this fast path.
3711 #define REMOVE_FB(fb, victim, pp) \
3712 do \
3714 victim = pp; \
3715 if (victim == NULL) \
3716 break; \
3717 pp = REVEAL_PTR (victim->fd); \
3718 if (__glibc_unlikely (pp != NULL && misaligned_chunk (pp))) \
3719 malloc_printerr ("malloc(): unaligned fastbin chunk detected"); \
3721 while ((pp = catomic_compare_and_exchange_val_acq (fb, pp, victim)) \
3722 != victim); \
3724 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3726 idx = fastbin_index (nb);
3727 mfastbinptr *fb = &fastbin (av, idx);
3728 mchunkptr pp;
3729 victim = *fb;
3731 if (victim != NULL)
3733 if (__glibc_unlikely (misaligned_chunk (victim)))
3734 malloc_printerr ("malloc(): unaligned fastbin chunk detected 2");
3736 if (SINGLE_THREAD_P)
3737 *fb = REVEAL_PTR (victim->fd);
3738 else
3739 REMOVE_FB (fb, pp, victim);
3740 if (__glibc_likely (victim != NULL))
3742 size_t victim_idx = fastbin_index (chunksize (victim));
3743 if (__builtin_expect (victim_idx != idx, 0))
3744 malloc_printerr ("malloc(): memory corruption (fast)");
3745 check_remalloced_chunk (av, victim, nb);
3746 #if USE_TCACHE
3747 /* While we're here, if we see other chunks of the same size,
3748 stash them in the tcache. */
3749 size_t tc_idx = csize2tidx (nb);
3750 if (tcache && tc_idx < mp_.tcache_bins)
3752 mchunkptr tc_victim;
3754 /* While bin not empty and tcache not full, copy chunks. */
3755 while (tcache->counts[tc_idx] < mp_.tcache_count
3756 && (tc_victim = *fb) != NULL)
3758 if (__glibc_unlikely (misaligned_chunk (tc_victim)))
3759 malloc_printerr ("malloc(): unaligned fastbin chunk detected 3");
3760 if (SINGLE_THREAD_P)
3761 *fb = REVEAL_PTR (tc_victim->fd);
3762 else
3764 REMOVE_FB (fb, pp, tc_victim);
3765 if (__glibc_unlikely (tc_victim == NULL))
3766 break;
3768 tcache_put (tc_victim, tc_idx);
3771 #endif
3772 void *p = chunk2mem (victim);
3773 alloc_perturb (p, bytes);
3774 return p;
3780 If a small request, check regular bin. Since these "smallbins"
3781 hold one size each, no searching within bins is necessary.
3782 (For a large request, we need to wait until unsorted chunks are
3783 processed to find best fit. But for small ones, fits are exact
3784 anyway, so we can check now, which is faster.)
3787 if (in_smallbin_range (nb))
3789 idx = smallbin_index (nb);
3790 bin = bin_at (av, idx);
3792 if ((victim = last (bin)) != bin)
3794 bck = victim->bk;
3795 if (__glibc_unlikely (bck->fd != victim))
3796 malloc_printerr ("malloc(): smallbin double linked list corrupted");
3797 set_inuse_bit_at_offset (victim, nb);
3798 bin->bk = bck;
3799 bck->fd = bin;
3801 if (av != &main_arena)
3802 set_non_main_arena (victim);
3803 check_malloced_chunk (av, victim, nb);
3804 #if USE_TCACHE
3805 /* While we're here, if we see other chunks of the same size,
3806 stash them in the tcache. */
3807 size_t tc_idx = csize2tidx (nb);
3808 if (tcache && tc_idx < mp_.tcache_bins)
3810 mchunkptr tc_victim;
3812 /* While bin not empty and tcache not full, copy chunks over. */
3813 while (tcache->counts[tc_idx] < mp_.tcache_count
3814 && (tc_victim = last (bin)) != bin)
3816 if (tc_victim != 0)
3818 bck = tc_victim->bk;
3819 set_inuse_bit_at_offset (tc_victim, nb);
3820 if (av != &main_arena)
3821 set_non_main_arena (tc_victim);
3822 bin->bk = bck;
3823 bck->fd = bin;
3825 tcache_put (tc_victim, tc_idx);
3829 #endif
3830 void *p = chunk2mem (victim);
3831 alloc_perturb (p, bytes);
3832 return p;
3837 If this is a large request, consolidate fastbins before continuing.
3838 While it might look excessive to kill all fastbins before
3839 even seeing if there is space available, this avoids
3840 fragmentation problems normally associated with fastbins.
3841 Also, in practice, programs tend to have runs of either small or
3842 large requests, but less often mixtures, so consolidation is not
3843 invoked all that often in most programs. And the programs that
3844 it is called frequently in otherwise tend to fragment.
3847 else
3849 idx = largebin_index (nb);
3850 if (atomic_load_relaxed (&av->have_fastchunks))
3851 malloc_consolidate (av);
3855 Process recently freed or remaindered chunks, taking one only if
3856 it is exact fit, or, if this a small request, the chunk is remainder from
3857 the most recent non-exact fit. Place other traversed chunks in
3858 bins. Note that this step is the only place in any routine where
3859 chunks are placed in bins.
3861 The outer loop here is needed because we might not realize until
3862 near the end of malloc that we should have consolidated, so must
3863 do so and retry. This happens at most once, and only when we would
3864 otherwise need to expand memory to service a "small" request.
3867 #if USE_TCACHE
3868 INTERNAL_SIZE_T tcache_nb = 0;
3869 size_t tc_idx = csize2tidx (nb);
3870 if (tcache && tc_idx < mp_.tcache_bins)
3871 tcache_nb = nb;
3872 int return_cached = 0;
3874 tcache_unsorted_count = 0;
3875 #endif
3877 for (;; )
3879 int iters = 0;
3880 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3882 bck = victim->bk;
3883 size = chunksize (victim);
3884 mchunkptr next = chunk_at_offset (victim, size);
3886 if (__glibc_unlikely (size <= CHUNK_HDR_SZ)
3887 || __glibc_unlikely (size > av->system_mem))
3888 malloc_printerr ("malloc(): invalid size (unsorted)");
3889 if (__glibc_unlikely (chunksize_nomask (next) < CHUNK_HDR_SZ)
3890 || __glibc_unlikely (chunksize_nomask (next) > av->system_mem))
3891 malloc_printerr ("malloc(): invalid next size (unsorted)");
3892 if (__glibc_unlikely ((prev_size (next) & ~(SIZE_BITS)) != size))
3893 malloc_printerr ("malloc(): mismatching next->prev_size (unsorted)");
3894 if (__glibc_unlikely (bck->fd != victim)
3895 || __glibc_unlikely (victim->fd != unsorted_chunks (av)))
3896 malloc_printerr ("malloc(): unsorted double linked list corrupted");
3897 if (__glibc_unlikely (prev_inuse (next)))
3898 malloc_printerr ("malloc(): invalid next->prev_inuse (unsorted)");
3901 If a small request, try to use last remainder if it is the
3902 only chunk in unsorted bin. This helps promote locality for
3903 runs of consecutive small requests. This is the only
3904 exception to best-fit, and applies only when there is
3905 no exact fit for a small chunk.
3908 if (in_smallbin_range (nb) &&
3909 bck == unsorted_chunks (av) &&
3910 victim == av->last_remainder &&
3911 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
3913 /* split and reattach remainder */
3914 remainder_size = size - nb;
3915 remainder = chunk_at_offset (victim, nb);
3916 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
3917 av->last_remainder = remainder;
3918 remainder->bk = remainder->fd = unsorted_chunks (av);
3919 if (!in_smallbin_range (remainder_size))
3921 remainder->fd_nextsize = NULL;
3922 remainder->bk_nextsize = NULL;
3925 set_head (victim, nb | PREV_INUSE |
3926 (av != &main_arena ? NON_MAIN_ARENA : 0));
3927 set_head (remainder, remainder_size | PREV_INUSE);
3928 set_foot (remainder, remainder_size);
3930 check_malloced_chunk (av, victim, nb);
3931 void *p = chunk2mem (victim);
3932 alloc_perturb (p, bytes);
3933 return p;
3936 /* remove from unsorted list */
3937 if (__glibc_unlikely (bck->fd != victim))
3938 malloc_printerr ("malloc(): corrupted unsorted chunks 3");
3939 unsorted_chunks (av)->bk = bck;
3940 bck->fd = unsorted_chunks (av);
3942 /* Take now instead of binning if exact fit */
3944 if (size == nb)
3946 set_inuse_bit_at_offset (victim, size);
3947 if (av != &main_arena)
3948 set_non_main_arena (victim);
3949 #if USE_TCACHE
3950 /* Fill cache first, return to user only if cache fills.
3951 We may return one of these chunks later. */
3952 if (tcache_nb
3953 && tcache->counts[tc_idx] < mp_.tcache_count)
3955 tcache_put (victim, tc_idx);
3956 return_cached = 1;
3957 continue;
3959 else
3961 #endif
3962 check_malloced_chunk (av, victim, nb);
3963 void *p = chunk2mem (victim);
3964 alloc_perturb (p, bytes);
3965 return p;
3966 #if USE_TCACHE
3968 #endif
3971 /* place chunk in bin */
3973 if (in_smallbin_range (size))
3975 victim_index = smallbin_index (size);
3976 bck = bin_at (av, victim_index);
3977 fwd = bck->fd;
3979 else
3981 victim_index = largebin_index (size);
3982 bck = bin_at (av, victim_index);
3983 fwd = bck->fd;
3985 /* maintain large bins in sorted order */
3986 if (fwd != bck)
3988 /* Or with inuse bit to speed comparisons */
3989 size |= PREV_INUSE;
3990 /* if smaller than smallest, bypass loop below */
3991 assert (chunk_main_arena (bck->bk));
3992 if ((unsigned long) (size)
3993 < (unsigned long) chunksize_nomask (bck->bk))
3995 fwd = bck;
3996 bck = bck->bk;
3998 victim->fd_nextsize = fwd->fd;
3999 victim->bk_nextsize = fwd->fd->bk_nextsize;
4000 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
4002 else
4004 assert (chunk_main_arena (fwd));
4005 while ((unsigned long) size < chunksize_nomask (fwd))
4007 fwd = fwd->fd_nextsize;
4008 assert (chunk_main_arena (fwd));
4011 if ((unsigned long) size
4012 == (unsigned long) chunksize_nomask (fwd))
4013 /* Always insert in the second position. */
4014 fwd = fwd->fd;
4015 else
4017 victim->fd_nextsize = fwd;
4018 victim->bk_nextsize = fwd->bk_nextsize;
4019 if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd))
4020 malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)");
4021 fwd->bk_nextsize = victim;
4022 victim->bk_nextsize->fd_nextsize = victim;
4024 bck = fwd->bk;
4025 if (bck->fd != fwd)
4026 malloc_printerr ("malloc(): largebin double linked list corrupted (bk)");
4029 else
4030 victim->fd_nextsize = victim->bk_nextsize = victim;
4033 mark_bin (av, victim_index);
4034 victim->bk = bck;
4035 victim->fd = fwd;
4036 fwd->bk = victim;
4037 bck->fd = victim;
4039 #if USE_TCACHE
4040 /* If we've processed as many chunks as we're allowed while
4041 filling the cache, return one of the cached ones. */
4042 ++tcache_unsorted_count;
4043 if (return_cached
4044 && mp_.tcache_unsorted_limit > 0
4045 && tcache_unsorted_count > mp_.tcache_unsorted_limit)
4047 return tcache_get (tc_idx);
4049 #endif
4051 #define MAX_ITERS 10000
4052 if (++iters >= MAX_ITERS)
4053 break;
4056 #if USE_TCACHE
4057 /* If all the small chunks we found ended up cached, return one now. */
4058 if (return_cached)
4060 return tcache_get (tc_idx);
4062 #endif
4065 If a large request, scan through the chunks of current bin in
4066 sorted order to find smallest that fits. Use the skip list for this.
4069 if (!in_smallbin_range (nb))
4071 bin = bin_at (av, idx);
4073 /* skip scan if empty or largest chunk is too small */
4074 if ((victim = first (bin)) != bin
4075 && (unsigned long) chunksize_nomask (victim)
4076 >= (unsigned long) (nb))
4078 victim = victim->bk_nextsize;
4079 while (((unsigned long) (size = chunksize (victim)) <
4080 (unsigned long) (nb)))
4081 victim = victim->bk_nextsize;
4083 /* Avoid removing the first entry for a size so that the skip
4084 list does not have to be rerouted. */
4085 if (victim != last (bin)
4086 && chunksize_nomask (victim)
4087 == chunksize_nomask (victim->fd))
4088 victim = victim->fd;
4090 remainder_size = size - nb;
4091 unlink_chunk (av, victim);
4093 /* Exhaust */
4094 if (remainder_size < MINSIZE)
4096 set_inuse_bit_at_offset (victim, size);
4097 if (av != &main_arena)
4098 set_non_main_arena (victim);
4100 /* Split */
4101 else
4103 remainder = chunk_at_offset (victim, nb);
4104 /* We cannot assume the unsorted list is empty and therefore
4105 have to perform a complete insert here. */
4106 bck = unsorted_chunks (av);
4107 fwd = bck->fd;
4108 if (__glibc_unlikely (fwd->bk != bck))
4109 malloc_printerr ("malloc(): corrupted unsorted chunks");
4110 remainder->bk = bck;
4111 remainder->fd = fwd;
4112 bck->fd = remainder;
4113 fwd->bk = remainder;
4114 if (!in_smallbin_range (remainder_size))
4116 remainder->fd_nextsize = NULL;
4117 remainder->bk_nextsize = NULL;
4119 set_head (victim, nb | PREV_INUSE |
4120 (av != &main_arena ? NON_MAIN_ARENA : 0));
4121 set_head (remainder, remainder_size | PREV_INUSE);
4122 set_foot (remainder, remainder_size);
4124 check_malloced_chunk (av, victim, nb);
4125 void *p = chunk2mem (victim);
4126 alloc_perturb (p, bytes);
4127 return p;
4132 Search for a chunk by scanning bins, starting with next largest
4133 bin. This search is strictly by best-fit; i.e., the smallest
4134 (with ties going to approximately the least recently used) chunk
4135 that fits is selected.
4137 The bitmap avoids needing to check that most blocks are nonempty.
4138 The particular case of skipping all bins during warm-up phases
4139 when no chunks have been returned yet is faster than it might look.
4142 ++idx;
4143 bin = bin_at (av, idx);
4144 block = idx2block (idx);
4145 map = av->binmap[block];
4146 bit = idx2bit (idx);
4148 for (;; )
4150 /* Skip rest of block if there are no more set bits in this block. */
4151 if (bit > map || bit == 0)
4155 if (++block >= BINMAPSIZE) /* out of bins */
4156 goto use_top;
4158 while ((map = av->binmap[block]) == 0);
4160 bin = bin_at (av, (block << BINMAPSHIFT));
4161 bit = 1;
4164 /* Advance to bin with set bit. There must be one. */
4165 while ((bit & map) == 0)
4167 bin = next_bin (bin);
4168 bit <<= 1;
4169 assert (bit != 0);
4172 /* Inspect the bin. It is likely to be non-empty */
4173 victim = last (bin);
4175 /* If a false alarm (empty bin), clear the bit. */
4176 if (victim == bin)
4178 av->binmap[block] = map &= ~bit; /* Write through */
4179 bin = next_bin (bin);
4180 bit <<= 1;
4183 else
4185 size = chunksize (victim);
4187 /* We know the first chunk in this bin is big enough to use. */
4188 assert ((unsigned long) (size) >= (unsigned long) (nb));
4190 remainder_size = size - nb;
4192 /* unlink */
4193 unlink_chunk (av, victim);
4195 /* Exhaust */
4196 if (remainder_size < MINSIZE)
4198 set_inuse_bit_at_offset (victim, size);
4199 if (av != &main_arena)
4200 set_non_main_arena (victim);
4203 /* Split */
4204 else
4206 remainder = chunk_at_offset (victim, nb);
4208 /* We cannot assume the unsorted list is empty and therefore
4209 have to perform a complete insert here. */
4210 bck = unsorted_chunks (av);
4211 fwd = bck->fd;
4212 if (__glibc_unlikely (fwd->bk != bck))
4213 malloc_printerr ("malloc(): corrupted unsorted chunks 2");
4214 remainder->bk = bck;
4215 remainder->fd = fwd;
4216 bck->fd = remainder;
4217 fwd->bk = remainder;
4219 /* advertise as last remainder */
4220 if (in_smallbin_range (nb))
4221 av->last_remainder = remainder;
4222 if (!in_smallbin_range (remainder_size))
4224 remainder->fd_nextsize = NULL;
4225 remainder->bk_nextsize = NULL;
4227 set_head (victim, nb | PREV_INUSE |
4228 (av != &main_arena ? NON_MAIN_ARENA : 0));
4229 set_head (remainder, remainder_size | PREV_INUSE);
4230 set_foot (remainder, remainder_size);
4232 check_malloced_chunk (av, victim, nb);
4233 void *p = chunk2mem (victim);
4234 alloc_perturb (p, bytes);
4235 return p;
4239 use_top:
4241 If large enough, split off the chunk bordering the end of memory
4242 (held in av->top). Note that this is in accord with the best-fit
4243 search rule. In effect, av->top is treated as larger (and thus
4244 less well fitting) than any other available chunk since it can
4245 be extended to be as large as necessary (up to system
4246 limitations).
4248 We require that av->top always exists (i.e., has size >=
4249 MINSIZE) after initialization, so if it would otherwise be
4250 exhausted by current request, it is replenished. (The main
4251 reason for ensuring it exists is that we may need MINSIZE space
4252 to put in fenceposts in sysmalloc.)
4255 victim = av->top;
4256 size = chunksize (victim);
4258 if (__glibc_unlikely (size > av->system_mem))
4259 malloc_printerr ("malloc(): corrupted top size");
4261 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
4263 remainder_size = size - nb;
4264 remainder = chunk_at_offset (victim, nb);
4265 av->top = remainder;
4266 set_head (victim, nb | PREV_INUSE |
4267 (av != &main_arena ? NON_MAIN_ARENA : 0));
4268 set_head (remainder, remainder_size | PREV_INUSE);
4270 check_malloced_chunk (av, victim, nb);
4271 void *p = chunk2mem (victim);
4272 alloc_perturb (p, bytes);
4273 return p;
4276 /* When we are using atomic ops to free fast chunks we can get
4277 here for all block sizes. */
4278 else if (atomic_load_relaxed (&av->have_fastchunks))
4280 malloc_consolidate (av);
4281 /* restore original bin index */
4282 if (in_smallbin_range (nb))
4283 idx = smallbin_index (nb);
4284 else
4285 idx = largebin_index (nb);
4289 Otherwise, relay to handle system-dependent cases
4291 else
4293 void *p = sysmalloc (nb, av);
4294 if (p != NULL)
4295 alloc_perturb (p, bytes);
4296 return p;
4302 ------------------------------ free ------------------------------
4305 static void
4306 _int_free (mstate av, mchunkptr p, int have_lock)
4308 INTERNAL_SIZE_T size; /* its size */
4309 mfastbinptr *fb; /* associated fastbin */
4310 mchunkptr nextchunk; /* next contiguous chunk */
4311 INTERNAL_SIZE_T nextsize; /* its size */
4312 int nextinuse; /* true if nextchunk is used */
4313 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
4314 mchunkptr bck; /* misc temp for linking */
4315 mchunkptr fwd; /* misc temp for linking */
4317 size = chunksize (p);
4319 /* Little security check which won't hurt performance: the
4320 allocator never wrapps around at the end of the address space.
4321 Therefore we can exclude some size values which might appear
4322 here by accident or by "design" from some intruder. */
4323 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
4324 || __builtin_expect (misaligned_chunk (p), 0))
4325 malloc_printerr ("free(): invalid pointer");
4326 /* We know that each chunk is at least MINSIZE bytes in size or a
4327 multiple of MALLOC_ALIGNMENT. */
4328 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
4329 malloc_printerr ("free(): invalid size");
4331 check_inuse_chunk(av, p);
4333 #if USE_TCACHE
4335 size_t tc_idx = csize2tidx (size);
4336 if (tcache != NULL && tc_idx < mp_.tcache_bins)
4338 /* Check to see if it's already in the tcache. */
4339 tcache_entry *e = (tcache_entry *) chunk2mem (p);
4341 /* This test succeeds on double free. However, we don't 100%
4342 trust it (it also matches random payload data at a 1 in
4343 2^<size_t> chance), so verify it's not an unlikely
4344 coincidence before aborting. */
4345 if (__glibc_unlikely (e->key == tcache_key))
4347 tcache_entry *tmp;
4348 size_t cnt = 0;
4349 LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
4350 for (tmp = tcache->entries[tc_idx];
4351 tmp;
4352 tmp = REVEAL_PTR (tmp->next), ++cnt)
4354 if (cnt >= mp_.tcache_count)
4355 malloc_printerr ("free(): too many chunks detected in tcache");
4356 if (__glibc_unlikely (!aligned_OK (tmp)))
4357 malloc_printerr ("free(): unaligned chunk detected in tcache 2");
4358 if (tmp == e)
4359 malloc_printerr ("free(): double free detected in tcache 2");
4360 /* If we get here, it was a coincidence. We've wasted a
4361 few cycles, but don't abort. */
4365 if (tcache->counts[tc_idx] < mp_.tcache_count)
4367 tcache_put (p, tc_idx);
4368 return;
4372 #endif
4375 If eligible, place chunk on a fastbin so it can be found
4376 and used quickly in malloc.
4379 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
4381 #if TRIM_FASTBINS
4383 If TRIM_FASTBINS set, don't place chunks
4384 bordering top into fastbins
4386 && (chunk_at_offset(p, size) != av->top)
4387 #endif
4390 if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
4391 <= CHUNK_HDR_SZ, 0)
4392 || __builtin_expect (chunksize (chunk_at_offset (p, size))
4393 >= av->system_mem, 0))
4395 bool fail = true;
4396 /* We might not have a lock at this point and concurrent modifications
4397 of system_mem might result in a false positive. Redo the test after
4398 getting the lock. */
4399 if (!have_lock)
4401 __libc_lock_lock (av->mutex);
4402 fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ
4403 || chunksize (chunk_at_offset (p, size)) >= av->system_mem);
4404 __libc_lock_unlock (av->mutex);
4407 if (fail)
4408 malloc_printerr ("free(): invalid next size (fast)");
4411 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4413 atomic_store_relaxed (&av->have_fastchunks, true);
4414 unsigned int idx = fastbin_index(size);
4415 fb = &fastbin (av, idx);
4417 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
4418 mchunkptr old = *fb, old2;
4420 if (SINGLE_THREAD_P)
4422 /* Check that the top of the bin is not the record we are going to
4423 add (i.e., double free). */
4424 if (__builtin_expect (old == p, 0))
4425 malloc_printerr ("double free or corruption (fasttop)");
4426 p->fd = PROTECT_PTR (&p->fd, old);
4427 *fb = p;
4429 else
4432 /* Check that the top of the bin is not the record we are going to
4433 add (i.e., double free). */
4434 if (__builtin_expect (old == p, 0))
4435 malloc_printerr ("double free or corruption (fasttop)");
4436 old2 = old;
4437 p->fd = PROTECT_PTR (&p->fd, old);
4439 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2))
4440 != old2);
4442 /* Check that size of fastbin chunk at the top is the same as
4443 size of the chunk that we are adding. We can dereference OLD
4444 only if we have the lock, otherwise it might have already been
4445 allocated again. */
4446 if (have_lock && old != NULL
4447 && __builtin_expect (fastbin_index (chunksize (old)) != idx, 0))
4448 malloc_printerr ("invalid fastbin entry (free)");
4452 Consolidate other non-mmapped chunks as they arrive.
4455 else if (!chunk_is_mmapped(p)) {
4457 /* If we're single-threaded, don't lock the arena. */
4458 if (SINGLE_THREAD_P)
4459 have_lock = true;
4461 if (!have_lock)
4462 __libc_lock_lock (av->mutex);
4464 nextchunk = chunk_at_offset(p, size);
4466 /* Lightweight tests: check whether the block is already the
4467 top block. */
4468 if (__glibc_unlikely (p == av->top))
4469 malloc_printerr ("double free or corruption (top)");
4470 /* Or whether the next chunk is beyond the boundaries of the arena. */
4471 if (__builtin_expect (contiguous (av)
4472 && (char *) nextchunk
4473 >= ((char *) av->top + chunksize(av->top)), 0))
4474 malloc_printerr ("double free or corruption (out)");
4475 /* Or whether the block is actually not marked used. */
4476 if (__glibc_unlikely (!prev_inuse(nextchunk)))
4477 malloc_printerr ("double free or corruption (!prev)");
4479 nextsize = chunksize(nextchunk);
4480 if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0)
4481 || __builtin_expect (nextsize >= av->system_mem, 0))
4482 malloc_printerr ("free(): invalid next size (normal)");
4484 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4486 /* consolidate backward */
4487 if (!prev_inuse(p)) {
4488 prevsize = prev_size (p);
4489 size += prevsize;
4490 p = chunk_at_offset(p, -((long) prevsize));
4491 if (__glibc_unlikely (chunksize(p) != prevsize))
4492 malloc_printerr ("corrupted size vs. prev_size while consolidating");
4493 unlink_chunk (av, p);
4496 if (nextchunk != av->top) {
4497 /* get and clear inuse bit */
4498 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4500 /* consolidate forward */
4501 if (!nextinuse) {
4502 unlink_chunk (av, nextchunk);
4503 size += nextsize;
4504 } else
4505 clear_inuse_bit_at_offset(nextchunk, 0);
4508 Place the chunk in unsorted chunk list. Chunks are
4509 not placed into regular bins until after they have
4510 been given one chance to be used in malloc.
4513 bck = unsorted_chunks(av);
4514 fwd = bck->fd;
4515 if (__glibc_unlikely (fwd->bk != bck))
4516 malloc_printerr ("free(): corrupted unsorted chunks");
4517 p->fd = fwd;
4518 p->bk = bck;
4519 if (!in_smallbin_range(size))
4521 p->fd_nextsize = NULL;
4522 p->bk_nextsize = NULL;
4524 bck->fd = p;
4525 fwd->bk = p;
4527 set_head(p, size | PREV_INUSE);
4528 set_foot(p, size);
4530 check_free_chunk(av, p);
4534 If the chunk borders the current high end of memory,
4535 consolidate into top
4538 else {
4539 size += nextsize;
4540 set_head(p, size | PREV_INUSE);
4541 av->top = p;
4542 check_chunk(av, p);
4546 If freeing a large space, consolidate possibly-surrounding
4547 chunks. Then, if the total unused topmost memory exceeds trim
4548 threshold, ask malloc_trim to reduce top.
4550 Unless max_fast is 0, we don't know if there are fastbins
4551 bordering top, so we cannot tell for sure whether threshold
4552 has been reached unless fastbins are consolidated. But we
4553 don't want to consolidate on each free. As a compromise,
4554 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4555 is reached.
4558 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4559 if (atomic_load_relaxed (&av->have_fastchunks))
4560 malloc_consolidate(av);
4562 if (av == &main_arena) {
4563 #ifndef MORECORE_CANNOT_TRIM
4564 if ((unsigned long)(chunksize(av->top)) >=
4565 (unsigned long)(mp_.trim_threshold))
4566 systrim(mp_.top_pad, av);
4567 #endif
4568 } else {
4569 /* Always try heap_trim(), even if the top chunk is not
4570 large, because the corresponding heap might go away. */
4571 heap_info *heap = heap_for_ptr(top(av));
4573 assert(heap->ar_ptr == av);
4574 heap_trim(heap, mp_.top_pad);
4578 if (!have_lock)
4579 __libc_lock_unlock (av->mutex);
4582 If the chunk was allocated via mmap, release via munmap().
4585 else {
4586 munmap_chunk (p);
4591 ------------------------- malloc_consolidate -------------------------
4593 malloc_consolidate is a specialized version of free() that tears
4594 down chunks held in fastbins. Free itself cannot be used for this
4595 purpose since, among other things, it might place chunks back onto
4596 fastbins. So, instead, we need to use a minor variant of the same
4597 code.
4600 static void malloc_consolidate(mstate av)
4602 mfastbinptr* fb; /* current fastbin being consolidated */
4603 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4604 mchunkptr p; /* current chunk being consolidated */
4605 mchunkptr nextp; /* next chunk to consolidate */
4606 mchunkptr unsorted_bin; /* bin header */
4607 mchunkptr first_unsorted; /* chunk to link to */
4609 /* These have same use as in free() */
4610 mchunkptr nextchunk;
4611 INTERNAL_SIZE_T size;
4612 INTERNAL_SIZE_T nextsize;
4613 INTERNAL_SIZE_T prevsize;
4614 int nextinuse;
4616 atomic_store_relaxed (&av->have_fastchunks, false);
4618 unsorted_bin = unsorted_chunks(av);
4621 Remove each chunk from fast bin and consolidate it, placing it
4622 then in unsorted bin. Among other reasons for doing this,
4623 placing in unsorted bin avoids needing to calculate actual bins
4624 until malloc is sure that chunks aren't immediately going to be
4625 reused anyway.
4628 maxfb = &fastbin (av, NFASTBINS - 1);
4629 fb = &fastbin (av, 0);
4630 do {
4631 p = atomic_exchange_acq (fb, NULL);
4632 if (p != 0) {
4633 do {
4635 if (__glibc_unlikely (misaligned_chunk (p)))
4636 malloc_printerr ("malloc_consolidate(): "
4637 "unaligned fastbin chunk detected");
4639 unsigned int idx = fastbin_index (chunksize (p));
4640 if ((&fastbin (av, idx)) != fb)
4641 malloc_printerr ("malloc_consolidate(): invalid chunk size");
4644 check_inuse_chunk(av, p);
4645 nextp = REVEAL_PTR (p->fd);
4647 /* Slightly streamlined version of consolidation code in free() */
4648 size = chunksize (p);
4649 nextchunk = chunk_at_offset(p, size);
4650 nextsize = chunksize(nextchunk);
4652 if (!prev_inuse(p)) {
4653 prevsize = prev_size (p);
4654 size += prevsize;
4655 p = chunk_at_offset(p, -((long) prevsize));
4656 if (__glibc_unlikely (chunksize(p) != prevsize))
4657 malloc_printerr ("corrupted size vs. prev_size in fastbins");
4658 unlink_chunk (av, p);
4661 if (nextchunk != av->top) {
4662 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4664 if (!nextinuse) {
4665 size += nextsize;
4666 unlink_chunk (av, nextchunk);
4667 } else
4668 clear_inuse_bit_at_offset(nextchunk, 0);
4670 first_unsorted = unsorted_bin->fd;
4671 unsorted_bin->fd = p;
4672 first_unsorted->bk = p;
4674 if (!in_smallbin_range (size)) {
4675 p->fd_nextsize = NULL;
4676 p->bk_nextsize = NULL;
4679 set_head(p, size | PREV_INUSE);
4680 p->bk = unsorted_bin;
4681 p->fd = first_unsorted;
4682 set_foot(p, size);
4685 else {
4686 size += nextsize;
4687 set_head(p, size | PREV_INUSE);
4688 av->top = p;
4691 } while ( (p = nextp) != 0);
4694 } while (fb++ != maxfb);
4698 ------------------------------ realloc ------------------------------
4701 static void *
4702 _int_realloc (mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4703 INTERNAL_SIZE_T nb)
4705 mchunkptr newp; /* chunk to return */
4706 INTERNAL_SIZE_T newsize; /* its size */
4707 void* newmem; /* corresponding user mem */
4709 mchunkptr next; /* next contiguous chunk after oldp */
4711 mchunkptr remainder; /* extra space at end of newp */
4712 unsigned long remainder_size; /* its size */
4714 /* oldmem size */
4715 if (__builtin_expect (chunksize_nomask (oldp) <= CHUNK_HDR_SZ, 0)
4716 || __builtin_expect (oldsize >= av->system_mem, 0))
4717 malloc_printerr ("realloc(): invalid old size");
4719 check_inuse_chunk (av, oldp);
4721 /* All callers already filter out mmap'ed chunks. */
4722 assert (!chunk_is_mmapped (oldp));
4724 next = chunk_at_offset (oldp, oldsize);
4725 INTERNAL_SIZE_T nextsize = chunksize (next);
4726 if (__builtin_expect (chunksize_nomask (next) <= CHUNK_HDR_SZ, 0)
4727 || __builtin_expect (nextsize >= av->system_mem, 0))
4728 malloc_printerr ("realloc(): invalid next size");
4730 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4732 /* already big enough; split below */
4733 newp = oldp;
4734 newsize = oldsize;
4737 else
4739 /* Try to expand forward into top */
4740 if (next == av->top &&
4741 (unsigned long) (newsize = oldsize + nextsize) >=
4742 (unsigned long) (nb + MINSIZE))
4744 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4745 av->top = chunk_at_offset (oldp, nb);
4746 set_head (av->top, (newsize - nb) | PREV_INUSE);
4747 check_inuse_chunk (av, oldp);
4748 return tag_new_usable (chunk2mem (oldp));
4751 /* Try to expand forward into next chunk; split off remainder below */
4752 else if (next != av->top &&
4753 !inuse (next) &&
4754 (unsigned long) (newsize = oldsize + nextsize) >=
4755 (unsigned long) (nb))
4757 newp = oldp;
4758 unlink_chunk (av, next);
4761 /* allocate, copy, free */
4762 else
4764 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4765 if (newmem == 0)
4766 return 0; /* propagate failure */
4768 newp = mem2chunk (newmem);
4769 newsize = chunksize (newp);
4772 Avoid copy if newp is next chunk after oldp.
4774 if (newp == next)
4776 newsize += oldsize;
4777 newp = oldp;
4779 else
4781 void *oldmem = chunk2mem (oldp);
4782 size_t sz = memsize (oldp);
4783 (void) tag_region (oldmem, sz);
4784 newmem = tag_new_usable (newmem);
4785 memcpy (newmem, oldmem, sz);
4786 _int_free (av, oldp, 1);
4787 check_inuse_chunk (av, newp);
4788 return newmem;
4793 /* If possible, free extra space in old or extended chunk */
4795 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
4797 remainder_size = newsize - nb;
4799 if (remainder_size < MINSIZE) /* not enough extra to split off */
4801 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4802 set_inuse_bit_at_offset (newp, newsize);
4804 else /* split remainder */
4806 remainder = chunk_at_offset (newp, nb);
4807 /* Clear any user-space tags before writing the header. */
4808 remainder = tag_region (remainder, remainder_size);
4809 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4810 set_head (remainder, remainder_size | PREV_INUSE |
4811 (av != &main_arena ? NON_MAIN_ARENA : 0));
4812 /* Mark remainder as inuse so free() won't complain */
4813 set_inuse_bit_at_offset (remainder, remainder_size);
4814 _int_free (av, remainder, 1);
4817 check_inuse_chunk (av, newp);
4818 return tag_new_usable (chunk2mem (newp));
4822 ------------------------------ memalign ------------------------------
4825 static void *
4826 _int_memalign (mstate av, size_t alignment, size_t bytes)
4828 INTERNAL_SIZE_T nb; /* padded request size */
4829 char *m; /* memory returned by malloc call */
4830 mchunkptr p; /* corresponding chunk */
4831 char *brk; /* alignment point within p */
4832 mchunkptr newp; /* chunk to return */
4833 INTERNAL_SIZE_T newsize; /* its size */
4834 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4835 mchunkptr remainder; /* spare room at end to split off */
4836 unsigned long remainder_size; /* its size */
4837 INTERNAL_SIZE_T size;
4841 if (!checked_request2size (bytes, &nb))
4843 __set_errno (ENOMEM);
4844 return NULL;
4848 Strategy: find a spot within that chunk that meets the alignment
4849 request, and then possibly free the leading and trailing space.
4852 /* Call malloc with worst case padding to hit alignment. */
4854 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4856 if (m == 0)
4857 return 0; /* propagate failure */
4859 p = mem2chunk (m);
4861 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4863 { /*
4864 Find an aligned spot inside chunk. Since we need to give back
4865 leading space in a chunk of at least MINSIZE, if the first
4866 calculation places us at a spot with less than MINSIZE leader,
4867 we can move to the next aligned spot -- we've allocated enough
4868 total room so that this is always possible.
4870 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4871 - ((signed long) alignment));
4872 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4873 brk += alignment;
4875 newp = (mchunkptr) brk;
4876 leadsize = brk - (char *) (p);
4877 newsize = chunksize (p) - leadsize;
4879 /* For mmapped chunks, just adjust offset */
4880 if (chunk_is_mmapped (p))
4882 set_prev_size (newp, prev_size (p) + leadsize);
4883 set_head (newp, newsize | IS_MMAPPED);
4884 return chunk2mem (newp);
4887 /* Otherwise, give back leader, use the rest */
4888 set_head (newp, newsize | PREV_INUSE |
4889 (av != &main_arena ? NON_MAIN_ARENA : 0));
4890 set_inuse_bit_at_offset (newp, newsize);
4891 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4892 _int_free (av, p, 1);
4893 p = newp;
4895 assert (newsize >= nb &&
4896 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
4899 /* Also give back spare room at the end */
4900 if (!chunk_is_mmapped (p))
4902 size = chunksize (p);
4903 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4905 remainder_size = size - nb;
4906 remainder = chunk_at_offset (p, nb);
4907 set_head (remainder, remainder_size | PREV_INUSE |
4908 (av != &main_arena ? NON_MAIN_ARENA : 0));
4909 set_head_size (p, nb);
4910 _int_free (av, remainder, 1);
4914 check_inuse_chunk (av, p);
4915 return chunk2mem (p);
4920 ------------------------------ malloc_trim ------------------------------
4923 static int
4924 mtrim (mstate av, size_t pad)
4926 /* Ensure all blocks are consolidated. */
4927 malloc_consolidate (av);
4929 const size_t ps = GLRO (dl_pagesize);
4930 int psindex = bin_index (ps);
4931 const size_t psm1 = ps - 1;
4933 int result = 0;
4934 for (int i = 1; i < NBINS; ++i)
4935 if (i == 1 || i >= psindex)
4937 mbinptr bin = bin_at (av, i);
4939 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4941 INTERNAL_SIZE_T size = chunksize (p);
4943 if (size > psm1 + sizeof (struct malloc_chunk))
4945 /* See whether the chunk contains at least one unused page. */
4946 char *paligned_mem = (char *) (((uintptr_t) p
4947 + sizeof (struct malloc_chunk)
4948 + psm1) & ~psm1);
4950 assert ((char *) chunk2mem (p) + 2 * CHUNK_HDR_SZ
4951 <= paligned_mem);
4952 assert ((char *) p + size > paligned_mem);
4954 /* This is the size we could potentially free. */
4955 size -= paligned_mem - (char *) p;
4957 if (size > psm1)
4959 #if MALLOC_DEBUG
4960 /* When debugging we simulate destroying the memory
4961 content. */
4962 memset (paligned_mem, 0x89, size & ~psm1);
4963 #endif
4964 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
4966 result = 1;
4972 #ifndef MORECORE_CANNOT_TRIM
4973 return result | (av == &main_arena ? systrim (pad, av) : 0);
4975 #else
4976 return result;
4977 #endif
4982 __malloc_trim (size_t s)
4984 int result = 0;
4986 if (!__malloc_initialized)
4987 ptmalloc_init ();
4989 mstate ar_ptr = &main_arena;
4992 __libc_lock_lock (ar_ptr->mutex);
4993 result |= mtrim (ar_ptr, s);
4994 __libc_lock_unlock (ar_ptr->mutex);
4996 ar_ptr = ar_ptr->next;
4998 while (ar_ptr != &main_arena);
5000 return result;
5005 ------------------------- malloc_usable_size -------------------------
5008 static size_t
5009 musable (void *mem)
5011 mchunkptr p = mem2chunk (mem);
5013 if (chunk_is_mmapped (p))
5014 return chunksize (p) - CHUNK_HDR_SZ;
5015 else if (inuse (p))
5016 return memsize (p);
5018 return 0;
5021 #if IS_IN (libc)
5022 size_t
5023 __malloc_usable_size (void *m)
5025 if (m == NULL)
5026 return 0;
5027 return musable (m);
5029 #endif
5032 ------------------------------ mallinfo ------------------------------
5033 Accumulate malloc statistics for arena AV into M.
5035 static void
5036 int_mallinfo (mstate av, struct mallinfo2 *m)
5038 size_t i;
5039 mbinptr b;
5040 mchunkptr p;
5041 INTERNAL_SIZE_T avail;
5042 INTERNAL_SIZE_T fastavail;
5043 int nblocks;
5044 int nfastblocks;
5046 check_malloc_state (av);
5048 /* Account for top */
5049 avail = chunksize (av->top);
5050 nblocks = 1; /* top always exists */
5052 /* traverse fastbins */
5053 nfastblocks = 0;
5054 fastavail = 0;
5056 for (i = 0; i < NFASTBINS; ++i)
5058 for (p = fastbin (av, i);
5059 p != 0;
5060 p = REVEAL_PTR (p->fd))
5062 if (__glibc_unlikely (misaligned_chunk (p)))
5063 malloc_printerr ("int_mallinfo(): "
5064 "unaligned fastbin chunk detected");
5065 ++nfastblocks;
5066 fastavail += chunksize (p);
5070 avail += fastavail;
5072 /* traverse regular bins */
5073 for (i = 1; i < NBINS; ++i)
5075 b = bin_at (av, i);
5076 for (p = last (b); p != b; p = p->bk)
5078 ++nblocks;
5079 avail += chunksize (p);
5083 m->smblks += nfastblocks;
5084 m->ordblks += nblocks;
5085 m->fordblks += avail;
5086 m->uordblks += av->system_mem - avail;
5087 m->arena += av->system_mem;
5088 m->fsmblks += fastavail;
5089 if (av == &main_arena)
5091 m->hblks = mp_.n_mmaps;
5092 m->hblkhd = mp_.mmapped_mem;
5093 m->usmblks = 0;
5094 m->keepcost = chunksize (av->top);
5099 struct mallinfo2
5100 __libc_mallinfo2 (void)
5102 struct mallinfo2 m;
5103 mstate ar_ptr;
5105 if (!__malloc_initialized)
5106 ptmalloc_init ();
5108 memset (&m, 0, sizeof (m));
5109 ar_ptr = &main_arena;
5112 __libc_lock_lock (ar_ptr->mutex);
5113 int_mallinfo (ar_ptr, &m);
5114 __libc_lock_unlock (ar_ptr->mutex);
5116 ar_ptr = ar_ptr->next;
5118 while (ar_ptr != &main_arena);
5120 return m;
5122 libc_hidden_def (__libc_mallinfo2)
5124 struct mallinfo
5125 __libc_mallinfo (void)
5127 struct mallinfo m;
5128 struct mallinfo2 m2 = __libc_mallinfo2 ();
5130 m.arena = m2.arena;
5131 m.ordblks = m2.ordblks;
5132 m.smblks = m2.smblks;
5133 m.hblks = m2.hblks;
5134 m.hblkhd = m2.hblkhd;
5135 m.usmblks = m2.usmblks;
5136 m.fsmblks = m2.fsmblks;
5137 m.uordblks = m2.uordblks;
5138 m.fordblks = m2.fordblks;
5139 m.keepcost = m2.keepcost;
5141 return m;
5146 ------------------------------ malloc_stats ------------------------------
5149 void
5150 __malloc_stats (void)
5152 int i;
5153 mstate ar_ptr;
5154 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
5156 if (!__malloc_initialized)
5157 ptmalloc_init ();
5158 _IO_flockfile (stderr);
5159 int old_flags2 = stderr->_flags2;
5160 stderr->_flags2 |= _IO_FLAGS2_NOTCANCEL;
5161 for (i = 0, ar_ptr = &main_arena;; i++)
5163 struct mallinfo2 mi;
5165 memset (&mi, 0, sizeof (mi));
5166 __libc_lock_lock (ar_ptr->mutex);
5167 int_mallinfo (ar_ptr, &mi);
5168 fprintf (stderr, "Arena %d:\n", i);
5169 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
5170 fprintf (stderr,