Add generic C.UTF-8 locale (Bug 17318)
[glibc.git] / malloc / malloc.c
blob2ba1fee144f5742daa0fdc72088f73d4c3049ffe
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2021 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation; either version 2.1 of the
8 License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If
17 not, see <https://www.gnu.org/licenses/>. */
20 This is a version (aka ptmalloc2) of malloc/free/realloc written by
21 Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
23 There have been substantial changes made after the integration into
24 glibc in all parts of the code. Do not look for much commonality
25 with the ptmalloc2 version.
27 * Version ptmalloc2-20011215
28 based on:
29 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
31 * Quickstart
33 In order to compile this implementation, a Makefile is provided with
34 the ptmalloc2 distribution, which has pre-defined targets for some
35 popular systems (e.g. "make posix" for Posix threads). All that is
36 typically required with regard to compiler flags is the selection of
37 the thread package via defining one out of USE_PTHREADS, USE_THR or
38 USE_SPROC. Check the thread-m.h file for what effects this has.
39 Many/most systems will additionally require USE_TSD_DATA_HACK to be
40 defined, so this is the default for "make posix".
42 * Why use this malloc?
44 This is not the fastest, most space-conserving, most portable, or
45 most tunable malloc ever written. However it is among the fastest
46 while also being among the most space-conserving, portable and tunable.
47 Consistent balance across these factors results in a good general-purpose
48 allocator for malloc-intensive programs.
50 The main properties of the algorithms are:
51 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
52 with ties normally decided via FIFO (i.e. least recently used).
53 * For small (<= 64 bytes by default) requests, it is a caching
54 allocator, that maintains pools of quickly recycled chunks.
55 * In between, and for combinations of large and small requests, it does
56 the best it can trying to meet both goals at once.
57 * For very large requests (>= 128KB by default), it relies on system
58 memory mapping facilities, if supported.
60 For a longer but slightly out of date high-level description, see
61 http://gee.cs.oswego.edu/dl/html/malloc.html
63 You may already by default be using a C library containing a malloc
64 that is based on some version of this malloc (for example in
65 linux). You might still want to use the one in this file in order to
66 customize settings or to avoid overheads associated with library
67 versions.
69 * Contents, described in more detail in "description of public routines" below.
71 Standard (ANSI/SVID/...) functions:
72 malloc(size_t n);
73 calloc(size_t n_elements, size_t element_size);
74 free(void* p);
75 realloc(void* p, size_t n);
76 memalign(size_t alignment, size_t n);
77 valloc(size_t n);
78 mallinfo()
79 mallopt(int parameter_number, int parameter_value)
81 Additional functions:
82 independent_calloc(size_t n_elements, size_t size, void* chunks[]);
83 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
84 pvalloc(size_t n);
85 malloc_trim(size_t pad);
86 malloc_usable_size(void* p);
87 malloc_stats();
89 * Vital statistics:
91 Supported pointer representation: 4 or 8 bytes
92 Supported size_t representation: 4 or 8 bytes
93 Note that size_t is allowed to be 4 bytes even if pointers are 8.
94 You can adjust this by defining INTERNAL_SIZE_T
96 Alignment: 2 * sizeof(size_t) (default)
97 (i.e., 8 byte alignment with 4byte size_t). This suffices for
98 nearly all current machines and C compilers. However, you can
99 define MALLOC_ALIGNMENT to be wider than this if necessary.
101 Minimum overhead per allocated chunk: 4 or 8 bytes
102 Each malloced chunk has a hidden word of overhead holding size
103 and status information.
105 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
106 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
108 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
109 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
110 needed; 4 (8) for a trailing size field and 8 (16) bytes for
111 free list pointers. Thus, the minimum allocatable size is
112 16/24/32 bytes.
114 Even a request for zero bytes (i.e., malloc(0)) returns a
115 pointer to something of the minimum allocatable size.
117 The maximum overhead wastage (i.e., number of extra bytes
118 allocated than were requested in malloc) is less than or equal
119 to the minimum size, except for requests >= mmap_threshold that
120 are serviced via mmap(), where the worst case wastage is 2 *
121 sizeof(size_t) bytes plus the remainder from a system page (the
122 minimal mmap unit); typically 4096 or 8192 bytes.
124 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
125 8-byte size_t: 2^64 minus about two pages
127 It is assumed that (possibly signed) size_t values suffice to
128 represent chunk sizes. `Possibly signed' is due to the fact
129 that `size_t' may be defined on a system as either a signed or
130 an unsigned type. The ISO C standard says that it must be
131 unsigned, but a few systems are known not to adhere to this.
132 Additionally, even when size_t is unsigned, sbrk (which is by
133 default used to obtain memory from system) accepts signed
134 arguments, and may not be able to handle size_t-wide arguments
135 with negative sign bit. Generally, values that would
136 appear as negative after accounting for overhead and alignment
137 are supported only via mmap(), which does not have this
138 limitation.
140 Requests for sizes outside the allowed range will perform an optional
141 failure action and then return null. (Requests may also
142 also fail because a system is out of memory.)
144 Thread-safety: thread-safe
146 Compliance: I believe it is compliant with the 1997 Single Unix Specification
147 Also SVID/XPG, ANSI C, and probably others as well.
149 * Synopsis of compile-time options:
151 People have reported using previous versions of this malloc on all
152 versions of Unix, sometimes by tweaking some of the defines
153 below. It has been tested most extensively on Solaris and Linux.
154 People also report using it in stand-alone embedded systems.
156 The implementation is in straight, hand-tuned ANSI C. It is not
157 at all modular. (Sorry!) It uses a lot of macros. To be at all
158 usable, this code should be compiled using an optimizing compiler
159 (for example gcc -O3) that can simplify expressions and control
160 paths. (FAQ: some macros import variables as arguments rather than
161 declare locals because people reported that some debuggers
162 otherwise get confused.)
164 OPTION DEFAULT VALUE
166 Compilation Environment options:
168 HAVE_MREMAP 0
170 Changing default word sizes:
172 INTERNAL_SIZE_T size_t
174 Configuration and functionality options:
176 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
177 USE_MALLOC_LOCK NOT defined
178 MALLOC_DEBUG NOT defined
179 REALLOC_ZERO_BYTES_FREES 1
180 TRIM_FASTBINS 0
182 Options for customizing MORECORE:
184 MORECORE sbrk
185 MORECORE_FAILURE -1
186 MORECORE_CONTIGUOUS 1
187 MORECORE_CANNOT_TRIM NOT defined
188 MORECORE_CLEARS 1
189 MMAP_AS_MORECORE_SIZE (1024 * 1024)
191 Tuning options that are also dynamically changeable via mallopt:
193 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
194 DEFAULT_TRIM_THRESHOLD 128 * 1024
195 DEFAULT_TOP_PAD 0
196 DEFAULT_MMAP_THRESHOLD 128 * 1024
197 DEFAULT_MMAP_MAX 65536
199 There are several other #defined constants and macros that you
200 probably don't want to touch unless you are extending or adapting malloc. */
203 void* is the pointer type that malloc should say it returns
206 #ifndef void
207 #define void void
208 #endif /*void*/
210 #include <stddef.h> /* for size_t */
211 #include <stdlib.h> /* for getenv(), abort() */
212 #include <unistd.h> /* for __libc_enable_secure */
214 #include <atomic.h>
215 #include <_itoa.h>
216 #include <bits/wordsize.h>
217 #include <sys/sysinfo.h>
219 #include <ldsodefs.h>
221 #include <unistd.h>
222 #include <stdio.h> /* needed for malloc_stats */
223 #include <errno.h>
224 #include <assert.h>
226 #include <shlib-compat.h>
228 /* For uintptr_t. */
229 #include <stdint.h>
231 /* For va_arg, va_start, va_end. */
232 #include <stdarg.h>
234 /* For MIN, MAX, powerof2. */
235 #include <sys/param.h>
237 /* For ALIGN_UP et. al. */
238 #include <libc-pointer-arith.h>
240 /* For DIAG_PUSH/POP_NEEDS_COMMENT et al. */
241 #include <libc-diag.h>
243 /* For memory tagging. */
244 #include <libc-mtag.h>
246 #include <malloc/malloc-internal.h>
248 /* For SINGLE_THREAD_P. */
249 #include <sysdep-cancel.h>
251 #include <libc-internal.h>
253 /* For tcache double-free check. */
254 #include <random-bits.h>
255 #include <sys/random.h>
258 Debugging:
260 Because freed chunks may be overwritten with bookkeeping fields, this
261 malloc will often die when freed memory is overwritten by user
262 programs. This can be very effective (albeit in an annoying way)
263 in helping track down dangling pointers.
265 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
266 enabled that will catch more memory errors. You probably won't be
267 able to make much sense of the actual assertion errors, but they
268 should help you locate incorrectly overwritten memory. The checking
269 is fairly extensive, and will slow down execution
270 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
271 will attempt to check every non-mmapped allocated and free chunk in
272 the course of computing the summmaries. (By nature, mmapped regions
273 cannot be checked very much automatically.)
275 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
276 this code. The assertions in the check routines spell out in more
277 detail the assumptions and invariants underlying the algorithms.
279 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
280 checking that all accesses to malloced memory stay within their
281 bounds. However, there are several add-ons and adaptations of this
282 or other mallocs available that do this.
285 #ifndef MALLOC_DEBUG
286 #define MALLOC_DEBUG 0
287 #endif
289 #if IS_IN (libc)
290 #ifndef NDEBUG
291 # define __assert_fail(assertion, file, line, function) \
292 __malloc_assert(assertion, file, line, function)
294 extern const char *__progname;
296 static void
297 __malloc_assert (const char *assertion, const char *file, unsigned int line,
298 const char *function)
300 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
301 __progname, __progname[0] ? ": " : "",
302 file, line,
303 function ? function : "", function ? ": " : "",
304 assertion);
305 fflush (stderr);
306 abort ();
308 #endif
309 #endif
311 #if USE_TCACHE
312 /* We want 64 entries. This is an arbitrary limit, which tunables can reduce. */
313 # define TCACHE_MAX_BINS 64
314 # define MAX_TCACHE_SIZE tidx2usize (TCACHE_MAX_BINS-1)
316 /* Only used to pre-fill the tunables. */
317 # define tidx2usize(idx) (((size_t) idx) * MALLOC_ALIGNMENT + MINSIZE - SIZE_SZ)
319 /* When "x" is from chunksize(). */
320 # define csize2tidx(x) (((x) - MINSIZE + MALLOC_ALIGNMENT - 1) / MALLOC_ALIGNMENT)
321 /* When "x" is a user-provided size. */
322 # define usize2tidx(x) csize2tidx (request2size (x))
324 /* With rounding and alignment, the bins are...
325 idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit)
326 idx 1 bytes 25..40 or 13..20
327 idx 2 bytes 41..56 or 21..28
328 etc. */
330 /* This is another arbitrary limit, which tunables can change. Each
331 tcache bin will hold at most this number of chunks. */
332 # define TCACHE_FILL_COUNT 7
334 /* Maximum chunks in tcache bins for tunables. This value must fit the range
335 of tcache->counts[] entries, else they may overflow. */
336 # define MAX_TCACHE_COUNT UINT16_MAX
337 #endif
339 /* Safe-Linking:
340 Use randomness from ASLR (mmap_base) to protect single-linked lists
341 of Fast-Bins and TCache. That is, mask the "next" pointers of the
342 lists' chunks, and also perform allocation alignment checks on them.
343 This mechanism reduces the risk of pointer hijacking, as was done with
344 Safe-Unlinking in the double-linked lists of Small-Bins.
345 It assumes a minimum page size of 4096 bytes (12 bits). Systems with
346 larger pages provide less entropy, although the pointer mangling
347 still works. */
348 #define PROTECT_PTR(pos, ptr) \
349 ((__typeof (ptr)) ((((size_t) pos) >> 12) ^ ((size_t) ptr)))
350 #define REVEAL_PTR(ptr) PROTECT_PTR (&ptr, ptr)
353 The REALLOC_ZERO_BYTES_FREES macro controls the behavior of realloc (p, 0)
354 when p is nonnull. If the macro is nonzero, the realloc call returns NULL;
355 otherwise, the call returns what malloc (0) would. In either case,
356 p is freed. Glibc uses a nonzero REALLOC_ZERO_BYTES_FREES, which
357 implements common historical practice.
359 ISO C17 says the realloc call has implementation-defined behavior,
360 and it might not even free p.
363 #ifndef REALLOC_ZERO_BYTES_FREES
364 #define REALLOC_ZERO_BYTES_FREES 1
365 #endif
368 TRIM_FASTBINS controls whether free() of a very small chunk can
369 immediately lead to trimming. Setting to true (1) can reduce memory
370 footprint, but will almost always slow down programs that use a lot
371 of small chunks.
373 Define this only if you are willing to give up some speed to more
374 aggressively reduce system-level memory footprint when releasing
375 memory in programs that use many small chunks. You can get
376 essentially the same effect by setting MXFAST to 0, but this can
377 lead to even greater slowdowns in programs using many small chunks.
378 TRIM_FASTBINS is an in-between compile-time option, that disables
379 only those chunks bordering topmost memory from being placed in
380 fastbins.
383 #ifndef TRIM_FASTBINS
384 #define TRIM_FASTBINS 0
385 #endif
387 /* Definition for getting more memory from the OS. */
388 #include "morecore.c"
390 #define MORECORE (*__glibc_morecore)
391 #define MORECORE_FAILURE 0
393 /* Memory tagging. */
395 /* Some systems support the concept of tagging (sometimes known as
396 coloring) memory locations on a fine grained basis. Each memory
397 location is given a color (normally allocated randomly) and
398 pointers are also colored. When the pointer is dereferenced, the
399 pointer's color is checked against the memory's color and if they
400 differ the access is faulted (sometimes lazily).
402 We use this in glibc by maintaining a single color for the malloc
403 data structures that are interleaved with the user data and then
404 assigning separate colors for each block allocation handed out. In
405 this way simple buffer overruns will be rapidly detected. When
406 memory is freed, the memory is recolored back to the glibc default
407 so that simple use-after-free errors can also be detected.
409 If memory is reallocated the buffer is recolored even if the
410 address remains the same. This has a performance impact, but
411 guarantees that the old pointer cannot mistakenly be reused (code
412 that compares old against new will see a mismatch and will then
413 need to behave as though realloc moved the data to a new location).
415 Internal API for memory tagging support.
417 The aim is to keep the code for memory tagging support as close to
418 the normal APIs in glibc as possible, so that if tagging is not
419 enabled in the library, or is disabled at runtime then standard
420 operations can continue to be used. Support macros are used to do
421 this:
423 void *tag_new_zero_region (void *ptr, size_t size)
425 Allocates a new tag, colors the memory with that tag, zeros the
426 memory and returns a pointer that is correctly colored for that
427 location. The non-tagging version will simply call memset with 0.
429 void *tag_region (void *ptr, size_t size)
431 Color the region of memory pointed to by PTR and size SIZE with
432 the color of PTR. Returns the original pointer.
434 void *tag_new_usable (void *ptr)
436 Allocate a new random color and use it to color the user region of
437 a chunk; this may include data from the subsequent chunk's header
438 if tagging is sufficiently fine grained. Returns PTR suitably
439 recolored for accessing the memory there.
441 void *tag_at (void *ptr)
443 Read the current color of the memory at the address pointed to by
444 PTR (ignoring it's current color) and return PTR recolored to that
445 color. PTR must be valid address in all other respects. When
446 tagging is not enabled, it simply returns the original pointer.
449 #ifdef USE_MTAG
450 static bool mtag_enabled = false;
451 static int mtag_mmap_flags = 0;
452 #else
453 # define mtag_enabled false
454 # define mtag_mmap_flags 0
455 #endif
457 static __always_inline void *
458 tag_region (void *ptr, size_t size)
460 if (__glibc_unlikely (mtag_enabled))
461 return __libc_mtag_tag_region (ptr, size);
462 return ptr;
465 static __always_inline void *
466 tag_new_zero_region (void *ptr, size_t size)
468 if (__glibc_unlikely (mtag_enabled))
469 return __libc_mtag_tag_zero_region (__libc_mtag_new_tag (ptr), size);
470 return memset (ptr, 0, size);
473 /* Defined later. */
474 static void *
475 tag_new_usable (void *ptr);
477 static __always_inline void *
478 tag_at (void *ptr)
480 if (__glibc_unlikely (mtag_enabled))
481 return __libc_mtag_address_get_tag (ptr);
482 return ptr;
485 #include <string.h>
488 MORECORE-related declarations. By default, rely on sbrk
493 MORECORE is the name of the routine to call to obtain more memory
494 from the system. See below for general guidance on writing
495 alternative MORECORE functions, as well as a version for WIN32 and a
496 sample version for pre-OSX macos.
499 #ifndef MORECORE
500 #define MORECORE sbrk
501 #endif
504 MORECORE_FAILURE is the value returned upon failure of MORECORE
505 as well as mmap. Since it cannot be an otherwise valid memory address,
506 and must reflect values of standard sys calls, you probably ought not
507 try to redefine it.
510 #ifndef MORECORE_FAILURE
511 #define MORECORE_FAILURE (-1)
512 #endif
515 If MORECORE_CONTIGUOUS is true, take advantage of fact that
516 consecutive calls to MORECORE with positive arguments always return
517 contiguous increasing addresses. This is true of unix sbrk. Even
518 if not defined, when regions happen to be contiguous, malloc will
519 permit allocations spanning regions obtained from different
520 calls. But defining this when applicable enables some stronger
521 consistency checks and space efficiencies.
524 #ifndef MORECORE_CONTIGUOUS
525 #define MORECORE_CONTIGUOUS 1
526 #endif
529 Define MORECORE_CANNOT_TRIM if your version of MORECORE
530 cannot release space back to the system when given negative
531 arguments. This is generally necessary only if you are using
532 a hand-crafted MORECORE function that cannot handle negative arguments.
535 /* #define MORECORE_CANNOT_TRIM */
537 /* MORECORE_CLEARS (default 1)
538 The degree to which the routine mapped to MORECORE zeroes out
539 memory: never (0), only for newly allocated space (1) or always
540 (2). The distinction between (1) and (2) is necessary because on
541 some systems, if the application first decrements and then
542 increments the break value, the contents of the reallocated space
543 are unspecified.
546 #ifndef MORECORE_CLEARS
547 # define MORECORE_CLEARS 1
548 #endif
552 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
553 sbrk fails, and mmap is used as a backup. The value must be a
554 multiple of page size. This backup strategy generally applies only
555 when systems have "holes" in address space, so sbrk cannot perform
556 contiguous expansion, but there is still space available on system.
557 On systems for which this is known to be useful (i.e. most linux
558 kernels), this occurs only when programs allocate huge amounts of
559 memory. Between this, and the fact that mmap regions tend to be
560 limited, the size should be large, to avoid too many mmap calls and
561 thus avoid running out of kernel resources. */
563 #ifndef MMAP_AS_MORECORE_SIZE
564 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
565 #endif
568 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
569 large blocks.
572 #ifndef HAVE_MREMAP
573 #define HAVE_MREMAP 0
574 #endif
577 This version of malloc supports the standard SVID/XPG mallinfo
578 routine that returns a struct containing usage properties and
579 statistics. It should work on any SVID/XPG compliant system that has
580 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
581 install such a thing yourself, cut out the preliminary declarations
582 as described above and below and save them in a malloc.h file. But
583 there's no compelling reason to bother to do this.)
585 The main declaration needed is the mallinfo struct that is returned
586 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
587 bunch of fields that are not even meaningful in this version of
588 malloc. These fields are are instead filled by mallinfo() with
589 other numbers that might be of interest.
593 /* ---------- description of public routines ------------ */
595 #if IS_IN (libc)
597 malloc(size_t n)
598 Returns a pointer to a newly allocated chunk of at least n bytes, or null
599 if no space is available. Additionally, on failure, errno is
600 set to ENOMEM on ANSI C systems.
602 If n is zero, malloc returns a minimum-sized chunk. (The minimum
603 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
604 systems.) On most systems, size_t is an unsigned type, so calls
605 with negative arguments are interpreted as requests for huge amounts
606 of space, which will often fail. The maximum supported value of n
607 differs across systems, but is in all cases less than the maximum
608 representable value of a size_t.
610 void* __libc_malloc(size_t);
611 libc_hidden_proto (__libc_malloc)
614 free(void* p)
615 Releases the chunk of memory pointed to by p, that had been previously
616 allocated using malloc or a related routine such as realloc.
617 It has no effect if p is null. It can have arbitrary (i.e., bad!)
618 effects if p has already been freed.
620 Unless disabled (using mallopt), freeing very large spaces will
621 when possible, automatically trigger operations that give
622 back unused memory to the system, thus reducing program footprint.
624 void __libc_free(void*);
625 libc_hidden_proto (__libc_free)
628 calloc(size_t n_elements, size_t element_size);
629 Returns a pointer to n_elements * element_size bytes, with all locations
630 set to zero.
632 void* __libc_calloc(size_t, size_t);
635 realloc(void* p, size_t n)
636 Returns a pointer to a chunk of size n that contains the same data
637 as does chunk p up to the minimum of (n, p's size) bytes, or null
638 if no space is available.
640 The returned pointer may or may not be the same as p. The algorithm
641 prefers extending p when possible, otherwise it employs the
642 equivalent of a malloc-copy-free sequence.
644 If p is null, realloc is equivalent to malloc.
646 If space is not available, realloc returns null, errno is set (if on
647 ANSI) and p is NOT freed.
649 if n is for fewer bytes than already held by p, the newly unused
650 space is lopped off and freed if possible. Unless the #define
651 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
652 zero (re)allocates a minimum-sized chunk.
654 Large chunks that were internally obtained via mmap will always be
655 grown using malloc-copy-free sequences unless the system supports
656 MREMAP (currently only linux).
658 The old unix realloc convention of allowing the last-free'd chunk
659 to be used as an argument to realloc is not supported.
661 void* __libc_realloc(void*, size_t);
662 libc_hidden_proto (__libc_realloc)
665 memalign(size_t alignment, size_t n);
666 Returns a pointer to a newly allocated chunk of n bytes, aligned
667 in accord with the alignment argument.
669 The alignment argument should be a power of two. If the argument is
670 not a power of two, the nearest greater power is used.
671 8-byte alignment is guaranteed by normal malloc calls, so don't
672 bother calling memalign with an argument of 8 or less.
674 Overreliance on memalign is a sure way to fragment space.
676 void* __libc_memalign(size_t, size_t);
677 libc_hidden_proto (__libc_memalign)
680 valloc(size_t n);
681 Equivalent to memalign(pagesize, n), where pagesize is the page
682 size of the system. If the pagesize is unknown, 4096 is used.
684 void* __libc_valloc(size_t);
689 mallinfo()
690 Returns (by copy) a struct containing various summary statistics:
692 arena: current total non-mmapped bytes allocated from system
693 ordblks: the number of free chunks
694 smblks: the number of fastbin blocks (i.e., small chunks that
695 have been freed but not use resused or consolidated)
696 hblks: current number of mmapped regions
697 hblkhd: total bytes held in mmapped regions
698 usmblks: always 0
699 fsmblks: total bytes held in fastbin blocks
700 uordblks: current total allocated space (normal or mmapped)
701 fordblks: total free space
702 keepcost: the maximum number of bytes that could ideally be released
703 back to system via malloc_trim. ("ideally" means that
704 it ignores page restrictions etc.)
706 Because these fields are ints, but internal bookkeeping may
707 be kept as longs, the reported values may wrap around zero and
708 thus be inaccurate.
710 struct mallinfo2 __libc_mallinfo2(void);
711 libc_hidden_proto (__libc_mallinfo2)
713 struct mallinfo __libc_mallinfo(void);
717 pvalloc(size_t n);
718 Equivalent to valloc(minimum-page-that-holds(n)), that is,
719 round up n to nearest pagesize.
721 void* __libc_pvalloc(size_t);
724 malloc_trim(size_t pad);
726 If possible, gives memory back to the system (via negative
727 arguments to sbrk) if there is unused memory at the `high' end of
728 the malloc pool. You can call this after freeing large blocks of
729 memory to potentially reduce the system-level memory requirements
730 of a program. However, it cannot guarantee to reduce memory. Under
731 some allocation patterns, some large free blocks of memory will be
732 locked between two used chunks, so they cannot be given back to
733 the system.
735 The `pad' argument to malloc_trim represents the amount of free
736 trailing space to leave untrimmed. If this argument is zero,
737 only the minimum amount of memory to maintain internal data
738 structures will be left (one page or less). Non-zero arguments
739 can be supplied to maintain enough trailing space to service
740 future expected allocations without having to re-obtain memory
741 from the system.
743 Malloc_trim returns 1 if it actually released any memory, else 0.
744 On systems that do not support "negative sbrks", it will always
745 return 0.
747 int __malloc_trim(size_t);
750 malloc_usable_size(void* p);
752 Returns the number of bytes you can actually use in
753 an allocated chunk, which may be more than you requested (although
754 often not) due to alignment and minimum size constraints.
755 You can use this many bytes without worrying about
756 overwriting other allocated objects. This is not a particularly great
757 programming practice. malloc_usable_size can be more useful in
758 debugging and assertions, for example:
760 p = malloc(n);
761 assert(malloc_usable_size(p) >= 256);
764 size_t __malloc_usable_size(void*);
767 malloc_stats();
768 Prints on stderr the amount of space obtained from the system (both
769 via sbrk and mmap), the maximum amount (which may be more than
770 current if malloc_trim and/or munmap got called), and the current
771 number of bytes allocated via malloc (or realloc, etc) but not yet
772 freed. Note that this is the number of bytes allocated, not the
773 number requested. It will be larger than the number requested
774 because of alignment and bookkeeping overhead. Because it includes
775 alignment wastage as being in use, this figure may be greater than
776 zero even when no user-level chunks are allocated.
778 The reported current and maximum system memory can be inaccurate if
779 a program makes other calls to system memory allocation functions
780 (normally sbrk) outside of malloc.
782 malloc_stats prints only the most commonly interesting statistics.
783 More information can be obtained by calling mallinfo.
786 void __malloc_stats(void);
789 posix_memalign(void **memptr, size_t alignment, size_t size);
791 POSIX wrapper like memalign(), checking for validity of size.
793 int __posix_memalign(void **, size_t, size_t);
794 #endif /* IS_IN (libc) */
797 mallopt(int parameter_number, int parameter_value)
798 Sets tunable parameters The format is to provide a
799 (parameter-number, parameter-value) pair. mallopt then sets the
800 corresponding parameter to the argument value if it can (i.e., so
801 long as the value is meaningful), and returns 1 if successful else
802 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
803 normally defined in malloc.h. Only one of these (M_MXFAST) is used
804 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
805 so setting them has no effect. But this malloc also supports four
806 other options in mallopt. See below for details. Briefly, supported
807 parameters are as follows (listed defaults are for "typical"
808 configurations).
810 Symbol param # default allowed param values
811 M_MXFAST 1 64 0-80 (0 disables fastbins)
812 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
813 M_TOP_PAD -2 0 any
814 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
815 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
817 int __libc_mallopt(int, int);
818 #if IS_IN (libc)
819 libc_hidden_proto (__libc_mallopt)
820 #endif
822 /* mallopt tuning options */
825 M_MXFAST is the maximum request size used for "fastbins", special bins
826 that hold returned chunks without consolidating their spaces. This
827 enables future requests for chunks of the same size to be handled
828 very quickly, but can increase fragmentation, and thus increase the
829 overall memory footprint of a program.
831 This malloc manages fastbins very conservatively yet still
832 efficiently, so fragmentation is rarely a problem for values less
833 than or equal to the default. The maximum supported value of MXFAST
834 is 80. You wouldn't want it any higher than this anyway. Fastbins
835 are designed especially for use with many small structs, objects or
836 strings -- the default handles structs/objects/arrays with sizes up
837 to 8 4byte fields, or small strings representing words, tokens,
838 etc. Using fastbins for larger objects normally worsens
839 fragmentation without improving speed.
841 M_MXFAST is set in REQUEST size units. It is internally used in
842 chunksize units, which adds padding and alignment. You can reduce
843 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
844 algorithm to be a closer approximation of fifo-best-fit in all cases,
845 not just for larger requests, but will generally cause it to be
846 slower.
850 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
851 #ifndef M_MXFAST
852 #define M_MXFAST 1
853 #endif
855 #ifndef DEFAULT_MXFAST
856 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
857 #endif
861 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
862 to keep before releasing via malloc_trim in free().
864 Automatic trimming is mainly useful in long-lived programs.
865 Because trimming via sbrk can be slow on some systems, and can
866 sometimes be wasteful (in cases where programs immediately
867 afterward allocate more large chunks) the value should be high
868 enough so that your overall system performance would improve by
869 releasing this much memory.
871 The trim threshold and the mmap control parameters (see below)
872 can be traded off with one another. Trimming and mmapping are
873 two different ways of releasing unused memory back to the
874 system. Between these two, it is often possible to keep
875 system-level demands of a long-lived program down to a bare
876 minimum. For example, in one test suite of sessions measuring
877 the XF86 X server on Linux, using a trim threshold of 128K and a
878 mmap threshold of 192K led to near-minimal long term resource
879 consumption.
881 If you are using this malloc in a long-lived program, it should
882 pay to experiment with these values. As a rough guide, you
883 might set to a value close to the average size of a process
884 (program) running on your system. Releasing this much memory
885 would allow such a process to run in memory. Generally, it's
886 worth it to tune for trimming rather tham memory mapping when a
887 program undergoes phases where several large chunks are
888 allocated and released in ways that can reuse each other's
889 storage, perhaps mixed with phases where there are no such
890 chunks at all. And in well-behaved long-lived programs,
891 controlling release of large blocks via trimming versus mapping
892 is usually faster.
894 However, in most programs, these parameters serve mainly as
895 protection against the system-level effects of carrying around
896 massive amounts of unneeded memory. Since frequent calls to
897 sbrk, mmap, and munmap otherwise degrade performance, the default
898 parameters are set to relatively high values that serve only as
899 safeguards.
901 The trim value It must be greater than page size to have any useful
902 effect. To disable trimming completely, you can set to
903 (unsigned long)(-1)
905 Trim settings interact with fastbin (MXFAST) settings: Unless
906 TRIM_FASTBINS is defined, automatic trimming never takes place upon
907 freeing a chunk with size less than or equal to MXFAST. Trimming is
908 instead delayed until subsequent freeing of larger chunks. However,
909 you can still force an attempted trim by calling malloc_trim.
911 Also, trimming is not generally possible in cases where
912 the main arena is obtained via mmap.
914 Note that the trick some people use of mallocing a huge space and
915 then freeing it at program startup, in an attempt to reserve system
916 memory, doesn't have the intended effect under automatic trimming,
917 since that memory will immediately be returned to the system.
920 #define M_TRIM_THRESHOLD -1
922 #ifndef DEFAULT_TRIM_THRESHOLD
923 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
924 #endif
927 M_TOP_PAD is the amount of extra `padding' space to allocate or
928 retain whenever sbrk is called. It is used in two ways internally:
930 * When sbrk is called to extend the top of the arena to satisfy
931 a new malloc request, this much padding is added to the sbrk
932 request.
934 * When malloc_trim is called automatically from free(),
935 it is used as the `pad' argument.
937 In both cases, the actual amount of padding is rounded
938 so that the end of the arena is always a system page boundary.
940 The main reason for using padding is to avoid calling sbrk so
941 often. Having even a small pad greatly reduces the likelihood
942 that nearly every malloc request during program start-up (or
943 after trimming) will invoke sbrk, which needlessly wastes
944 time.
946 Automatic rounding-up to page-size units is normally sufficient
947 to avoid measurable overhead, so the default is 0. However, in
948 systems where sbrk is relatively slow, it can pay to increase
949 this value, at the expense of carrying around more memory than
950 the program needs.
953 #define M_TOP_PAD -2
955 #ifndef DEFAULT_TOP_PAD
956 #define DEFAULT_TOP_PAD (0)
957 #endif
960 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
961 adjusted MMAP_THRESHOLD.
964 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
965 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
966 #endif
968 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
969 /* For 32-bit platforms we cannot increase the maximum mmap
970 threshold much because it is also the minimum value for the
971 maximum heap size and its alignment. Going above 512k (i.e., 1M
972 for new heaps) wastes too much address space. */
973 # if __WORDSIZE == 32
974 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
975 # else
976 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
977 # endif
978 #endif
981 M_MMAP_THRESHOLD is the request size threshold for using mmap()
982 to service a request. Requests of at least this size that cannot
983 be allocated using already-existing space will be serviced via mmap.
984 (If enough normal freed space already exists it is used instead.)
986 Using mmap segregates relatively large chunks of memory so that
987 they can be individually obtained and released from the host
988 system. A request serviced through mmap is never reused by any
989 other request (at least not directly; the system may just so
990 happen to remap successive requests to the same locations).
992 Segregating space in this way has the benefits that:
994 1. Mmapped space can ALWAYS be individually released back
995 to the system, which helps keep the system level memory
996 demands of a long-lived program low.
997 2. Mapped memory can never become `locked' between
998 other chunks, as can happen with normally allocated chunks, which
999 means that even trimming via malloc_trim would not release them.
1000 3. On some systems with "holes" in address spaces, mmap can obtain
1001 memory that sbrk cannot.
1003 However, it has the disadvantages that:
1005 1. The space cannot be reclaimed, consolidated, and then
1006 used to service later requests, as happens with normal chunks.
1007 2. It can lead to more wastage because of mmap page alignment
1008 requirements
1009 3. It causes malloc performance to be more dependent on host
1010 system memory management support routines which may vary in
1011 implementation quality and may impose arbitrary
1012 limitations. Generally, servicing a request via normal
1013 malloc steps is faster than going through a system's mmap.
1015 The advantages of mmap nearly always outweigh disadvantages for
1016 "large" chunks, but the value of "large" varies across systems. The
1017 default is an empirically derived value that works well in most
1018 systems.
1021 Update in 2006:
1022 The above was written in 2001. Since then the world has changed a lot.
1023 Memory got bigger. Applications got bigger. The virtual address space
1024 layout in 32 bit linux changed.
1026 In the new situation, brk() and mmap space is shared and there are no
1027 artificial limits on brk size imposed by the kernel. What is more,
1028 applications have started using transient allocations larger than the
1029 128Kb as was imagined in 2001.
1031 The price for mmap is also high now; each time glibc mmaps from the
1032 kernel, the kernel is forced to zero out the memory it gives to the
1033 application. Zeroing memory is expensive and eats a lot of cache and
1034 memory bandwidth. This has nothing to do with the efficiency of the
1035 virtual memory system, by doing mmap the kernel just has no choice but
1036 to zero.
1038 In 2001, the kernel had a maximum size for brk() which was about 800
1039 megabytes on 32 bit x86, at that point brk() would hit the first
1040 mmaped shared libaries and couldn't expand anymore. With current 2.6
1041 kernels, the VA space layout is different and brk() and mmap
1042 both can span the entire heap at will.
1044 Rather than using a static threshold for the brk/mmap tradeoff,
1045 we are now using a simple dynamic one. The goal is still to avoid
1046 fragmentation. The old goals we kept are
1047 1) try to get the long lived large allocations to use mmap()
1048 2) really large allocations should always use mmap()
1049 and we're adding now:
1050 3) transient allocations should use brk() to avoid forcing the kernel
1051 having to zero memory over and over again
1053 The implementation works with a sliding threshold, which is by default
1054 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
1055 out at 128Kb as per the 2001 default.
1057 This allows us to satisfy requirement 1) under the assumption that long
1058 lived allocations are made early in the process' lifespan, before it has
1059 started doing dynamic allocations of the same size (which will
1060 increase the threshold).
1062 The upperbound on the threshold satisfies requirement 2)
1064 The threshold goes up in value when the application frees memory that was
1065 allocated with the mmap allocator. The idea is that once the application
1066 starts freeing memory of a certain size, it's highly probable that this is
1067 a size the application uses for transient allocations. This estimator
1068 is there to satisfy the new third requirement.
1072 #define M_MMAP_THRESHOLD -3
1074 #ifndef DEFAULT_MMAP_THRESHOLD
1075 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1076 #endif
1079 M_MMAP_MAX is the maximum number of requests to simultaneously
1080 service using mmap. This parameter exists because
1081 some systems have a limited number of internal tables for
1082 use by mmap, and using more than a few of them may degrade
1083 performance.
1085 The default is set to a value that serves only as a safeguard.
1086 Setting to 0 disables use of mmap for servicing large requests.
1089 #define M_MMAP_MAX -4
1091 #ifndef DEFAULT_MMAP_MAX
1092 #define DEFAULT_MMAP_MAX (65536)
1093 #endif
1095 #include <malloc.h>
1097 #ifndef RETURN_ADDRESS
1098 #define RETURN_ADDRESS(X_) (NULL)
1099 #endif
1101 /* Forward declarations. */
1102 struct malloc_chunk;
1103 typedef struct malloc_chunk* mchunkptr;
1105 /* Internal routines. */
1107 static void* _int_malloc(mstate, size_t);
1108 static void _int_free(mstate, mchunkptr, int);
1109 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1110 INTERNAL_SIZE_T);
1111 static void* _int_memalign(mstate, size_t, size_t);
1112 #if IS_IN (libc)
1113 static void* _mid_memalign(size_t, size_t, void *);
1114 #endif
1116 static void malloc_printerr(const char *str) __attribute__ ((noreturn));
1118 static void munmap_chunk(mchunkptr p);
1119 #if HAVE_MREMAP
1120 static mchunkptr mremap_chunk(mchunkptr p, size_t new_size);
1121 #endif
1123 /* ------------------ MMAP support ------------------ */
1126 #include <fcntl.h>
1127 #include <sys/mman.h>
1129 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1130 # define MAP_ANONYMOUS MAP_ANON
1131 #endif
1133 #ifndef MAP_NORESERVE
1134 # define MAP_NORESERVE 0
1135 #endif
1137 #define MMAP(addr, size, prot, flags) \
1138 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1142 ----------------------- Chunk representations -----------------------
1147 This struct declaration is misleading (but accurate and necessary).
1148 It declares a "view" into memory allowing access to necessary
1149 fields at known offsets from a given base. See explanation below.
1152 struct malloc_chunk {
1154 INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk (if free). */
1155 INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
1157 struct malloc_chunk* fd; /* double links -- used only if free. */
1158 struct malloc_chunk* bk;
1160 /* Only used for large blocks: pointer to next larger size. */
1161 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1162 struct malloc_chunk* bk_nextsize;
1167 malloc_chunk details:
1169 (The following includes lightly edited explanations by Colin Plumb.)
1171 Chunks of memory are maintained using a `boundary tag' method as
1172 described in e.g., Knuth or Standish. (See the paper by Paul
1173 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1174 survey of such techniques.) Sizes of free chunks are stored both
1175 in the front of each chunk and at the end. This makes
1176 consolidating fragmented chunks into bigger chunks very fast. The
1177 size fields also hold bits representing whether chunks are free or
1178 in use.
1180 An allocated chunk looks like this:
1183 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1184 | Size of previous chunk, if unallocated (P clear) |
1185 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1186 | Size of chunk, in bytes |A|M|P|
1187 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1188 | User data starts here... .
1190 . (malloc_usable_size() bytes) .
1192 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1193 | (size of chunk, but used for application data) |
1194 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1195 | Size of next chunk, in bytes |A|0|1|
1196 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1198 Where "chunk" is the front of the chunk for the purpose of most of
1199 the malloc code, but "mem" is the pointer that is returned to the
1200 user. "Nextchunk" is the beginning of the next contiguous chunk.
1202 Chunks always begin on even word boundaries, so the mem portion
1203 (which is returned to the user) is also on an even word boundary, and
1204 thus at least double-word aligned.
1206 Free chunks are stored in circular doubly-linked lists, and look like this:
1208 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1209 | Size of previous chunk, if unallocated (P clear) |
1210 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1211 `head:' | Size of chunk, in bytes |A|0|P|
1212 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1213 | Forward pointer to next chunk in list |
1214 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1215 | Back pointer to previous chunk in list |
1216 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1217 | Unused space (may be 0 bytes long) .
1220 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1221 `foot:' | Size of chunk, in bytes |
1222 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1223 | Size of next chunk, in bytes |A|0|0|
1224 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1226 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1227 chunk size (which is always a multiple of two words), is an in-use
1228 bit for the *previous* chunk. If that bit is *clear*, then the
1229 word before the current chunk size contains the previous chunk
1230 size, and can be used to find the front of the previous chunk.
1231 The very first chunk allocated always has this bit set,
1232 preventing access to non-existent (or non-owned) memory. If
1233 prev_inuse is set for any given chunk, then you CANNOT determine
1234 the size of the previous chunk, and might even get a memory
1235 addressing fault when trying to do so.
1237 The A (NON_MAIN_ARENA) bit is cleared for chunks on the initial,
1238 main arena, described by the main_arena variable. When additional
1239 threads are spawned, each thread receives its own arena (up to a
1240 configurable limit, after which arenas are reused for multiple
1241 threads), and the chunks in these arenas have the A bit set. To
1242 find the arena for a chunk on such a non-main arena, heap_for_ptr
1243 performs a bit mask operation and indirection through the ar_ptr
1244 member of the per-heap header heap_info (see arena.c).
1246 Note that the `foot' of the current chunk is actually represented
1247 as the prev_size of the NEXT chunk. This makes it easier to
1248 deal with alignments etc but can be very confusing when trying
1249 to extend or adapt this code.
1251 The three exceptions to all this are:
1253 1. The special chunk `top' doesn't bother using the
1254 trailing size field since there is no next contiguous chunk
1255 that would have to index off it. After initialization, `top'
1256 is forced to always exist. If it would become less than
1257 MINSIZE bytes long, it is replenished.
1259 2. Chunks allocated via mmap, which have the second-lowest-order
1260 bit M (IS_MMAPPED) set in their size fields. Because they are
1261 allocated one-by-one, each must contain its own trailing size
1262 field. If the M bit is set, the other bits are ignored
1263 (because mmapped chunks are neither in an arena, nor adjacent
1264 to a freed chunk). The M bit is also used for chunks which
1265 originally came from a dumped heap via malloc_set_state in
1266 hooks.c.
1268 3. Chunks in fastbins are treated as allocated chunks from the
1269 point of view of the chunk allocator. They are consolidated
1270 with their neighbors only in bulk, in malloc_consolidate.
1274 ---------- Size and alignment checks and conversions ----------
1277 /* Conversion from malloc headers to user pointers, and back. When
1278 using memory tagging the user data and the malloc data structure
1279 headers have distinct tags. Converting fully from one to the other
1280 involves extracting the tag at the other address and creating a
1281 suitable pointer using it. That can be quite expensive. There are
1282 cases when the pointers are not dereferenced (for example only used
1283 for alignment check) so the tags are not relevant, and there are
1284 cases when user data is not tagged distinctly from malloc headers
1285 (user data is untagged because tagging is done late in malloc and
1286 early in free). User memory tagging across internal interfaces:
1288 sysmalloc: Returns untagged memory.
1289 _int_malloc: Returns untagged memory.
1290 _int_free: Takes untagged memory.
1291 _int_memalign: Returns untagged memory.
1292 _int_memalign: Returns untagged memory.
1293 _mid_memalign: Returns tagged memory.
1294 _int_realloc: Takes and returns tagged memory.
1297 /* The chunk header is two SIZE_SZ elements, but this is used widely, so
1298 we define it here for clarity later. */
1299 #define CHUNK_HDR_SZ (2 * SIZE_SZ)
1301 /* Convert a chunk address to a user mem pointer without correcting
1302 the tag. */
1303 #define chunk2mem(p) ((void*)((char*)(p) + CHUNK_HDR_SZ))
1305 /* Convert a chunk address to a user mem pointer and extract the right tag. */
1306 #define chunk2mem_tag(p) ((void*)tag_at ((char*)(p) + CHUNK_HDR_SZ))
1308 /* Convert a user mem pointer to a chunk address and extract the right tag. */
1309 #define mem2chunk(mem) ((mchunkptr)tag_at (((char*)(mem) - CHUNK_HDR_SZ)))
1311 /* The smallest possible chunk */
1312 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1314 /* The smallest size we can malloc is an aligned minimal chunk */
1316 #define MINSIZE \
1317 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1319 /* Check if m has acceptable alignment */
1321 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1323 #define misaligned_chunk(p) \
1324 ((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \
1325 & MALLOC_ALIGN_MASK)
1327 /* pad request bytes into a usable size -- internal version */
1328 /* Note: This must be a macro that evaluates to a compile time constant
1329 if passed a literal constant. */
1330 #define request2size(req) \
1331 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1332 MINSIZE : \
1333 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1335 /* Check if REQ overflows when padded and aligned and if the resulting value
1336 is less than PTRDIFF_T. Returns TRUE and the requested size or MINSIZE in
1337 case the value is less than MINSIZE on SZ or false if any of the previous
1338 check fail. */
1339 static inline bool
1340 checked_request2size (size_t req, size_t *sz) __nonnull (1)
1342 if (__glibc_unlikely (req > PTRDIFF_MAX))
1343 return false;
1345 /* When using tagged memory, we cannot share the end of the user
1346 block with the header for the next chunk, so ensure that we
1347 allocate blocks that are rounded up to the granule size. Take
1348 care not to overflow from close to MAX_SIZE_T to a small
1349 number. Ideally, this would be part of request2size(), but that
1350 must be a macro that produces a compile time constant if passed
1351 a constant literal. */
1352 if (__glibc_unlikely (mtag_enabled))
1354 /* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551. */
1355 asm ("");
1357 req = (req + (__MTAG_GRANULE_SIZE - 1)) &
1358 ~(size_t)(__MTAG_GRANULE_SIZE - 1);
1361 *sz = request2size (req);
1362 return true;
1366 --------------- Physical chunk operations ---------------
1370 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1371 #define PREV_INUSE 0x1
1373 /* extract inuse bit of previous chunk */
1374 #define prev_inuse(p) ((p)->mchunk_size & PREV_INUSE)
1377 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1378 #define IS_MMAPPED 0x2
1380 /* check for mmap()'ed chunk */
1381 #define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)
1384 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1385 from a non-main arena. This is only set immediately before handing
1386 the chunk to the user, if necessary. */
1387 #define NON_MAIN_ARENA 0x4
1389 /* Check for chunk from main arena. */
1390 #define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)
1392 /* Mark a chunk as not being on the main arena. */
1393 #define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
1397 Bits to mask off when extracting size
1399 Note: IS_MMAPPED is intentionally not masked off from size field in
1400 macros for which mmapped chunks should never be seen. This should
1401 cause helpful core dumps to occur if it is tried by accident by
1402 people extending or adapting this malloc.
1404 #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1406 /* Get size, ignoring use bits */
1407 #define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))
1409 /* Like chunksize, but do not mask SIZE_BITS. */
1410 #define chunksize_nomask(p) ((p)->mchunk_size)
1412 /* Ptr to next physical malloc_chunk. */
1413 #define next_chunk(p) ((mchunkptr) (((char *) (p)) + chunksize (p)))
1415 /* Size of the chunk below P. Only valid if !prev_inuse (P). */
1416 #define prev_size(p) ((p)->mchunk_prev_size)
1418 /* Set the size of the chunk below P. Only valid if !prev_inuse (P). */
1419 #define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))
1421 /* Ptr to previous physical malloc_chunk. Only valid if !prev_inuse (P). */
1422 #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - prev_size (p)))
1424 /* Treat space at ptr + offset as a chunk */
1425 #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1427 /* extract p's inuse bit */
1428 #define inuse(p) \
1429 ((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
1431 /* set/clear chunk as being inuse without otherwise disturbing */
1432 #define set_inuse(p) \
1433 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
1435 #define clear_inuse(p) \
1436 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
1439 /* check/set/clear inuse bits in known places */
1440 #define inuse_bit_at_offset(p, s) \
1441 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
1443 #define set_inuse_bit_at_offset(p, s) \
1444 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
1446 #define clear_inuse_bit_at_offset(p, s) \
1447 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
1450 /* Set size at head, without disturbing its use bit */
1451 #define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
1453 /* Set size/use field */
1454 #define set_head(p, s) ((p)->mchunk_size = (s))
1456 /* Set size at footer (only when chunk is not in use) */
1457 #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
1459 #pragma GCC poison mchunk_size
1460 #pragma GCC poison mchunk_prev_size
1462 /* This is the size of the real usable data in the chunk. Not valid for
1463 dumped heap chunks. */
1464 #define memsize(p) \
1465 (__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \
1466 chunksize (p) - CHUNK_HDR_SZ : \
1467 chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ))
1469 /* If memory tagging is enabled the layout changes to accommodate the granule
1470 size, this is wasteful for small allocations so not done by default.
1471 Both the chunk header and user data has to be granule aligned. */
1472 _Static_assert (__MTAG_GRANULE_SIZE <= CHUNK_HDR_SZ,
1473 "memory tagging is not supported with large granule.");
1475 static __always_inline void *
1476 tag_new_usable (void *ptr)
1478 if (__glibc_unlikely (mtag_enabled) && ptr)
1480 mchunkptr cp = mem2chunk(ptr);
1481 ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp));
1483 return ptr;
1487 -------------------- Internal data structures --------------------
1489 All internal state is held in an instance of malloc_state defined
1490 below. There are no other static variables, except in two optional
1491 cases:
1492 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1493 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1494 for mmap.
1496 Beware of lots of tricks that minimize the total bookkeeping space
1497 requirements. The result is a little over 1K bytes (for 4byte
1498 pointers and size_t.)
1502 Bins
1504 An array of bin headers for free chunks. Each bin is doubly
1505 linked. The bins are approximately proportionally (log) spaced.
1506 There are a lot of these bins (128). This may look excessive, but
1507 works very well in practice. Most bins hold sizes that are
1508 unusual as malloc request sizes, but are more usual for fragments
1509 and consolidated sets of chunks, which is what these bins hold, so
1510 they can be found quickly. All procedures maintain the invariant
1511 that no consolidated chunk physically borders another one, so each
1512 chunk in a list is known to be preceeded and followed by either
1513 inuse chunks or the ends of memory.
1515 Chunks in bins are kept in size order, with ties going to the
1516 approximately least recently used chunk. Ordering isn't needed
1517 for the small bins, which all contain the same-sized chunks, but
1518 facilitates best-fit allocation for larger chunks. These lists
1519 are just sequential. Keeping them in order almost never requires
1520 enough traversal to warrant using fancier ordered data
1521 structures.
1523 Chunks of the same size are linked with the most
1524 recently freed at the front, and allocations are taken from the
1525 back. This results in LRU (FIFO) allocation order, which tends
1526 to give each chunk an equal opportunity to be consolidated with
1527 adjacent freed chunks, resulting in larger free chunks and less
1528 fragmentation.
1530 To simplify use in double-linked lists, each bin header acts
1531 as a malloc_chunk. This avoids special-casing for headers.
1532 But to conserve space and improve locality, we allocate
1533 only the fd/bk pointers of bins, and then use repositioning tricks
1534 to treat these as the fields of a malloc_chunk*.
1537 typedef struct malloc_chunk *mbinptr;
1539 /* addressing -- note that bin_at(0) does not exist */
1540 #define bin_at(m, i) \
1541 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1542 - offsetof (struct malloc_chunk, fd))
1544 /* analog of ++bin */
1545 #define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
1547 /* Reminders about list directionality within bins */
1548 #define first(b) ((b)->fd)
1549 #define last(b) ((b)->bk)
1552 Indexing
1554 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1555 8 bytes apart. Larger bins are approximately logarithmically spaced:
1557 64 bins of size 8
1558 32 bins of size 64
1559 16 bins of size 512
1560 8 bins of size 4096
1561 4 bins of size 32768
1562 2 bins of size 262144
1563 1 bin of size what's left
1565 There is actually a little bit of slop in the numbers in bin_index
1566 for the sake of speed. This makes no difference elsewhere.
1568 The bins top out around 1MB because we expect to service large
1569 requests via mmap.
1571 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1572 a valid chunk size the small bins are bumped up one.
1575 #define NBINS 128
1576 #define NSMALLBINS 64
1577 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1578 #define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > CHUNK_HDR_SZ)
1579 #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
1581 #define in_smallbin_range(sz) \
1582 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
1584 #define smallbin_index(sz) \
1585 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
1586 + SMALLBIN_CORRECTION)
1588 #define largebin_index_32(sz) \
1589 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1590 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1591 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1592 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1593 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1594 126)
1596 #define largebin_index_32_big(sz) \
1597 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1598 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1599 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1600 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1601 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1602 126)
1604 // XXX It remains to be seen whether it is good to keep the widths of
1605 // XXX the buckets the same or whether it should be scaled by a factor
1606 // XXX of two as well.
1607 #define largebin_index_64(sz) \
1608 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1609 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1610 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1611 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1612 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1613 126)
1615 #define largebin_index(sz) \
1616 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1617 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1618 : largebin_index_32 (sz))
1620 #define bin_index(sz) \
1621 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
1623 /* Take a chunk off a bin list. */
1624 static void
1625 unlink_chunk (mstate av, mchunkptr p)
1627 if (chunksize (p) != prev_size (next_chunk (p)))
1628 malloc_printerr ("corrupted size vs. prev_size");
1630 mchunkptr fd = p->fd;
1631 mchunkptr bk = p->bk;
1633 if (__builtin_expect (fd->bk != p || bk->fd != p, 0))
1634 malloc_printerr ("corrupted double-linked list");
1636 fd->bk = bk;
1637 bk->fd = fd;
1638 if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL)
1640 if (p->fd_nextsize->bk_nextsize != p
1641 || p->bk_nextsize->fd_nextsize != p)
1642 malloc_printerr ("corrupted double-linked list (not small)");
1644 if (fd->fd_nextsize == NULL)
1646 if (p->fd_nextsize == p)
1647 fd->fd_nextsize = fd->bk_nextsize = fd;
1648 else
1650 fd->fd_nextsize = p->fd_nextsize;
1651 fd->bk_nextsize = p->bk_nextsize;
1652 p->fd_nextsize->bk_nextsize = fd;
1653 p->bk_nextsize->fd_nextsize = fd;
1656 else
1658 p->fd_nextsize->bk_nextsize = p->bk_nextsize;
1659 p->bk_nextsize->fd_nextsize = p->fd_nextsize;
1665 Unsorted chunks
1667 All remainders from chunk splits, as well as all returned chunks,
1668 are first placed in the "unsorted" bin. They are then placed
1669 in regular bins after malloc gives them ONE chance to be used before
1670 binning. So, basically, the unsorted_chunks list acts as a queue,
1671 with chunks being placed on it in free (and malloc_consolidate),
1672 and taken off (to be either used or placed in bins) in malloc.
1674 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1675 does not have to be taken into account in size comparisons.
1678 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1679 #define unsorted_chunks(M) (bin_at (M, 1))
1684 The top-most available chunk (i.e., the one bordering the end of
1685 available memory) is treated specially. It is never included in
1686 any bin, is used only if no other chunk is available, and is
1687 released back to the system if it is very large (see
1688 M_TRIM_THRESHOLD). Because top initially
1689 points to its own bin with initial zero size, thus forcing
1690 extension on the first malloc request, we avoid having any special
1691 code in malloc to check whether it even exists yet. But we still
1692 need to do so when getting memory from system, so we make
1693 initial_top treat the bin as a legal but unusable chunk during the
1694 interval between initialization and the first call to
1695 sysmalloc. (This is somewhat delicate, since it relies on
1696 the 2 preceding words to be zero during this interval as well.)
1699 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1700 #define initial_top(M) (unsorted_chunks (M))
1703 Binmap
1705 To help compensate for the large number of bins, a one-level index
1706 structure is used for bin-by-bin searching. `binmap' is a
1707 bitvector recording whether bins are definitely empty so they can
1708 be skipped over during during traversals. The bits are NOT always
1709 cleared as soon as bins are empty, but instead only
1710 when they are noticed to be empty during traversal in malloc.
1713 /* Conservatively use 32 bits per map word, even if on 64bit system */
1714 #define BINMAPSHIFT 5
1715 #define BITSPERMAP (1U << BINMAPSHIFT)
1716 #define BINMAPSIZE (NBINS / BITSPERMAP)
1718 #define idx2block(i) ((i) >> BINMAPSHIFT)
1719 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
1721 #define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1722 #define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1723 #define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
1726 Fastbins
1728 An array of lists holding recently freed small chunks. Fastbins
1729 are not doubly linked. It is faster to single-link them, and
1730 since chunks are never removed from the middles of these lists,
1731 double linking is not necessary. Also, unlike regular bins, they
1732 are not even processed in FIFO order (they use faster LIFO) since
1733 ordering doesn't much matter in the transient contexts in which
1734 fastbins are normally used.
1736 Chunks in fastbins keep their inuse bit set, so they cannot
1737 be consolidated with other free chunks. malloc_consolidate
1738 releases all chunks in fastbins and consolidates them with
1739 other free chunks.
1742 typedef struct malloc_chunk *mfastbinptr;
1743 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1745 /* offset 2 to use otherwise unindexable first 2 bins */
1746 #define fastbin_index(sz) \
1747 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1750 /* The maximum fastbin request size we support */
1751 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1753 #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
1756 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1757 that triggers automatic consolidation of possibly-surrounding
1758 fastbin chunks. This is a heuristic, so the exact value should not
1759 matter too much. It is defined at half the default trim threshold as a
1760 compromise heuristic to only attempt consolidation if it is likely
1761 to lead to trimming. However, it is not dynamically tunable, since
1762 consolidation reduces fragmentation surrounding large chunks even
1763 if trimming is not used.
1766 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1769 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1770 regions. Otherwise, contiguity is exploited in merging together,
1771 when possible, results from consecutive MORECORE calls.
1773 The initial value comes from MORECORE_CONTIGUOUS, but is
1774 changed dynamically if mmap is ever used as an sbrk substitute.
1777 #define NONCONTIGUOUS_BIT (2U)
1779 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1780 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1781 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1782 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1784 /* Maximum size of memory handled in fastbins. */
1785 static INTERNAL_SIZE_T global_max_fast;
1788 Set value of max_fast.
1789 Use impossibly small value if 0.
1790 Precondition: there are no existing fastbin chunks in the main arena.
1791 Since do_check_malloc_state () checks this, we call malloc_consolidate ()
1792 before changing max_fast. Note other arenas will leak their fast bin
1793 entries if max_fast is reduced.
1796 #define set_max_fast(s) \
1797 global_max_fast = (((size_t) (s) <= MALLOC_ALIGN_MASK - SIZE_SZ) \
1798 ? MIN_CHUNK_SIZE / 2 : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1800 static inline INTERNAL_SIZE_T
1801 get_max_fast (void)
1803 /* Tell the GCC optimizers that global_max_fast is never larger
1804 than MAX_FAST_SIZE. This avoids out-of-bounds array accesses in
1805 _int_malloc after constant propagation of the size parameter.
1806 (The code never executes because malloc preserves the
1807 global_max_fast invariant, but the optimizers may not recognize
1808 this.) */
1809 if (global_max_fast > MAX_FAST_SIZE)
1810 __builtin_unreachable ();
1811 return global_max_fast;
1815 ----------- Internal state representation and initialization -----------
1819 have_fastchunks indicates that there are probably some fastbin chunks.
1820 It is set true on entering a chunk into any fastbin, and cleared early in
1821 malloc_consolidate. The value is approximate since it may be set when there
1822 are no fastbin chunks, or it may be clear even if there are fastbin chunks
1823 available. Given it's sole purpose is to reduce number of redundant calls to
1824 malloc_consolidate, it does not affect correctness. As a result we can safely
1825 use relaxed atomic accesses.
1829 struct malloc_state
1831 /* Serialize access. */
1832 __libc_lock_define (, mutex);
1834 /* Flags (formerly in max_fast). */
1835 int flags;
1837 /* Set if the fastbin chunks contain recently inserted free blocks. */
1838 /* Note this is a bool but not all targets support atomics on booleans. */
1839 int have_fastchunks;
1841 /* Fastbins */
1842 mfastbinptr fastbinsY[NFASTBINS];
1844 /* Base of the topmost chunk -- not otherwise kept in a bin */
1845 mchunkptr top;
1847 /* The remainder from the most recent split of a small request */
1848 mchunkptr last_remainder;
1850 /* Normal bins packed as described above */
1851 mchunkptr bins[NBINS * 2 - 2];
1853 /* Bitmap of bins */
1854 unsigned int binmap[BINMAPSIZE];
1856 /* Linked list */
1857 struct malloc_state *next;
1859 /* Linked list for free arenas. Access to this field is serialized
1860 by free_list_lock in arena.c. */
1861 struct malloc_state *next_free;
1863 /* Number of threads attached to this arena. 0 if the arena is on
1864 the free list. Access to this field is serialized by
1865 free_list_lock in arena.c. */
1866 INTERNAL_SIZE_T attached_threads;
1868 /* Memory allocated from the system in this arena. */
1869 INTERNAL_SIZE_T system_mem;
1870 INTERNAL_SIZE_T max_system_mem;
1873 struct malloc_par
1875 /* Tunable parameters */
1876 unsigned long trim_threshold;
1877 INTERNAL_SIZE_T top_pad;
1878 INTERNAL_SIZE_T mmap_threshold;
1879 INTERNAL_SIZE_T arena_test;
1880 INTERNAL_SIZE_T arena_max;
1882 /* Memory map support */
1883 int n_mmaps;
1884 int n_mmaps_max;
1885 int max_n_mmaps;
1886 /* the mmap_threshold is dynamic, until the user sets
1887 it manually, at which point we need to disable any
1888 dynamic behavior. */
1889 int no_dyn_threshold;
1891 /* Statistics */
1892 INTERNAL_SIZE_T mmapped_mem;
1893 INTERNAL_SIZE_T max_mmapped_mem;
1895 /* First address handed out by MORECORE/sbrk. */
1896 char *sbrk_base;
1898 #if USE_TCACHE
1899 /* Maximum number of buckets to use. */
1900 size_t tcache_bins;
1901 size_t tcache_max_bytes;
1902 /* Maximum number of chunks in each bucket. */
1903 size_t tcache_count;
1904 /* Maximum number of chunks to remove from the unsorted list, which
1905 aren't used to prefill the cache. */
1906 size_t tcache_unsorted_limit;
1907 #endif
1910 /* There are several instances of this struct ("arenas") in this
1911 malloc. If you are adapting this malloc in a way that does NOT use
1912 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1913 before using. This malloc relies on the property that malloc_state
1914 is initialized to all zeroes (as is true of C statics). */
1916 static struct malloc_state main_arena =
1918 .mutex = _LIBC_LOCK_INITIALIZER,
1919 .next = &main_arena,
1920 .attached_threads = 1
1923 /* There is only one instance of the malloc parameters. */
1925 static struct malloc_par mp_ =
1927 .top_pad = DEFAULT_TOP_PAD,
1928 .n_mmaps_max = DEFAULT_MMAP_MAX,
1929 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1930 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1931 #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1932 .arena_test = NARENAS_FROM_NCORES (1)
1933 #if USE_TCACHE
1935 .tcache_count = TCACHE_FILL_COUNT,
1936 .tcache_bins = TCACHE_MAX_BINS,
1937 .tcache_max_bytes = tidx2usize (TCACHE_MAX_BINS-1),
1938 .tcache_unsorted_limit = 0 /* No limit. */
1939 #endif
1943 Initialize a malloc_state struct.
1945 This is called from ptmalloc_init () or from _int_new_arena ()
1946 when creating a new arena.
1949 static void
1950 malloc_init_state (mstate av)
1952 int i;
1953 mbinptr bin;
1955 /* Establish circular links for normal bins */
1956 for (i = 1; i < NBINS; ++i)
1958 bin = bin_at (av, i);
1959 bin->fd = bin->bk = bin;
1962 #if MORECORE_CONTIGUOUS
1963 if (av != &main_arena)
1964 #endif
1965 set_noncontiguous (av);
1966 if (av == &main_arena)
1967 set_max_fast (DEFAULT_MXFAST);
1968 atomic_store_relaxed (&av->have_fastchunks, false);
1970 av->top = initial_top (av);
1974 Other internal utilities operating on mstates
1977 static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1978 static int systrim (size_t, mstate);
1979 static void malloc_consolidate (mstate);
1982 /* -------------- Early definitions for debugging hooks ---------------- */
1984 /* This function is called from the arena shutdown hook, to free the
1985 thread cache (if it exists). */
1986 static void tcache_thread_shutdown (void);
1988 /* ------------------ Testing support ----------------------------------*/
1990 static int perturb_byte;
1992 static void
1993 alloc_perturb (char *p, size_t n)
1995 if (__glibc_unlikely (perturb_byte))
1996 memset (p, perturb_byte ^ 0xff, n);
1999 static void
2000 free_perturb (char *p, size_t n)
2002 if (__glibc_unlikely (perturb_byte))
2003 memset (p, perturb_byte, n);
2008 #include <stap-probe.h>
2010 /* ------------------- Support for multiple arenas -------------------- */
2011 #include "arena.c"
2014 Debugging support
2016 These routines make a number of assertions about the states
2017 of data structures that should be true at all times. If any
2018 are not true, it's very likely that a user program has somehow
2019 trashed memory. (It's also possible that there is a coding error
2020 in malloc. In which case, please report it!)
2023 #if !MALLOC_DEBUG
2025 # define check_chunk(A, P)
2026 # define check_free_chunk(A, P)
2027 # define check_inuse_chunk(A, P)
2028 # define check_remalloced_chunk(A, P, N)
2029 # define check_malloced_chunk(A, P, N)
2030 # define check_malloc_state(A)
2032 #else
2034 # define check_chunk(A, P) do_check_chunk (A, P)
2035 # define check_free_chunk(A, P) do_check_free_chunk (A, P)
2036 # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
2037 # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
2038 # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
2039 # define check_malloc_state(A) do_check_malloc_state (A)
2042 Properties of all chunks
2045 static void
2046 do_check_chunk (mstate av, mchunkptr p)
2048 unsigned long sz = chunksize (p);
2049 /* min and max possible addresses assuming contiguous allocation */
2050 char *max_address = (char *) (av->top) + chunksize (av->top);
2051 char *min_address = max_address - av->system_mem;
2053 if (!chunk_is_mmapped (p))
2055 /* Has legal address ... */
2056 if (p != av->top)
2058 if (contiguous (av))
2060 assert (((char *) p) >= min_address);
2061 assert (((char *) p + sz) <= ((char *) (av->top)));
2064 else
2066 /* top size is always at least MINSIZE */
2067 assert ((unsigned long) (sz) >= MINSIZE);
2068 /* top predecessor always marked inuse */
2069 assert (prev_inuse (p));
2072 else
2074 /* address is outside main heap */
2075 if (contiguous (av) && av->top != initial_top (av))
2077 assert (((char *) p) < min_address || ((char *) p) >= max_address);
2079 /* chunk is page-aligned */
2080 assert (((prev_size (p) + sz) & (GLRO (dl_pagesize) - 1)) == 0);
2081 /* mem is aligned */
2082 assert (aligned_OK (chunk2mem (p)));
2087 Properties of free chunks
2090 static void
2091 do_check_free_chunk (mstate av, mchunkptr p)
2093 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2094 mchunkptr next = chunk_at_offset (p, sz);
2096 do_check_chunk (av, p);
2098 /* Chunk must claim to be free ... */
2099 assert (!inuse (p));
2100 assert (!chunk_is_mmapped (p));
2102 /* Unless a special marker, must have OK fields */
2103 if ((unsigned long) (sz) >= MINSIZE)
2105 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2106 assert (aligned_OK (chunk2mem (p)));
2107 /* ... matching footer field */
2108 assert (prev_size (next_chunk (p)) == sz);
2109 /* ... and is fully consolidated */
2110 assert (prev_inuse (p));
2111 assert (next == av->top || inuse (next));
2113 /* ... and has minimally sane links */
2114 assert (p->fd->bk == p);
2115 assert (p->bk->fd == p);
2117 else /* markers are always of size SIZE_SZ */
2118 assert (sz == SIZE_SZ);
2122 Properties of inuse chunks
2125 static void
2126 do_check_inuse_chunk (mstate av, mchunkptr p)
2128 mchunkptr next;
2130 do_check_chunk (av, p);
2132 if (chunk_is_mmapped (p))
2133 return; /* mmapped chunks have no next/prev */
2135 /* Check whether it claims to be in use ... */
2136 assert (inuse (p));
2138 next = next_chunk (p);
2140 /* ... and is surrounded by OK chunks.
2141 Since more things can be checked with free chunks than inuse ones,
2142 if an inuse chunk borders them and debug is on, it's worth doing them.
2144 if (!prev_inuse (p))
2146 /* Note that we cannot even look at prev unless it is not inuse */
2147 mchunkptr prv = prev_chunk (p);
2148 assert (next_chunk (prv) == p);
2149 do_check_free_chunk (av, prv);
2152 if (next == av->top)
2154 assert (prev_inuse (next));
2155 assert (chunksize (next) >= MINSIZE);
2157 else if (!inuse (next))
2158 do_check_free_chunk (av, next);
2162 Properties of chunks recycled from fastbins
2165 static void
2166 do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2168 INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
2170 if (!chunk_is_mmapped (p))
2172 assert (av == arena_for_chunk (p));
2173 if (chunk_main_arena (p))
2174 assert (av == &main_arena);
2175 else
2176 assert (av != &main_arena);
2179 do_check_inuse_chunk (av, p);
2181 /* Legal size ... */
2182 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2183 assert ((unsigned long) (sz) >= MINSIZE);
2184 /* ... and alignment */
2185 assert (aligned_OK (chunk2mem (p)));
2186 /* chunk is less than MINSIZE more than request */
2187 assert ((long) (sz) - (long) (s) >= 0);
2188 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2192 Properties of nonrecycled chunks at the point they are malloced
2195 static void
2196 do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2198 /* same as recycled case ... */
2199 do_check_remalloced_chunk (av, p, s);
2202 ... plus, must obey implementation invariant that prev_inuse is
2203 always true of any allocated chunk; i.e., that each allocated
2204 chunk borders either a previously allocated and still in-use
2205 chunk, or the base of its memory arena. This is ensured
2206 by making all allocations from the `lowest' part of any found
2207 chunk. This does not necessarily hold however for chunks
2208 recycled via fastbins.
2211 assert (prev_inuse (p));
2216 Properties of malloc_state.
2218 This may be useful for debugging malloc, as well as detecting user
2219 programmer errors that somehow write into malloc_state.
2221 If you are extending or experimenting with this malloc, you can
2222 probably figure out how to hack this routine to print out or
2223 display chunk addresses, sizes, bins, and other instrumentation.
2226 static void
2227 do_check_malloc_state (mstate av)
2229 int i;
2230 mchunkptr p;
2231 mchunkptr q;
2232 mbinptr b;
2233 unsigned int idx;
2234 INTERNAL_SIZE_T size;
2235 unsigned long total = 0;
2236 int max_fast_bin;
2238 /* internal size_t must be no wider than pointer type */
2239 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2241 /* alignment is a power of 2 */
2242 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2244 /* Check the arena is initialized. */
2245 assert (av->top != 0);
2247 /* No memory has been allocated yet, so doing more tests is not possible. */
2248 if (av->top == initial_top (av))
2249 return;
2251 /* pagesize is a power of 2 */
2252 assert (powerof2(GLRO (dl_pagesize)));
2254 /* A contiguous main_arena is consistent with sbrk_base. */
2255 if (av == &main_arena && contiguous (av))
2256 assert ((char *) mp_.sbrk_base + av->system_mem ==
2257 (char *) av->top + chunksize (av->top));
2259 /* properties of fastbins */
2261 /* max_fast is in allowed range */
2262 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2264 max_fast_bin = fastbin_index (get_max_fast ());
2266 for (i = 0; i < NFASTBINS; ++i)
2268 p = fastbin (av, i);
2270 /* The following test can only be performed for the main arena.
2271 While mallopt calls malloc_consolidate to get rid of all fast
2272 bins (especially those larger than the new maximum) this does
2273 only happen for the main arena. Trying to do this for any
2274 other arena would mean those arenas have to be locked and
2275 malloc_consolidate be called for them. This is excessive. And
2276 even if this is acceptable to somebody it still cannot solve
2277 the problem completely since if the arena is locked a
2278 concurrent malloc call might create a new arena which then
2279 could use the newly invalid fast bins. */
2281 /* all bins past max_fast are empty */
2282 if (av == &main_arena && i > max_fast_bin)
2283 assert (p == 0);
2285 while (p != 0)
2287 if (__glibc_unlikely (misaligned_chunk (p)))
2288 malloc_printerr ("do_check_malloc_state(): "
2289 "unaligned fastbin chunk detected");
2290 /* each chunk claims to be inuse */
2291 do_check_inuse_chunk (av, p);
2292 total += chunksize (p);
2293 /* chunk belongs in this bin */
2294 assert (fastbin_index (chunksize (p)) == i);
2295 p = REVEAL_PTR (p->fd);
2299 /* check normal bins */
2300 for (i = 1; i < NBINS; ++i)
2302 b = bin_at (av, i);
2304 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2305 if (i >= 2)
2307 unsigned int binbit = get_binmap (av, i);
2308 int empty = last (b) == b;
2309 if (!binbit)
2310 assert (empty);
2311 else if (!empty)
2312 assert (binbit);
2315 for (p = last (b); p != b; p = p->bk)
2317 /* each chunk claims to be free */
2318 do_check_free_chunk (av, p);
2319 size = chunksize (p);
2320 total += size;
2321 if (i >= 2)
2323 /* chunk belongs in bin */
2324 idx = bin_index (size);
2325 assert (idx == i);
2326 /* lists are sorted */
2327 assert (p->bk == b ||
2328 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2330 if (!in_smallbin_range (size))
2332 if (p->fd_nextsize != NULL)
2334 if (p->fd_nextsize == p)
2335 assert (p->bk_nextsize == p);
2336 else
2338 if (p->fd_nextsize == first (b))
2339 assert (chunksize (p) < chunksize (p->fd_nextsize));
2340 else
2341 assert (chunksize (p) > chunksize (p->fd_nextsize));
2343 if (p == first (b))
2344 assert (chunksize (p) > chunksize (p->bk_nextsize));
2345 else
2346 assert (chunksize (p) < chunksize (p->bk_nextsize));
2349 else
2350 assert (p->bk_nextsize == NULL);
2353 else if (!in_smallbin_range (size))
2354 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2355 /* chunk is followed by a legal chain of inuse chunks */
2356 for (q = next_chunk (p);
2357 (q != av->top && inuse (q) &&
2358 (unsigned long) (chunksize (q)) >= MINSIZE);
2359 q = next_chunk (q))
2360 do_check_inuse_chunk (av, q);
2364 /* top chunk is OK */
2365 check_chunk (av, av->top);
2367 #endif
2370 /* ----------------- Support for debugging hooks -------------------- */
2371 #if IS_IN (libc)
2372 #include "hooks.c"
2373 #endif
2376 /* ----------- Routines dealing with system allocation -------------- */
2379 sysmalloc handles malloc cases requiring more memory from the system.
2380 On entry, it is assumed that av->top does not have enough
2381 space to service request for nb bytes, thus requiring that av->top
2382 be extended or replaced.
2385 static void *
2386 sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2388 mchunkptr old_top; /* incoming value of av->top */
2389 INTERNAL_SIZE_T old_size; /* its size */
2390 char *old_end; /* its end address */
2392 long size; /* arg to first MORECORE or mmap call */
2393 char *brk; /* return value from MORECORE */
2395 long correction; /* arg to 2nd MORECORE call */
2396 char *snd_brk; /* 2nd return val */
2398 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2399 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2400 char *aligned_brk; /* aligned offset into brk */
2402 mchunkptr p; /* the allocated/returned chunk */
2403 mchunkptr remainder; /* remainder from allocation */
2404 unsigned long remainder_size; /* its size */
2407 size_t pagesize = GLRO (dl_pagesize);
2408 bool tried_mmap = false;
2412 If have mmap, and the request size meets the mmap threshold, and
2413 the system supports mmap, and there are few enough currently
2414 allocated mmapped regions, try to directly map this request
2415 rather than expanding top.
2418 if (av == NULL
2419 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2420 && (mp_.n_mmaps < mp_.n_mmaps_max)))
2422 char *mm; /* return value from mmap call*/
2424 try_mmap:
2426 Round up size to nearest page. For mmapped chunks, the overhead
2427 is one SIZE_SZ unit larger than for normal chunks, because there
2428 is no following chunk whose prev_size field could be used.
2430 See the front_misalign handling below, for glibc there is no
2431 need for further alignments unless we have have high alignment.
2433 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2434 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2435 else
2436 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2437 tried_mmap = true;
2439 /* Don't try if size wraps around 0 */
2440 if ((unsigned long) (size) > (unsigned long) (nb))
2442 mm = (char *) (MMAP (0, size,
2443 mtag_mmap_flags | PROT_READ | PROT_WRITE, 0));
2445 if (mm != MAP_FAILED)
2448 The offset to the start of the mmapped region is stored
2449 in the prev_size field of the chunk. This allows us to adjust
2450 returned start address to meet alignment requirements here
2451 and in memalign(), and still be able to compute proper
2452 address argument for later munmap in free() and realloc().
2455 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2457 /* For glibc, chunk2mem increases the address by
2458 CHUNK_HDR_SZ and MALLOC_ALIGN_MASK is
2459 CHUNK_HDR_SZ-1. Each mmap'ed area is page
2460 aligned and therefore definitely
2461 MALLOC_ALIGN_MASK-aligned. */
2462 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2463 front_misalign = 0;
2465 else
2466 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2467 if (front_misalign > 0)
2469 correction = MALLOC_ALIGNMENT - front_misalign;
2470 p = (mchunkptr) (mm + correction);
2471 set_prev_size (p, correction);
2472 set_head (p, (size - correction) | IS_MMAPPED);
2474 else
2476 p = (mchunkptr) mm;
2477 set_prev_size (p, 0);
2478 set_head (p, size | IS_MMAPPED);
2481 /* update statistics */
2483 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2484 atomic_max (&mp_.max_n_mmaps, new);
2486 unsigned long sum;
2487 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2488 atomic_max (&mp_.max_mmapped_mem, sum);
2490 check_chunk (av, p);
2492 return chunk2mem (p);
2497 /* There are no usable arenas and mmap also failed. */
2498 if (av == NULL)
2499 return 0;
2501 /* Record incoming configuration of top */
2503 old_top = av->top;
2504 old_size = chunksize (old_top);
2505 old_end = (char *) (chunk_at_offset (old_top, old_size));
2507 brk = snd_brk = (char *) (MORECORE_FAILURE);
2510 If not the first time through, we require old_size to be
2511 at least MINSIZE and to have prev_inuse set.
2514 assert ((old_top == initial_top (av) && old_size == 0) ||
2515 ((unsigned long) (old_size) >= MINSIZE &&
2516 prev_inuse (old_top) &&
2517 ((unsigned long) old_end & (pagesize - 1)) == 0));
2519 /* Precondition: not enough current space to satisfy nb request */
2520 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2523 if (av != &main_arena)
2525 heap_info *old_heap, *heap;
2526 size_t old_heap_size;
2528 /* First try to extend the current heap. */
2529 old_heap = heap_for_ptr (old_top);
2530 old_heap_size = old_heap->size;
2531 if ((long) (MINSIZE + nb - old_size) > 0
2532 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2534 av->system_mem += old_heap->size - old_heap_size;
2535 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2536 | PREV_INUSE);
2538 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2540 /* Use a newly allocated heap. */
2541 heap->ar_ptr = av;
2542 heap->prev = old_heap;
2543 av->system_mem += heap->size;
2544 /* Set up the new top. */
2545 top (av) = chunk_at_offset (heap, sizeof (*heap));
2546 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2548 /* Setup fencepost and free the old top chunk with a multiple of
2549 MALLOC_ALIGNMENT in size. */
2550 /* The fencepost takes at least MINSIZE bytes, because it might
2551 become the top chunk again later. Note that a footer is set
2552 up, too, although the chunk is marked in use. */
2553 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2554 set_head (chunk_at_offset (old_top, old_size + CHUNK_HDR_SZ),
2555 0 | PREV_INUSE);
2556 if (old_size >= MINSIZE)
2558 set_head (chunk_at_offset (old_top, old_size),
2559 CHUNK_HDR_SZ | PREV_INUSE);
2560 set_foot (chunk_at_offset (old_top, old_size), CHUNK_HDR_SZ);
2561 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2562 _int_free (av, old_top, 1);
2564 else
2566 set_head (old_top, (old_size + CHUNK_HDR_SZ) | PREV_INUSE);
2567 set_foot (old_top, (old_size + CHUNK_HDR_SZ));
2570 else if (!tried_mmap)
2571 /* We can at least try to use to mmap memory. */
2572 goto try_mmap;
2574 else /* av == main_arena */
2577 { /* Request enough space for nb + pad + overhead */
2578 size = nb + mp_.top_pad + MINSIZE;
2581 If contiguous, we can subtract out existing space that we hope to
2582 combine with new space. We add it back later only if
2583 we don't actually get contiguous space.
2586 if (contiguous (av))
2587 size -= old_size;
2590 Round to a multiple of page size.
2591 If MORECORE is not contiguous, this ensures that we only call it
2592 with whole-page arguments. And if MORECORE is contiguous and
2593 this is not first time through, this preserves page-alignment of
2594 previous calls. Otherwise, we correct to page-align below.
2597 size = ALIGN_UP (size, pagesize);
2600 Don't try to call MORECORE if argument is so big as to appear
2601 negative. Note that since mmap takes size_t arg, it may succeed
2602 below even if we cannot call MORECORE.
2605 if (size > 0)
2607 brk = (char *) (MORECORE (size));
2608 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2611 if (brk == (char *) (MORECORE_FAILURE))
2614 If have mmap, try using it as a backup when MORECORE fails or
2615 cannot be used. This is worth doing on systems that have "holes" in
2616 address space, so sbrk cannot extend to give contiguous space, but
2617 space is available elsewhere. Note that we ignore mmap max count
2618 and threshold limits, since the space will not be used as a
2619 segregated mmap region.
2622 /* Cannot merge with old top, so add its size back in */
2623 if (contiguous (av))
2624 size = ALIGN_UP (size + old_size, pagesize);
2626 /* If we are relying on mmap as backup, then use larger units */
2627 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2628 size = MMAP_AS_MORECORE_SIZE;
2630 /* Don't try if size wraps around 0 */
2631 if ((unsigned long) (size) > (unsigned long) (nb))
2633 char *mbrk = (char *) (MMAP (0, size,
2634 mtag_mmap_flags | PROT_READ | PROT_WRITE,
2635 0));
2637 if (mbrk != MAP_FAILED)
2639 /* We do not need, and cannot use, another sbrk call to find end */
2640 brk = mbrk;
2641 snd_brk = brk + size;
2644 Record that we no longer have a contiguous sbrk region.
2645 After the first time mmap is used as backup, we do not
2646 ever rely on contiguous space since this could incorrectly
2647 bridge regions.
2649 set_noncontiguous (av);
2654 if (brk != (char *) (MORECORE_FAILURE))
2656 if (mp_.sbrk_base == 0)
2657 mp_.sbrk_base = brk;
2658 av->system_mem += size;
2661 If MORECORE extends previous space, we can likewise extend top size.
2664 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2665 set_head (old_top, (size + old_size) | PREV_INUSE);
2667 else if (contiguous (av) && old_size && brk < old_end)
2668 /* Oops! Someone else killed our space.. Can't touch anything. */
2669 malloc_printerr ("break adjusted to free malloc space");
2672 Otherwise, make adjustments:
2674 * If the first time through or noncontiguous, we need to call sbrk
2675 just to find out where the end of memory lies.
2677 * We need to ensure that all returned chunks from malloc will meet
2678 MALLOC_ALIGNMENT
2680 * If there was an intervening foreign sbrk, we need to adjust sbrk
2681 request size to account for fact that we will not be able to
2682 combine new space with existing space in old_top.
2684 * Almost all systems internally allocate whole pages at a time, in
2685 which case we might as well use the whole last page of request.
2686 So we allocate enough more memory to hit a page boundary now,
2687 which in turn causes future contiguous calls to page-align.
2690 else
2692 front_misalign = 0;
2693 end_misalign = 0;
2694 correction = 0;
2695 aligned_brk = brk;
2697 /* handle contiguous cases */
2698 if (contiguous (av))
2700 /* Count foreign sbrk as system_mem. */
2701 if (old_size)
2702 av->system_mem += brk - old_end;
2704 /* Guarantee alignment of first new chunk made from this space */
2706 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2707 if (front_misalign > 0)
2710 Skip over some bytes to arrive at an aligned position.
2711 We don't need to specially mark these wasted front bytes.
2712 They will never be accessed anyway because
2713 prev_inuse of av->top (and any chunk created from its start)
2714 is always true after initialization.
2717 correction = MALLOC_ALIGNMENT - front_misalign;
2718 aligned_brk += correction;
2722 If this isn't adjacent to existing space, then we will not
2723 be able to merge with old_top space, so must add to 2nd request.
2726 correction += old_size;
2728 /* Extend the end address to hit a page boundary */
2729 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2730 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2732 assert (correction >= 0);
2733 snd_brk = (char *) (MORECORE (correction));
2736 If can't allocate correction, try to at least find out current
2737 brk. It might be enough to proceed without failing.
2739 Note that if second sbrk did NOT fail, we assume that space
2740 is contiguous with first sbrk. This is a safe assumption unless
2741 program is multithreaded but doesn't use locks and a foreign sbrk
2742 occurred between our first and second calls.
2745 if (snd_brk == (char *) (MORECORE_FAILURE))
2747 correction = 0;
2748 snd_brk = (char *) (MORECORE (0));
2752 /* handle non-contiguous cases */
2753 else
2755 if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ)
2756 /* MORECORE/mmap must correctly align */
2757 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2758 else
2760 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2761 if (front_misalign > 0)
2764 Skip over some bytes to arrive at an aligned position.
2765 We don't need to specially mark these wasted front bytes.
2766 They will never be accessed anyway because
2767 prev_inuse of av->top (and any chunk created from its start)
2768 is always true after initialization.
2771 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2775 /* Find out current end of memory */
2776 if (snd_brk == (char *) (MORECORE_FAILURE))
2778 snd_brk = (char *) (MORECORE (0));
2782 /* Adjust top based on results of second sbrk */
2783 if (snd_brk != (char *) (MORECORE_FAILURE))
2785 av->top = (mchunkptr) aligned_brk;
2786 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2787 av->system_mem += correction;
2790 If not the first time through, we either have a
2791 gap due to foreign sbrk or a non-contiguous region. Insert a
2792 double fencepost at old_top to prevent consolidation with space
2793 we don't own. These fenceposts are artificial chunks that are
2794 marked as inuse and are in any case too small to use. We need
2795 two to make sizes and alignments work out.
2798 if (old_size != 0)
2801 Shrink old_top to insert fenceposts, keeping size a
2802 multiple of MALLOC_ALIGNMENT. We know there is at least
2803 enough space in old_top to do this.
2805 old_size = (old_size - 2 * CHUNK_HDR_SZ) & ~MALLOC_ALIGN_MASK;
2806 set_head (old_top, old_size | PREV_INUSE);
2809 Note that the following assignments completely overwrite
2810 old_top when old_size was previously MINSIZE. This is
2811 intentional. We need the fencepost, even if old_top otherwise gets
2812 lost.
2814 set_head (chunk_at_offset (old_top, old_size),
2815 CHUNK_HDR_SZ | PREV_INUSE);
2816 set_head (chunk_at_offset (old_top,
2817 old_size + CHUNK_HDR_SZ),
2818 CHUNK_HDR_SZ | PREV_INUSE);
2820 /* If possible, release the rest. */
2821 if (old_size >= MINSIZE)
2823 _int_free (av, old_top, 1);
2829 } /* if (av != &main_arena) */
2831 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2832 av->max_system_mem = av->system_mem;
2833 check_malloc_state (av);
2835 /* finally, do the allocation */
2836 p = av->top;
2837 size = chunksize (p);
2839 /* check that one of the above allocation paths succeeded */
2840 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2842 remainder_size = size - nb;
2843 remainder = chunk_at_offset (p, nb);
2844 av->top = remainder;
2845 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2846 set_head (remainder, remainder_size | PREV_INUSE);
2847 check_malloced_chunk (av, p, nb);
2848 return chunk2mem (p);
2851 /* catch all failure paths */
2852 __set_errno (ENOMEM);
2853 return 0;
2858 systrim is an inverse of sorts to sysmalloc. It gives memory back
2859 to the system (via negative arguments to sbrk) if there is unused
2860 memory at the `high' end of the malloc pool. It is called
2861 automatically by free() when top space exceeds the trim
2862 threshold. It is also called by the public malloc_trim routine. It
2863 returns 1 if it actually released any memory, else 0.
2866 static int
2867 systrim (size_t pad, mstate av)
2869 long top_size; /* Amount of top-most memory */
2870 long extra; /* Amount to release */
2871 long released; /* Amount actually released */
2872 char *current_brk; /* address returned by pre-check sbrk call */
2873 char *new_brk; /* address returned by post-check sbrk call */
2874 size_t pagesize;
2875 long top_area;
2877 pagesize = GLRO (dl_pagesize);
2878 top_size = chunksize (av->top);
2880 top_area = top_size - MINSIZE - 1;
2881 if (top_area <= pad)
2882 return 0;
2884 /* Release in pagesize units and round down to the nearest page. */
2885 extra = ALIGN_DOWN(top_area - pad, pagesize);
2887 if (extra == 0)
2888 return 0;
2891 Only proceed if end of memory is where we last set it.
2892 This avoids problems if there were foreign sbrk calls.
2894 current_brk = (char *) (MORECORE (0));
2895 if (current_brk == (char *) (av->top) + top_size)
2898 Attempt to release memory. We ignore MORECORE return value,
2899 and instead call again to find out where new end of memory is.
2900 This avoids problems if first call releases less than we asked,
2901 of if failure somehow altered brk value. (We could still
2902 encounter problems if it altered brk in some very bad way,
2903 but the only thing we can do is adjust anyway, which will cause
2904 some downstream failure.)
2907 MORECORE (-extra);
2908 new_brk = (char *) (MORECORE (0));
2910 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2912 if (new_brk != (char *) MORECORE_FAILURE)
2914 released = (long) (current_brk - new_brk);
2916 if (released != 0)
2918 /* Success. Adjust top. */
2919 av->system_mem -= released;
2920 set_head (av->top, (top_size - released) | PREV_INUSE);
2921 check_malloc_state (av);
2922 return 1;
2926 return 0;
2929 static void
2930 munmap_chunk (mchunkptr p)
2932 size_t pagesize = GLRO (dl_pagesize);
2933 INTERNAL_SIZE_T size = chunksize (p);
2935 assert (chunk_is_mmapped (p));
2937 uintptr_t mem = (uintptr_t) chunk2mem (p);
2938 uintptr_t block = (uintptr_t) p - prev_size (p);
2939 size_t total_size = prev_size (p) + size;
2940 /* Unfortunately we have to do the compilers job by hand here. Normally
2941 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2942 page size. But gcc does not recognize the optimization possibility
2943 (in the moment at least) so we combine the two values into one before
2944 the bit test. */
2945 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
2946 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
2947 malloc_printerr ("munmap_chunk(): invalid pointer");
2949 atomic_decrement (&mp_.n_mmaps);
2950 atomic_add (&mp_.mmapped_mem, -total_size);
2952 /* If munmap failed the process virtual memory address space is in a
2953 bad shape. Just leave the block hanging around, the process will
2954 terminate shortly anyway since not much can be done. */
2955 __munmap ((char *) block, total_size);
2958 #if HAVE_MREMAP
2960 static mchunkptr
2961 mremap_chunk (mchunkptr p, size_t new_size)
2963 size_t pagesize = GLRO (dl_pagesize);
2964 INTERNAL_SIZE_T offset = prev_size (p);
2965 INTERNAL_SIZE_T size = chunksize (p);
2966 char *cp;
2968 assert (chunk_is_mmapped (p));
2970 uintptr_t block = (uintptr_t) p - offset;
2971 uintptr_t mem = (uintptr_t) chunk2mem(p);
2972 size_t total_size = offset + size;
2973 if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
2974 || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
2975 malloc_printerr("mremap_chunk(): invalid pointer");
2977 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2978 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
2980 /* No need to remap if the number of pages does not change. */
2981 if (total_size == new_size)
2982 return p;
2984 cp = (char *) __mremap ((char *) block, total_size, new_size,
2985 MREMAP_MAYMOVE);
2987 if (cp == MAP_FAILED)
2988 return 0;
2990 p = (mchunkptr) (cp + offset);
2992 assert (aligned_OK (chunk2mem (p)));
2994 assert (prev_size (p) == offset);
2995 set_head (p, (new_size - offset) | IS_MMAPPED);
2997 INTERNAL_SIZE_T new;
2998 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
2999 + new_size - size - offset;
3000 atomic_max (&mp_.max_mmapped_mem, new);
3001 return p;
3003 #endif /* HAVE_MREMAP */
3005 /*------------------------ Public wrappers. --------------------------------*/
3007 #if USE_TCACHE
3009 /* We overlay this structure on the user-data portion of a chunk when
3010 the chunk is stored in the per-thread cache. */
3011 typedef struct tcache_entry
3013 struct tcache_entry *next;
3014 /* This field exists to detect double frees. */
3015 uintptr_t key;
3016 } tcache_entry;
3018 /* There is one of these for each thread, which contains the
3019 per-thread cache (hence "tcache_perthread_struct"). Keeping
3020 overall size low is mildly important. Note that COUNTS and ENTRIES
3021 are redundant (we could have just counted the linked list each
3022 time), this is for performance reasons. */
3023 typedef struct tcache_perthread_struct
3025 uint16_t counts[TCACHE_MAX_BINS];
3026 tcache_entry *entries[TCACHE_MAX_BINS];
3027 } tcache_perthread_struct;
3029 static __thread bool tcache_shutting_down = false;
3030 static __thread tcache_perthread_struct *tcache = NULL;
3032 /* Process-wide key to try and catch a double-free in the same thread. */
3033 static uintptr_t tcache_key;
3035 /* The value of tcache_key does not really have to be a cryptographically
3036 secure random number. It only needs to be arbitrary enough so that it does
3037 not collide with values present in applications. If a collision does happen
3038 consistently enough, it could cause a degradation in performance since the
3039 entire list is checked to check if the block indeed has been freed the
3040 second time. The odds of this happening are exceedingly low though, about 1
3041 in 2^wordsize. There is probably a higher chance of the performance
3042 degradation being due to a double free where the first free happened in a
3043 different thread; that's a case this check does not cover. */
3044 static void
3045 tcache_key_initialize (void)
3047 if (__getrandom (&tcache_key, sizeof(tcache_key), GRND_NONBLOCK)
3048 != sizeof (tcache_key))
3050 tcache_key = random_bits ();
3051 #if __WORDSIZE == 64
3052 tcache_key = (tcache_key << 32) | random_bits ();
3053 #endif
3057 /* Caller must ensure that we know tc_idx is valid and there's room
3058 for more chunks. */
3059 static __always_inline void
3060 tcache_put (mchunkptr chunk, size_t tc_idx)
3062 tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
3064 /* Mark this chunk as "in the tcache" so the test in _int_free will
3065 detect a double free. */
3066 e->key = tcache_key;
3068 e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]);
3069 tcache->entries[tc_idx] = e;
3070 ++(tcache->counts[tc_idx]);
3073 /* Caller must ensure that we know tc_idx is valid and there's
3074 available chunks to remove. */
3075 static __always_inline void *
3076 tcache_get (size_t tc_idx)
3078 tcache_entry *e = tcache->entries[tc_idx];
3079 if (__glibc_unlikely (!aligned_OK (e)))
3080 malloc_printerr ("malloc(): unaligned tcache chunk detected");
3081 tcache->entries[tc_idx] = REVEAL_PTR (e->next);
3082 --(tcache->counts[tc_idx]);
3083 e->key = 0;
3084 return (void *) e;
3087 static void
3088 tcache_thread_shutdown (void)
3090 int i;
3091 tcache_perthread_struct *tcache_tmp = tcache;
3093 tcache_shutting_down = true;
3095 if (!tcache)
3096 return;
3098 /* Disable the tcache and prevent it from being reinitialized. */
3099 tcache = NULL;
3101 /* Free all of the entries and the tcache itself back to the arena
3102 heap for coalescing. */
3103 for (i = 0; i < TCACHE_MAX_BINS; ++i)
3105 while (tcache_tmp->entries[i])
3107 tcache_entry *e = tcache_tmp->entries[i];
3108 if (__glibc_unlikely (!aligned_OK (e)))
3109 malloc_printerr ("tcache_thread_shutdown(): "
3110 "unaligned tcache chunk detected");
3111 tcache_tmp->entries[i] = REVEAL_PTR (e->next);
3112 __libc_free (e);
3116 __libc_free (tcache_tmp);
3119 static void
3120 tcache_init(void)
3122 mstate ar_ptr;
3123 void *victim = 0;
3124 const size_t bytes = sizeof (tcache_perthread_struct);
3126 if (tcache_shutting_down)
3127 return;
3129 arena_get (ar_ptr, bytes);
3130 victim = _int_malloc (ar_ptr, bytes);
3131 if (!victim && ar_ptr != NULL)
3133 ar_ptr = arena_get_retry (ar_ptr, bytes);
3134 victim = _int_malloc (ar_ptr, bytes);
3138 if (ar_ptr != NULL)
3139 __libc_lock_unlock (ar_ptr->mutex);
3141 /* In a low memory situation, we may not be able to allocate memory
3142 - in which case, we just keep trying later. However, we
3143 typically do this very early, so either there is sufficient
3144 memory, or there isn't enough memory to do non-trivial
3145 allocations anyway. */
3146 if (victim)
3148 tcache = (tcache_perthread_struct *) victim;
3149 memset (tcache, 0, sizeof (tcache_perthread_struct));
3154 # define MAYBE_INIT_TCACHE() \
3155 if (__glibc_unlikely (tcache == NULL)) \
3156 tcache_init();
3158 #else /* !USE_TCACHE */
3159 # define MAYBE_INIT_TCACHE()
3161 static void
3162 tcache_thread_shutdown (void)
3164 /* Nothing to do if there is no thread cache. */
3167 #endif /* !USE_TCACHE */
3169 #if IS_IN (libc)
3170 void *
3171 __libc_malloc (size_t bytes)
3173 mstate ar_ptr;
3174 void *victim;
3176 _Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2,
3177 "PTRDIFF_MAX is not more than half of SIZE_MAX");
3179 if (!__malloc_initialized)
3180 ptmalloc_init ();
3181 #if USE_TCACHE
3182 /* int_free also calls request2size, be careful to not pad twice. */
3183 size_t tbytes;
3184 if (!checked_request2size (bytes, &tbytes))
3186 __set_errno (ENOMEM);
3187 return NULL;
3189 size_t tc_idx = csize2tidx (tbytes);
3191 MAYBE_INIT_TCACHE ();
3193 DIAG_PUSH_NEEDS_COMMENT;
3194 if (tc_idx < mp_.tcache_bins
3195 && tcache
3196 && tcache->counts[tc_idx] > 0)
3198 victim = tcache_get (tc_idx);
3199 return tag_new_usable (victim);
3201 DIAG_POP_NEEDS_COMMENT;
3202 #endif
3204 if (SINGLE_THREAD_P)
3206 victim = tag_new_usable (_int_malloc (&main_arena, bytes));
3207 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3208 &main_arena == arena_for_chunk (mem2chunk (victim)));
3209 return victim;
3212 arena_get (ar_ptr, bytes);
3214 victim = _int_malloc (ar_ptr, bytes);
3215 /* Retry with another arena only if we were able to find a usable arena
3216 before. */
3217 if (!victim && ar_ptr != NULL)
3219 LIBC_PROBE (memory_malloc_retry, 1, bytes);
3220 ar_ptr = arena_get_retry (ar_ptr, bytes);
3221 victim = _int_malloc (ar_ptr, bytes);
3224 if (ar_ptr != NULL)
3225 __libc_lock_unlock (ar_ptr->mutex);
3227 victim = tag_new_usable (victim);
3229 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
3230 ar_ptr == arena_for_chunk (mem2chunk (victim)));
3231 return victim;
3233 libc_hidden_def (__libc_malloc)
3235 void
3236 __libc_free (void *mem)
3238 mstate ar_ptr;
3239 mchunkptr p; /* chunk corresponding to mem */
3241 if (mem == 0) /* free(0) has no effect */
3242 return;
3244 /* Quickly check that the freed pointer matches the tag for the memory.
3245 This gives a useful double-free detection. */
3246 if (__glibc_unlikely (mtag_enabled))
3247 *(volatile char *)mem;
3249 int err = errno;
3251 p = mem2chunk (mem);
3253 if (chunk_is_mmapped (p)) /* release mmapped memory. */
3255 /* See if the dynamic brk/mmap threshold needs adjusting.
3256 Dumped fake mmapped chunks do not affect the threshold. */
3257 if (!mp_.no_dyn_threshold
3258 && chunksize_nomask (p) > mp_.mmap_threshold
3259 && chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX)
3261 mp_.mmap_threshold = chunksize (p);
3262 mp_.trim_threshold = 2 * mp_.mmap_threshold;
3263 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
3264 mp_.mmap_threshold, mp_.trim_threshold);
3266 munmap_chunk (p);
3268 else
3270 MAYBE_INIT_TCACHE ();
3272 /* Mark the chunk as belonging to the library again. */
3273 (void)tag_region (chunk2mem (p), memsize (p));
3275 ar_ptr = arena_for_chunk (p);
3276 _int_free (ar_ptr, p, 0);
3279 __set_errno (err);
3281 libc_hidden_def (__libc_free)
3283 void *
3284 __libc_realloc (void *oldmem, size_t bytes)
3286 mstate ar_ptr;
3287 INTERNAL_SIZE_T nb; /* padded request size */
3289 void *newp; /* chunk to return */
3291 if (!__malloc_initialized)
3292 ptmalloc_init ();
3294 #if REALLOC_ZERO_BYTES_FREES
3295 if (bytes == 0 && oldmem != NULL)
3297 __libc_free (oldmem); return 0;
3299 #endif
3301 /* realloc of null is supposed to be same as malloc */
3302 if (oldmem == 0)
3303 return __libc_malloc (bytes);
3305 /* Perform a quick check to ensure that the pointer's tag matches the
3306 memory's tag. */
3307 if (__glibc_unlikely (mtag_enabled))
3308 *(volatile char*) oldmem;
3310 /* chunk corresponding to oldmem */
3311 const mchunkptr oldp = mem2chunk (oldmem);
3312 /* its size */
3313 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
3315 if (chunk_is_mmapped (oldp))
3316 ar_ptr = NULL;
3317 else
3319 MAYBE_INIT_TCACHE ();
3320 ar_ptr = arena_for_chunk (oldp);
3323 /* Little security check which won't hurt performance: the allocator
3324 never wrapps around at the end of the address space. Therefore
3325 we can exclude some size values which might appear here by
3326 accident or by "design" from some intruder. */
3327 if ((__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
3328 || __builtin_expect (misaligned_chunk (oldp), 0)))
3329 malloc_printerr ("realloc(): invalid pointer");
3331 if (!checked_request2size (bytes, &nb))
3333 __set_errno (ENOMEM);
3334 return NULL;
3337 if (chunk_is_mmapped (oldp))
3339 void *newmem;
3341 #if HAVE_MREMAP
3342 newp = mremap_chunk (oldp, nb);
3343 if (newp)
3345 void *newmem = chunk2mem_tag (newp);
3346 /* Give the new block a different tag. This helps to ensure
3347 that stale handles to the previous mapping are not
3348 reused. There's a performance hit for both us and the
3349 caller for doing this, so we might want to
3350 reconsider. */
3351 return tag_new_usable (newmem);
3353 #endif
3354 /* Note the extra SIZE_SZ overhead. */
3355 if (oldsize - SIZE_SZ >= nb)
3356 return oldmem; /* do nothing */
3358 /* Must alloc, copy, free. */
3359 newmem = __libc_malloc (bytes);
3360 if (newmem == 0)
3361 return 0; /* propagate failure */
3363 memcpy (newmem, oldmem, oldsize - CHUNK_HDR_SZ);
3364 munmap_chunk (oldp);
3365 return newmem;
3368 if (SINGLE_THREAD_P)
3370 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3371 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3372 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3374 return newp;
3377 __libc_lock_lock (ar_ptr->mutex);
3379 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3381 __libc_lock_unlock (ar_ptr->mutex);
3382 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3383 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3385 if (newp == NULL)
3387 /* Try harder to allocate memory in other arenas. */
3388 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3389 newp = __libc_malloc (bytes);
3390 if (newp != NULL)
3392 size_t sz = memsize (oldp);
3393 memcpy (newp, oldmem, sz);
3394 (void) tag_region (chunk2mem (oldp), sz);
3395 _int_free (ar_ptr, oldp, 0);
3399 return newp;
3401 libc_hidden_def (__libc_realloc)
3403 void *
3404 __libc_memalign (size_t alignment, size_t bytes)
3406 if (!__malloc_initialized)
3407 ptmalloc_init ();
3409 void *address = RETURN_ADDRESS (0);
3410 return _mid_memalign (alignment, bytes, address);
3413 static void *
3414 _mid_memalign (size_t alignment, size_t bytes, void *address)
3416 mstate ar_ptr;
3417 void *p;
3419 /* If we need less alignment than we give anyway, just relay to malloc. */
3420 if (alignment <= MALLOC_ALIGNMENT)
3421 return __libc_malloc (bytes);
3423 /* Otherwise, ensure that it is at least a minimum chunk size */
3424 if (alignment < MINSIZE)
3425 alignment = MINSIZE;
3427 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3428 power of 2 and will cause overflow in the check below. */
3429 if (alignment > SIZE_MAX / 2 + 1)
3431 __set_errno (EINVAL);
3432 return 0;
3436 /* Make sure alignment is power of 2. */
3437 if (!powerof2 (alignment))
3439 size_t a = MALLOC_ALIGNMENT * 2;
3440 while (a < alignment)
3441 a <<= 1;
3442 alignment = a;
3445 if (SINGLE_THREAD_P)
3447 p = _int_memalign (&main_arena, alignment, bytes);
3448 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3449 &main_arena == arena_for_chunk (mem2chunk (p)));
3450 return tag_new_usable (p);
3453 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3455 p = _int_memalign (ar_ptr, alignment, bytes);
3456 if (!p && ar_ptr != NULL)
3458 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3459 ar_ptr = arena_get_retry (ar_ptr, bytes);
3460 p = _int_memalign (ar_ptr, alignment, bytes);
3463 if (ar_ptr != NULL)
3464 __libc_lock_unlock (ar_ptr->mutex);
3466 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3467 ar_ptr == arena_for_chunk (mem2chunk (p)));
3468 return tag_new_usable (p);
3470 /* For ISO C11. */
3471 weak_alias (__libc_memalign, aligned_alloc)
3472 libc_hidden_def (__libc_memalign)
3474 void *
3475 __libc_valloc (size_t bytes)
3477 if (!__malloc_initialized)
3478 ptmalloc_init ();
3480 void *address = RETURN_ADDRESS (0);
3481 size_t pagesize = GLRO (dl_pagesize);
3482 return _mid_memalign (pagesize, bytes, address);
3485 void *
3486 __libc_pvalloc (size_t bytes)
3488 if (!__malloc_initialized)
3489 ptmalloc_init ();
3491 void *address = RETURN_ADDRESS (0);
3492 size_t pagesize = GLRO (dl_pagesize);
3493 size_t rounded_bytes;
3494 /* ALIGN_UP with overflow check. */
3495 if (__glibc_unlikely (__builtin_add_overflow (bytes,
3496 pagesize - 1,
3497 &rounded_bytes)))
3499 __set_errno (ENOMEM);
3500 return 0;
3502 rounded_bytes = rounded_bytes & -(pagesize - 1);
3504 return _mid_memalign (pagesize, rounded_bytes, address);
3507 void *
3508 __libc_calloc (size_t n, size_t elem_size)
3510 mstate av;
3511 mchunkptr oldtop;
3512 INTERNAL_SIZE_T sz, oldtopsize;
3513 void *mem;
3514 unsigned long clearsize;
3515 unsigned long nclears;
3516 INTERNAL_SIZE_T *d;
3517 ptrdiff_t bytes;
3519 if (__glibc_unlikely (__builtin_mul_overflow (n, elem_size, &bytes)))
3521 __set_errno (ENOMEM);
3522 return NULL;
3525 sz = bytes;
3527 if (!__malloc_initialized)
3528 ptmalloc_init ();
3530 MAYBE_INIT_TCACHE ();
3532 if (SINGLE_THREAD_P)
3533 av = &main_arena;
3534 else
3535 arena_get (av, sz);
3537 if (av)
3539 /* Check if we hand out the top chunk, in which case there may be no
3540 need to clear. */
3541 #if MORECORE_CLEARS
3542 oldtop = top (av);
3543 oldtopsize = chunksize (top (av));
3544 # if MORECORE_CLEARS < 2
3545 /* Only newly allocated memory is guaranteed to be cleared. */
3546 if (av == &main_arena &&
3547 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3548 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3549 # endif
3550 if (av != &main_arena)
3552 heap_info *heap = heap_for_ptr (oldtop);
3553 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3554 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3556 #endif
3558 else
3560 /* No usable arenas. */
3561 oldtop = 0;
3562 oldtopsize = 0;
3564 mem = _int_malloc (av, sz);
3566 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3567 av == arena_for_chunk (mem2chunk (mem)));
3569 if (!SINGLE_THREAD_P)
3571 if (mem == 0 && av != NULL)
3573 LIBC_PROBE (memory_calloc_retry, 1, sz);
3574 av = arena_get_retry (av, sz);
3575 mem = _int_malloc (av, sz);
3578 if (av != NULL)
3579 __libc_lock_unlock (av->mutex);
3582 /* Allocation failed even after a retry. */
3583 if (mem == 0)
3584 return 0;
3586 mchunkptr p = mem2chunk (mem);
3588 /* If we are using memory tagging, then we need to set the tags
3589 regardless of MORECORE_CLEARS, so we zero the whole block while
3590 doing so. */
3591 if (__glibc_unlikely (mtag_enabled))
3592 return tag_new_zero_region (mem, memsize (p));
3594 INTERNAL_SIZE_T csz = chunksize (p);
3596 /* Two optional cases in which clearing not necessary */
3597 if (chunk_is_mmapped (p))
3599 if (__builtin_expect (perturb_byte, 0))
3600 return memset (mem, 0, sz);
3602 return mem;
3605 #if MORECORE_CLEARS
3606 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3608 /* clear only the bytes from non-freshly-sbrked memory */
3609 csz = oldtopsize;
3611 #endif
3613 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3614 contents have an odd number of INTERNAL_SIZE_T-sized words;
3615 minimally 3. */
3616 d = (INTERNAL_SIZE_T *) mem;
3617 clearsize = csz - SIZE_SZ;
3618 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3619 assert (nclears >= 3);
3621 if (nclears > 9)
3622 return memset (d, 0, clearsize);
3624 else
3626 *(d + 0) = 0;
3627 *(d + 1) = 0;
3628 *(d + 2) = 0;
3629 if (nclears > 4)
3631 *(d + 3) = 0;
3632 *(d + 4) = 0;
3633 if (nclears > 6)
3635 *(d + 5) = 0;
3636 *(d + 6) = 0;
3637 if (nclears > 8)
3639 *(d + 7) = 0;
3640 *(d + 8) = 0;
3646 return mem;
3648 #endif /* IS_IN (libc) */
3651 ------------------------------ malloc ------------------------------
3654 static void *
3655 _int_malloc (mstate av, size_t bytes)
3657 INTERNAL_SIZE_T nb; /* normalized request size */
3658 unsigned int idx; /* associated bin index */
3659 mbinptr bin; /* associated bin */
3661 mchunkptr victim; /* inspected/selected chunk */
3662 INTERNAL_SIZE_T size; /* its size */
3663 int victim_index; /* its bin index */
3665 mchunkptr remainder; /* remainder from a split */
3666 unsigned long remainder_size; /* its size */
3668 unsigned int block; /* bit map traverser */
3669 unsigned int bit; /* bit map traverser */
3670 unsigned int map; /* current word of binmap */
3672 mchunkptr fwd; /* misc temp for linking */
3673 mchunkptr bck; /* misc temp for linking */
3675 #if USE_TCACHE
3676 size_t tcache_unsorted_count; /* count of unsorted chunks processed */
3677 #endif
3680 Convert request size to internal form by adding SIZE_SZ bytes
3681 overhead plus possibly more to obtain necessary alignment and/or
3682 to obtain a size of at least MINSIZE, the smallest allocatable
3683 size. Also, checked_request2size returns false for request sizes
3684 that are so large that they wrap around zero when padded and
3685 aligned.
3688 if (!checked_request2size (bytes, &nb))
3690 __set_errno (ENOMEM);
3691 return NULL;
3694 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3695 mmap. */
3696 if (__glibc_unlikely (av == NULL))
3698 void *p = sysmalloc (nb, av);
3699 if (p != NULL)
3700 alloc_perturb (p, bytes);
3701 return p;
3705 If the size qualifies as a fastbin, first check corresponding bin.
3706 This code is safe to execute even if av is not yet initialized, so we
3707 can try it without checking, which saves some time on this fast path.
3710 #define REMOVE_FB(fb, victim, pp) \
3711 do \
3713 victim = pp; \
3714 if (victim == NULL) \
3715 break; \
3716 pp = REVEAL_PTR (victim->fd); \
3717 if (__glibc_unlikely (pp != NULL && misaligned_chunk (pp))) \
3718 malloc_printerr ("malloc(): unaligned fastbin chunk detected"); \
3720 while ((pp = catomic_compare_and_exchange_val_acq (fb, pp, victim)) \
3721 != victim); \
3723 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3725 idx = fastbin_index (nb);
3726 mfastbinptr *fb = &fastbin (av, idx);
3727 mchunkptr pp;
3728 victim = *fb;
3730 if (victim != NULL)
3732 if (__glibc_unlikely (misaligned_chunk (victim)))
3733 malloc_printerr ("malloc(): unaligned fastbin chunk detected 2");
3735 if (SINGLE_THREAD_P)
3736 *fb = REVEAL_PTR (victim->fd);
3737 else
3738 REMOVE_FB (fb, pp, victim);
3739 if (__glibc_likely (victim != NULL))
3741 size_t victim_idx = fastbin_index (chunksize (victim));
3742 if (__builtin_expect (victim_idx != idx, 0))
3743 malloc_printerr ("malloc(): memory corruption (fast)");
3744 check_remalloced_chunk (av, victim, nb);
3745 #if USE_TCACHE
3746 /* While we're here, if we see other chunks of the same size,
3747 stash them in the tcache. */
3748 size_t tc_idx = csize2tidx (nb);
3749 if (tcache && tc_idx < mp_.tcache_bins)
3751 mchunkptr tc_victim;
3753 /* While bin not empty and tcache not full, copy chunks. */
3754 while (tcache->counts[tc_idx] < mp_.tcache_count
3755 && (tc_victim = *fb) != NULL)
3757 if (__glibc_unlikely (misaligned_chunk (tc_victim)))
3758 malloc_printerr ("malloc(): unaligned fastbin chunk detected 3");
3759 if (SINGLE_THREAD_P)
3760 *fb = REVEAL_PTR (tc_victim->fd);
3761 else
3763 REMOVE_FB (fb, pp, tc_victim);
3764 if (__glibc_unlikely (tc_victim == NULL))
3765 break;
3767 tcache_put (tc_victim, tc_idx);
3770 #endif
3771 void *p = chunk2mem (victim);
3772 alloc_perturb (p, bytes);
3773 return p;
3779 If a small request, check regular bin. Since these "smallbins"
3780 hold one size each, no searching within bins is necessary.
3781 (For a large request, we need to wait until unsorted chunks are
3782 processed to find best fit. But for small ones, fits are exact
3783 anyway, so we can check now, which is faster.)
3786 if (in_smallbin_range (nb))
3788 idx = smallbin_index (nb);
3789 bin = bin_at (av, idx);
3791 if ((victim = last (bin)) != bin)
3793 bck = victim->bk;
3794 if (__glibc_unlikely (bck->fd != victim))
3795 malloc_printerr ("malloc(): smallbin double linked list corrupted");
3796 set_inuse_bit_at_offset (victim, nb);
3797 bin->bk = bck;
3798 bck->fd = bin;
3800 if (av != &main_arena)
3801 set_non_main_arena (victim);
3802 check_malloced_chunk (av, victim, nb);
3803 #if USE_TCACHE
3804 /* While we're here, if we see other chunks of the same size,
3805 stash them in the tcache. */
3806 size_t tc_idx = csize2tidx (nb);
3807 if (tcache && tc_idx < mp_.tcache_bins)
3809 mchunkptr tc_victim;
3811 /* While bin not empty and tcache not full, copy chunks over. */
3812 while (tcache->counts[tc_idx] < mp_.tcache_count
3813 && (tc_victim = last (bin)) != bin)
3815 if (tc_victim != 0)
3817 bck = tc_victim->bk;
3818 set_inuse_bit_at_offset (tc_victim, nb);
3819 if (av != &main_arena)
3820 set_non_main_arena (tc_victim);
3821 bin->bk = bck;
3822 bck->fd = bin;
3824 tcache_put (tc_victim, tc_idx);
3828 #endif
3829 void *p = chunk2mem (victim);
3830 alloc_perturb (p, bytes);
3831 return p;
3836 If this is a large request, consolidate fastbins before continuing.
3837 While it might look excessive to kill all fastbins before
3838 even seeing if there is space available, this avoids
3839 fragmentation problems normally associated with fastbins.
3840 Also, in practice, programs tend to have runs of either small or
3841 large requests, but less often mixtures, so consolidation is not
3842 invoked all that often in most programs. And the programs that
3843 it is called frequently in otherwise tend to fragment.
3846 else
3848 idx = largebin_index (nb);
3849 if (atomic_load_relaxed (&av->have_fastchunks))
3850 malloc_consolidate (av);
3854 Process recently freed or remaindered chunks, taking one only if
3855 it is exact fit, or, if this a small request, the chunk is remainder from
3856 the most recent non-exact fit. Place other traversed chunks in
3857 bins. Note that this step is the only place in any routine where
3858 chunks are placed in bins.
3860 The outer loop here is needed because we might not realize until
3861 near the end of malloc that we should have consolidated, so must
3862 do so and retry. This happens at most once, and only when we would
3863 otherwise need to expand memory to service a "small" request.
3866 #if USE_TCACHE
3867 INTERNAL_SIZE_T tcache_nb = 0;
3868 size_t tc_idx = csize2tidx (nb);
3869 if (tcache && tc_idx < mp_.tcache_bins)
3870 tcache_nb = nb;
3871 int return_cached = 0;
3873 tcache_unsorted_count = 0;
3874 #endif
3876 for (;; )
3878 int iters = 0;
3879 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3881 bck = victim->bk;
3882 size = chunksize (victim);
3883 mchunkptr next = chunk_at_offset (victim, size);
3885 if (__glibc_unlikely (size <= CHUNK_HDR_SZ)
3886 || __glibc_unlikely (size > av->system_mem))
3887 malloc_printerr ("malloc(): invalid size (unsorted)");
3888 if (__glibc_unlikely (chunksize_nomask (next) < CHUNK_HDR_SZ)
3889 || __glibc_unlikely (chunksize_nomask (next) > av->system_mem))
3890 malloc_printerr ("malloc(): invalid next size (unsorted)");
3891 if (__glibc_unlikely ((prev_size (next) & ~(SIZE_BITS)) != size))
3892 malloc_printerr ("malloc(): mismatching next->prev_size (unsorted)");
3893 if (__glibc_unlikely (bck->fd != victim)
3894 || __glibc_unlikely (victim->fd != unsorted_chunks (av)))
3895 malloc_printerr ("malloc(): unsorted double linked list corrupted");
3896 if (__glibc_unlikely (prev_inuse (next)))
3897 malloc_printerr ("malloc(): invalid next->prev_inuse (unsorted)");
3900 If a small request, try to use last remainder if it is the
3901 only chunk in unsorted bin. This helps promote locality for
3902 runs of consecutive small requests. This is the only
3903 exception to best-fit, and applies only when there is
3904 no exact fit for a small chunk.
3907 if (in_smallbin_range (nb) &&
3908 bck == unsorted_chunks (av) &&
3909 victim == av->last_remainder &&
3910 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
3912 /* split and reattach remainder */
3913 remainder_size = size - nb;
3914 remainder = chunk_at_offset (victim, nb);
3915 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
3916 av->last_remainder = remainder;
3917 remainder->bk = remainder->fd = unsorted_chunks (av);
3918 if (!in_smallbin_range (remainder_size))
3920 remainder->fd_nextsize = NULL;
3921 remainder->bk_nextsize = NULL;
3924 set_head (victim, nb | PREV_INUSE |
3925 (av != &main_arena ? NON_MAIN_ARENA : 0));
3926 set_head (remainder, remainder_size | PREV_INUSE);
3927 set_foot (remainder, remainder_size);
3929 check_malloced_chunk (av, victim, nb);
3930 void *p = chunk2mem (victim);
3931 alloc_perturb (p, bytes);
3932 return p;
3935 /* remove from unsorted list */
3936 if (__glibc_unlikely (bck->fd != victim))
3937 malloc_printerr ("malloc(): corrupted unsorted chunks 3");
3938 unsorted_chunks (av)->bk = bck;
3939 bck->fd = unsorted_chunks (av);
3941 /* Take now instead of binning if exact fit */
3943 if (size == nb)
3945 set_inuse_bit_at_offset (victim, size);
3946 if (av != &main_arena)
3947 set_non_main_arena (victim);
3948 #if USE_TCACHE
3949 /* Fill cache first, return to user only if cache fills.
3950 We may return one of these chunks later. */
3951 if (tcache_nb
3952 && tcache->counts[tc_idx] < mp_.tcache_count)
3954 tcache_put (victim, tc_idx);
3955 return_cached = 1;
3956 continue;
3958 else
3960 #endif
3961 check_malloced_chunk (av, victim, nb);
3962 void *p = chunk2mem (victim);
3963 alloc_perturb (p, bytes);
3964 return p;
3965 #if USE_TCACHE
3967 #endif
3970 /* place chunk in bin */
3972 if (in_smallbin_range (size))
3974 victim_index = smallbin_index (size);
3975 bck = bin_at (av, victim_index);
3976 fwd = bck->fd;
3978 else
3980 victim_index = largebin_index (size);
3981 bck = bin_at (av, victim_index);
3982 fwd = bck->fd;
3984 /* maintain large bins in sorted order */
3985 if (fwd != bck)
3987 /* Or with inuse bit to speed comparisons */
3988 size |= PREV_INUSE;
3989 /* if smaller than smallest, bypass loop below */
3990 assert (chunk_main_arena (bck->bk));
3991 if ((unsigned long) (size)
3992 < (unsigned long) chunksize_nomask (bck->bk))
3994 fwd = bck;
3995 bck = bck->bk;
3997 victim->fd_nextsize = fwd->fd;
3998 victim->bk_nextsize = fwd->fd->bk_nextsize;
3999 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
4001 else
4003 assert (chunk_main_arena (fwd));
4004 while ((unsigned long) size < chunksize_nomask (fwd))
4006 fwd = fwd->fd_nextsize;
4007 assert (chunk_main_arena (fwd));
4010 if ((unsigned long) size
4011 == (unsigned long) chunksize_nomask (fwd))
4012 /* Always insert in the second position. */
4013 fwd = fwd->fd;
4014 else
4016 victim->fd_nextsize = fwd;
4017 victim->bk_nextsize = fwd->bk_nextsize;
4018 if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd))
4019 malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)");
4020 fwd->bk_nextsize = victim;
4021 victim->bk_nextsize->fd_nextsize = victim;
4023 bck = fwd->bk;
4024 if (bck->fd != fwd)
4025 malloc_printerr ("malloc(): largebin double linked list corrupted (bk)");
4028 else
4029 victim->fd_nextsize = victim->bk_nextsize = victim;
4032 mark_bin (av, victim_index);
4033 victim->bk = bck;
4034 victim->fd = fwd;
4035 fwd->bk = victim;
4036 bck->fd = victim;
4038 #if USE_TCACHE
4039 /* If we've processed as many chunks as we're allowed while
4040 filling the cache, return one of the cached ones. */
4041 ++tcache_unsorted_count;
4042 if (return_cached
4043 && mp_.tcache_unsorted_limit > 0
4044 && tcache_unsorted_count > mp_.tcache_unsorted_limit)
4046 return tcache_get (tc_idx);
4048 #endif
4050 #define MAX_ITERS 10000
4051 if (++iters >= MAX_ITERS)
4052 break;
4055 #if USE_TCACHE
4056 /* If all the small chunks we found ended up cached, return one now. */
4057 if (return_cached)
4059 return tcache_get (tc_idx);
4061 #endif
4064 If a large request, scan through the chunks of current bin in
4065 sorted order to find smallest that fits. Use the skip list for this.
4068 if (!in_smallbin_range (nb))
4070 bin = bin_at (av, idx);
4072 /* skip scan if empty or largest chunk is too small */
4073 if ((victim = first (bin)) != bin
4074 && (unsigned long) chunksize_nomask (victim)
4075 >= (unsigned long) (nb))
4077 victim = victim->bk_nextsize;
4078 while (((unsigned long) (size = chunksize (victim)) <
4079 (unsigned long) (nb)))
4080 victim = victim->bk_nextsize;
4082 /* Avoid removing the first entry for a size so that the skip
4083 list does not have to be rerouted. */
4084 if (victim != last (bin)
4085 && chunksize_nomask (victim)
4086 == chunksize_nomask (victim->fd))
4087 victim = victim->fd;
4089 remainder_size = size - nb;
4090 unlink_chunk (av, victim);
4092 /* Exhaust */
4093 if (remainder_size < MINSIZE)
4095 set_inuse_bit_at_offset (victim, size);
4096 if (av != &main_arena)
4097 set_non_main_arena (victim);
4099 /* Split */
4100 else
4102 remainder = chunk_at_offset (victim, nb);
4103 /* We cannot assume the unsorted list is empty and therefore
4104 have to perform a complete insert here. */
4105 bck = unsorted_chunks (av);
4106 fwd = bck->fd;
4107 if (__glibc_unlikely (fwd->bk != bck))
4108 malloc_printerr ("malloc(): corrupted unsorted chunks");
4109 remainder->bk = bck;
4110 remainder->fd = fwd;
4111 bck->fd = remainder;
4112 fwd->bk = remainder;
4113 if (!in_smallbin_range (remainder_size))
4115 remainder->fd_nextsize = NULL;
4116 remainder->bk_nextsize = NULL;
4118 set_head (victim, nb | PREV_INUSE |
4119 (av != &main_arena ? NON_MAIN_ARENA : 0));
4120 set_head (remainder, remainder_size | PREV_INUSE);
4121 set_foot (remainder, remainder_size);
4123 check_malloced_chunk (av, victim, nb);
4124 void *p = chunk2mem (victim);
4125 alloc_perturb (p, bytes);
4126 return p;
4131 Search for a chunk by scanning bins, starting with next largest
4132 bin. This search is strictly by best-fit; i.e., the smallest
4133 (with ties going to approximately the least recently used) chunk
4134 that fits is selected.
4136 The bitmap avoids needing to check that most blocks are nonempty.
4137 The particular case of skipping all bins during warm-up phases
4138 when no chunks have been returned yet is faster than it might look.
4141 ++idx;
4142 bin = bin_at (av, idx);
4143 block = idx2block (idx);
4144 map = av->binmap[block];
4145 bit = idx2bit (idx);
4147 for (;; )
4149 /* Skip rest of block if there are no more set bits in this block. */
4150 if (bit > map || bit == 0)
4154 if (++block >= BINMAPSIZE) /* out of bins */
4155 goto use_top;
4157 while ((map = av->binmap[block]) == 0);
4159 bin = bin_at (av, (block << BINMAPSHIFT));
4160 bit = 1;
4163 /* Advance to bin with set bit. There must be one. */
4164 while ((bit & map) == 0)
4166 bin = next_bin (bin);
4167 bit <<= 1;
4168 assert (bit != 0);
4171 /* Inspect the bin. It is likely to be non-empty */
4172 victim = last (bin);
4174 /* If a false alarm (empty bin), clear the bit. */
4175 if (victim == bin)
4177 av->binmap[block] = map &= ~bit; /* Write through */
4178 bin = next_bin (bin);
4179 bit <<= 1;
4182 else
4184 size = chunksize (victim);
4186 /* We know the first chunk in this bin is big enough to use. */
4187 assert ((unsigned long) (size) >= (unsigned long) (nb));
4189 remainder_size = size - nb;
4191 /* unlink */
4192 unlink_chunk (av, victim);
4194 /* Exhaust */
4195 if (remainder_size < MINSIZE)
4197 set_inuse_bit_at_offset (victim, size);
4198 if (av != &main_arena)
4199 set_non_main_arena (victim);
4202 /* Split */
4203 else
4205 remainder = chunk_at_offset (victim, nb);
4207 /* We cannot assume the unsorted list is empty and therefore
4208 have to perform a complete insert here. */
4209 bck = unsorted_chunks (av);
4210 fwd = bck->fd;
4211 if (__glibc_unlikely (fwd->bk != bck))
4212 malloc_printerr ("malloc(): corrupted unsorted chunks 2");
4213 remainder->bk = bck;
4214 remainder->fd = fwd;
4215 bck->fd = remainder;
4216 fwd->bk = remainder;
4218 /* advertise as last remainder */
4219 if (in_smallbin_range (nb))
4220 av->last_remainder = remainder;
4221 if (!in_smallbin_range (remainder_size))
4223 remainder->fd_nextsize = NULL;
4224 remainder->bk_nextsize = NULL;
4226 set_head (victim, nb | PREV_INUSE |
4227 (av != &main_arena ? NON_MAIN_ARENA : 0));
4228 set_head (remainder, remainder_size | PREV_INUSE);
4229 set_foot (remainder, remainder_size);
4231 check_malloced_chunk (av, victim, nb);
4232 void *p = chunk2mem (victim);
4233 alloc_perturb (p, bytes);
4234 return p;
4238 use_top:
4240 If large enough, split off the chunk bordering the end of memory
4241 (held in av->top). Note that this is in accord with the best-fit
4242 search rule. In effect, av->top is treated as larger (and thus
4243 less well fitting) than any other available chunk since it can
4244 be extended to be as large as necessary (up to system
4245 limitations).
4247 We require that av->top always exists (i.e., has size >=
4248 MINSIZE) after initialization, so if it would otherwise be
4249 exhausted by current request, it is replenished. (The main
4250 reason for ensuring it exists is that we may need MINSIZE space
4251 to put in fenceposts in sysmalloc.)
4254 victim = av->top;
4255 size = chunksize (victim);
4257 if (__glibc_unlikely (size > av->system_mem))
4258 malloc_printerr ("malloc(): corrupted top size");
4260 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
4262 remainder_size = size - nb;
4263 remainder = chunk_at_offset (victim, nb);
4264 av->top = remainder;
4265 set_head (victim, nb | PREV_INUSE |
4266 (av != &main_arena ? NON_MAIN_ARENA : 0));
4267 set_head (remainder, remainder_size | PREV_INUSE);
4269 check_malloced_chunk (av, victim, nb);
4270 void *p = chunk2mem (victim);
4271 alloc_perturb (p, bytes);
4272 return p;
4275 /* When we are using atomic ops to free fast chunks we can get
4276 here for all block sizes. */
4277 else if (atomic_load_relaxed (&av->have_fastchunks))
4279 malloc_consolidate (av);
4280 /* restore original bin index */
4281 if (in_smallbin_range (nb))
4282 idx = smallbin_index (nb);
4283 else
4284 idx = largebin_index (nb);
4288 Otherwise, relay to handle system-dependent cases
4290 else
4292 void *p = sysmalloc (nb, av);
4293 if (p != NULL)
4294 alloc_perturb (p, bytes);
4295 return p;
4301 ------------------------------ free ------------------------------
4304 static void
4305 _int_free (mstate av, mchunkptr p, int have_lock)
4307 INTERNAL_SIZE_T size; /* its size */
4308 mfastbinptr *fb; /* associated fastbin */
4309 mchunkptr nextchunk; /* next contiguous chunk */
4310 INTERNAL_SIZE_T nextsize; /* its size */
4311 int nextinuse; /* true if nextchunk is used */
4312 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
4313 mchunkptr bck; /* misc temp for linking */
4314 mchunkptr fwd; /* misc temp for linking */
4316 size = chunksize (p);
4318 /* Little security check which won't hurt performance: the
4319 allocator never wrapps around at the end of the address space.
4320 Therefore we can exclude some size values which might appear
4321 here by accident or by "design" from some intruder. */
4322 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
4323 || __builtin_expect (misaligned_chunk (p), 0))
4324 malloc_printerr ("free(): invalid pointer");
4325 /* We know that each chunk is at least MINSIZE bytes in size or a
4326 multiple of MALLOC_ALIGNMENT. */
4327 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
4328 malloc_printerr ("free(): invalid size");
4330 check_inuse_chunk(av, p);
4332 #if USE_TCACHE
4334 size_t tc_idx = csize2tidx (size);
4335 if (tcache != NULL && tc_idx < mp_.tcache_bins)
4337 /* Check to see if it's already in the tcache. */
4338 tcache_entry *e = (tcache_entry *) chunk2mem (p);
4340 /* This test succeeds on double free. However, we don't 100%
4341 trust it (it also matches random payload data at a 1 in
4342 2^<size_t> chance), so verify it's not an unlikely
4343 coincidence before aborting. */
4344 if (__glibc_unlikely (e->key == tcache_key))
4346 tcache_entry *tmp;
4347 size_t cnt = 0;
4348 LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
4349 for (tmp = tcache->entries[tc_idx];
4350 tmp;
4351 tmp = REVEAL_PTR (tmp->next), ++cnt)
4353 if (cnt >= mp_.tcache_count)
4354 malloc_printerr ("free(): too many chunks detected in tcache");
4355 if (__glibc_unlikely (!aligned_OK (tmp)))
4356 malloc_printerr ("free(): unaligned chunk detected in tcache 2");
4357 if (tmp == e)
4358 malloc_printerr ("free(): double free detected in tcache 2");
4359 /* If we get here, it was a coincidence. We've wasted a
4360 few cycles, but don't abort. */
4364 if (tcache->counts[tc_idx] < mp_.tcache_count)
4366 tcache_put (p, tc_idx);
4367 return;
4371 #endif
4374 If eligible, place chunk on a fastbin so it can be found
4375 and used quickly in malloc.
4378 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
4380 #if TRIM_FASTBINS
4382 If TRIM_FASTBINS set, don't place chunks
4383 bordering top into fastbins
4385 && (chunk_at_offset(p, size) != av->top)
4386 #endif
4389 if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
4390 <= CHUNK_HDR_SZ, 0)
4391 || __builtin_expect (chunksize (chunk_at_offset (p, size))
4392 >= av->system_mem, 0))
4394 bool fail = true;
4395 /* We might not have a lock at this point and concurrent modifications
4396 of system_mem might result in a false positive. Redo the test after
4397 getting the lock. */
4398 if (!have_lock)
4400 __libc_lock_lock (av->mutex);
4401 fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ
4402 || chunksize (chunk_at_offset (p, size)) >= av->system_mem);
4403 __libc_lock_unlock (av->mutex);
4406 if (fail)
4407 malloc_printerr ("free(): invalid next size (fast)");
4410 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4412 atomic_store_relaxed (&av->have_fastchunks, true);
4413 unsigned int idx = fastbin_index(size);
4414 fb = &fastbin (av, idx);
4416 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
4417 mchunkptr old = *fb, old2;
4419 if (SINGLE_THREAD_P)
4421 /* Check that the top of the bin is not the record we are going to
4422 add (i.e., double free). */
4423 if (__builtin_expect (old == p, 0))
4424 malloc_printerr ("double free or corruption (fasttop)");
4425 p->fd = PROTECT_PTR (&p->fd, old);
4426 *fb = p;
4428 else
4431 /* Check that the top of the bin is not the record we are going to
4432 add (i.e., double free). */
4433 if (__builtin_expect (old == p, 0))
4434 malloc_printerr ("double free or corruption (fasttop)");
4435 old2 = old;
4436 p->fd = PROTECT_PTR (&p->fd, old);
4438 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2))
4439 != old2);
4441 /* Check that size of fastbin chunk at the top is the same as
4442 size of the chunk that we are adding. We can dereference OLD
4443 only if we have the lock, otherwise it might have already been
4444 allocated again. */
4445 if (have_lock && old != NULL
4446 && __builtin_expect (fastbin_index (chunksize (old)) != idx, 0))
4447 malloc_printerr ("invalid fastbin entry (free)");
4451 Consolidate other non-mmapped chunks as they arrive.
4454 else if (!chunk_is_mmapped(p)) {
4456 /* If we're single-threaded, don't lock the arena. */
4457 if (SINGLE_THREAD_P)
4458 have_lock = true;
4460 if (!have_lock)
4461 __libc_lock_lock (av->mutex);
4463 nextchunk = chunk_at_offset(p, size);
4465 /* Lightweight tests: check whether the block is already the
4466 top block. */
4467 if (__glibc_unlikely (p == av->top))
4468 malloc_printerr ("double free or corruption (top)");
4469 /* Or whether the next chunk is beyond the boundaries of the arena. */
4470 if (__builtin_expect (contiguous (av)
4471 && (char *) nextchunk
4472 >= ((char *) av->top + chunksize(av->top)), 0))
4473 malloc_printerr ("double free or corruption (out)");
4474 /* Or whether the block is actually not marked used. */
4475 if (__glibc_unlikely (!prev_inuse(nextchunk)))
4476 malloc_printerr ("double free or corruption (!prev)");
4478 nextsize = chunksize(nextchunk);
4479 if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0)
4480 || __builtin_expect (nextsize >= av->system_mem, 0))
4481 malloc_printerr ("free(): invalid next size (normal)");
4483 free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
4485 /* consolidate backward */
4486 if (!prev_inuse(p)) {
4487 prevsize = prev_size (p);
4488 size += prevsize;
4489 p = chunk_at_offset(p, -((long) prevsize));
4490 if (__glibc_unlikely (chunksize(p) != prevsize))
4491 malloc_printerr ("corrupted size vs. prev_size while consolidating");
4492 unlink_chunk (av, p);
4495 if (nextchunk != av->top) {
4496 /* get and clear inuse bit */
4497 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4499 /* consolidate forward */
4500 if (!nextinuse) {
4501 unlink_chunk (av, nextchunk);
4502 size += nextsize;
4503 } else
4504 clear_inuse_bit_at_offset(nextchunk, 0);
4507 Place the chunk in unsorted chunk list. Chunks are
4508 not placed into regular bins until after they have
4509 been given one chance to be used in malloc.
4512 bck = unsorted_chunks(av);
4513 fwd = bck->fd;
4514 if (__glibc_unlikely (fwd->bk != bck))
4515 malloc_printerr ("free(): corrupted unsorted chunks");
4516 p->fd = fwd;
4517 p->bk = bck;
4518 if (!in_smallbin_range(size))
4520 p->fd_nextsize = NULL;
4521 p->bk_nextsize = NULL;
4523 bck->fd = p;
4524 fwd->bk = p;
4526 set_head(p, size | PREV_INUSE);
4527 set_foot(p, size);
4529 check_free_chunk(av, p);
4533 If the chunk borders the current high end of memory,
4534 consolidate into top
4537 else {
4538 size += nextsize;
4539 set_head(p, size | PREV_INUSE);
4540 av->top = p;
4541 check_chunk(av, p);
4545 If freeing a large space, consolidate possibly-surrounding
4546 chunks. Then, if the total unused topmost memory exceeds trim
4547 threshold, ask malloc_trim to reduce top.
4549 Unless max_fast is 0, we don't know if there are fastbins
4550 bordering top, so we cannot tell for sure whether threshold
4551 has been reached unless fastbins are consolidated. But we
4552 don't want to consolidate on each free. As a compromise,
4553 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4554 is reached.
4557 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4558 if (atomic_load_relaxed (&av->have_fastchunks))
4559 malloc_consolidate(av);
4561 if (av == &main_arena) {
4562 #ifndef MORECORE_CANNOT_TRIM
4563 if ((unsigned long)(chunksize(av->top)) >=
4564 (unsigned long)(mp_.trim_threshold))
4565 systrim(mp_.top_pad, av);
4566 #endif
4567 } else {
4568 /* Always try heap_trim(), even if the top chunk is not
4569 large, because the corresponding heap might go away. */
4570 heap_info *heap = heap_for_ptr(top(av));
4572 assert(heap->ar_ptr == av);
4573 heap_trim(heap, mp_.top_pad);
4577 if (!have_lock)
4578 __libc_lock_unlock (av->mutex);
4581 If the chunk was allocated via mmap, release via munmap().
4584 else {
4585 munmap_chunk (p);
4590 ------------------------- malloc_consolidate -------------------------
4592 malloc_consolidate is a specialized version of free() that tears
4593 down chunks held in fastbins. Free itself cannot be used for this
4594 purpose since, among other things, it might place chunks back onto
4595 fastbins. So, instead, we need to use a minor variant of the same
4596 code.
4599 static void malloc_consolidate(mstate av)
4601 mfastbinptr* fb; /* current fastbin being consolidated */
4602 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4603 mchunkptr p; /* current chunk being consolidated */
4604 mchunkptr nextp; /* next chunk to consolidate */
4605 mchunkptr unsorted_bin; /* bin header */
4606 mchunkptr first_unsorted; /* chunk to link to */
4608 /* These have same use as in free() */
4609 mchunkptr nextchunk;
4610 INTERNAL_SIZE_T size;
4611 INTERNAL_SIZE_T nextsize;
4612 INTERNAL_SIZE_T prevsize;
4613 int nextinuse;
4615 atomic_store_relaxed (&av->have_fastchunks, false);
4617 unsorted_bin = unsorted_chunks(av);
4620 Remove each chunk from fast bin and consolidate it, placing it
4621 then in unsorted bin. Among other reasons for doing this,
4622 placing in unsorted bin avoids needing to calculate actual bins
4623 until malloc is sure that chunks aren't immediately going to be
4624 reused anyway.
4627 maxfb = &fastbin (av, NFASTBINS - 1);
4628 fb = &fastbin (av, 0);
4629 do {
4630 p = atomic_exchange_acq (fb, NULL);
4631 if (p != 0) {
4632 do {
4634 if (__glibc_unlikely (misaligned_chunk (p)))
4635 malloc_printerr ("malloc_consolidate(): "
4636 "unaligned fastbin chunk detected");
4638 unsigned int idx = fastbin_index (chunksize (p));
4639 if ((&fastbin (av, idx)) != fb)
4640 malloc_printerr ("malloc_consolidate(): invalid chunk size");
4643 check_inuse_chunk(av, p);
4644 nextp = REVEAL_PTR (p->fd);
4646 /* Slightly streamlined version of consolidation code in free() */
4647 size = chunksize (p);
4648 nextchunk = chunk_at_offset(p, size);
4649 nextsize = chunksize(nextchunk);
4651 if (!prev_inuse(p)) {
4652 prevsize = prev_size (p);
4653 size += prevsize;
4654 p = chunk_at_offset(p, -((long) prevsize));
4655 if (__glibc_unlikely (chunksize(p) != prevsize))
4656 malloc_printerr ("corrupted size vs. prev_size in fastbins");
4657 unlink_chunk (av, p);
4660 if (nextchunk != av->top) {
4661 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4663 if (!nextinuse) {
4664 size += nextsize;
4665 unlink_chunk (av, nextchunk);
4666 } else
4667 clear_inuse_bit_at_offset(nextchunk, 0);
4669 first_unsorted = unsorted_bin->fd;
4670 unsorted_bin->fd = p;
4671 first_unsorted->bk = p;
4673 if (!in_smallbin_range (size)) {
4674 p->fd_nextsize = NULL;
4675 p->bk_nextsize = NULL;
4678 set_head(p, size | PREV_INUSE);
4679 p->bk = unsorted_bin;
4680 p->fd = first_unsorted;
4681 set_foot(p, size);
4684 else {
4685 size += nextsize;
4686 set_head(p, size | PREV_INUSE);
4687 av->top = p;
4690 } while ( (p = nextp) != 0);
4693 } while (fb++ != maxfb);
4697 ------------------------------ realloc ------------------------------
4700 static void *
4701 _int_realloc (mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4702 INTERNAL_SIZE_T nb)
4704 mchunkptr newp; /* chunk to return */
4705 INTERNAL_SIZE_T newsize; /* its size */
4706 void* newmem; /* corresponding user mem */
4708 mchunkptr next; /* next contiguous chunk after oldp */
4710 mchunkptr remainder; /* extra space at end of newp */
4711 unsigned long remainder_size; /* its size */
4713 /* oldmem size */
4714 if (__builtin_expect (chunksize_nomask (oldp) <= CHUNK_HDR_SZ, 0)
4715 || __builtin_expect (oldsize >= av->system_mem, 0))
4716 malloc_printerr ("realloc(): invalid old size");
4718 check_inuse_chunk (av, oldp);
4720 /* All callers already filter out mmap'ed chunks. */
4721 assert (!chunk_is_mmapped (oldp));
4723 next = chunk_at_offset (oldp, oldsize);
4724 INTERNAL_SIZE_T nextsize = chunksize (next);
4725 if (__builtin_expect (chunksize_nomask (next) <= CHUNK_HDR_SZ, 0)
4726 || __builtin_expect (nextsize >= av->system_mem, 0))
4727 malloc_printerr ("realloc(): invalid next size");
4729 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4731 /* already big enough; split below */
4732 newp = oldp;
4733 newsize = oldsize;
4736 else
4738 /* Try to expand forward into top */
4739 if (next == av->top &&
4740 (unsigned long) (newsize = oldsize + nextsize) >=
4741 (unsigned long) (nb + MINSIZE))
4743 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4744 av->top = chunk_at_offset (oldp, nb);
4745 set_head (av->top, (newsize - nb) | PREV_INUSE);
4746 check_inuse_chunk (av, oldp);
4747 return tag_new_usable (chunk2mem (oldp));
4750 /* Try to expand forward into next chunk; split off remainder below */
4751 else if (next != av->top &&
4752 !inuse (next) &&
4753 (unsigned long) (newsize = oldsize + nextsize) >=
4754 (unsigned long) (nb))
4756 newp = oldp;
4757 unlink_chunk (av, next);
4760 /* allocate, copy, free */
4761 else
4763 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4764 if (newmem == 0)
4765 return 0; /* propagate failure */
4767 newp = mem2chunk (newmem);
4768 newsize = chunksize (newp);
4771 Avoid copy if newp is next chunk after oldp.
4773 if (newp == next)
4775 newsize += oldsize;
4776 newp = oldp;
4778 else
4780 void *oldmem = chunk2mem (oldp);
4781 size_t sz = memsize (oldp);
4782 (void) tag_region (oldmem, sz);
4783 newmem = tag_new_usable (newmem);
4784 memcpy (newmem, oldmem, sz);
4785 _int_free (av, oldp, 1);
4786 check_inuse_chunk (av, newp);
4787 return newmem;
4792 /* If possible, free extra space in old or extended chunk */
4794 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
4796 remainder_size = newsize - nb;
4798 if (remainder_size < MINSIZE) /* not enough extra to split off */
4800 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4801 set_inuse_bit_at_offset (newp, newsize);
4803 else /* split remainder */
4805 remainder = chunk_at_offset (newp, nb);
4806 /* Clear any user-space tags before writing the header. */
4807 remainder = tag_region (remainder, remainder_size);
4808 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4809 set_head (remainder, remainder_size | PREV_INUSE |
4810 (av != &main_arena ? NON_MAIN_ARENA : 0));
4811 /* Mark remainder as inuse so free() won't complain */
4812 set_inuse_bit_at_offset (remainder, remainder_size);
4813 _int_free (av, remainder, 1);
4816 check_inuse_chunk (av, newp);
4817 return tag_new_usable (chunk2mem (newp));
4821 ------------------------------ memalign ------------------------------
4824 static void *
4825 _int_memalign (mstate av, size_t alignment, size_t bytes)
4827 INTERNAL_SIZE_T nb; /* padded request size */
4828 char *m; /* memory returned by malloc call */
4829 mchunkptr p; /* corresponding chunk */
4830 char *brk; /* alignment point within p */
4831 mchunkptr newp; /* chunk to return */
4832 INTERNAL_SIZE_T newsize; /* its size */
4833 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4834 mchunkptr remainder; /* spare room at end to split off */
4835 unsigned long remainder_size; /* its size */
4836 INTERNAL_SIZE_T size;
4840 if (!checked_request2size (bytes, &nb))
4842 __set_errno (ENOMEM);
4843 return NULL;
4847 Strategy: find a spot within that chunk that meets the alignment
4848 request, and then possibly free the leading and trailing space.
4851 /* Call malloc with worst case padding to hit alignment. */
4853 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4855 if (m == 0)
4856 return 0; /* propagate failure */
4858 p = mem2chunk (m);
4860 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4862 { /*
4863 Find an aligned spot inside chunk. Since we need to give back
4864 leading space in a chunk of at least MINSIZE, if the first
4865 calculation places us at a spot with less than MINSIZE leader,
4866 we can move to the next aligned spot -- we've allocated enough
4867 total room so that this is always possible.
4869 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4870 - ((signed long) alignment));
4871 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4872 brk += alignment;
4874 newp = (mchunkptr) brk;
4875 leadsize = brk - (char *) (p);
4876 newsize = chunksize (p) - leadsize;
4878 /* For mmapped chunks, just adjust offset */
4879 if (chunk_is_mmapped (p))
4881 set_prev_size (newp, prev_size (p) + leadsize);
4882 set_head (newp, newsize | IS_MMAPPED);
4883 return chunk2mem (newp);
4886 /* Otherwise, give back leader, use the rest */
4887 set_head (newp, newsize | PREV_INUSE |
4888 (av != &main_arena ? NON_MAIN_ARENA : 0));
4889 set_inuse_bit_at_offset (newp, newsize);
4890 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4891 _int_free (av, p, 1);
4892 p = newp;
4894 assert (newsize >= nb &&
4895 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
4898 /* Also give back spare room at the end */
4899 if (!chunk_is_mmapped (p))
4901 size = chunksize (p);
4902 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4904 remainder_size = size - nb;
4905 remainder = chunk_at_offset (p, nb);
4906 set_head (remainder, remainder_size | PREV_INUSE |
4907 (av != &main_arena ? NON_MAIN_ARENA : 0));
4908 set_head_size (p, nb);
4909 _int_free (av, remainder, 1);
4913 check_inuse_chunk (av, p);
4914 return chunk2mem (p);
4919 ------------------------------ malloc_trim ------------------------------
4922 static int
4923 mtrim (mstate av, size_t pad)
4925 /* Ensure all blocks are consolidated. */
4926 malloc_consolidate (av);
4928 const size_t ps = GLRO (dl_pagesize);
4929 int psindex = bin_index (ps);
4930 const size_t psm1 = ps - 1;
4932 int result = 0;
4933 for (int i = 1; i < NBINS; ++i)
4934 if (i == 1 || i >= psindex)
4936 mbinptr bin = bin_at (av, i);
4938 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4940 INTERNAL_SIZE_T size = chunksize (p);
4942 if (size > psm1 + sizeof (struct malloc_chunk))
4944 /* See whether the chunk contains at least one unused page. */
4945 char *paligned_mem = (char *) (((uintptr_t) p
4946 + sizeof (struct malloc_chunk)
4947 + psm1) & ~psm1);
4949 assert ((char *) chunk2mem (p) + 2 * CHUNK_HDR_SZ
4950 <= paligned_mem);
4951 assert ((char *) p + size > paligned_mem);
4953 /* This is the size we could potentially free. */
4954 size -= paligned_mem - (char *) p;
4956 if (size > psm1)
4958 #if MALLOC_DEBUG
4959 /* When debugging we simulate destroying the memory
4960 content. */
4961 memset (paligned_mem, 0x89, size & ~psm1);
4962 #endif
4963 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
4965 result = 1;
4971 #ifndef MORECORE_CANNOT_TRIM
4972 return result | (av == &main_arena ? systrim (pad, av) : 0);
4974 #else
4975 return result;
4976 #endif
4981 __malloc_trim (size_t s)
4983 int result = 0;
4985 if (!__malloc_initialized)
4986 ptmalloc_init ();
4988 mstate ar_ptr = &main_arena;
4991 __libc_lock_lock (ar_ptr->mutex);
4992 result |= mtrim (ar_ptr, s);
4993 __libc_lock_unlock (ar_ptr->mutex);
4995 ar_ptr = ar_ptr->next;
4997 while (ar_ptr != &main_arena);
4999 return result;
5004 ------------------------- malloc_usable_size -------------------------
5007 static size_t
5008 musable (void *mem)
5010 mchunkptr p;
5011 if (mem != 0)
5013 size_t result = 0;
5015 p = mem2chunk (mem);
5017 if (chunk_is_mmapped (p))
5018 result = chunksize (p) - CHUNK_HDR_SZ;
5019 else if (inuse (p))
5020 result = memsize (p);
5022 return result;
5024 return 0;
5027 #if IS_IN (libc)
5028 size_t
5029 __malloc_usable_size (void *m)
5031 size_t result;
5033 result = musable (m);
5034 return result;
5036 #endif
5039 ------------------------------ mallinfo ------------------------------
5040 Accumulate malloc statistics for arena AV into M.
5042 static void
5043 int_mallinfo (mstate av, struct mallinfo2 *m)
5045 size_t i;
5046 mbinptr b;
5047 mchunkptr p;
5048 INTERNAL_SIZE_T avail;
5049 INTERNAL_SIZE_T fastavail;
5050 int nblocks;
5051 int nfastblocks;
5053 check_malloc_state (av);
5055 /* Account for top */
5056 avail = chunksize (av->top);
5057 nblocks = 1; /* top always exists */
5059 /* traverse fastbins */
5060 nfastblocks = 0;
5061 fastavail = 0;
5063 for (i = 0; i < NFASTBINS; ++i)
5065 for (p = fastbin (av, i);
5066 p != 0;
5067 p = REVEAL_PTR (p->fd))
5069 if (__glibc_unlikely (misaligned_chunk (p)))
5070 malloc_printerr ("int_mallinfo(): "
5071 "unaligned fastbin chunk detected");
5072 ++nfastblocks;
5073 fastavail += chunksize (p);
5077 avail += fastavail;
5079 /* traverse regular bins */
5080 for (i = 1; i < NBINS; ++i)
5082 b = bin_at (av, i);
5083 for (p = last (b); p != b; p = p->bk)
5085 ++nblocks;
5086 avail += chunksize (p);
5090 m->smblks += nfastblocks;
5091 m->ordblks += nblocks;
5092 m->fordblks += avail;
5093 m->uordblks += av->system_mem - avail;
5094 m->arena += av->system_mem;
5095 m->fsmblks += fastavail;
5096 if (av == &main_arena)
5098 m->hblks = mp_.n_mmaps;
5099 m->hblkhd = mp_.mmapped_mem;
5100 m->usmblks = 0;
5101 m->keepcost = chunksize (av->top);
5106 struct mallinfo2
5107 __libc_mallinfo2 (void)
5109 struct mallinfo2 m;
5110 mstate ar_ptr;
5112 if (!__malloc_initialized)
5113 ptmalloc_init ();
5115 memset (&m, 0, sizeof (m));
5116 ar_ptr = &main_arena;
5119 __libc_lock_lock (ar_ptr->mutex);
5120 int_mallinfo (ar_ptr, &m);
5121 __libc_lock_unlock (ar_ptr->mutex);
5123 ar_ptr = ar_ptr->next;
5125 while (ar_ptr != &main_arena);
5127 return m;
5129 libc_hidden_def (__libc_mallinfo2)
5131 struct mallinfo
5132 __libc_mallinfo (void)
5134 struct mallinfo m;
5135 struct mallinfo2 m2 = __libc_mallinfo2 ();
5137 m.arena = m2.arena;
5138 m.ordblks = m2.ordblks;
5139 m.smblks = m2.smblks;
5140 m.hblks = m2.hblks;
5141 m.hblkhd = m2.hblkhd;
5142 m.usmblks = m2.usmblks;
5143 m.fsmblks = m2.fsmblks;
5144 m.uordblks = m2.uordblks;
5145 m.fordblks = m2.fordblks;
5146 m.keepcost = m2.keepcost;
5148 return m;
5153 ------------------------------ malloc_stats ------------------------------
5156 void
5157 __malloc_stats (void)
5159 int i;
5160 mstate ar_ptr;
5161 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
5163 if (!__malloc_initialized)
5164 ptmalloc_init ();
5165 _IO_flockfile (stderr);
5166 int old_flags2 = stderr->_flags2;
5167 stderr->_flags2 |= _IO_FLAGS2_NOTCANCEL;
5168 for (i = 0, ar_ptr = &main_arena;; i++)
5170 struct mallinfo2 mi;
5172 memset (&mi, 0, sizeof (mi));
5173 __libc_lock_lock (ar_ptr->mutex);
5174 int_mallinfo (ar_ptr, &mi);
5175 fprintf (stderr, "Arena %d:\n", i);
5176 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
5177 fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
5178 #if MALLOC_DEBUG > 1
5179 if (i > 0)
5180 dump_heap (heap_for_ptr (top (ar_ptr)));
5181 #endif
5182 system_b += mi.arena;
5183 in_use_b += mi.uordblks;
5184 __libc_lock_unlock (ar_ptr->mutex);
5185 ar_ptr = ar_ptr->next;
5186 if (ar_ptr == &main_arena)
5187 break;
5189 fprintf (stderr, "Total (incl. mmap):\n");
5190 fprintf (stderr, "system bytes = %10u\n", system_b);
5191 fprintf (stderr, "in use bytes = %10u\n", in_use_b);
5192 fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
5193 fprintf (stderr, "max mmap bytes = %10lu\n",
5194 (unsigned long) mp_.max_mmapped_mem);
5195 stderr->_flags2 = old_flags2;
5196 _IO_funlockfile (stderr);
5201 ------------------------------ mallopt ------------------------------
5203 static __always_inline int
5204 do_set_trim_threshold (size_t value)
5206 LIBC_PROBE (memory_mallopt_trim_threshold, 3, value, mp_.trim_threshold,
5207 mp_.no_dyn_threshold);
5208 mp_.trim_threshold = value;
5209 mp_.no_dyn_threshold = 1;
5210 return 1;
5213 static __always_inline int
5214 do_set_top_pad (size_t value)
5216 LIBC_PROBE (memory_mallopt_top_pad, 3, value, mp_.top_pad,
5217 mp_.no_dyn_threshold);
5218 mp_.top_pad = value;
5219 mp_.no_dyn_threshold = 1;
5220 return 1;
5223 static __always_inline int
5224 do_set_mmap_threshold (size_t value)
5226 /* Forbid setting the threshold too high. */
5227 if (value <= HEAP_MAX_SIZE / 2)
5229 LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value, mp_.mmap_threshold,
5230 mp_.no_dyn_threshold);
5231 mp_.mmap_threshold = value;
5232 mp_.no_dyn_threshold = 1;
5233 return 1;
5235 return 0;
5238 static __always_inline int
5239 do_set_mmaps_max (int32_t value)
5241 LIBC_PROBE (memory_mallopt_mmap_max, 3, value, mp_.n_mmaps_max,
5242 mp_.no_dyn_threshold);
5243 mp_.n_mmaps_max = value;
5244 mp_.no_dyn_threshold = 1;
5245 return 1;
5248 static __always_inline int
5249 do_set_mallopt_check (int32_t value)
5251 return 1;
5254 static __always_inline int
5255 do_set_perturb_byte (int32_t value)
5257 LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
5258 perturb_byte = value;
5259 return 1;
5262 static __always_inline int
5263 do_set_arena_test (size_t value)
5265 LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
5266 mp_.arena_test = value;
5267 return 1;
5270 static __always_inline int
5271 do_set_arena_max (size_t value)
5273 LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
5274 mp_.arena_max = value;
5275 return 1;
5278 #if USE_TCACHE
5279 static __always_inline int
5280 do_set_tcache_max (size_t value)
5282 if (value <= MAX_TCACHE_SIZE)
5284 LIBC_PROBE (memory_tunable_tcache_max_bytes, 2, value, mp_.tcache_max_bytes);
5285 mp_.tcache_max_bytes = value;
5286 mp_.tcache_bins = csize2tidx (request2size(value)) + 1;
5287 return 1;
5289 return 0;
5292 static __always_inline int
5293 do_set_tcache_count (size_t value)
5295 if (value <= MAX_TCACHE_COUNT)
5297 LIBC_PROBE (memory_tunable_tcache_count, 2, value, mp_.tcache_count);
5298 mp_.tcache_count = value;
5299 return 1;
5301 return 0;
5304 static __always_inline int
5305 do_set_tcache_unsorted_limit (size_t value)
5307 LIBC_PROBE (memory_tunable_tcache_unsorted_limit, 2, value, mp_.tcache_unsorted_limit);
5308 mp_.tcache_unsorted_limit = value;
5309 return 1;
5311 #endif
5313 static inline int
5314 __always_inline
5315 do_set_mxfast (size_t value)
5317 if (value <= MAX_FAST_SIZE)
5319 LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
5320 set_max_fast (value);
5321 return 1;
5323 return 0;
5327 __libc_mallopt (int param_number, int value)
5329 mstate av = &main_arena;
5330 int res = 1;
5332 if (!__malloc_initialized)
5333 ptmalloc_init ();
5334 __libc_lock_lock (av->mutex);
5336 LIBC_PROBE (memory_mallopt, 2, param_number, value);
5338 /* We must consolidate main arena before changing max_fast
5339 (see definition of set_max_fast). */
5340 malloc_consolidate (av);
5342 /* Many of these helper functions take a size_t. We do not worry
5343 about overflow here, because negative int values will wrap to
5344 very large size_t values and the helpers have sufficient range
5345 checking for such conversions. Many of these helpers are also
5346 used by the tunables macros in arena.c. */
5348 switch (param_number)
5350 case M_MXFAST:
5351 res = do_set_mxfast (value);
5352 break;
5354 case M_TRIM_THRESHOLD:
5355 res = do_set_trim_threshold (value);
5356 break;
5358 case M_TOP_PAD:
5359 res = do_set_top_pad (value);
5360 break;
5362 case M_MMAP_THRESHOLD:
5363 res = do_set_mmap_threshold (value);
5364 break;
5366 case M_MMAP_MAX:
5367 res = do_set_mmaps_max (value);
5368 break;
5370 case M_CHECK_ACTION:
5371 res = do_set_mallopt_check (value);
5372 break;
5374 case M_PERTURB:
5375 res = do_set_perturb_byte (value);
5376 break;
5378 case M_ARENA_TEST:
5379 if (value > 0)
5380 res = do_set_arena_test (value);
5381 break;
5383 case M_ARENA_MAX:
5384 if (value > 0)
5385 res = do_set_arena_max (value);
5386 break;
5388 __libc_lock_unlock (av->mutex);
5389 return res;
5391 libc_hidden_def (__libc_mallopt)
5395 -------------------- Alternative MORECORE functions --------------------
5400 General Requirements for MORECORE.
5402 The MORECORE function must have the following properties:
5404 If MORECORE_CONTIGUOUS is false:
5406 * MORECORE must allocate in multiples of pagesize. It will
5407 only be called with arguments that are multiples of pagesize.
5409 * MORECORE(0) must return an address that is at least
5410 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
5412 else (i.e. If MORECORE_CONTIGUOUS is true):
5414 * Consecutive calls to MORECORE with positive arguments
5415 return increasing addresses, indicating that space has been
5416 contiguously extended.
5418 * MORECORE need not allocate in multiples of pagesize.
5419 Calls to MORECORE need not have args of multiples of pagesize.
5421 * MORECORE need not page-align.
5423 In either case:
5425 * MORECORE may allocate more memory than requested. (Or even less,
5426 but this will generally result in a malloc failure.)
5428 * MORECORE must not allocate memory when given argument zero, but
5429 instead return one past the end address of memory from previous
5430 nonzero call. This malloc does NOT call MORECORE(0)
5431 until at least one call with positive arguments is made, so
5432 the initial value returned is not important.
5434 * Even though consecutive calls to MORECORE need not return contiguous
5435 addresses, it must be OK for malloc'ed chunks to span multiple
5436 regions in those cases where they do happen to be contiguous.
5438 * MORECORE need not handle negative arguments -- it may instead
5439 just return MORECORE_FAILURE when given negative arguments.
5440 Negative arguments are always multiples of pagesize. MORECORE
5441 must not misinterpret negative args as large positive unsigned
5442 args. You can suppress all such calls from even occurring by defining
5443 MORECORE_CANNOT_TRIM,
5445 There is some variation across systems about the type of the
5446 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
5447 actually be size_t, because sbrk supports negative args, so it is
5448 normally the signed type of the same width as size_t (sometimes
5449 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
5450 matter though. Internally, we use "long" as arguments, which should
5451 work across all reasonable possibilities.
5453 Additionally, if MORECORE ever returns failure for a positive
5454 request, then mmap is used as a noncontiguous system allocator. This
5455 is a useful backup strategy for systems with holes in address spaces
5456 -- in this case sbrk cannot contiguously expand the heap, but mmap
5457 may be able to map noncontiguous space.
5459 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
5460 a function that always returns MORECORE_FAILURE.
5462 If you are using this malloc with something other than sbrk (or its
5463 emulation) to supply memory regions, you probably want to set
5464 MORECORE_CONTIGUOUS as false. As an example, here is a custom
5465 allocator kindly contributed for pre-OSX macOS. It uses virtually
5466 but not necessarily physically contiguous non-paged memory (locked
5467 in, present and won't get swapped out). You can use it by
5468 uncommenting this section, adding some #includes, and setting up the
5469 appropriate defines above:
5471 *#define MORECORE osMoreCore
5472 *#define MORECORE_CONTIGUOUS 0
5474 There is also a shutdown routine that should somehow be called for
5475 cleanup upon program exit.
5477 *#define MAX_POOL_ENTRIES 100
5478 *#define MINIMUM_MORECORE_SIZE (64 * 1024)
5479 static int next_os_pool;
5480 void *our_os_pools[MAX_POOL_ENTRIES];
5482 void *osMoreCore(int size)
5484 void *ptr = 0;
5485 static void *sbrk_top = 0;
5487 if (size > 0)
5489 if (size < MINIMUM_MORECORE_SIZE)
5490 size = MINIMUM_MORECORE_SIZE;
5491 if (CurrentExecutionLevel() == kTaskLevel)
5492 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
5493 if (ptr == 0)
5495 return (void *) MORECORE_FAILURE;
5497 // save ptrs so they can be freed during cleanup
5498 our_os_pools[next_os_pool] = ptr;
5499 next_os_pool++;
5500 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
5501 sbrk_top = (char *) ptr + size;
5502 return ptr;
5504 else if (size < 0)
5506 // we don't currently support shrink behavior
5507 return (void *) MORECORE_FAILURE;
5509 else
5511 return sbrk_top;
5515 // cleanup any allocated memory pools
5516 // called as last thing before shutting down driver
5518 void osCleanupMem(void)
5520 void **ptr;
5522 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
5523 if (*ptr)
5525 PoolDeallocate(*ptr);
5526 * ptr = 0;
5533 /* Helper code. */
5535 extern char **__libc_argv attribute_hidden;
5537 static void
5538 malloc_printerr (const char *str)
5540 #if IS_IN (libc)
5541 __libc_message (do_abort, "%s\n", str);
5542 #else
5543 __libc_fatal (str);
5544 #endif
5545 __builtin_unreachable ();
5548 #if IS_IN (libc)
5549 /* We need a wrapper function for one of the additions of POSIX. */
5551 __posix_memalign (void **memptr, size_t alignment, size_t size)
5553 void *mem;
5555 if (!__malloc_initialized)
5556 ptmalloc_init ();
5558 /* Test whether the SIZE argument is valid. It must be a power of
5559 two multiple of sizeof (void *). */
5560 if (alignment % sizeof (void *) != 0
5561 || !powerof2 (alignment / sizeof (void *))
5562 || alignment == 0)
5563 return EINVAL;
5566 void *address = RETURN_ADDRESS (0);
5567 mem = _mid_memalign (alignment, size, address);
5569 if (mem != NULL)
5571 *memptr = mem;
5572 return 0;
5575 return ENOMEM;
5577 weak_alias (__posix_memalign, posix_memalign)
5578 #endif
5582 __malloc_info (int options, FILE *fp)
5584 /* For now, at least. */
5585 if (options != 0)
5586 return EINVAL;
5588 int n = 0;
5589 size_t total_nblocks = 0;
5590 size_t total_nfastblocks = 0;
5591 size_t total_avail = 0;
5592 size_t total_fastavail = 0;
5593 size_t total_system = 0;
5594 size_t total_max_system = 0;
5595 size_t total_aspace = 0;
5596 size_t total_aspace_mprotect = 0;
5600 if (!__malloc_initialized)
5601 ptmalloc_init ();
5603 fputs ("<malloc version=\"1\">\n", fp);
5605 /* Iterate over all arenas currently in use. */
5606 mstate ar_ptr = &main_arena;
5609 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
5611 size_t nblocks = 0;
5612 size_t nfastblocks = 0;
5613 size_t avail = 0;
5614 size_t fastavail = 0;
5615 struct
5617 size_t from;
5618 size_t to;
5619 size_t total;
5620 size_t count;
5621 } sizes[NFASTBINS + NBINS - 1];
5622 #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
5624 __libc_lock_lock (ar_ptr->mutex);
5626 /* Account for top chunk. The top-most available chunk is
5627 treated specially and is never in any bin. See "initial_top"
5628 comments. */
5629 avail = chunksize (ar_ptr->top);
5630 nblocks = 1; /* Top always exists. */
5632 for (size_t i = 0; i < NFASTBINS; ++i)
5634 mchunkptr p = fastbin (ar_ptr, i);
5635 if (p != NULL)
5637 size_t nthissize = 0;
5638 size_t thissize = chunksize (p);
5640 while (p != NULL)
5642 if (__glibc_unlikely (misaligned_chunk (p)))
5643 malloc_printerr ("__malloc_info(): "
5644 "unaligned fastbin chunk detected");
5645 ++nthissize;
5646 p = REVEAL_PTR (p->fd);
5649 fastavail += nthissize * thissize;
5650 nfastblocks += nthissize;
5651 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
5652 sizes[i].to = thissize;
5653 sizes[i].count = nthissize;
5655 else
5656 sizes[i].from = sizes[i].to = sizes[i].count = 0;
5658 sizes[i].total = sizes[i].count * sizes[i].to;
5662 mbinptr bin;
5663 struct malloc_chunk *r;
5665 for (size_t i = 1; i < NBINS; ++i)
5667 bin = bin_at (ar_ptr, i);
5668 r = bin->fd;
5669 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5670 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5671 = sizes[NFASTBINS - 1 + i].count = 0;
5673 if (r != NULL)
5674 while (r != bin)
5676 size_t r_size = chunksize_nomask (r);
5677 ++sizes[NFASTBINS - 1 + i].count;
5678 sizes[NFASTBINS - 1 + i].total += r_size;
5679 sizes[NFASTBINS - 1 + i].from
5680 = MIN (sizes[NFASTBINS - 1 + i].from, r_size);
5681 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5682 r_size);
5684 r = r->fd;
5687 if (sizes[NFASTBINS - 1 + i].count == 0)
5688 sizes[NFASTBINS - 1 + i].from = 0;
5689 nblocks += sizes[NFASTBINS - 1 + i].count;
5690 avail += sizes[NFASTBINS - 1 + i].total;
5693 size_t heap_size = 0;
5694 size_t heap_mprotect_size = 0;
5695 size_t heap_count = 0;
5696 if (ar_ptr != &main_arena)
5698 /* Iterate over the arena heaps from back to front. */
5699 heap_info *heap = heap_for_ptr (top (ar_ptr));
5702 heap_size += heap->size;
5703 heap_mprotect_size += heap->mprotect_size;
5704 heap = heap->prev;
5705 ++heap_count;
5707 while (heap != NULL);
5710 __libc_lock_unlock (ar_ptr->mutex);
5712 total_nfastblocks += nfastblocks;
5713 total_fastavail += fastavail;
5715 total_nblocks += nblocks;
5716 total_avail += avail;
5718 for (size_t i = 0; i < nsizes; ++i)
5719 if (sizes[i].count != 0 && i != NFASTBINS)
5720 fprintf (fp, "\
5721 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5722 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
5724 if (sizes[NFASTBINS].count != 0)
5725 fprintf (fp, "\
5726 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5727 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5728 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
5730 total_system += ar_ptr->system_mem;
5731 total_max_system += ar_ptr->max_system_mem;
5733 fprintf (fp,
5734 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5735 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5736 "<system type=\"current\" size=\"%zu\"/>\n"
5737 "<system type=\"max\" size=\"%zu\"/>\n",
5738 nfastblocks, fastavail, nblocks, avail,
5739 ar_ptr->system_mem, ar_ptr->max_system_mem);
5741 if (ar_ptr != &main_arena)
5743 fprintf (fp,
5744 "<aspace type=\"total\" size=\"%zu\"/>\n"
5745 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5746 "<aspace type=\"subheaps\" size=\"%zu\"/>\n",
5747 heap_size, heap_mprotect_size, heap_count);
5748 total_aspace += heap_size;
5749 total_aspace_mprotect += heap_mprotect_size;
5751 else
5753 fprintf (fp,
5754 "<aspace type=\"total\" size=\"%zu\"/>\n"
5755 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5756 ar_ptr->system_mem, ar_ptr->system_mem);
5757 total_aspace += ar_ptr->system_mem;
5758 total_aspace_mprotect += ar_ptr->system_mem;
5761 fputs ("</heap>\n", fp);
5762 ar_ptr = ar_ptr->next;
5764 while (ar_ptr != &main_arena);
5766 fprintf (fp,
5767 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5768 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5769 "<total type=\"mmap\" count=\"%d\" size=\"%zu\"/>\n"
5770 "<system type=\"current\" size=\"%zu\"/>\n"
5771 "<system type=\"max\" size=\"%zu\"/>\n"
5772 "<aspace type=\"total\" size=\"%zu\"/>\n"
5773 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5774 "</malloc>\n",
5775 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
5776 mp_.n_mmaps, mp_.mmapped_mem,
5777 total_system, total_max_system,
5778 total_aspace, total_aspace_mprotect);
5780 return 0;
5782 #if IS_IN (libc)
5783 weak_alias (__malloc_info, malloc_info)
5785 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5786 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5787 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5788 strong_alias (__libc_memalign, __memalign)
5789 weak_alias (__libc_memalign, memalign)
5790 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5791 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5792 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5793 strong_alias (__libc_mallinfo, __mallinfo)
5794 weak_alias (__libc_mallinfo, mallinfo)
5795 strong_alias (__libc_mallinfo2, __mallinfo2)
5796 weak_alias (__libc_mallinfo2, mallinfo2)
5797 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5799 weak_alias (__malloc_stats, malloc_stats)
5800 weak_alias (__malloc_usable_size, malloc_usable_size)
5801 weak_alias (__malloc_trim, malloc_trim)
5802 #endif
5804 #if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_26)
5805 compat_symbol (libc, __libc_free, cfree, GLIBC_2_0);
5806 #endif
5808 /* ------------------------------------------------------------
5809 History:
5811 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
5815 * Local variables:
5816 * c-basic-offset: 2
5817 * End: