]> git.ipfire.org Git - thirdparty/glibc.git/blame - malloc/malloc.c
Prevent check-local-headers.sh hang.
[thirdparty/glibc.git] / malloc / malloc.c
CommitLineData
56137dbc 1/* Malloc implementation for multiple threads without lock contention.
b168057a 2 Copyright (C) 1996-2015 Free Software Foundation, Inc.
f65fd747 3 This file is part of the GNU C Library.
fa8d436c
UD
4 Contributed by Wolfram Gloger <wg@malloc.de>
5 and Doug Lea <dl@cs.oswego.edu>, 2001.
f65fd747
UD
6
7 The GNU C Library is free software; you can redistribute it and/or
cc7375ce
RM
8 modify it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
fa8d436c 10 License, or (at your option) any later version.
f65fd747
UD
11
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
cc7375ce 15 Lesser General Public License for more details.
f65fd747 16
cc7375ce 17 You should have received a copy of the GNU Lesser General Public
59ba27a6
PE
18 License along with the GNU C Library; see the file COPYING.LIB. If
19 not, see <http://www.gnu.org/licenses/>. */
f65fd747 20
fa8d436c
UD
21/*
22 This is a version (aka ptmalloc2) of malloc/free/realloc written by
23 Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
24
bb2ce416 25 There have been substantial changes made after the integration into
da2d2fb6
UD
26 glibc in all parts of the code. Do not look for much commonality
27 with the ptmalloc2 version.
28
fa8d436c 29* Version ptmalloc2-20011215
fa8d436c
UD
30 based on:
31 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
f65fd747 32
fa8d436c 33* Quickstart
f65fd747 34
fa8d436c
UD
35 In order to compile this implementation, a Makefile is provided with
36 the ptmalloc2 distribution, which has pre-defined targets for some
37 popular systems (e.g. "make posix" for Posix threads). All that is
38 typically required with regard to compiler flags is the selection of
39 the thread package via defining one out of USE_PTHREADS, USE_THR or
40 USE_SPROC. Check the thread-m.h file for what effects this has.
41 Many/most systems will additionally require USE_TSD_DATA_HACK to be
42 defined, so this is the default for "make posix".
f65fd747
UD
43
44* Why use this malloc?
45
46 This is not the fastest, most space-conserving, most portable, or
47 most tunable malloc ever written. However it is among the fastest
48 while also being among the most space-conserving, portable and tunable.
49 Consistent balance across these factors results in a good general-purpose
fa8d436c
UD
50 allocator for malloc-intensive programs.
51
52 The main properties of the algorithms are:
53 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
54 with ties normally decided via FIFO (i.e. least recently used).
55 * For small (<= 64 bytes by default) requests, it is a caching
56 allocator, that maintains pools of quickly recycled chunks.
57 * In between, and for combinations of large and small requests, it does
58 the best it can trying to meet both goals at once.
59 * For very large requests (>= 128KB by default), it relies on system
60 memory mapping facilities, if supported.
61
62 For a longer but slightly out of date high-level description, see
63 http://gee.cs.oswego.edu/dl/html/malloc.html
64
65 You may already by default be using a C library containing a malloc
66 that is based on some version of this malloc (for example in
67 linux). You might still want to use the one in this file in order to
68 customize settings or to avoid overheads associated with library
69 versions.
70
71* Contents, described in more detail in "description of public routines" below.
72
73 Standard (ANSI/SVID/...) functions:
74 malloc(size_t n);
75 calloc(size_t n_elements, size_t element_size);
22a89187
UD
76 free(void* p);
77 realloc(void* p, size_t n);
fa8d436c
UD
78 memalign(size_t alignment, size_t n);
79 valloc(size_t n);
80 mallinfo()
81 mallopt(int parameter_number, int parameter_value)
82
83 Additional functions:
22a89187
UD
84 independent_calloc(size_t n_elements, size_t size, void* chunks[]);
85 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
fa8d436c 86 pvalloc(size_t n);
22a89187 87 cfree(void* p);
fa8d436c 88 malloc_trim(size_t pad);
22a89187 89 malloc_usable_size(void* p);
fa8d436c 90 malloc_stats();
f65fd747
UD
91
92* Vital statistics:
93
fa8d436c 94 Supported pointer representation: 4 or 8 bytes
a9177ff5 95 Supported size_t representation: 4 or 8 bytes
f65fd747 96 Note that size_t is allowed to be 4 bytes even if pointers are 8.
fa8d436c
UD
97 You can adjust this by defining INTERNAL_SIZE_T
98
99 Alignment: 2 * sizeof(size_t) (default)
100 (i.e., 8 byte alignment with 4byte size_t). This suffices for
101 nearly all current machines and C compilers. However, you can
102 define MALLOC_ALIGNMENT to be wider than this if necessary.
f65fd747 103
fa8d436c
UD
104 Minimum overhead per allocated chunk: 4 or 8 bytes
105 Each malloced chunk has a hidden word of overhead holding size
f65fd747
UD
106 and status information.
107
108 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
72f90263 109 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
f65fd747
UD
110
111 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
112 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
fa8d436c
UD
113 needed; 4 (8) for a trailing size field and 8 (16) bytes for
114 free list pointers. Thus, the minimum allocatable size is
115 16/24/32 bytes.
f65fd747
UD
116
117 Even a request for zero bytes (i.e., malloc(0)) returns a
118 pointer to something of the minimum allocatable size.
119
fa8d436c
UD
120 The maximum overhead wastage (i.e., number of extra bytes
121 allocated than were requested in malloc) is less than or equal
122 to the minimum size, except for requests >= mmap_threshold that
123 are serviced via mmap(), where the worst case wastage is 2 *
124 sizeof(size_t) bytes plus the remainder from a system page (the
125 minimal mmap unit); typically 4096 or 8192 bytes.
f65fd747 126
a9177ff5 127 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
72f90263 128 8-byte size_t: 2^64 minus about two pages
fa8d436c
UD
129
130 It is assumed that (possibly signed) size_t values suffice to
f65fd747
UD
131 represent chunk sizes. `Possibly signed' is due to the fact
132 that `size_t' may be defined on a system as either a signed or
fa8d436c
UD
133 an unsigned type. The ISO C standard says that it must be
134 unsigned, but a few systems are known not to adhere to this.
135 Additionally, even when size_t is unsigned, sbrk (which is by
136 default used to obtain memory from system) accepts signed
137 arguments, and may not be able to handle size_t-wide arguments
138 with negative sign bit. Generally, values that would
139 appear as negative after accounting for overhead and alignment
140 are supported only via mmap(), which does not have this
141 limitation.
142
143 Requests for sizes outside the allowed range will perform an optional
144 failure action and then return null. (Requests may also
145 also fail because a system is out of memory.)
146
22a89187 147 Thread-safety: thread-safe
fa8d436c
UD
148
149 Compliance: I believe it is compliant with the 1997 Single Unix Specification
2b0fba75 150 Also SVID/XPG, ANSI C, and probably others as well.
f65fd747
UD
151
152* Synopsis of compile-time options:
153
154 People have reported using previous versions of this malloc on all
155 versions of Unix, sometimes by tweaking some of the defines
22a89187 156 below. It has been tested most extensively on Solaris and Linux.
fa8d436c
UD
157 People also report using it in stand-alone embedded systems.
158
159 The implementation is in straight, hand-tuned ANSI C. It is not
160 at all modular. (Sorry!) It uses a lot of macros. To be at all
161 usable, this code should be compiled using an optimizing compiler
162 (for example gcc -O3) that can simplify expressions and control
163 paths. (FAQ: some macros import variables as arguments rather than
164 declare locals because people reported that some debuggers
165 otherwise get confused.)
166
167 OPTION DEFAULT VALUE
168
169 Compilation Environment options:
170
2a26ef3a 171 HAVE_MREMAP 0
fa8d436c
UD
172
173 Changing default word sizes:
174
175 INTERNAL_SIZE_T size_t
073f560e
UD
176 MALLOC_ALIGNMENT MAX (2 * sizeof(INTERNAL_SIZE_T),
177 __alignof__ (long double))
fa8d436c
UD
178
179 Configuration and functionality options:
180
fa8d436c
UD
181 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
182 USE_MALLOC_LOCK NOT defined
183 MALLOC_DEBUG NOT defined
184 REALLOC_ZERO_BYTES_FREES 1
fa8d436c
UD
185 TRIM_FASTBINS 0
186
187 Options for customizing MORECORE:
188
189 MORECORE sbrk
190 MORECORE_FAILURE -1
a9177ff5 191 MORECORE_CONTIGUOUS 1
fa8d436c
UD
192 MORECORE_CANNOT_TRIM NOT defined
193 MORECORE_CLEARS 1
a9177ff5 194 MMAP_AS_MORECORE_SIZE (1024 * 1024)
fa8d436c
UD
195
196 Tuning options that are also dynamically changeable via mallopt:
197
425ce2ed 198 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
fa8d436c
UD
199 DEFAULT_TRIM_THRESHOLD 128 * 1024
200 DEFAULT_TOP_PAD 0
201 DEFAULT_MMAP_THRESHOLD 128 * 1024
202 DEFAULT_MMAP_MAX 65536
203
204 There are several other #defined constants and macros that you
205 probably don't want to touch unless you are extending or adapting malloc. */
f65fd747
UD
206
207/*
22a89187 208 void* is the pointer type that malloc should say it returns
f65fd747
UD
209*/
210
22a89187
UD
211#ifndef void
212#define void void
213#endif /*void*/
f65fd747 214
fa8d436c
UD
215#include <stddef.h> /* for size_t */
216#include <stdlib.h> /* for getenv(), abort() */
2a26ef3a 217#include <unistd.h> /* for __libc_enable_secure */
f65fd747 218
3c6904fb 219#include <malloc-machine.h>
2a26ef3a 220#include <malloc-sysdep.h>
3c6904fb 221
425ce2ed 222#include <atomic.h>
eb96ffb0 223#include <_itoa.h>
e404fb16 224#include <bits/wordsize.h>
425ce2ed 225#include <sys/sysinfo.h>
c56da3a3 226
02d46fc4
UD
227#include <ldsodefs.h>
228
fa8d436c 229#include <unistd.h>
fa8d436c 230#include <stdio.h> /* needed for malloc_stats */
8e58439c 231#include <errno.h>
f65fd747 232
66274218
AJ
233#include <shlib-compat.h>
234
5d78bb43
UD
235/* For uintptr_t. */
236#include <stdint.h>
f65fd747 237
3e030bd5
UD
238/* For va_arg, va_start, va_end. */
239#include <stdarg.h>
240
070906ff
RM
241/* For MIN, MAX, powerof2. */
242#include <sys/param.h>
243
8a35c3fe
CD
244/* For ALIGN_UP. */
245#include <libc-internal.h>
246
c0f62c56 247
fa8d436c
UD
248/*
249 Debugging:
250
251 Because freed chunks may be overwritten with bookkeeping fields, this
252 malloc will often die when freed memory is overwritten by user
253 programs. This can be very effective (albeit in an annoying way)
254 in helping track down dangling pointers.
255
256 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
257 enabled that will catch more memory errors. You probably won't be
258 able to make much sense of the actual assertion errors, but they
259 should help you locate incorrectly overwritten memory. The checking
260 is fairly extensive, and will slow down execution
261 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
262 will attempt to check every non-mmapped allocated and free chunk in
263 the course of computing the summmaries. (By nature, mmapped regions
264 cannot be checked very much automatically.)
265
266 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
267 this code. The assertions in the check routines spell out in more
268 detail the assumptions and invariants underlying the algorithms.
269
270 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
271 checking that all accesses to malloced memory stay within their
272 bounds. However, there are several add-ons and adaptations of this
273 or other mallocs available that do this.
f65fd747
UD
274*/
275
439bda32
WN
276#ifndef MALLOC_DEBUG
277#define MALLOC_DEBUG 0
278#endif
279
72f90263
UD
280#ifdef NDEBUG
281# define assert(expr) ((void) 0)
282#else
283# define assert(expr) \
284 ((expr) \
285 ? ((void) 0) \
286 : __malloc_assert (__STRING (expr), __FILE__, __LINE__, __func__))
287
288extern const char *__progname;
289
290static void
291__malloc_assert (const char *assertion, const char *file, unsigned int line,
292 const char *function)
293{
294 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
295 __progname, __progname[0] ? ": " : "",
296 file, line,
297 function ? function : "", function ? ": " : "",
298 assertion);
299 fflush (stderr);
300 abort ();
301}
302#endif
f65fd747
UD
303
304
305/*
306 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
fa8d436c
UD
307 of chunk sizes.
308
309 The default version is the same as size_t.
310
311 While not strictly necessary, it is best to define this as an
312 unsigned type, even if size_t is a signed type. This may avoid some
313 artificial size limitations on some systems.
314
315 On a 64-bit machine, you may be able to reduce malloc overhead by
316 defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
317 expense of not being able to handle more than 2^32 of malloced
318 space. If this limitation is acceptable, you are encouraged to set
319 this unless you are on a platform requiring 16byte alignments. In
320 this case the alignment requirements turn out to negate any
321 potential advantages of decreasing size_t word size.
322
323 Implementors: Beware of the possible combinations of:
324 - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
325 and might be the same width as int or as long
326 - size_t might have different width and signedness as INTERNAL_SIZE_T
327 - int and long might be 32 or 64 bits, and might be the same width
328 To deal with this, most comparisons and difference computations
329 among INTERNAL_SIZE_Ts should cast them to unsigned long, being
330 aware of the fact that casting an unsigned int to a wider long does
331 not sign-extend. (This also makes checking for negative numbers
332 awkward.) Some of these casts result in harmless compiler warnings
333 on some systems.
f65fd747
UD
334*/
335
336#ifndef INTERNAL_SIZE_T
337#define INTERNAL_SIZE_T size_t
338#endif
339
fa8d436c
UD
340/* The corresponding word size */
341#define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
342
343
344/*
345 MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
346 It must be a power of two at least 2 * SIZE_SZ, even on machines
347 for which smaller alignments would suffice. It may be defined as
348 larger than this though. Note however that code and data structures
349 are optimized for the case of 8-byte alignment.
350*/
351
352
353#ifndef MALLOC_ALIGNMENT
cbc00a03
RM
354# if !SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_16)
355/* This is the correct definition when there is no past ABI to constrain it.
356
357 Among configurations with a past ABI constraint, it differs from
358 2*SIZE_SZ only on powerpc32. For the time being, changing this is
359 causing more compatibility problems due to malloc_get_state and
360 malloc_set_state than will returning blocks not adequately aligned for
361 long double objects under -mlong-double-128. */
362
6c8dbf00
OB
363# define MALLOC_ALIGNMENT (2 *SIZE_SZ < __alignof__ (long double) \
364 ? __alignof__ (long double) : 2 *SIZE_SZ)
cbc00a03 365# else
6c8dbf00 366# define MALLOC_ALIGNMENT (2 *SIZE_SZ)
cbc00a03 367# endif
fa8d436c
UD
368#endif
369
370/* The corresponding bit mask value */
371#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
372
373
374
375/*
376 REALLOC_ZERO_BYTES_FREES should be set if a call to
377 realloc with zero bytes should be the same as a call to free.
378 This is required by the C standard. Otherwise, since this malloc
379 returns a unique pointer for malloc(0), so does realloc(p, 0).
380*/
381
382#ifndef REALLOC_ZERO_BYTES_FREES
383#define REALLOC_ZERO_BYTES_FREES 1
384#endif
385
386/*
387 TRIM_FASTBINS controls whether free() of a very small chunk can
388 immediately lead to trimming. Setting to true (1) can reduce memory
389 footprint, but will almost always slow down programs that use a lot
390 of small chunks.
391
392 Define this only if you are willing to give up some speed to more
393 aggressively reduce system-level memory footprint when releasing
394 memory in programs that use many small chunks. You can get
395 essentially the same effect by setting MXFAST to 0, but this can
396 lead to even greater slowdowns in programs using many small chunks.
397 TRIM_FASTBINS is an in-between compile-time option, that disables
398 only those chunks bordering topmost memory from being placed in
399 fastbins.
400*/
401
402#ifndef TRIM_FASTBINS
403#define TRIM_FASTBINS 0
404#endif
405
406
3b49edc0 407/* Definition for getting more memory from the OS. */
fa8d436c
UD
408#define MORECORE (*__morecore)
409#define MORECORE_FAILURE 0
22a89187
UD
410void * __default_morecore (ptrdiff_t);
411void *(*__morecore)(ptrdiff_t) = __default_morecore;
f65fd747 412
f65fd747 413
22a89187 414#include <string.h>
f65fd747 415
fa8d436c
UD
416/*
417 MORECORE-related declarations. By default, rely on sbrk
418*/
09f5e163 419
f65fd747 420
fa8d436c
UD
421/*
422 MORECORE is the name of the routine to call to obtain more memory
423 from the system. See below for general guidance on writing
424 alternative MORECORE functions, as well as a version for WIN32 and a
425 sample version for pre-OSX macos.
426*/
f65fd747 427
fa8d436c
UD
428#ifndef MORECORE
429#define MORECORE sbrk
430#endif
f65fd747 431
fa8d436c
UD
432/*
433 MORECORE_FAILURE is the value returned upon failure of MORECORE
434 as well as mmap. Since it cannot be an otherwise valid memory address,
435 and must reflect values of standard sys calls, you probably ought not
436 try to redefine it.
437*/
09f5e163 438
fa8d436c
UD
439#ifndef MORECORE_FAILURE
440#define MORECORE_FAILURE (-1)
441#endif
442
443/*
444 If MORECORE_CONTIGUOUS is true, take advantage of fact that
445 consecutive calls to MORECORE with positive arguments always return
446 contiguous increasing addresses. This is true of unix sbrk. Even
447 if not defined, when regions happen to be contiguous, malloc will
448 permit allocations spanning regions obtained from different
449 calls. But defining this when applicable enables some stronger
450 consistency checks and space efficiencies.
451*/
f65fd747 452
fa8d436c
UD
453#ifndef MORECORE_CONTIGUOUS
454#define MORECORE_CONTIGUOUS 1
f65fd747
UD
455#endif
456
fa8d436c
UD
457/*
458 Define MORECORE_CANNOT_TRIM if your version of MORECORE
459 cannot release space back to the system when given negative
460 arguments. This is generally necessary only if you are using
461 a hand-crafted MORECORE function that cannot handle negative arguments.
462*/
463
464/* #define MORECORE_CANNOT_TRIM */
f65fd747 465
fa8d436c
UD
466/* MORECORE_CLEARS (default 1)
467 The degree to which the routine mapped to MORECORE zeroes out
468 memory: never (0), only for newly allocated space (1) or always
469 (2). The distinction between (1) and (2) is necessary because on
470 some systems, if the application first decrements and then
471 increments the break value, the contents of the reallocated space
472 are unspecified.
6c8dbf00 473 */
fa8d436c
UD
474
475#ifndef MORECORE_CLEARS
6c8dbf00 476# define MORECORE_CLEARS 1
7cabd57c
UD
477#endif
478
fa8d436c 479
a9177ff5 480/*
fa8d436c 481 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
22a89187
UD
482 sbrk fails, and mmap is used as a backup. The value must be a
483 multiple of page size. This backup strategy generally applies only
484 when systems have "holes" in address space, so sbrk cannot perform
485 contiguous expansion, but there is still space available on system.
486 On systems for which this is known to be useful (i.e. most linux
487 kernels), this occurs only when programs allocate huge amounts of
488 memory. Between this, and the fact that mmap regions tend to be
489 limited, the size should be large, to avoid too many mmap calls and
490 thus avoid running out of kernel resources. */
fa8d436c
UD
491
492#ifndef MMAP_AS_MORECORE_SIZE
493#define MMAP_AS_MORECORE_SIZE (1024 * 1024)
f65fd747
UD
494#endif
495
496/*
497 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
2a26ef3a 498 large blocks.
f65fd747
UD
499*/
500
501#ifndef HAVE_MREMAP
fa8d436c 502#define HAVE_MREMAP 0
f65fd747
UD
503#endif
504
f65fd747 505
f65fd747 506/*
f65fd747 507 This version of malloc supports the standard SVID/XPG mallinfo
fa8d436c
UD
508 routine that returns a struct containing usage properties and
509 statistics. It should work on any SVID/XPG compliant system that has
510 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
511 install such a thing yourself, cut out the preliminary declarations
512 as described above and below and save them in a malloc.h file. But
513 there's no compelling reason to bother to do this.)
f65fd747
UD
514
515 The main declaration needed is the mallinfo struct that is returned
516 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
fa8d436c
UD
517 bunch of fields that are not even meaningful in this version of
518 malloc. These fields are are instead filled by mallinfo() with
519 other numbers that might be of interest.
f65fd747
UD
520*/
521
f65fd747 522
fa8d436c 523/* ---------- description of public routines ------------ */
f65fd747
UD
524
525/*
fa8d436c
UD
526 malloc(size_t n)
527 Returns a pointer to a newly allocated chunk of at least n bytes, or null
528 if no space is available. Additionally, on failure, errno is
529 set to ENOMEM on ANSI C systems.
530
531 If n is zero, malloc returns a minumum-sized chunk. (The minimum
532 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
533 systems.) On most systems, size_t is an unsigned type, so calls
534 with negative arguments are interpreted as requests for huge amounts
535 of space, which will often fail. The maximum supported value of n
536 differs across systems, but is in all cases less than the maximum
537 representable value of a size_t.
f65fd747 538*/
3b49edc0
UD
539void* __libc_malloc(size_t);
540libc_hidden_proto (__libc_malloc)
f65fd747 541
fa8d436c 542/*
22a89187 543 free(void* p)
fa8d436c
UD
544 Releases the chunk of memory pointed to by p, that had been previously
545 allocated using malloc or a related routine such as realloc.
546 It has no effect if p is null. It can have arbitrary (i.e., bad!)
547 effects if p has already been freed.
548
549 Unless disabled (using mallopt), freeing very large spaces will
550 when possible, automatically trigger operations that give
551 back unused memory to the system, thus reducing program footprint.
552*/
3b49edc0
UD
553void __libc_free(void*);
554libc_hidden_proto (__libc_free)
f65fd747 555
fa8d436c
UD
556/*
557 calloc(size_t n_elements, size_t element_size);
558 Returns a pointer to n_elements * element_size bytes, with all locations
559 set to zero.
560*/
3b49edc0 561void* __libc_calloc(size_t, size_t);
f65fd747
UD
562
563/*
22a89187 564 realloc(void* p, size_t n)
fa8d436c
UD
565 Returns a pointer to a chunk of size n that contains the same data
566 as does chunk p up to the minimum of (n, p's size) bytes, or null
a9177ff5 567 if no space is available.
f65fd747 568
fa8d436c
UD
569 The returned pointer may or may not be the same as p. The algorithm
570 prefers extending p when possible, otherwise it employs the
571 equivalent of a malloc-copy-free sequence.
f65fd747 572
a9177ff5 573 If p is null, realloc is equivalent to malloc.
f65fd747 574
fa8d436c
UD
575 If space is not available, realloc returns null, errno is set (if on
576 ANSI) and p is NOT freed.
f65fd747 577
fa8d436c
UD
578 if n is for fewer bytes than already held by p, the newly unused
579 space is lopped off and freed if possible. Unless the #define
580 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
581 zero (re)allocates a minimum-sized chunk.
f65fd747 582
fa8d436c
UD
583 Large chunks that were internally obtained via mmap will always
584 be reallocated using malloc-copy-free sequences unless
585 the system supports MREMAP (currently only linux).
f65fd747 586
fa8d436c
UD
587 The old unix realloc convention of allowing the last-free'd chunk
588 to be used as an argument to realloc is not supported.
f65fd747 589*/
3b49edc0
UD
590void* __libc_realloc(void*, size_t);
591libc_hidden_proto (__libc_realloc)
f65fd747 592
fa8d436c
UD
593/*
594 memalign(size_t alignment, size_t n);
595 Returns a pointer to a newly allocated chunk of n bytes, aligned
596 in accord with the alignment argument.
597
598 The alignment argument should be a power of two. If the argument is
599 not a power of two, the nearest greater power is used.
600 8-byte alignment is guaranteed by normal malloc calls, so don't
601 bother calling memalign with an argument of 8 or less.
602
603 Overreliance on memalign is a sure way to fragment space.
604*/
3b49edc0
UD
605void* __libc_memalign(size_t, size_t);
606libc_hidden_proto (__libc_memalign)
f65fd747
UD
607
608/*
fa8d436c
UD
609 valloc(size_t n);
610 Equivalent to memalign(pagesize, n), where pagesize is the page
611 size of the system. If the pagesize is unknown, 4096 is used.
612*/
3b49edc0 613void* __libc_valloc(size_t);
fa8d436c 614
f65fd747 615
f65fd747 616
fa8d436c
UD
617/*
618 mallopt(int parameter_number, int parameter_value)
619 Sets tunable parameters The format is to provide a
620 (parameter-number, parameter-value) pair. mallopt then sets the
621 corresponding parameter to the argument value if it can (i.e., so
622 long as the value is meaningful), and returns 1 if successful else
623 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
624 normally defined in malloc.h. Only one of these (M_MXFAST) is used
625 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
626 so setting them has no effect. But this malloc also supports four
627 other options in mallopt. See below for details. Briefly, supported
628 parameters are as follows (listed defaults are for "typical"
629 configurations).
630
631 Symbol param # default allowed param values
632 M_MXFAST 1 64 0-80 (0 disables fastbins)
633 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
a9177ff5 634 M_TOP_PAD -2 0 any
fa8d436c
UD
635 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
636 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
637*/
3b49edc0
UD
638int __libc_mallopt(int, int);
639libc_hidden_proto (__libc_mallopt)
fa8d436c
UD
640
641
642/*
643 mallinfo()
644 Returns (by copy) a struct containing various summary statistics:
645
a9177ff5
RM
646 arena: current total non-mmapped bytes allocated from system
647 ordblks: the number of free chunks
fa8d436c 648 smblks: the number of fastbin blocks (i.e., small chunks that
72f90263 649 have been freed but not use resused or consolidated)
a9177ff5
RM
650 hblks: current number of mmapped regions
651 hblkhd: total bytes held in mmapped regions
fa8d436c 652 usmblks: the maximum total allocated space. This will be greater
72f90263 653 than current total if trimming has occurred.
a9177ff5 654 fsmblks: total bytes held in fastbin blocks
fa8d436c 655 uordblks: current total allocated space (normal or mmapped)
a9177ff5 656 fordblks: total free space
fa8d436c 657 keepcost: the maximum number of bytes that could ideally be released
72f90263
UD
658 back to system via malloc_trim. ("ideally" means that
659 it ignores page restrictions etc.)
fa8d436c
UD
660
661 Because these fields are ints, but internal bookkeeping may
a9177ff5 662 be kept as longs, the reported values may wrap around zero and
fa8d436c
UD
663 thus be inaccurate.
664*/
3b49edc0 665struct mallinfo __libc_mallinfo(void);
88764ae2 666
f65fd747 667
fa8d436c
UD
668/*
669 pvalloc(size_t n);
670 Equivalent to valloc(minimum-page-that-holds(n)), that is,
671 round up n to nearest pagesize.
672 */
3b49edc0 673void* __libc_pvalloc(size_t);
fa8d436c
UD
674
675/*
676 malloc_trim(size_t pad);
677
678 If possible, gives memory back to the system (via negative
679 arguments to sbrk) if there is unused memory at the `high' end of
680 the malloc pool. You can call this after freeing large blocks of
681 memory to potentially reduce the system-level memory requirements
682 of a program. However, it cannot guarantee to reduce memory. Under
683 some allocation patterns, some large free blocks of memory will be
684 locked between two used chunks, so they cannot be given back to
685 the system.
a9177ff5 686
fa8d436c
UD
687 The `pad' argument to malloc_trim represents the amount of free
688 trailing space to leave untrimmed. If this argument is zero,
689 only the minimum amount of memory to maintain internal data
690 structures will be left (one page or less). Non-zero arguments
691 can be supplied to maintain enough trailing space to service
692 future expected allocations without having to re-obtain memory
693 from the system.
a9177ff5 694
fa8d436c
UD
695 Malloc_trim returns 1 if it actually released any memory, else 0.
696 On systems that do not support "negative sbrks", it will always
c958a6a4 697 return 0.
fa8d436c 698*/
3b49edc0 699int __malloc_trim(size_t);
fa8d436c
UD
700
701/*
22a89187 702 malloc_usable_size(void* p);
fa8d436c
UD
703
704 Returns the number of bytes you can actually use in
705 an allocated chunk, which may be more than you requested (although
706 often not) due to alignment and minimum size constraints.
707 You can use this many bytes without worrying about
708 overwriting other allocated objects. This is not a particularly great
709 programming practice. malloc_usable_size can be more useful in
710 debugging and assertions, for example:
711
712 p = malloc(n);
713 assert(malloc_usable_size(p) >= 256);
714
715*/
3b49edc0 716size_t __malloc_usable_size(void*);
fa8d436c
UD
717
718/*
719 malloc_stats();
720 Prints on stderr the amount of space obtained from the system (both
721 via sbrk and mmap), the maximum amount (which may be more than
722 current if malloc_trim and/or munmap got called), and the current
723 number of bytes allocated via malloc (or realloc, etc) but not yet
724 freed. Note that this is the number of bytes allocated, not the
725 number requested. It will be larger than the number requested
726 because of alignment and bookkeeping overhead. Because it includes
727 alignment wastage as being in use, this figure may be greater than
728 zero even when no user-level chunks are allocated.
729
730 The reported current and maximum system memory can be inaccurate if
731 a program makes other calls to system memory allocation functions
732 (normally sbrk) outside of malloc.
733
734 malloc_stats prints only the most commonly interesting statistics.
735 More information can be obtained by calling mallinfo.
736
737*/
3b49edc0 738void __malloc_stats(void);
f65fd747 739
f7ddf3d3
UD
740/*
741 malloc_get_state(void);
742
743 Returns the state of all malloc variables in an opaque data
744 structure.
745*/
3b49edc0 746void* __malloc_get_state(void);
f7ddf3d3
UD
747
748/*
22a89187 749 malloc_set_state(void* state);
f7ddf3d3
UD
750
751 Restore the state of all malloc variables from data obtained with
752 malloc_get_state().
753*/
3b49edc0 754int __malloc_set_state(void*);
f7ddf3d3 755
f7ddf3d3
UD
756/*
757 posix_memalign(void **memptr, size_t alignment, size_t size);
758
759 POSIX wrapper like memalign(), checking for validity of size.
760*/
761int __posix_memalign(void **, size_t, size_t);
f7ddf3d3 762
fa8d436c
UD
763/* mallopt tuning options */
764
f65fd747 765/*
fa8d436c
UD
766 M_MXFAST is the maximum request size used for "fastbins", special bins
767 that hold returned chunks without consolidating their spaces. This
768 enables future requests for chunks of the same size to be handled
769 very quickly, but can increase fragmentation, and thus increase the
770 overall memory footprint of a program.
771
772 This malloc manages fastbins very conservatively yet still
773 efficiently, so fragmentation is rarely a problem for values less
774 than or equal to the default. The maximum supported value of MXFAST
775 is 80. You wouldn't want it any higher than this anyway. Fastbins
776 are designed especially for use with many small structs, objects or
777 strings -- the default handles structs/objects/arrays with sizes up
778 to 8 4byte fields, or small strings representing words, tokens,
779 etc. Using fastbins for larger objects normally worsens
780 fragmentation without improving speed.
781
782 M_MXFAST is set in REQUEST size units. It is internally used in
783 chunksize units, which adds padding and alignment. You can reduce
784 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
785 algorithm to be a closer approximation of fifo-best-fit in all cases,
786 not just for larger requests, but will generally cause it to be
787 slower.
f65fd747
UD
788*/
789
790
fa8d436c
UD
791/* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
792#ifndef M_MXFAST
a9177ff5 793#define M_MXFAST 1
fa8d436c 794#endif
f65fd747 795
fa8d436c 796#ifndef DEFAULT_MXFAST
425ce2ed 797#define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
10dc2a90
UD
798#endif
799
10dc2a90 800
fa8d436c
UD
801/*
802 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
803 to keep before releasing via malloc_trim in free().
804
805 Automatic trimming is mainly useful in long-lived programs.
806 Because trimming via sbrk can be slow on some systems, and can
807 sometimes be wasteful (in cases where programs immediately
808 afterward allocate more large chunks) the value should be high
809 enough so that your overall system performance would improve by
810 releasing this much memory.
811
812 The trim threshold and the mmap control parameters (see below)
813 can be traded off with one another. Trimming and mmapping are
814 two different ways of releasing unused memory back to the
815 system. Between these two, it is often possible to keep
816 system-level demands of a long-lived program down to a bare
817 minimum. For example, in one test suite of sessions measuring
818 the XF86 X server on Linux, using a trim threshold of 128K and a
819 mmap threshold of 192K led to near-minimal long term resource
820 consumption.
821
822 If you are using this malloc in a long-lived program, it should
823 pay to experiment with these values. As a rough guide, you
824 might set to a value close to the average size of a process
825 (program) running on your system. Releasing this much memory
826 would allow such a process to run in memory. Generally, it's
827 worth it to tune for trimming rather tham memory mapping when a
828 program undergoes phases where several large chunks are
829 allocated and released in ways that can reuse each other's
830 storage, perhaps mixed with phases where there are no such
831 chunks at all. And in well-behaved long-lived programs,
832 controlling release of large blocks via trimming versus mapping
833 is usually faster.
834
835 However, in most programs, these parameters serve mainly as
836 protection against the system-level effects of carrying around
837 massive amounts of unneeded memory. Since frequent calls to
838 sbrk, mmap, and munmap otherwise degrade performance, the default
839 parameters are set to relatively high values that serve only as
840 safeguards.
841
842 The trim value It must be greater than page size to have any useful
a9177ff5 843 effect. To disable trimming completely, you can set to
fa8d436c
UD
844 (unsigned long)(-1)
845
846 Trim settings interact with fastbin (MXFAST) settings: Unless
847 TRIM_FASTBINS is defined, automatic trimming never takes place upon
848 freeing a chunk with size less than or equal to MXFAST. Trimming is
849 instead delayed until subsequent freeing of larger chunks. However,
850 you can still force an attempted trim by calling malloc_trim.
851
852 Also, trimming is not generally possible in cases where
853 the main arena is obtained via mmap.
854
855 Note that the trick some people use of mallocing a huge space and
856 then freeing it at program startup, in an attempt to reserve system
857 memory, doesn't have the intended effect under automatic trimming,
858 since that memory will immediately be returned to the system.
859*/
860
861#define M_TRIM_THRESHOLD -1
862
863#ifndef DEFAULT_TRIM_THRESHOLD
864#define DEFAULT_TRIM_THRESHOLD (128 * 1024)
865#endif
866
867/*
868 M_TOP_PAD is the amount of extra `padding' space to allocate or
869 retain whenever sbrk is called. It is used in two ways internally:
870
871 * When sbrk is called to extend the top of the arena to satisfy
872 a new malloc request, this much padding is added to the sbrk
873 request.
874
875 * When malloc_trim is called automatically from free(),
876 it is used as the `pad' argument.
877
878 In both cases, the actual amount of padding is rounded
879 so that the end of the arena is always a system page boundary.
880
881 The main reason for using padding is to avoid calling sbrk so
882 often. Having even a small pad greatly reduces the likelihood
883 that nearly every malloc request during program start-up (or
884 after trimming) will invoke sbrk, which needlessly wastes
885 time.
886
887 Automatic rounding-up to page-size units is normally sufficient
888 to avoid measurable overhead, so the default is 0. However, in
889 systems where sbrk is relatively slow, it can pay to increase
890 this value, at the expense of carrying around more memory than
891 the program needs.
892*/
10dc2a90 893
fa8d436c 894#define M_TOP_PAD -2
10dc2a90 895
fa8d436c
UD
896#ifndef DEFAULT_TOP_PAD
897#define DEFAULT_TOP_PAD (0)
898#endif
f65fd747 899
1d05c2fb
UD
900/*
901 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
902 adjusted MMAP_THRESHOLD.
903*/
904
905#ifndef DEFAULT_MMAP_THRESHOLD_MIN
906#define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
907#endif
908
909#ifndef DEFAULT_MMAP_THRESHOLD_MAX
e404fb16
UD
910 /* For 32-bit platforms we cannot increase the maximum mmap
911 threshold much because it is also the minimum value for the
bd2c2341
UD
912 maximum heap size and its alignment. Going above 512k (i.e., 1M
913 for new heaps) wastes too much address space. */
e404fb16 914# if __WORDSIZE == 32
bd2c2341 915# define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
e404fb16 916# else
bd2c2341 917# define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
e404fb16 918# endif
1d05c2fb
UD
919#endif
920
fa8d436c
UD
921/*
922 M_MMAP_THRESHOLD is the request size threshold for using mmap()
923 to service a request. Requests of at least this size that cannot
924 be allocated using already-existing space will be serviced via mmap.
925 (If enough normal freed space already exists it is used instead.)
926
927 Using mmap segregates relatively large chunks of memory so that
928 they can be individually obtained and released from the host
929 system. A request serviced through mmap is never reused by any
930 other request (at least not directly; the system may just so
931 happen to remap successive requests to the same locations).
932
933 Segregating space in this way has the benefits that:
934
a9177ff5
RM
935 1. Mmapped space can ALWAYS be individually released back
936 to the system, which helps keep the system level memory
937 demands of a long-lived program low.
fa8d436c
UD
938 2. Mapped memory can never become `locked' between
939 other chunks, as can happen with normally allocated chunks, which
940 means that even trimming via malloc_trim would not release them.
941 3. On some systems with "holes" in address spaces, mmap can obtain
942 memory that sbrk cannot.
943
944 However, it has the disadvantages that:
945
946 1. The space cannot be reclaimed, consolidated, and then
947 used to service later requests, as happens with normal chunks.
948 2. It can lead to more wastage because of mmap page alignment
949 requirements
950 3. It causes malloc performance to be more dependent on host
951 system memory management support routines which may vary in
952 implementation quality and may impose arbitrary
953 limitations. Generally, servicing a request via normal
954 malloc steps is faster than going through a system's mmap.
955
956 The advantages of mmap nearly always outweigh disadvantages for
957 "large" chunks, but the value of "large" varies across systems. The
958 default is an empirically derived value that works well in most
959 systems.
1d05c2fb
UD
960
961
962 Update in 2006:
963 The above was written in 2001. Since then the world has changed a lot.
964 Memory got bigger. Applications got bigger. The virtual address space
965 layout in 32 bit linux changed.
966
967 In the new situation, brk() and mmap space is shared and there are no
968 artificial limits on brk size imposed by the kernel. What is more,
969 applications have started using transient allocations larger than the
970 128Kb as was imagined in 2001.
971
972 The price for mmap is also high now; each time glibc mmaps from the
973 kernel, the kernel is forced to zero out the memory it gives to the
974 application. Zeroing memory is expensive and eats a lot of cache and
975 memory bandwidth. This has nothing to do with the efficiency of the
976 virtual memory system, by doing mmap the kernel just has no choice but
977 to zero.
978
979 In 2001, the kernel had a maximum size for brk() which was about 800
980 megabytes on 32 bit x86, at that point brk() would hit the first
981 mmaped shared libaries and couldn't expand anymore. With current 2.6
982 kernels, the VA space layout is different and brk() and mmap
983 both can span the entire heap at will.
984
985 Rather than using a static threshold for the brk/mmap tradeoff,
986 we are now using a simple dynamic one. The goal is still to avoid
987 fragmentation. The old goals we kept are
988 1) try to get the long lived large allocations to use mmap()
989 2) really large allocations should always use mmap()
990 and we're adding now:
991 3) transient allocations should use brk() to avoid forcing the kernel
992 having to zero memory over and over again
993
994 The implementation works with a sliding threshold, which is by default
995 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
996 out at 128Kb as per the 2001 default.
997
998 This allows us to satisfy requirement 1) under the assumption that long
999 lived allocations are made early in the process' lifespan, before it has
1000 started doing dynamic allocations of the same size (which will
1001 increase the threshold).
1002
1003 The upperbound on the threshold satisfies requirement 2)
1004
1005 The threshold goes up in value when the application frees memory that was
1006 allocated with the mmap allocator. The idea is that once the application
1007 starts freeing memory of a certain size, it's highly probable that this is
1008 a size the application uses for transient allocations. This estimator
1009 is there to satisfy the new third requirement.
1010
f65fd747
UD
1011*/
1012
fa8d436c 1013#define M_MMAP_THRESHOLD -3
f65fd747 1014
fa8d436c 1015#ifndef DEFAULT_MMAP_THRESHOLD
1d05c2fb 1016#define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
fa8d436c
UD
1017#endif
1018
1019/*
1020 M_MMAP_MAX is the maximum number of requests to simultaneously
1021 service using mmap. This parameter exists because
1022 some systems have a limited number of internal tables for
1023 use by mmap, and using more than a few of them may degrade
1024 performance.
1025
1026 The default is set to a value that serves only as a safeguard.
22a89187 1027 Setting to 0 disables use of mmap for servicing large requests.
fa8d436c 1028*/
f65fd747 1029
fa8d436c
UD
1030#define M_MMAP_MAX -4
1031
1032#ifndef DEFAULT_MMAP_MAX
fa8d436c 1033#define DEFAULT_MMAP_MAX (65536)
f65fd747
UD
1034#endif
1035
100351c3 1036#include <malloc.h>
f65fd747 1037
fa8d436c
UD
1038#ifndef RETURN_ADDRESS
1039#define RETURN_ADDRESS(X_) (NULL)
9ae6fc54 1040#endif
431c33c0
UD
1041
1042/* On some platforms we can compile internal, not exported functions better.
1043 Let the environment provide a macro and define it to be empty if it
1044 is not available. */
1045#ifndef internal_function
1046# define internal_function
1047#endif
1048
fa8d436c
UD
1049/* Forward declarations. */
1050struct malloc_chunk;
1051typedef struct malloc_chunk* mchunkptr;
431c33c0 1052
fa8d436c 1053/* Internal routines. */
f65fd747 1054
22a89187 1055static void* _int_malloc(mstate, size_t);
425ce2ed 1056static void _int_free(mstate, mchunkptr, int);
22a89187 1057static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
6e4b2107 1058 INTERNAL_SIZE_T);
22a89187 1059static void* _int_memalign(mstate, size_t, size_t);
10ad46bc
OB
1060static void* _mid_memalign(size_t, size_t, void *);
1061
fff94fa2 1062static void malloc_printerr(int action, const char *str, void *ptr, mstate av);
fa8d436c 1063
22a89187 1064static void* internal_function mem2mem_check(void *p, size_t sz);
fa8d436c
UD
1065static int internal_function top_check(void);
1066static void internal_function munmap_chunk(mchunkptr p);
a9177ff5 1067#if HAVE_MREMAP
fa8d436c 1068static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
a9177ff5 1069#endif
fa8d436c 1070
22a89187
UD
1071static void* malloc_check(size_t sz, const void *caller);
1072static void free_check(void* mem, const void *caller);
1073static void* realloc_check(void* oldmem, size_t bytes,
1074 const void *caller);
1075static void* memalign_check(size_t alignment, size_t bytes,
1076 const void *caller);
750c1f2a 1077#ifndef NO_THREADS
22a89187
UD
1078static void* malloc_atfork(size_t sz, const void *caller);
1079static void free_atfork(void* mem, const void *caller);
750c1f2a 1080#endif
f65fd747 1081
fa8d436c 1082/* ------------------ MMAP support ------------------ */
f65fd747 1083
f65fd747 1084
fa8d436c 1085#include <fcntl.h>
fa8d436c 1086#include <sys/mman.h>
f65fd747 1087
fa8d436c
UD
1088#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1089# define MAP_ANONYMOUS MAP_ANON
1090#endif
f65fd747 1091
fa8d436c 1092#ifndef MAP_NORESERVE
3b49edc0 1093# define MAP_NORESERVE 0
f65fd747
UD
1094#endif
1095
fa8d436c 1096#define MMAP(addr, size, prot, flags) \
3b49edc0 1097 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
f65fd747 1098
f65fd747
UD
1099
1100/*
fa8d436c 1101 ----------------------- Chunk representations -----------------------
f65fd747
UD
1102*/
1103
1104
fa8d436c
UD
1105/*
1106 This struct declaration is misleading (but accurate and necessary).
1107 It declares a "view" into memory allowing access to necessary
1108 fields at known offsets from a given base. See explanation below.
1109*/
1110
1111struct malloc_chunk {
1112
1113 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
1114 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
1115
1116 struct malloc_chunk* fd; /* double links -- used only if free. */
f65fd747 1117 struct malloc_chunk* bk;
7ecfbd38
UD
1118
1119 /* Only used for large blocks: pointer to next larger size. */
1120 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1121 struct malloc_chunk* bk_nextsize;
f65fd747
UD
1122};
1123
f65fd747
UD
1124
1125/*
f65fd747
UD
1126 malloc_chunk details:
1127
1128 (The following includes lightly edited explanations by Colin Plumb.)
1129
1130 Chunks of memory are maintained using a `boundary tag' method as
1131 described in e.g., Knuth or Standish. (See the paper by Paul
1132 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1133 survey of such techniques.) Sizes of free chunks are stored both
1134 in the front of each chunk and at the end. This makes
1135 consolidating fragmented chunks into bigger chunks very fast. The
1136 size fields also hold bits representing whether chunks are free or
1137 in use.
1138
1139 An allocated chunk looks like this:
1140
1141
1142 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72f90263
UD
1143 | Size of previous chunk, if allocated | |
1144 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1145 | Size of chunk, in bytes |M|P|
f65fd747 1146 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72f90263
UD
1147 | User data starts here... .
1148 . .
1149 . (malloc_usable_size() bytes) .
1150 . |
f65fd747 1151nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72f90263
UD
1152 | Size of chunk |
1153 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
f65fd747
UD
1154
1155
1156 Where "chunk" is the front of the chunk for the purpose of most of
1157 the malloc code, but "mem" is the pointer that is returned to the
1158 user. "Nextchunk" is the beginning of the next contiguous chunk.
1159
6f65e668 1160 Chunks always begin on even word boundaries, so the mem portion
f65fd747 1161 (which is returned to the user) is also on an even word boundary, and
fa8d436c 1162 thus at least double-word aligned.
f65fd747
UD
1163
1164 Free chunks are stored in circular doubly-linked lists, and look like this:
1165
1166 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72f90263
UD
1167 | Size of previous chunk |
1168 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
f65fd747
UD
1169 `head:' | Size of chunk, in bytes |P|
1170 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72f90263
UD
1171 | Forward pointer to next chunk in list |
1172 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1173 | Back pointer to previous chunk in list |
1174 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1175 | Unused space (may be 0 bytes long) .
1176 . .
1177 . |
f65fd747
UD
1178nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1179 `foot:' | Size of chunk, in bytes |
72f90263 1180 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
f65fd747
UD
1181
1182 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1183 chunk size (which is always a multiple of two words), is an in-use
1184 bit for the *previous* chunk. If that bit is *clear*, then the
1185 word before the current chunk size contains the previous chunk
1186 size, and can be used to find the front of the previous chunk.
fa8d436c
UD
1187 The very first chunk allocated always has this bit set,
1188 preventing access to non-existent (or non-owned) memory. If
1189 prev_inuse is set for any given chunk, then you CANNOT determine
1190 the size of the previous chunk, and might even get a memory
1191 addressing fault when trying to do so.
f65fd747
UD
1192
1193 Note that the `foot' of the current chunk is actually represented
fa8d436c
UD
1194 as the prev_size of the NEXT chunk. This makes it easier to
1195 deal with alignments etc but can be very confusing when trying
1196 to extend or adapt this code.
f65fd747
UD
1197
1198 The two exceptions to all this are
1199
fa8d436c 1200 1. The special chunk `top' doesn't bother using the
72f90263
UD
1201 trailing size field since there is no next contiguous chunk
1202 that would have to index off it. After initialization, `top'
1203 is forced to always exist. If it would become less than
1204 MINSIZE bytes long, it is replenished.
f65fd747
UD
1205
1206 2. Chunks allocated via mmap, which have the second-lowest-order
72f90263
UD
1207 bit M (IS_MMAPPED) set in their size fields. Because they are
1208 allocated one-by-one, each must contain its own trailing size field.
f65fd747
UD
1209
1210*/
1211
1212/*
fa8d436c
UD
1213 ---------- Size and alignment checks and conversions ----------
1214*/
f65fd747 1215
fa8d436c 1216/* conversion from malloc headers to user pointers, and back */
f65fd747 1217
22a89187 1218#define chunk2mem(p) ((void*)((char*)(p) + 2*SIZE_SZ))
fa8d436c 1219#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
f65fd747 1220
fa8d436c 1221/* The smallest possible chunk */
7ecfbd38 1222#define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
f65fd747 1223
fa8d436c 1224/* The smallest size we can malloc is an aligned minimal chunk */
f65fd747 1225
fa8d436c
UD
1226#define MINSIZE \
1227 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
f65fd747 1228
fa8d436c 1229/* Check if m has acceptable alignment */
f65fd747 1230
073f560e
UD
1231#define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1232
1233#define misaligned_chunk(p) \
1234 ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
1235 & MALLOC_ALIGN_MASK)
f65fd747 1236
f65fd747 1237
a9177ff5 1238/*
fa8d436c
UD
1239 Check if a request is so large that it would wrap around zero when
1240 padded and aligned. To simplify some other code, the bound is made
1241 low enough so that adding MINSIZE will also not wrap around zero.
6c8dbf00 1242 */
f65fd747 1243
fa8d436c 1244#define REQUEST_OUT_OF_RANGE(req) \
6c8dbf00
OB
1245 ((unsigned long) (req) >= \
1246 (unsigned long) (INTERNAL_SIZE_T) (-2 * MINSIZE))
f65fd747 1247
fa8d436c 1248/* pad request bytes into a usable size -- internal version */
f65fd747 1249
fa8d436c
UD
1250#define request2size(req) \
1251 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1252 MINSIZE : \
1253 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
f65fd747 1254
fa8d436c 1255/* Same, except also perform argument check */
f65fd747 1256
fa8d436c 1257#define checked_request2size(req, sz) \
6c8dbf00
OB
1258 if (REQUEST_OUT_OF_RANGE (req)) { \
1259 __set_errno (ENOMEM); \
1260 return 0; \
1261 } \
1262 (sz) = request2size (req);
f65fd747
UD
1263
1264/*
6c8dbf00
OB
1265 --------------- Physical chunk operations ---------------
1266 */
f65fd747 1267
10dc2a90 1268
fa8d436c
UD
1269/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1270#define PREV_INUSE 0x1
f65fd747 1271
fa8d436c
UD
1272/* extract inuse bit of previous chunk */
1273#define prev_inuse(p) ((p)->size & PREV_INUSE)
f65fd747 1274
f65fd747 1275
fa8d436c
UD
1276/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1277#define IS_MMAPPED 0x2
f65fd747 1278
fa8d436c
UD
1279/* check for mmap()'ed chunk */
1280#define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
f65fd747 1281
f65fd747 1282
fa8d436c
UD
1283/* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1284 from a non-main arena. This is only set immediately before handing
1285 the chunk to the user, if necessary. */
1286#define NON_MAIN_ARENA 0x4
f65fd747 1287
fa8d436c
UD
1288/* check for chunk from non-main arena */
1289#define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)
f65fd747
UD
1290
1291
a9177ff5 1292/*
6c8dbf00 1293 Bits to mask off when extracting size
f65fd747 1294
6c8dbf00
OB
1295 Note: IS_MMAPPED is intentionally not masked off from size field in
1296 macros for which mmapped chunks should never be seen. This should
1297 cause helpful core dumps to occur if it is tried by accident by
1298 people extending or adapting this malloc.
1299 */
1300#define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
f65fd747 1301
fa8d436c
UD
1302/* Get size, ignoring use bits */
1303#define chunksize(p) ((p)->size & ~(SIZE_BITS))
f65fd747 1304
f65fd747 1305
fa8d436c 1306/* Ptr to next physical malloc_chunk. */
6c8dbf00 1307#define next_chunk(p) ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))
f65fd747 1308
fa8d436c 1309/* Ptr to previous physical malloc_chunk */
6c8dbf00 1310#define prev_chunk(p) ((mchunkptr) (((char *) (p)) - ((p)->prev_size)))
f65fd747 1311
fa8d436c 1312/* Treat space at ptr + offset as a chunk */
6c8dbf00 1313#define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
fa8d436c
UD
1314
1315/* extract p's inuse bit */
6c8dbf00
OB
1316#define inuse(p) \
1317 ((((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)
f65fd747 1318
fa8d436c 1319/* set/clear chunk as being inuse without otherwise disturbing */
6c8dbf00
OB
1320#define set_inuse(p) \
1321 ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE
f65fd747 1322
6c8dbf00
OB
1323#define clear_inuse(p) \
1324 ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)
f65fd747
UD
1325
1326
fa8d436c 1327/* check/set/clear inuse bits in known places */
6c8dbf00
OB
1328#define inuse_bit_at_offset(p, s) \
1329 (((mchunkptr) (((char *) (p)) + (s)))->size & PREV_INUSE)
f65fd747 1330
6c8dbf00
OB
1331#define set_inuse_bit_at_offset(p, s) \
1332 (((mchunkptr) (((char *) (p)) + (s)))->size |= PREV_INUSE)
f65fd747 1333
6c8dbf00
OB
1334#define clear_inuse_bit_at_offset(p, s) \
1335 (((mchunkptr) (((char *) (p)) + (s)))->size &= ~(PREV_INUSE))
f65fd747 1336
f65fd747 1337
fa8d436c
UD
1338/* Set size at head, without disturbing its use bit */
1339#define set_head_size(p, s) ((p)->size = (((p)->size & SIZE_BITS) | (s)))
f65fd747 1340
fa8d436c
UD
1341/* Set size/use field */
1342#define set_head(p, s) ((p)->size = (s))
f65fd747 1343
fa8d436c 1344/* Set size at footer (only when chunk is not in use) */
6c8dbf00 1345#define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->prev_size = (s))
f65fd747
UD
1346
1347
fa8d436c 1348/*
6c8dbf00 1349 -------------------- Internal data structures --------------------
fa8d436c
UD
1350
1351 All internal state is held in an instance of malloc_state defined
1352 below. There are no other static variables, except in two optional
a9177ff5 1353 cases:
6c8dbf00
OB
1354 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1355 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
22a89187 1356 for mmap.
fa8d436c
UD
1357
1358 Beware of lots of tricks that minimize the total bookkeeping space
1359 requirements. The result is a little over 1K bytes (for 4byte
1360 pointers and size_t.)
6c8dbf00 1361 */
f65fd747
UD
1362
1363/*
6c8dbf00 1364 Bins
fa8d436c
UD
1365
1366 An array of bin headers for free chunks. Each bin is doubly
1367 linked. The bins are approximately proportionally (log) spaced.
1368 There are a lot of these bins (128). This may look excessive, but
1369 works very well in practice. Most bins hold sizes that are
1370 unusual as malloc request sizes, but are more usual for fragments
1371 and consolidated sets of chunks, which is what these bins hold, so
1372 they can be found quickly. All procedures maintain the invariant
1373 that no consolidated chunk physically borders another one, so each
1374 chunk in a list is known to be preceeded and followed by either
1375 inuse chunks or the ends of memory.
1376
1377 Chunks in bins are kept in size order, with ties going to the
1378 approximately least recently used chunk. Ordering isn't needed
1379 for the small bins, which all contain the same-sized chunks, but
1380 facilitates best-fit allocation for larger chunks. These lists
1381 are just sequential. Keeping them in order almost never requires
1382 enough traversal to warrant using fancier ordered data
a9177ff5 1383 structures.
fa8d436c
UD
1384
1385 Chunks of the same size are linked with the most
1386 recently freed at the front, and allocations are taken from the
1387 back. This results in LRU (FIFO) allocation order, which tends
1388 to give each chunk an equal opportunity to be consolidated with
1389 adjacent freed chunks, resulting in larger free chunks and less
1390 fragmentation.
1391
1392 To simplify use in double-linked lists, each bin header acts
1393 as a malloc_chunk. This avoids special-casing for headers.
1394 But to conserve space and improve locality, we allocate
1395 only the fd/bk pointers of bins, and then use repositioning tricks
a9177ff5 1396 to treat these as the fields of a malloc_chunk*.
6c8dbf00 1397 */
f65fd747 1398
6c8dbf00 1399typedef struct malloc_chunk *mbinptr;
f65fd747 1400
fa8d436c 1401/* addressing -- note that bin_at(0) does not exist */
41999a1a
UD
1402#define bin_at(m, i) \
1403 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
6c8dbf00 1404 - offsetof (struct malloc_chunk, fd))
f65fd747 1405
fa8d436c 1406/* analog of ++bin */
6c8dbf00 1407#define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
f65fd747 1408
fa8d436c
UD
1409/* Reminders about list directionality within bins */
1410#define first(b) ((b)->fd)
1411#define last(b) ((b)->bk)
f65fd747 1412
fa8d436c 1413/* Take a chunk off a bin list */
fff94fa2 1414#define unlink(AV, P, BK, FD) { \
6c8dbf00
OB
1415 FD = P->fd; \
1416 BK = P->bk; \
1417 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
fff94fa2 1418 malloc_printerr (check_action, "corrupted double-linked list", P, AV); \
6c8dbf00
OB
1419 else { \
1420 FD->bk = BK; \
1421 BK->fd = FD; \
1422 if (!in_smallbin_range (P->size) \
1423 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \
52ffbdf2
FW
1424 if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \
1425 || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \
1426 malloc_printerr (check_action, \
fff94fa2
SP
1427 "corrupted double-linked list (not small)", \
1428 P, AV); \
6c8dbf00
OB
1429 if (FD->fd_nextsize == NULL) { \
1430 if (P->fd_nextsize == P) \
1431 FD->fd_nextsize = FD->bk_nextsize = FD; \
1432 else { \
1433 FD->fd_nextsize = P->fd_nextsize; \
1434 FD->bk_nextsize = P->bk_nextsize; \
1435 P->fd_nextsize->bk_nextsize = FD; \
1436 P->bk_nextsize->fd_nextsize = FD; \
1437 } \
1438 } else { \
1439 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \
1440 P->bk_nextsize->fd_nextsize = P->fd_nextsize; \
1441 } \
1442 } \
1443 } \
fa8d436c 1444}
f65fd747 1445
fa8d436c 1446/*
6c8dbf00 1447 Indexing
fa8d436c
UD
1448
1449 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1450 8 bytes apart. Larger bins are approximately logarithmically spaced:
f65fd747 1451
fa8d436c
UD
1452 64 bins of size 8
1453 32 bins of size 64
1454 16 bins of size 512
1455 8 bins of size 4096
1456 4 bins of size 32768
1457 2 bins of size 262144
1458 1 bin of size what's left
f65fd747 1459
fa8d436c
UD
1460 There is actually a little bit of slop in the numbers in bin_index
1461 for the sake of speed. This makes no difference elsewhere.
f65fd747 1462
fa8d436c
UD
1463 The bins top out around 1MB because we expect to service large
1464 requests via mmap.
b5a2bbe6
L
1465
1466 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1467 a valid chunk size the small bins are bumped up one.
6c8dbf00 1468 */
f65fd747 1469
fa8d436c
UD
1470#define NBINS 128
1471#define NSMALLBINS 64
1d47e92f 1472#define SMALLBIN_WIDTH MALLOC_ALIGNMENT
b5a2bbe6
L
1473#define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > 2 * SIZE_SZ)
1474#define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
f65fd747 1475
fa8d436c 1476#define in_smallbin_range(sz) \
6c8dbf00 1477 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
f65fd747 1478
1d47e92f 1479#define smallbin_index(sz) \
6c8dbf00 1480 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
b5a2bbe6 1481 + SMALLBIN_CORRECTION)
f65fd747 1482
1d47e92f 1483#define largebin_index_32(sz) \
6c8dbf00
OB
1484 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1485 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1486 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1487 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1488 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1489 126)
f65fd747 1490
b5a2bbe6 1491#define largebin_index_32_big(sz) \
6c8dbf00
OB
1492 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1493 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1494 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1495 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1496 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1497 126)
b5a2bbe6 1498
1d47e92f
UD
1499// XXX It remains to be seen whether it is good to keep the widths of
1500// XXX the buckets the same or whether it should be scaled by a factor
1501// XXX of two as well.
1502#define largebin_index_64(sz) \
6c8dbf00
OB
1503 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1504 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1505 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1506 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1507 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1508 126)
1d47e92f
UD
1509
1510#define largebin_index(sz) \
b5a2bbe6
L
1511 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1512 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1513 : largebin_index_32 (sz))
1d47e92f 1514
fa8d436c 1515#define bin_index(sz) \
6c8dbf00 1516 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
f65fd747 1517
f65fd747
UD
1518
1519/*
6c8dbf00 1520 Unsorted chunks
fa8d436c
UD
1521
1522 All remainders from chunk splits, as well as all returned chunks,
1523 are first placed in the "unsorted" bin. They are then placed
1524 in regular bins after malloc gives them ONE chance to be used before
1525 binning. So, basically, the unsorted_chunks list acts as a queue,
1526 with chunks being placed on it in free (and malloc_consolidate),
1527 and taken off (to be either used or placed in bins) in malloc.
1528
1529 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1530 does not have to be taken into account in size comparisons.
6c8dbf00 1531 */
f65fd747 1532
fa8d436c 1533/* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
6c8dbf00 1534#define unsorted_chunks(M) (bin_at (M, 1))
f65fd747 1535
fa8d436c 1536/*
6c8dbf00 1537 Top
fa8d436c
UD
1538
1539 The top-most available chunk (i.e., the one bordering the end of
1540 available memory) is treated specially. It is never included in
1541 any bin, is used only if no other chunk is available, and is
1542 released back to the system if it is very large (see
1543 M_TRIM_THRESHOLD). Because top initially
1544 points to its own bin with initial zero size, thus forcing
1545 extension on the first malloc request, we avoid having any special
1546 code in malloc to check whether it even exists yet. But we still
1547 need to do so when getting memory from system, so we make
1548 initial_top treat the bin as a legal but unusable chunk during the
1549 interval between initialization and the first call to
3b49edc0 1550 sysmalloc. (This is somewhat delicate, since it relies on
fa8d436c 1551 the 2 preceding words to be zero during this interval as well.)
6c8dbf00 1552 */
f65fd747 1553
fa8d436c 1554/* Conveniently, the unsorted bin can be used as dummy top on first call */
6c8dbf00 1555#define initial_top(M) (unsorted_chunks (M))
f65fd747 1556
fa8d436c 1557/*
6c8dbf00 1558 Binmap
f65fd747 1559
fa8d436c
UD
1560 To help compensate for the large number of bins, a one-level index
1561 structure is used for bin-by-bin searching. `binmap' is a
1562 bitvector recording whether bins are definitely empty so they can
1563 be skipped over during during traversals. The bits are NOT always
1564 cleared as soon as bins are empty, but instead only
1565 when they are noticed to be empty during traversal in malloc.
6c8dbf00 1566 */
f65fd747 1567
fa8d436c
UD
1568/* Conservatively use 32 bits per map word, even if on 64bit system */
1569#define BINMAPSHIFT 5
1570#define BITSPERMAP (1U << BINMAPSHIFT)
1571#define BINMAPSIZE (NBINS / BITSPERMAP)
f65fd747 1572
fa8d436c 1573#define idx2block(i) ((i) >> BINMAPSHIFT)
6c8dbf00 1574#define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
f65fd747 1575
6c8dbf00
OB
1576#define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1577#define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1578#define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
f65fd747 1579
fa8d436c 1580/*
6c8dbf00 1581 Fastbins
fa8d436c
UD
1582
1583 An array of lists holding recently freed small chunks. Fastbins
1584 are not doubly linked. It is faster to single-link them, and
1585 since chunks are never removed from the middles of these lists,
1586 double linking is not necessary. Also, unlike regular bins, they
1587 are not even processed in FIFO order (they use faster LIFO) since
1588 ordering doesn't much matter in the transient contexts in which
1589 fastbins are normally used.
1590
1591 Chunks in fastbins keep their inuse bit set, so they cannot
1592 be consolidated with other free chunks. malloc_consolidate
1593 releases all chunks in fastbins and consolidates them with
a9177ff5 1594 other free chunks.
6c8dbf00 1595 */
f65fd747 1596
6c8dbf00 1597typedef struct malloc_chunk *mfastbinptr;
425ce2ed 1598#define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
f65fd747 1599
fa8d436c 1600/* offset 2 to use otherwise unindexable first 2 bins */
425ce2ed 1601#define fastbin_index(sz) \
6c8dbf00 1602 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
425ce2ed 1603
f65fd747 1604
fa8d436c 1605/* The maximum fastbin request size we support */
425ce2ed 1606#define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
f65fd747 1607
6c8dbf00 1608#define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
f65fd747
UD
1609
1610/*
6c8dbf00
OB
1611 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1612 that triggers automatic consolidation of possibly-surrounding
1613 fastbin chunks. This is a heuristic, so the exact value should not
1614 matter too much. It is defined at half the default trim threshold as a
1615 compromise heuristic to only attempt consolidation if it is likely
1616 to lead to trimming. However, it is not dynamically tunable, since
1617 consolidation reduces fragmentation surrounding large chunks even
1618 if trimming is not used.
1619 */
f65fd747 1620
fa8d436c 1621#define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
f65fd747
UD
1622
1623/*
6c8dbf00
OB
1624 Since the lowest 2 bits in max_fast don't matter in size comparisons,
1625 they are used as flags.
1626 */
f65fd747 1627
fa8d436c 1628/*
6c8dbf00
OB
1629 FASTCHUNKS_BIT held in max_fast indicates that there are probably
1630 some fastbin chunks. It is set true on entering a chunk into any
1631 fastbin, and cleared only in malloc_consolidate.
f65fd747 1632
6c8dbf00
OB
1633 The truth value is inverted so that have_fastchunks will be true
1634 upon startup (since statics are zero-filled), simplifying
1635 initialization checks.
1636 */
f65fd747 1637
fa8d436c 1638#define FASTCHUNKS_BIT (1U)
f65fd747 1639
6c8dbf00 1640#define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
425ce2ed
UD
1641#define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT)
1642#define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT)
f65fd747
UD
1643
1644/*
6c8dbf00
OB
1645 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1646 regions. Otherwise, contiguity is exploited in merging together,
1647 when possible, results from consecutive MORECORE calls.
f65fd747 1648
6c8dbf00
OB
1649 The initial value comes from MORECORE_CONTIGUOUS, but is
1650 changed dynamically if mmap is ever used as an sbrk substitute.
1651 */
f65fd747 1652
fa8d436c 1653#define NONCONTIGUOUS_BIT (2U)
f65fd747 1654
6c8dbf00
OB
1655#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1656#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1657#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
9bf248c6 1658#define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
f65fd747 1659
fff94fa2
SP
1660/* ARENA_CORRUPTION_BIT is set if a memory corruption was detected on the
1661 arena. Such an arena is no longer used to allocate chunks. Chunks
1662 allocated in that arena before detecting corruption are not freed. */
1663
1664#define ARENA_CORRUPTION_BIT (4U)
1665
1666#define arena_is_corrupt(A) (((A)->flags & ARENA_CORRUPTION_BIT))
1667#define set_arena_corrupt(A) ((A)->flags |= ARENA_CORRUPTION_BIT)
1668
a9177ff5
RM
1669/*
1670 Set value of max_fast.
fa8d436c
UD
1671 Use impossibly small value if 0.
1672 Precondition: there are no existing fastbin chunks.
1673 Setting the value clears fastchunk bit but preserves noncontiguous bit.
6c8dbf00 1674 */
f65fd747 1675
9bf248c6 1676#define set_max_fast(s) \
991eda1e 1677 global_max_fast = (((s) == 0) \
6c8dbf00 1678 ? SMALLBIN_WIDTH : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
9bf248c6 1679#define get_max_fast() global_max_fast
f65fd747 1680
f65fd747
UD
1681
1682/*
fa8d436c 1683 ----------- Internal state representation and initialization -----------
6c8dbf00 1684 */
f65fd747 1685
6c8dbf00
OB
1686struct malloc_state
1687{
fa8d436c
UD
1688 /* Serialize access. */
1689 mutex_t mutex;
9bf248c6
UD
1690
1691 /* Flags (formerly in max_fast). */
1692 int flags;
f65fd747 1693
fa8d436c 1694 /* Fastbins */
6c8dbf00 1695 mfastbinptr fastbinsY[NFASTBINS];
f65fd747 1696
fa8d436c 1697 /* Base of the topmost chunk -- not otherwise kept in a bin */
6c8dbf00 1698 mchunkptr top;
f65fd747 1699
fa8d436c 1700 /* The remainder from the most recent split of a small request */
6c8dbf00 1701 mchunkptr last_remainder;
f65fd747 1702
fa8d436c 1703 /* Normal bins packed as described above */
6c8dbf00 1704 mchunkptr bins[NBINS * 2 - 2];
f65fd747 1705
fa8d436c 1706 /* Bitmap of bins */
6c8dbf00 1707 unsigned int binmap[BINMAPSIZE];
f65fd747 1708
fa8d436c
UD
1709 /* Linked list */
1710 struct malloc_state *next;
f65fd747 1711
425ce2ed
UD
1712 /* Linked list for free arenas. */
1713 struct malloc_state *next_free;
425ce2ed 1714
fa8d436c
UD
1715 /* Memory allocated from the system in this arena. */
1716 INTERNAL_SIZE_T system_mem;
1717 INTERNAL_SIZE_T max_system_mem;
1718};
f65fd747 1719
6c8dbf00
OB
1720struct malloc_par
1721{
fa8d436c 1722 /* Tunable parameters */
6c8dbf00
OB
1723 unsigned long trim_threshold;
1724 INTERNAL_SIZE_T top_pad;
1725 INTERNAL_SIZE_T mmap_threshold;
1726 INTERNAL_SIZE_T arena_test;
1727 INTERNAL_SIZE_T arena_max;
fa8d436c
UD
1728
1729 /* Memory map support */
6c8dbf00
OB
1730 int n_mmaps;
1731 int n_mmaps_max;
1732 int max_n_mmaps;
1d05c2fb
UD
1733 /* the mmap_threshold is dynamic, until the user sets
1734 it manually, at which point we need to disable any
1735 dynamic behavior. */
6c8dbf00 1736 int no_dyn_threshold;
fa8d436c 1737
fa8d436c 1738 /* Statistics */
6c8dbf00 1739 INTERNAL_SIZE_T mmapped_mem;
fa8d436c
UD
1740 /*INTERNAL_SIZE_T sbrked_mem;*/
1741 /*INTERNAL_SIZE_T max_sbrked_mem;*/
6c8dbf00
OB
1742 INTERNAL_SIZE_T max_mmapped_mem;
1743 INTERNAL_SIZE_T max_total_mem; /* only kept for NO_THREADS */
fa8d436c
UD
1744
1745 /* First address handed out by MORECORE/sbrk. */
6c8dbf00 1746 char *sbrk_base;
fa8d436c 1747};
f65fd747 1748
fa8d436c
UD
1749/* There are several instances of this struct ("arenas") in this
1750 malloc. If you are adapting this malloc in a way that does NOT use
1751 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1752 before using. This malloc relies on the property that malloc_state
1753 is initialized to all zeroes (as is true of C statics). */
f65fd747 1754
02d46fc4 1755static struct malloc_state main_arena =
6c8dbf00
OB
1756{
1757 .mutex = MUTEX_INITIALIZER,
1758 .next = &main_arena
1759};
f65fd747 1760
fa8d436c 1761/* There is only one instance of the malloc parameters. */
f65fd747 1762
02d46fc4 1763static struct malloc_par mp_ =
6c8dbf00
OB
1764{
1765 .top_pad = DEFAULT_TOP_PAD,
1766 .n_mmaps_max = DEFAULT_MMAP_MAX,
1767 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1768 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1769#define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1770 .arena_test = NARENAS_FROM_NCORES (1)
1771};
f65fd747 1772
9bf248c6 1773
425ce2ed
UD
1774/* Non public mallopt parameters. */
1775#define M_ARENA_TEST -7
1776#define M_ARENA_MAX -8
425ce2ed
UD
1777
1778
9bf248c6
UD
1779/* Maximum size of memory handled in fastbins. */
1780static INTERNAL_SIZE_T global_max_fast;
1781
fa8d436c 1782/*
6c8dbf00 1783 Initialize a malloc_state struct.
f65fd747 1784
6c8dbf00
OB
1785 This is called only from within malloc_consolidate, which needs
1786 be called in the same contexts anyway. It is never called directly
1787 outside of malloc_consolidate because some optimizing compilers try
1788 to inline it at all call points, which turns out not to be an
1789 optimization at all. (Inlining it in malloc_consolidate is fine though.)
1790 */
f65fd747 1791
6c8dbf00
OB
1792static void
1793malloc_init_state (mstate av)
fa8d436c 1794{
6c8dbf00 1795 int i;
fa8d436c 1796 mbinptr bin;
a9177ff5 1797
fa8d436c 1798 /* Establish circular links for normal bins */
6c8dbf00
OB
1799 for (i = 1; i < NBINS; ++i)
1800 {
1801 bin = bin_at (av, i);
1802 bin->fd = bin->bk = bin;
1803 }
f65fd747 1804
fa8d436c
UD
1805#if MORECORE_CONTIGUOUS
1806 if (av != &main_arena)
1807#endif
6c8dbf00 1808 set_noncontiguous (av);
9bf248c6 1809 if (av == &main_arena)
6c8dbf00 1810 set_max_fast (DEFAULT_MXFAST);
9bf248c6 1811 av->flags |= FASTCHUNKS_BIT;
f65fd747 1812
6c8dbf00 1813 av->top = initial_top (av);
fa8d436c 1814}
e9b3e3c5 1815
a9177ff5 1816/*
fa8d436c 1817 Other internal utilities operating on mstates
6c8dbf00 1818 */
f65fd747 1819
6c8dbf00
OB
1820static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1821static int systrim (size_t, mstate);
1822static void malloc_consolidate (mstate);
7e3be507 1823
404d4cef
RM
1824
1825/* -------------- Early definitions for debugging hooks ---------------- */
1826
1827/* Define and initialize the hook variables. These weak definitions must
1828 appear before any use of the variables in a function (arena.c uses one). */
1829#ifndef weak_variable
404d4cef
RM
1830/* In GNU libc we want the hook variables to be weak definitions to
1831 avoid a problem with Emacs. */
22a89187 1832# define weak_variable weak_function
404d4cef
RM
1833#endif
1834
1835/* Forward declarations. */
6c8dbf00
OB
1836static void *malloc_hook_ini (size_t sz,
1837 const void *caller) __THROW;
1838static void *realloc_hook_ini (void *ptr, size_t sz,
1839 const void *caller) __THROW;
1840static void *memalign_hook_ini (size_t alignment, size_t sz,
1841 const void *caller) __THROW;
404d4cef 1842
06d6611a 1843void weak_variable (*__malloc_initialize_hook) (void) = NULL;
a222d91a 1844void weak_variable (*__free_hook) (void *__ptr,
6c8dbf00 1845 const void *) = NULL;
a222d91a 1846void *weak_variable (*__malloc_hook)
6c8dbf00 1847 (size_t __size, const void *) = malloc_hook_ini;
a222d91a 1848void *weak_variable (*__realloc_hook)
6c8dbf00
OB
1849 (void *__ptr, size_t __size, const void *)
1850 = realloc_hook_ini;
a222d91a 1851void *weak_variable (*__memalign_hook)
6c8dbf00
OB
1852 (size_t __alignment, size_t __size, const void *)
1853 = memalign_hook_ini;
06d6611a 1854void weak_variable (*__after_morecore_hook) (void) = NULL;
404d4cef
RM
1855
1856
3e030bd5
UD
1857/* ---------------- Error behavior ------------------------------------ */
1858
1859#ifndef DEFAULT_CHECK_ACTION
6c8dbf00 1860# define DEFAULT_CHECK_ACTION 3
3e030bd5
UD
1861#endif
1862
1863static int check_action = DEFAULT_CHECK_ACTION;
1864
1865
854278df
UD
1866/* ------------------ Testing support ----------------------------------*/
1867
1868static int perturb_byte;
1869
af102d95 1870static void
e8349efd
OB
1871alloc_perturb (char *p, size_t n)
1872{
1873 if (__glibc_unlikely (perturb_byte))
1874 memset (p, perturb_byte ^ 0xff, n);
1875}
1876
af102d95 1877static void
e8349efd
OB
1878free_perturb (char *p, size_t n)
1879{
1880 if (__glibc_unlikely (perturb_byte))
1881 memset (p, perturb_byte, n);
1882}
1883
854278df
UD
1884
1885
3ea5be54
AO
1886#include <stap-probe.h>
1887
fa8d436c
UD
1888/* ------------------- Support for multiple arenas -------------------- */
1889#include "arena.c"
f65fd747 1890
fa8d436c 1891/*
6c8dbf00 1892 Debugging support
f65fd747 1893
6c8dbf00
OB
1894 These routines make a number of assertions about the states
1895 of data structures that should be true at all times. If any
1896 are not true, it's very likely that a user program has somehow
1897 trashed memory. (It's also possible that there is a coding error
1898 in malloc. In which case, please report it!)
1899 */
ee74a442 1900
6c8dbf00 1901#if !MALLOC_DEBUG
d8f00d46 1902
6c8dbf00
OB
1903# define check_chunk(A, P)
1904# define check_free_chunk(A, P)
1905# define check_inuse_chunk(A, P)
1906# define check_remalloced_chunk(A, P, N)
1907# define check_malloced_chunk(A, P, N)
1908# define check_malloc_state(A)
d8f00d46 1909
fa8d436c 1910#else
ca34d7a7 1911
6c8dbf00
OB
1912# define check_chunk(A, P) do_check_chunk (A, P)
1913# define check_free_chunk(A, P) do_check_free_chunk (A, P)
1914# define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
1915# define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
1916# define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
1917# define check_malloc_state(A) do_check_malloc_state (A)
ca34d7a7 1918
fa8d436c 1919/*
6c8dbf00
OB
1920 Properties of all chunks
1921 */
ca34d7a7 1922
6c8dbf00
OB
1923static void
1924do_check_chunk (mstate av, mchunkptr p)
ca34d7a7 1925{
6c8dbf00 1926 unsigned long sz = chunksize (p);
fa8d436c 1927 /* min and max possible addresses assuming contiguous allocation */
6c8dbf00
OB
1928 char *max_address = (char *) (av->top) + chunksize (av->top);
1929 char *min_address = max_address - av->system_mem;
fa8d436c 1930
6c8dbf00
OB
1931 if (!chunk_is_mmapped (p))
1932 {
1933 /* Has legal address ... */
1934 if (p != av->top)
1935 {
1936 if (contiguous (av))
1937 {
1938 assert (((char *) p) >= min_address);
1939 assert (((char *) p + sz) <= ((char *) (av->top)));
1940 }
1941 }
1942 else
1943 {
1944 /* top size is always at least MINSIZE */
1945 assert ((unsigned long) (sz) >= MINSIZE);
1946 /* top predecessor always marked inuse */
1947 assert (prev_inuse (p));
1948 }
fa8d436c 1949 }
6c8dbf00
OB
1950 else
1951 {
1952 /* address is outside main heap */
1953 if (contiguous (av) && av->top != initial_top (av))
1954 {
1955 assert (((char *) p) < min_address || ((char *) p) >= max_address);
1956 }
1957 /* chunk is page-aligned */
1958 assert (((p->prev_size + sz) & (GLRO (dl_pagesize) - 1)) == 0);
1959 /* mem is aligned */
1960 assert (aligned_OK (chunk2mem (p)));
fa8d436c 1961 }
eb406346
UD
1962}
1963
fa8d436c 1964/*
6c8dbf00
OB
1965 Properties of free chunks
1966 */
ee74a442 1967
6c8dbf00
OB
1968static void
1969do_check_free_chunk (mstate av, mchunkptr p)
67c94753 1970{
6c8dbf00
OB
1971 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
1972 mchunkptr next = chunk_at_offset (p, sz);
67c94753 1973
6c8dbf00 1974 do_check_chunk (av, p);
67c94753 1975
fa8d436c 1976 /* Chunk must claim to be free ... */
6c8dbf00
OB
1977 assert (!inuse (p));
1978 assert (!chunk_is_mmapped (p));
67c94753 1979
fa8d436c 1980 /* Unless a special marker, must have OK fields */
6c8dbf00
OB
1981 if ((unsigned long) (sz) >= MINSIZE)
1982 {
1983 assert ((sz & MALLOC_ALIGN_MASK) == 0);
1984 assert (aligned_OK (chunk2mem (p)));
1985 /* ... matching footer field */
1986 assert (next->prev_size == sz);
1987 /* ... and is fully consolidated */
1988 assert (prev_inuse (p));
1989 assert (next == av->top || inuse (next));
1990
1991 /* ... and has minimally sane links */
1992 assert (p->fd->bk == p);
1993 assert (p->bk->fd == p);
1994 }
fa8d436c 1995 else /* markers are always of size SIZE_SZ */
6c8dbf00 1996 assert (sz == SIZE_SZ);
67c94753 1997}
67c94753 1998
fa8d436c 1999/*
6c8dbf00
OB
2000 Properties of inuse chunks
2001 */
fa8d436c 2002
6c8dbf00
OB
2003static void
2004do_check_inuse_chunk (mstate av, mchunkptr p)
f65fd747 2005{
fa8d436c 2006 mchunkptr next;
f65fd747 2007
6c8dbf00 2008 do_check_chunk (av, p);
f65fd747 2009
6c8dbf00 2010 if (chunk_is_mmapped (p))
fa8d436c 2011 return; /* mmapped chunks have no next/prev */
ca34d7a7 2012
fa8d436c 2013 /* Check whether it claims to be in use ... */
6c8dbf00 2014 assert (inuse (p));
10dc2a90 2015
6c8dbf00 2016 next = next_chunk (p);
10dc2a90 2017
fa8d436c 2018 /* ... and is surrounded by OK chunks.
6c8dbf00
OB
2019 Since more things can be checked with free chunks than inuse ones,
2020 if an inuse chunk borders them and debug is on, it's worth doing them.
2021 */
2022 if (!prev_inuse (p))
2023 {
2024 /* Note that we cannot even look at prev unless it is not inuse */
2025 mchunkptr prv = prev_chunk (p);
2026 assert (next_chunk (prv) == p);
2027 do_check_free_chunk (av, prv);
2028 }
fa8d436c 2029
6c8dbf00
OB
2030 if (next == av->top)
2031 {
2032 assert (prev_inuse (next));
2033 assert (chunksize (next) >= MINSIZE);
2034 }
2035 else if (!inuse (next))
2036 do_check_free_chunk (av, next);
10dc2a90
UD
2037}
2038
fa8d436c 2039/*
6c8dbf00
OB
2040 Properties of chunks recycled from fastbins
2041 */
fa8d436c 2042
6c8dbf00
OB
2043static void
2044do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
10dc2a90 2045{
6c8dbf00 2046 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
fa8d436c 2047
6c8dbf00
OB
2048 if (!chunk_is_mmapped (p))
2049 {
2050 assert (av == arena_for_chunk (p));
2051 if (chunk_non_main_arena (p))
2052 assert (av != &main_arena);
2053 else
2054 assert (av == &main_arena);
2055 }
fa8d436c 2056
6c8dbf00 2057 do_check_inuse_chunk (av, p);
fa8d436c
UD
2058
2059 /* Legal size ... */
6c8dbf00
OB
2060 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2061 assert ((unsigned long) (sz) >= MINSIZE);
fa8d436c 2062 /* ... and alignment */
6c8dbf00 2063 assert (aligned_OK (chunk2mem (p)));
fa8d436c 2064 /* chunk is less than MINSIZE more than request */
6c8dbf00
OB
2065 assert ((long) (sz) - (long) (s) >= 0);
2066 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
10dc2a90
UD
2067}
2068
fa8d436c 2069/*
6c8dbf00
OB
2070 Properties of nonrecycled chunks at the point they are malloced
2071 */
fa8d436c 2072
6c8dbf00
OB
2073static void
2074do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
10dc2a90 2075{
fa8d436c 2076 /* same as recycled case ... */
6c8dbf00 2077 do_check_remalloced_chunk (av, p, s);
10dc2a90 2078
fa8d436c 2079 /*
6c8dbf00
OB
2080 ... plus, must obey implementation invariant that prev_inuse is
2081 always true of any allocated chunk; i.e., that each allocated
2082 chunk borders either a previously allocated and still in-use
2083 chunk, or the base of its memory arena. This is ensured
2084 by making all allocations from the `lowest' part of any found
2085 chunk. This does not necessarily hold however for chunks
2086 recycled via fastbins.
2087 */
2088
2089 assert (prev_inuse (p));
fa8d436c 2090}
10dc2a90 2091
f65fd747 2092
fa8d436c 2093/*
6c8dbf00 2094 Properties of malloc_state.
f65fd747 2095
6c8dbf00
OB
2096 This may be useful for debugging malloc, as well as detecting user
2097 programmer errors that somehow write into malloc_state.
f65fd747 2098
6c8dbf00
OB
2099 If you are extending or experimenting with this malloc, you can
2100 probably figure out how to hack this routine to print out or
2101 display chunk addresses, sizes, bins, and other instrumentation.
2102 */
f65fd747 2103
6c8dbf00
OB
2104static void
2105do_check_malloc_state (mstate av)
fa8d436c
UD
2106{
2107 int i;
2108 mchunkptr p;
2109 mchunkptr q;
2110 mbinptr b;
fa8d436c
UD
2111 unsigned int idx;
2112 INTERNAL_SIZE_T size;
2113 unsigned long total = 0;
2114 int max_fast_bin;
f65fd747 2115
fa8d436c 2116 /* internal size_t must be no wider than pointer type */
6c8dbf00 2117 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
f65fd747 2118
fa8d436c 2119 /* alignment is a power of 2 */
6c8dbf00 2120 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
f65fd747 2121
fa8d436c 2122 /* cannot run remaining checks until fully initialized */
6c8dbf00 2123 if (av->top == 0 || av->top == initial_top (av))
fa8d436c 2124 return;
f65fd747 2125
fa8d436c 2126 /* pagesize is a power of 2 */
8a35c3fe 2127 assert (powerof2(GLRO (dl_pagesize)));
f65fd747 2128
fa8d436c 2129 /* A contiguous main_arena is consistent with sbrk_base. */
6c8dbf00
OB
2130 if (av == &main_arena && contiguous (av))
2131 assert ((char *) mp_.sbrk_base + av->system_mem ==
2132 (char *) av->top + chunksize (av->top));
fa8d436c
UD
2133
2134 /* properties of fastbins */
2135
2136 /* max_fast is in allowed range */
6c8dbf00
OB
2137 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2138
2139 max_fast_bin = fastbin_index (get_max_fast ());
2140
2141 for (i = 0; i < NFASTBINS; ++i)
2142 {
2143 p = fastbin (av, i);
2144
2145 /* The following test can only be performed for the main arena.
2146 While mallopt calls malloc_consolidate to get rid of all fast
2147 bins (especially those larger than the new maximum) this does
2148 only happen for the main arena. Trying to do this for any
2149 other arena would mean those arenas have to be locked and
2150 malloc_consolidate be called for them. This is excessive. And
2151 even if this is acceptable to somebody it still cannot solve
2152 the problem completely since if the arena is locked a
2153 concurrent malloc call might create a new arena which then
2154 could use the newly invalid fast bins. */
2155
2156 /* all bins past max_fast are empty */
2157 if (av == &main_arena && i > max_fast_bin)
2158 assert (p == 0);
2159
2160 while (p != 0)
2161 {
2162 /* each chunk claims to be inuse */
2163 do_check_inuse_chunk (av, p);
2164 total += chunksize (p);
2165 /* chunk belongs in this bin */
2166 assert (fastbin_index (chunksize (p)) == i);
2167 p = p->fd;
2168 }
fa8d436c 2169 }
fa8d436c
UD
2170
2171 if (total != 0)
6c8dbf00
OB
2172 assert (have_fastchunks (av));
2173 else if (!have_fastchunks (av))
2174 assert (total == 0);
fa8d436c
UD
2175
2176 /* check normal bins */
6c8dbf00
OB
2177 for (i = 1; i < NBINS; ++i)
2178 {
2179 b = bin_at (av, i);
2180
2181 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2182 if (i >= 2)
2183 {
2184 unsigned int binbit = get_binmap (av, i);
2185 int empty = last (b) == b;
2186 if (!binbit)
2187 assert (empty);
2188 else if (!empty)
2189 assert (binbit);
2190 }
2191
2192 for (p = last (b); p != b; p = p->bk)
2193 {
2194 /* each chunk claims to be free */
2195 do_check_free_chunk (av, p);
2196 size = chunksize (p);
2197 total += size;
2198 if (i >= 2)
2199 {
2200 /* chunk belongs in bin */
2201 idx = bin_index (size);
2202 assert (idx == i);
2203 /* lists are sorted */
2204 assert (p->bk == b ||
2205 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2206
2207 if (!in_smallbin_range (size))
2208 {
2209 if (p->fd_nextsize != NULL)
2210 {
2211 if (p->fd_nextsize == p)
2212 assert (p->bk_nextsize == p);
2213 else
2214 {
2215 if (p->fd_nextsize == first (b))
2216 assert (chunksize (p) < chunksize (p->fd_nextsize));
2217 else
2218 assert (chunksize (p) > chunksize (p->fd_nextsize));
2219
2220 if (p == first (b))
2221 assert (chunksize (p) > chunksize (p->bk_nextsize));
2222 else
2223 assert (chunksize (p) < chunksize (p->bk_nextsize));
2224 }
2225 }
2226 else
2227 assert (p->bk_nextsize == NULL);
2228 }
2229 }
2230 else if (!in_smallbin_range (size))
2231 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2232 /* chunk is followed by a legal chain of inuse chunks */
2233 for (q = next_chunk (p);
2234 (q != av->top && inuse (q) &&
2235 (unsigned long) (chunksize (q)) >= MINSIZE);
2236 q = next_chunk (q))
2237 do_check_inuse_chunk (av, q);
2238 }
fa8d436c 2239 }
f65fd747 2240
fa8d436c 2241 /* top chunk is OK */
6c8dbf00 2242 check_chunk (av, av->top);
fa8d436c
UD
2243}
2244#endif
2245
2246
2247/* ----------------- Support for debugging hooks -------------------- */
2248#include "hooks.c"
2249
2250
2251/* ----------- Routines dealing with system allocation -------------- */
2252
2253/*
6c8dbf00
OB
2254 sysmalloc handles malloc cases requiring more memory from the system.
2255 On entry, it is assumed that av->top does not have enough
2256 space to service request for nb bytes, thus requiring that av->top
2257 be extended or replaced.
2258 */
fa8d436c 2259
6c8dbf00
OB
2260static void *
2261sysmalloc (INTERNAL_SIZE_T nb, mstate av)
f65fd747 2262{
6c8dbf00 2263 mchunkptr old_top; /* incoming value of av->top */
fa8d436c 2264 INTERNAL_SIZE_T old_size; /* its size */
6c8dbf00 2265 char *old_end; /* its end address */
f65fd747 2266
6c8dbf00
OB
2267 long size; /* arg to first MORECORE or mmap call */
2268 char *brk; /* return value from MORECORE */
f65fd747 2269
6c8dbf00
OB
2270 long correction; /* arg to 2nd MORECORE call */
2271 char *snd_brk; /* 2nd return val */
f65fd747 2272
fa8d436c
UD
2273 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2274 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
6c8dbf00 2275 char *aligned_brk; /* aligned offset into brk */
f65fd747 2276
6c8dbf00
OB
2277 mchunkptr p; /* the allocated/returned chunk */
2278 mchunkptr remainder; /* remainder from allocation */
2279 unsigned long remainder_size; /* its size */
fa8d436c 2280
fa8d436c 2281
8a35c3fe 2282 size_t pagesize = GLRO (dl_pagesize);
6c8dbf00 2283 bool tried_mmap = false;
fa8d436c
UD
2284
2285
fa8d436c 2286 /*
6c8dbf00
OB
2287 If have mmap, and the request size meets the mmap threshold, and
2288 the system supports mmap, and there are few enough currently
2289 allocated mmapped regions, try to directly map this request
2290 rather than expanding top.
2291 */
2292
fff94fa2
SP
2293 if (av == NULL
2294 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2295 && (mp_.n_mmaps < mp_.n_mmaps_max)))
6c8dbf00
OB
2296 {
2297 char *mm; /* return value from mmap call*/
a9177ff5 2298
6c8dbf00
OB
2299 try_mmap:
2300 /*
2301 Round up size to nearest page. For mmapped chunks, the overhead
2302 is one SIZE_SZ unit larger than for normal chunks, because there
2303 is no following chunk whose prev_size field could be used.
2304
2305 See the front_misalign handling below, for glibc there is no
2306 need for further alignments unless we have have high alignment.
2307 */
2308 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
8a35c3fe 2309 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
6c8dbf00 2310 else
8a35c3fe 2311 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
6c8dbf00
OB
2312 tried_mmap = true;
2313
2314 /* Don't try if size wraps around 0 */
2315 if ((unsigned long) (size) > (unsigned long) (nb))
2316 {
2317 mm = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2318
2319 if (mm != MAP_FAILED)
2320 {
2321 /*
2322 The offset to the start of the mmapped region is stored
2323 in the prev_size field of the chunk. This allows us to adjust
2324 returned start address to meet alignment requirements here
2325 and in memalign(), and still be able to compute proper
2326 address argument for later munmap in free() and realloc().
2327 */
2328
2329 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2330 {
2331 /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and
2332 MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
2333 aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
2334 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2335 front_misalign = 0;
2336 }
2337 else
2338 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2339 if (front_misalign > 0)
2340 {
2341 correction = MALLOC_ALIGNMENT - front_misalign;
2342 p = (mchunkptr) (mm + correction);
2343 p->prev_size = correction;
2344 set_head (p, (size - correction) | IS_MMAPPED);
2345 }
2346 else
2347 {
2348 p = (mchunkptr) mm;
2349 set_head (p, size | IS_MMAPPED);
2350 }
2351
2352 /* update statistics */
2353
2354 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2355 atomic_max (&mp_.max_n_mmaps, new);
2356
2357 unsigned long sum;
2358 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2359 atomic_max (&mp_.max_mmapped_mem, sum);
2360
2361 check_chunk (av, p);
2362
2363 return chunk2mem (p);
2364 }
2365 }
fa8d436c 2366 }
fa8d436c 2367
fff94fa2
SP
2368 /* There are no usable arenas and mmap also failed. */
2369 if (av == NULL)
2370 return 0;
2371
fa8d436c
UD
2372 /* Record incoming configuration of top */
2373
6c8dbf00
OB
2374 old_top = av->top;
2375 old_size = chunksize (old_top);
2376 old_end = (char *) (chunk_at_offset (old_top, old_size));
fa8d436c 2377
6c8dbf00 2378 brk = snd_brk = (char *) (MORECORE_FAILURE);
fa8d436c 2379
a9177ff5 2380 /*
fa8d436c
UD
2381 If not the first time through, we require old_size to be
2382 at least MINSIZE and to have prev_inuse set.
6c8dbf00 2383 */
fa8d436c 2384
6c8dbf00
OB
2385 assert ((old_top == initial_top (av) && old_size == 0) ||
2386 ((unsigned long) (old_size) >= MINSIZE &&
2387 prev_inuse (old_top) &&
8a35c3fe 2388 ((unsigned long) old_end & (pagesize - 1)) == 0));
fa8d436c
UD
2389
2390 /* Precondition: not enough current space to satisfy nb request */
6c8dbf00 2391 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
a9177ff5 2392
72f90263 2393
6c8dbf00
OB
2394 if (av != &main_arena)
2395 {
2396 heap_info *old_heap, *heap;
2397 size_t old_heap_size;
2398
2399 /* First try to extend the current heap. */
2400 old_heap = heap_for_ptr (old_top);
2401 old_heap_size = old_heap->size;
2402 if ((long) (MINSIZE + nb - old_size) > 0
2403 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2404 {
2405 av->system_mem += old_heap->size - old_heap_size;
2406 arena_mem += old_heap->size - old_heap_size;
2407 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2408 | PREV_INUSE);
2409 }
2410 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2411 {
2412 /* Use a newly allocated heap. */
2413 heap->ar_ptr = av;
2414 heap->prev = old_heap;
2415 av->system_mem += heap->size;
2416 arena_mem += heap->size;
2417 /* Set up the new top. */
2418 top (av) = chunk_at_offset (heap, sizeof (*heap));
2419 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2420
2421 /* Setup fencepost and free the old top chunk with a multiple of
2422 MALLOC_ALIGNMENT in size. */
2423 /* The fencepost takes at least MINSIZE bytes, because it might
2424 become the top chunk again later. Note that a footer is set
2425 up, too, although the chunk is marked in use. */
2426 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2427 set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ), 0 | PREV_INUSE);
2428 if (old_size >= MINSIZE)
2429 {
2430 set_head (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE);
2431 set_foot (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ));
2432 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2433 _int_free (av, old_top, 1);
2434 }
2435 else
2436 {
2437 set_head (old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE);
2438 set_foot (old_top, (old_size + 2 * SIZE_SZ));
2439 }
2440 }
2441 else if (!tried_mmap)
2442 /* We can at least try to use to mmap memory. */
2443 goto try_mmap;
fa8d436c 2444 }
6c8dbf00 2445 else /* av == main_arena */
fa8d436c 2446
fa8d436c 2447
6c8dbf00
OB
2448 { /* Request enough space for nb + pad + overhead */
2449 size = nb + mp_.top_pad + MINSIZE;
a9177ff5 2450
6c8dbf00
OB
2451 /*
2452 If contiguous, we can subtract out existing space that we hope to
2453 combine with new space. We add it back later only if
2454 we don't actually get contiguous space.
2455 */
a9177ff5 2456
6c8dbf00
OB
2457 if (contiguous (av))
2458 size -= old_size;
fa8d436c 2459
6c8dbf00
OB
2460 /*
2461 Round to a multiple of page size.
2462 If MORECORE is not contiguous, this ensures that we only call it
2463 with whole-page arguments. And if MORECORE is contiguous and
2464 this is not first time through, this preserves page-alignment of
2465 previous calls. Otherwise, we correct to page-align below.
2466 */
fa8d436c 2467
8a35c3fe 2468 size = ALIGN_UP (size, pagesize);
fa8d436c 2469
6c8dbf00
OB
2470 /*
2471 Don't try to call MORECORE if argument is so big as to appear
2472 negative. Note that since mmap takes size_t arg, it may succeed
2473 below even if we cannot call MORECORE.
2474 */
2475
2476 if (size > 0)
2477 {
2478 brk = (char *) (MORECORE (size));
2479 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2480 }
2481
2482 if (brk != (char *) (MORECORE_FAILURE))
2483 {
2484 /* Call the `morecore' hook if necessary. */
2485 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2486 if (__builtin_expect (hook != NULL, 0))
2487 (*hook)();
2488 }
2489 else
2490 {
2491 /*
2492 If have mmap, try using it as a backup when MORECORE fails or
2493 cannot be used. This is worth doing on systems that have "holes" in
2494 address space, so sbrk cannot extend to give contiguous space, but
2495 space is available elsewhere. Note that we ignore mmap max count
2496 and threshold limits, since the space will not be used as a
2497 segregated mmap region.
2498 */
2499
2500 /* Cannot merge with old top, so add its size back in */
2501 if (contiguous (av))
8a35c3fe 2502 size = ALIGN_UP (size + old_size, pagesize);
6c8dbf00
OB
2503
2504 /* If we are relying on mmap as backup, then use larger units */
2505 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2506 size = MMAP_AS_MORECORE_SIZE;
2507
2508 /* Don't try if size wraps around 0 */
2509 if ((unsigned long) (size) > (unsigned long) (nb))
2510 {
2511 char *mbrk = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2512
2513 if (mbrk != MAP_FAILED)
2514 {
2515 /* We do not need, and cannot use, another sbrk call to find end */
2516 brk = mbrk;
2517 snd_brk = brk + size;
2518
2519 /*
2520 Record that we no longer have a contiguous sbrk region.
2521 After the first time mmap is used as backup, we do not
2522 ever rely on contiguous space since this could incorrectly
2523 bridge regions.
2524 */
2525 set_noncontiguous (av);
2526 }
2527 }
2528 }
2529
2530 if (brk != (char *) (MORECORE_FAILURE))
2531 {
2532 if (mp_.sbrk_base == 0)
2533 mp_.sbrk_base = brk;
2534 av->system_mem += size;
2535
2536 /*
2537 If MORECORE extends previous space, we can likewise extend top size.
2538 */
2539
2540 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2541 set_head (old_top, (size + old_size) | PREV_INUSE);
2542
2543 else if (contiguous (av) && old_size && brk < old_end)
2544 {
2545 /* Oops! Someone else killed our space.. Can't touch anything. */
fff94fa2
SP
2546 malloc_printerr (3, "break adjusted to free malloc space", brk,
2547 av);
6c8dbf00
OB
2548 }
2549
2550 /*
2551 Otherwise, make adjustments:
2552
2553 * If the first time through or noncontiguous, we need to call sbrk
2554 just to find out where the end of memory lies.
2555
2556 * We need to ensure that all returned chunks from malloc will meet
2557 MALLOC_ALIGNMENT
2558
2559 * If there was an intervening foreign sbrk, we need to adjust sbrk
2560 request size to account for fact that we will not be able to
2561 combine new space with existing space in old_top.
2562
2563 * Almost all systems internally allocate whole pages at a time, in
2564 which case we might as well use the whole last page of request.
2565 So we allocate enough more memory to hit a page boundary now,
2566 which in turn causes future contiguous calls to page-align.
2567 */
2568
2569 else
2570 {
2571 front_misalign = 0;
2572 end_misalign = 0;
2573 correction = 0;
2574 aligned_brk = brk;
2575
2576 /* handle contiguous cases */
2577 if (contiguous (av))
2578 {
2579 /* Count foreign sbrk as system_mem. */
2580 if (old_size)
2581 av->system_mem += brk - old_end;
2582
2583 /* Guarantee alignment of first new chunk made from this space */
2584
2585 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2586 if (front_misalign > 0)
2587 {
2588 /*
2589 Skip over some bytes to arrive at an aligned position.
2590 We don't need to specially mark these wasted front bytes.
2591 They will never be accessed anyway because
2592 prev_inuse of av->top (and any chunk created from its start)
2593 is always true after initialization.
2594 */
2595
2596 correction = MALLOC_ALIGNMENT - front_misalign;
2597 aligned_brk += correction;
2598 }
2599
2600 /*
2601 If this isn't adjacent to existing space, then we will not
2602 be able to merge with old_top space, so must add to 2nd request.
2603 */
2604
2605 correction += old_size;
2606
2607 /* Extend the end address to hit a page boundary */
2608 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
8a35c3fe 2609 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
6c8dbf00
OB
2610
2611 assert (correction >= 0);
2612 snd_brk = (char *) (MORECORE (correction));
2613
2614 /*
2615 If can't allocate correction, try to at least find out current
2616 brk. It might be enough to proceed without failing.
2617
2618 Note that if second sbrk did NOT fail, we assume that space
2619 is contiguous with first sbrk. This is a safe assumption unless
2620 program is multithreaded but doesn't use locks and a foreign sbrk
2621 occurred between our first and second calls.
2622 */
2623
2624 if (snd_brk == (char *) (MORECORE_FAILURE))
2625 {
2626 correction = 0;
2627 snd_brk = (char *) (MORECORE (0));
2628 }
2629 else
2630 {
2631 /* Call the `morecore' hook if necessary. */
2632 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2633 if (__builtin_expect (hook != NULL, 0))
2634 (*hook)();
2635 }
2636 }
2637
2638 /* handle non-contiguous cases */
2639 else
2640 {
2641 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2642 /* MORECORE/mmap must correctly align */
2643 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2644 else
2645 {
2646 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2647 if (front_misalign > 0)
2648 {
2649 /*
2650 Skip over some bytes to arrive at an aligned position.
2651 We don't need to specially mark these wasted front bytes.
2652 They will never be accessed anyway because
2653 prev_inuse of av->top (and any chunk created from its start)
2654 is always true after initialization.
2655 */
2656
2657 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2658 }
2659 }
2660
2661 /* Find out current end of memory */
2662 if (snd_brk == (char *) (MORECORE_FAILURE))
2663 {
2664 snd_brk = (char *) (MORECORE (0));
2665 }
2666 }
2667
2668 /* Adjust top based on results of second sbrk */
2669 if (snd_brk != (char *) (MORECORE_FAILURE))
2670 {
2671 av->top = (mchunkptr) aligned_brk;
2672 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2673 av->system_mem += correction;
2674
2675 /*
2676 If not the first time through, we either have a
2677 gap due to foreign sbrk or a non-contiguous region. Insert a
2678 double fencepost at old_top to prevent consolidation with space
2679 we don't own. These fenceposts are artificial chunks that are
2680 marked as inuse and are in any case too small to use. We need
2681 two to make sizes and alignments work out.
2682 */
2683
2684 if (old_size != 0)
2685 {
2686 /*
2687 Shrink old_top to insert fenceposts, keeping size a
2688 multiple of MALLOC_ALIGNMENT. We know there is at least
2689 enough space in old_top to do this.
2690 */
2691 old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK;
2692 set_head (old_top, old_size | PREV_INUSE);
2693
2694 /*
2695 Note that the following assignments completely overwrite
2696 old_top when old_size was previously MINSIZE. This is
2697 intentional. We need the fencepost, even if old_top otherwise gets
2698 lost.
2699 */
2700 chunk_at_offset (old_top, old_size)->size =
2701 (2 * SIZE_SZ) | PREV_INUSE;
2702
2703 chunk_at_offset (old_top, old_size + 2 * SIZE_SZ)->size =
2704 (2 * SIZE_SZ) | PREV_INUSE;
2705
2706 /* If possible, release the rest. */
2707 if (old_size >= MINSIZE)
2708 {
2709 _int_free (av, old_top, 1);
2710 }
2711 }
2712 }
2713 }
2714 }
2715 } /* if (av != &main_arena) */
2716
2717 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
fa8d436c 2718 av->max_system_mem = av->system_mem;
6c8dbf00 2719 check_malloc_state (av);
a9177ff5 2720
fa8d436c
UD
2721 /* finally, do the allocation */
2722 p = av->top;
6c8dbf00 2723 size = chunksize (p);
fa8d436c
UD
2724
2725 /* check that one of the above allocation paths succeeded */
6c8dbf00
OB
2726 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2727 {
2728 remainder_size = size - nb;
2729 remainder = chunk_at_offset (p, nb);
2730 av->top = remainder;
2731 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2732 set_head (remainder, remainder_size | PREV_INUSE);
2733 check_malloced_chunk (av, p, nb);
2734 return chunk2mem (p);
2735 }
fa8d436c
UD
2736
2737 /* catch all failure paths */
8e58439c 2738 __set_errno (ENOMEM);
fa8d436c
UD
2739 return 0;
2740}
2741
2742
2743/*
6c8dbf00
OB
2744 systrim is an inverse of sorts to sysmalloc. It gives memory back
2745 to the system (via negative arguments to sbrk) if there is unused
2746 memory at the `high' end of the malloc pool. It is called
2747 automatically by free() when top space exceeds the trim
2748 threshold. It is also called by the public malloc_trim routine. It
2749 returns 1 if it actually released any memory, else 0.
2750 */
fa8d436c 2751
6c8dbf00
OB
2752static int
2753systrim (size_t pad, mstate av)
fa8d436c 2754{
6c8dbf00
OB
2755 long top_size; /* Amount of top-most memory */
2756 long extra; /* Amount to release */
2757 long released; /* Amount actually released */
2758 char *current_brk; /* address returned by pre-check sbrk call */
2759 char *new_brk; /* address returned by post-check sbrk call */
8a35c3fe 2760 size_t pagesize;
6c8dbf00 2761 long top_area;
fa8d436c 2762
8a35c3fe 2763 pagesize = GLRO (dl_pagesize);
6c8dbf00 2764 top_size = chunksize (av->top);
a9177ff5 2765
4b5b548c
FS
2766 top_area = top_size - MINSIZE - 1;
2767 if (top_area <= pad)
2768 return 0;
2769
fa8d436c 2770 /* Release in pagesize units, keeping at least one page */
8a35c3fe 2771 extra = (top_area - pad) & ~(pagesize - 1);
a9177ff5 2772
51a7380b
WN
2773 if (extra == 0)
2774 return 0;
2775
4b5b548c 2776 /*
6c8dbf00
OB
2777 Only proceed if end of memory is where we last set it.
2778 This avoids problems if there were foreign sbrk calls.
2779 */
2780 current_brk = (char *) (MORECORE (0));
2781 if (current_brk == (char *) (av->top) + top_size)
2782 {
2783 /*
2784 Attempt to release memory. We ignore MORECORE return value,
2785 and instead call again to find out where new end of memory is.
2786 This avoids problems if first call releases less than we asked,
2787 of if failure somehow altered brk value. (We could still
2788 encounter problems if it altered brk in some very bad way,
2789 but the only thing we can do is adjust anyway, which will cause
2790 some downstream failure.)
2791 */
2792
2793 MORECORE (-extra);
2794 /* Call the `morecore' hook if necessary. */
2795 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2796 if (__builtin_expect (hook != NULL, 0))
2797 (*hook)();
2798 new_brk = (char *) (MORECORE (0));
2799
2800 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2801
2802 if (new_brk != (char *) MORECORE_FAILURE)
2803 {
2804 released = (long) (current_brk - new_brk);
2805
2806 if (released != 0)
2807 {
2808 /* Success. Adjust top. */
2809 av->system_mem -= released;
2810 set_head (av->top, (top_size - released) | PREV_INUSE);
2811 check_malloc_state (av);
2812 return 1;
2813 }
2814 }
fa8d436c 2815 }
fa8d436c 2816 return 0;
f65fd747
UD
2817}
2818
431c33c0
UD
2819static void
2820internal_function
6c8dbf00 2821munmap_chunk (mchunkptr p)
f65fd747 2822{
6c8dbf00 2823 INTERNAL_SIZE_T size = chunksize (p);
f65fd747 2824
6c8dbf00 2825 assert (chunk_is_mmapped (p));
8e635611
UD
2826
2827 uintptr_t block = (uintptr_t) p - p->prev_size;
2828 size_t total_size = p->prev_size + size;
2829 /* Unfortunately we have to do the compilers job by hand here. Normally
2830 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2831 page size. But gcc does not recognize the optimization possibility
2832 (in the moment at least) so we combine the two values into one before
2833 the bit test. */
6c8dbf00 2834 if (__builtin_expect (((block | total_size) & (GLRO (dl_pagesize) - 1)) != 0, 0))
8e635611
UD
2835 {
2836 malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
fff94fa2 2837 chunk2mem (p), NULL);
8e635611
UD
2838 return;
2839 }
f65fd747 2840
c6e4925d
OB
2841 atomic_decrement (&mp_.n_mmaps);
2842 atomic_add (&mp_.mmapped_mem, -total_size);
f65fd747 2843
6ef76f3b
UD
2844 /* If munmap failed the process virtual memory address space is in a
2845 bad shape. Just leave the block hanging around, the process will
2846 terminate shortly anyway since not much can be done. */
6c8dbf00 2847 __munmap ((char *) block, total_size);
f65fd747
UD
2848}
2849
2850#if HAVE_MREMAP
2851
431c33c0
UD
2852static mchunkptr
2853internal_function
6c8dbf00 2854mremap_chunk (mchunkptr p, size_t new_size)
f65fd747 2855{
8a35c3fe 2856 size_t pagesize = GLRO (dl_pagesize);
f65fd747 2857 INTERNAL_SIZE_T offset = p->prev_size;
6c8dbf00 2858 INTERNAL_SIZE_T size = chunksize (p);
f65fd747
UD
2859 char *cp;
2860
6c8dbf00
OB
2861 assert (chunk_is_mmapped (p));
2862 assert (((size + offset) & (GLRO (dl_pagesize) - 1)) == 0);
f65fd747
UD
2863
2864 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
8a35c3fe 2865 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
f65fd747 2866
68f3802d
UD
2867 /* No need to remap if the number of pages does not change. */
2868 if (size + offset == new_size)
2869 return p;
2870
6c8dbf00
OB
2871 cp = (char *) __mremap ((char *) p - offset, size + offset, new_size,
2872 MREMAP_MAYMOVE);
f65fd747 2873
6c8dbf00
OB
2874 if (cp == MAP_FAILED)
2875 return 0;
f65fd747 2876
6c8dbf00 2877 p = (mchunkptr) (cp + offset);
f65fd747 2878
6c8dbf00 2879 assert (aligned_OK (chunk2mem (p)));
f65fd747 2880
6c8dbf00
OB
2881 assert ((p->prev_size == offset));
2882 set_head (p, (new_size - offset) | IS_MMAPPED);
f65fd747 2883
c6e4925d
OB
2884 INTERNAL_SIZE_T new;
2885 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
6c8dbf00 2886 + new_size - size - offset;
c6e4925d 2887 atomic_max (&mp_.max_mmapped_mem, new);
f65fd747
UD
2888 return p;
2889}
f65fd747
UD
2890#endif /* HAVE_MREMAP */
2891
fa8d436c 2892/*------------------------ Public wrappers. --------------------------------*/
f65fd747 2893
6c8dbf00
OB
2894void *
2895__libc_malloc (size_t bytes)
fa8d436c
UD
2896{
2897 mstate ar_ptr;
22a89187 2898 void *victim;
f65fd747 2899
a222d91a 2900 void *(*hook) (size_t, const void *)
f3eeb3fc 2901 = atomic_forced_read (__malloc_hook);
bfacf1af 2902 if (__builtin_expect (hook != NULL, 0))
fa8d436c 2903 return (*hook)(bytes, RETURN_ADDRESS (0));
f65fd747 2904
94c5a52a 2905 arena_get (ar_ptr, bytes);
425ce2ed 2906
6c8dbf00 2907 victim = _int_malloc (ar_ptr, bytes);
fff94fa2
SP
2908 /* Retry with another arena only if we were able to find a usable arena
2909 before. */
2910 if (!victim && ar_ptr != NULL)
6c8dbf00
OB
2911 {
2912 LIBC_PROBE (memory_malloc_retry, 1, bytes);
2913 ar_ptr = arena_get_retry (ar_ptr, bytes);
fff94fa2 2914 victim = _int_malloc (ar_ptr, bytes);
60f0e64b 2915 }
fff94fa2
SP
2916
2917 if (ar_ptr != NULL)
6c8dbf00 2918 (void) mutex_unlock (&ar_ptr->mutex);
fff94fa2 2919
6c8dbf00
OB
2920 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
2921 ar_ptr == arena_for_chunk (mem2chunk (victim)));
fa8d436c 2922 return victim;
f65fd747 2923}
6c8dbf00 2924libc_hidden_def (__libc_malloc)
f65fd747 2925
fa8d436c 2926void
6c8dbf00 2927__libc_free (void *mem)
f65fd747 2928{
fa8d436c
UD
2929 mstate ar_ptr;
2930 mchunkptr p; /* chunk corresponding to mem */
2931
a222d91a 2932 void (*hook) (void *, const void *)
f3eeb3fc 2933 = atomic_forced_read (__free_hook);
6c8dbf00
OB
2934 if (__builtin_expect (hook != NULL, 0))
2935 {
2936 (*hook)(mem, RETURN_ADDRESS (0));
2937 return;
2938 }
f65fd747 2939
fa8d436c
UD
2940 if (mem == 0) /* free(0) has no effect */
2941 return;
f65fd747 2942
6c8dbf00 2943 p = mem2chunk (mem);
f65fd747 2944
6c8dbf00
OB
2945 if (chunk_is_mmapped (p)) /* release mmapped memory. */
2946 {
2947 /* see if the dynamic brk/mmap threshold needs adjusting */
2948 if (!mp_.no_dyn_threshold
2949 && p->size > mp_.mmap_threshold
2950 && p->size <= DEFAULT_MMAP_THRESHOLD_MAX)
2951 {
2952 mp_.mmap_threshold = chunksize (p);
2953 mp_.trim_threshold = 2 * mp_.mmap_threshold;
2954 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
2955 mp_.mmap_threshold, mp_.trim_threshold);
2956 }
2957 munmap_chunk (p);
2958 return;
2959 }
f65fd747 2960
6c8dbf00
OB
2961 ar_ptr = arena_for_chunk (p);
2962 _int_free (ar_ptr, p, 0);
f65fd747 2963}
3b49edc0 2964libc_hidden_def (__libc_free)
f65fd747 2965
6c8dbf00
OB
2966void *
2967__libc_realloc (void *oldmem, size_t bytes)
f65fd747 2968{
fa8d436c 2969 mstate ar_ptr;
6c8dbf00 2970 INTERNAL_SIZE_T nb; /* padded request size */
f65fd747 2971
6c8dbf00 2972 void *newp; /* chunk to return */
f65fd747 2973
a222d91a 2974 void *(*hook) (void *, size_t, const void *) =
f3eeb3fc 2975 atomic_forced_read (__realloc_hook);
bfacf1af 2976 if (__builtin_expect (hook != NULL, 0))
fa8d436c 2977 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
f65fd747 2978
fa8d436c 2979#if REALLOC_ZERO_BYTES_FREES
6c8dbf00
OB
2980 if (bytes == 0 && oldmem != NULL)
2981 {
2982 __libc_free (oldmem); return 0;
2983 }
f65fd747 2984#endif
f65fd747 2985
fa8d436c 2986 /* realloc of null is supposed to be same as malloc */
6c8dbf00
OB
2987 if (oldmem == 0)
2988 return __libc_malloc (bytes);
f65fd747 2989
78ac92ad 2990 /* chunk corresponding to oldmem */
6c8dbf00 2991 const mchunkptr oldp = mem2chunk (oldmem);
78ac92ad 2992 /* its size */
6c8dbf00 2993 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
f65fd747 2994
fff94fa2
SP
2995 if (chunk_is_mmapped (oldp))
2996 ar_ptr = NULL;
2997 else
2998 ar_ptr = arena_for_chunk (oldp);
2999
dc165f7b
UD
3000 /* Little security check which won't hurt performance: the
3001 allocator never wrapps around at the end of the address space.
3002 Therefore we can exclude some size values which might appear
3003 here by accident or by "design" from some intruder. */
3004 if (__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
073f560e 3005 || __builtin_expect (misaligned_chunk (oldp), 0))
dc165f7b 3006 {
fff94fa2
SP
3007 malloc_printerr (check_action, "realloc(): invalid pointer", oldmem,
3008 ar_ptr);
dc165f7b
UD
3009 return NULL;
3010 }
3011
6c8dbf00 3012 checked_request2size (bytes, nb);
f65fd747 3013
6c8dbf00
OB
3014 if (chunk_is_mmapped (oldp))
3015 {
3016 void *newmem;
f65fd747 3017
fa8d436c 3018#if HAVE_MREMAP
6c8dbf00
OB
3019 newp = mremap_chunk (oldp, nb);
3020 if (newp)
3021 return chunk2mem (newp);
f65fd747 3022#endif
6c8dbf00
OB
3023 /* Note the extra SIZE_SZ overhead. */
3024 if (oldsize - SIZE_SZ >= nb)
3025 return oldmem; /* do nothing */
3026
3027 /* Must alloc, copy, free. */
3028 newmem = __libc_malloc (bytes);
3029 if (newmem == 0)
3030 return 0; /* propagate failure */
fa8d436c 3031
6c8dbf00
OB
3032 memcpy (newmem, oldmem, oldsize - 2 * SIZE_SZ);
3033 munmap_chunk (oldp);
3034 return newmem;
3035 }
3036
6c8dbf00 3037 (void) mutex_lock (&ar_ptr->mutex);
f65fd747 3038
6c8dbf00 3039 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
f65fd747 3040
6c8dbf00
OB
3041 (void) mutex_unlock (&ar_ptr->mutex);
3042 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3043 ar_ptr == arena_for_chunk (mem2chunk (newp)));
07014fca
UD
3044
3045 if (newp == NULL)
3046 {
3047 /* Try harder to allocate memory in other arenas. */
35fed6f1 3048 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
6c8dbf00 3049 newp = __libc_malloc (bytes);
07014fca 3050 if (newp != NULL)
6c8dbf00
OB
3051 {
3052 memcpy (newp, oldmem, oldsize - SIZE_SZ);
3053 _int_free (ar_ptr, oldp, 0);
3054 }
07014fca
UD
3055 }
3056
fa8d436c
UD
3057 return newp;
3058}
3b49edc0 3059libc_hidden_def (__libc_realloc)
f65fd747 3060
6c8dbf00
OB
3061void *
3062__libc_memalign (size_t alignment, size_t bytes)
10ad46bc
OB
3063{
3064 void *address = RETURN_ADDRESS (0);
3065 return _mid_memalign (alignment, bytes, address);
3066}
3067
3068static void *
3069_mid_memalign (size_t alignment, size_t bytes, void *address)
fa8d436c
UD
3070{
3071 mstate ar_ptr;
22a89187 3072 void *p;
f65fd747 3073
a222d91a 3074 void *(*hook) (size_t, size_t, const void *) =
f3eeb3fc 3075 atomic_forced_read (__memalign_hook);
bfacf1af 3076 if (__builtin_expect (hook != NULL, 0))
10ad46bc 3077 return (*hook)(alignment, bytes, address);
f65fd747 3078
10ad46bc 3079 /* If we need less alignment than we give anyway, just relay to malloc. */
6c8dbf00
OB
3080 if (alignment <= MALLOC_ALIGNMENT)
3081 return __libc_malloc (bytes);
1228ed5c 3082
fa8d436c 3083 /* Otherwise, ensure that it is at least a minimum chunk size */
6c8dbf00
OB
3084 if (alignment < MINSIZE)
3085 alignment = MINSIZE;
f65fd747 3086
a56ee40b
WN
3087 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3088 power of 2 and will cause overflow in the check below. */
3089 if (alignment > SIZE_MAX / 2 + 1)
3090 {
3091 __set_errno (EINVAL);
3092 return 0;
3093 }
3094
b73ed247
WN
3095 /* Check for overflow. */
3096 if (bytes > SIZE_MAX - alignment - MINSIZE)
3097 {
3098 __set_errno (ENOMEM);
3099 return 0;
3100 }
3101
10ad46bc
OB
3102
3103 /* Make sure alignment is power of 2. */
6c8dbf00
OB
3104 if (!powerof2 (alignment))
3105 {
3106 size_t a = MALLOC_ALIGNMENT * 2;
3107 while (a < alignment)
3108 a <<= 1;
3109 alignment = a;
3110 }
10ad46bc 3111
6c8dbf00 3112 arena_get (ar_ptr, bytes + alignment + MINSIZE);
6c8dbf00
OB
3113
3114 p = _int_memalign (ar_ptr, alignment, bytes);
fff94fa2 3115 if (!p && ar_ptr != NULL)
6c8dbf00
OB
3116 {
3117 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3118 ar_ptr = arena_get_retry (ar_ptr, bytes);
fff94fa2 3119 p = _int_memalign (ar_ptr, alignment, bytes);
f65fd747 3120 }
fff94fa2
SP
3121
3122 if (ar_ptr != NULL)
6c8dbf00 3123 (void) mutex_unlock (&ar_ptr->mutex);
fff94fa2 3124
6c8dbf00
OB
3125 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3126 ar_ptr == arena_for_chunk (mem2chunk (p)));
fa8d436c 3127 return p;
f65fd747 3128}
380d7e87 3129/* For ISO C11. */
3b49edc0
UD
3130weak_alias (__libc_memalign, aligned_alloc)
3131libc_hidden_def (__libc_memalign)
f65fd747 3132
6c8dbf00
OB
3133void *
3134__libc_valloc (size_t bytes)
fa8d436c 3135{
6c8dbf00 3136 if (__malloc_initialized < 0)
fa8d436c 3137 ptmalloc_init ();
8088488d 3138
10ad46bc 3139 void *address = RETURN_ADDRESS (0);
8a35c3fe
CD
3140 size_t pagesize = GLRO (dl_pagesize);
3141 return _mid_memalign (pagesize, bytes, address);
fa8d436c 3142}
f65fd747 3143
6c8dbf00
OB
3144void *
3145__libc_pvalloc (size_t bytes)
fa8d436c 3146{
6c8dbf00 3147 if (__malloc_initialized < 0)
fa8d436c 3148 ptmalloc_init ();
8088488d 3149
10ad46bc 3150 void *address = RETURN_ADDRESS (0);
8a35c3fe
CD
3151 size_t pagesize = GLRO (dl_pagesize);
3152 size_t rounded_bytes = ALIGN_UP (bytes, pagesize);
dba38551 3153
1159a193 3154 /* Check for overflow. */
8a35c3fe 3155 if (bytes > SIZE_MAX - 2 * pagesize - MINSIZE)
1159a193
WN
3156 {
3157 __set_errno (ENOMEM);
3158 return 0;
3159 }
3160
8a35c3fe 3161 return _mid_memalign (pagesize, rounded_bytes, address);
fa8d436c 3162}
f65fd747 3163
6c8dbf00
OB
3164void *
3165__libc_calloc (size_t n, size_t elem_size)
f65fd747 3166{
d6285c9f
CD
3167 mstate av;
3168 mchunkptr oldtop, p;
3169 INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
6c8dbf00 3170 void *mem;
d6285c9f
CD
3171 unsigned long clearsize;
3172 unsigned long nclears;
3173 INTERNAL_SIZE_T *d;
0950889b
UD
3174
3175 /* size_t is unsigned so the behavior on overflow is defined. */
3176 bytes = n * elem_size;
d9af917d
UD
3177#define HALF_INTERNAL_SIZE_T \
3178 (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
6c8dbf00
OB
3179 if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0))
3180 {
3181 if (elem_size != 0 && bytes / elem_size != n)
3182 {
3183 __set_errno (ENOMEM);
3184 return 0;
3185 }
d9af917d 3186 }
0950889b 3187
a222d91a 3188 void *(*hook) (size_t, const void *) =
f3eeb3fc 3189 atomic_forced_read (__malloc_hook);
6c8dbf00
OB
3190 if (__builtin_expect (hook != NULL, 0))
3191 {
d6285c9f
CD
3192 sz = bytes;
3193 mem = (*hook)(sz, RETURN_ADDRESS (0));
3194 if (mem == 0)
3195 return 0;
3196
3197 return memset (mem, 0, sz);
7799b7b3 3198 }
f65fd747 3199
d6285c9f
CD
3200 sz = bytes;
3201
3202 arena_get (av, sz);
fff94fa2
SP
3203 if (av)
3204 {
3205 /* Check if we hand out the top chunk, in which case there may be no
3206 need to clear. */
d6285c9f 3207#if MORECORE_CLEARS
fff94fa2
SP
3208 oldtop = top (av);
3209 oldtopsize = chunksize (top (av));
d6285c9f 3210# if MORECORE_CLEARS < 2
fff94fa2
SP
3211 /* Only newly allocated memory is guaranteed to be cleared. */
3212 if (av == &main_arena &&
3213 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3214 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
d6285c9f 3215# endif
fff94fa2
SP
3216 if (av != &main_arena)
3217 {
3218 heap_info *heap = heap_for_ptr (oldtop);
3219 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3220 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3221 }
3222#endif
3223 }
3224 else
d6285c9f 3225 {
fff94fa2
SP
3226 /* No usable arenas. */
3227 oldtop = 0;
3228 oldtopsize = 0;
d6285c9f 3229 }
d6285c9f
CD
3230 mem = _int_malloc (av, sz);
3231
3232
3233 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3234 av == arena_for_chunk (mem2chunk (mem)));
3235
fff94fa2 3236 if (mem == 0 && av != NULL)
d6285c9f
CD
3237 {
3238 LIBC_PROBE (memory_calloc_retry, 1, sz);
3239 av = arena_get_retry (av, sz);
fff94fa2 3240 mem = _int_malloc (av, sz);
d6285c9f 3241 }
fff94fa2
SP
3242
3243 if (av != NULL)
d6285c9f 3244 (void) mutex_unlock (&av->mutex);
fff94fa2
SP
3245
3246 /* Allocation failed even after a retry. */
3247 if (mem == 0)
3248 return 0;
3249
d6285c9f
CD
3250 p = mem2chunk (mem);
3251
3252 /* Two optional cases in which clearing not necessary */
3253 if (chunk_is_mmapped (p))
3254 {
3255 if (__builtin_expect (perturb_byte, 0))
3256 return memset (mem, 0, sz);
3257
3258 return mem;
3259 }
3260
3261 csz = chunksize (p);
3262
3263#if MORECORE_CLEARS
3264 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3265 {
3266 /* clear only the bytes from non-freshly-sbrked memory */
3267 csz = oldtopsize;
3268 }
3269#endif
3270
3271 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3272 contents have an odd number of INTERNAL_SIZE_T-sized words;
3273 minimally 3. */
3274 d = (INTERNAL_SIZE_T *) mem;
3275 clearsize = csz - SIZE_SZ;
3276 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3277 assert (nclears >= 3);
3278
3279 if (nclears > 9)
3280 return memset (d, 0, clearsize);
3281
3282 else
3283 {
3284 *(d + 0) = 0;
3285 *(d + 1) = 0;
3286 *(d + 2) = 0;
3287 if (nclears > 4)
3288 {
3289 *(d + 3) = 0;
3290 *(d + 4) = 0;
3291 if (nclears > 6)
3292 {
3293 *(d + 5) = 0;
3294 *(d + 6) = 0;
3295 if (nclears > 8)
3296 {
3297 *(d + 7) = 0;
3298 *(d + 8) = 0;
3299 }
3300 }
3301 }
3302 }
3303
3304 return mem;
fa8d436c 3305}
f65fd747 3306
f65fd747 3307/*
6c8dbf00
OB
3308 ------------------------------ malloc ------------------------------
3309 */
f65fd747 3310
6c8dbf00
OB
3311static void *
3312_int_malloc (mstate av, size_t bytes)
f65fd747 3313{
fa8d436c 3314 INTERNAL_SIZE_T nb; /* normalized request size */
6c8dbf00
OB
3315 unsigned int idx; /* associated bin index */
3316 mbinptr bin; /* associated bin */
f65fd747 3317
6c8dbf00 3318 mchunkptr victim; /* inspected/selected chunk */
fa8d436c 3319 INTERNAL_SIZE_T size; /* its size */
6c8dbf00 3320 int victim_index; /* its bin index */
f65fd747 3321
6c8dbf00
OB
3322 mchunkptr remainder; /* remainder from a split */
3323 unsigned long remainder_size; /* its size */
8a4b65b4 3324
6c8dbf00
OB
3325 unsigned int block; /* bit map traverser */
3326 unsigned int bit; /* bit map traverser */
3327 unsigned int map; /* current word of binmap */
8a4b65b4 3328
6c8dbf00
OB
3329 mchunkptr fwd; /* misc temp for linking */
3330 mchunkptr bck; /* misc temp for linking */
8a4b65b4 3331
f6887a0d
UD
3332 const char *errstr = NULL;
3333
fa8d436c 3334 /*
6c8dbf00
OB
3335 Convert request size to internal form by adding SIZE_SZ bytes
3336 overhead plus possibly more to obtain necessary alignment and/or
3337 to obtain a size of at least MINSIZE, the smallest allocatable
3338 size. Also, checked_request2size traps (returning 0) request sizes
3339 that are so large that they wrap around zero when padded and
3340 aligned.
3341 */
f65fd747 3342
6c8dbf00 3343 checked_request2size (bytes, nb);
f65fd747 3344
fff94fa2
SP
3345 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3346 mmap. */
3347 if (__glibc_unlikely (av == NULL))
3348 {
3349 void *p = sysmalloc (nb, av);
3350 if (p != NULL)
3351 alloc_perturb (p, bytes);
3352 return p;
3353 }
3354
fa8d436c 3355 /*
6c8dbf00
OB
3356 If the size qualifies as a fastbin, first check corresponding bin.
3357 This code is safe to execute even if av is not yet initialized, so we
3358 can try it without checking, which saves some time on this fast path.
3359 */
f65fd747 3360
6c8dbf00
OB
3361 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3362 {
3363 idx = fastbin_index (nb);
3364 mfastbinptr *fb = &fastbin (av, idx);
3365 mchunkptr pp = *fb;
3366 do
3367 {
3368 victim = pp;
3369 if (victim == NULL)
3370 break;
3371 }
3372 while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim))
3373 != victim);
3374 if (victim != 0)
3375 {
3376 if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
3377 {
3378 errstr = "malloc(): memory corruption (fast)";
3379 errout:
fff94fa2 3380 malloc_printerr (check_action, errstr, chunk2mem (victim), av);
6c8dbf00
OB
3381 return NULL;
3382 }
3383 check_remalloced_chunk (av, victim, nb);
3384 void *p = chunk2mem (victim);
3385 alloc_perturb (p, bytes);
3386 return p;
3387 }
fa8d436c 3388 }
f65fd747 3389
fa8d436c 3390 /*
6c8dbf00
OB
3391 If a small request, check regular bin. Since these "smallbins"
3392 hold one size each, no searching within bins is necessary.
3393 (For a large request, we need to wait until unsorted chunks are
3394 processed to find best fit. But for small ones, fits are exact
3395 anyway, so we can check now, which is faster.)
3396 */
3397
3398 if (in_smallbin_range (nb))
3399 {
3400 idx = smallbin_index (nb);
3401 bin = bin_at (av, idx);
3402
3403 if ((victim = last (bin)) != bin)
3404 {
3405 if (victim == 0) /* initialization check */
3406 malloc_consolidate (av);
3407 else
3408 {
3409 bck = victim->bk;
a1ffb40e 3410 if (__glibc_unlikely (bck->fd != victim))
6c8dbf00
OB
3411 {
3412 errstr = "malloc(): smallbin double linked list corrupted";
3413 goto errout;
3414 }
3415 set_inuse_bit_at_offset (victim, nb);
3416 bin->bk = bck;
3417 bck->fd = bin;
3418
3419 if (av != &main_arena)
3420 victim->size |= NON_MAIN_ARENA;
3421 check_malloced_chunk (av, victim, nb);
3422 void *p = chunk2mem (victim);
3423 alloc_perturb (p, bytes);
3424 return p;
3425 }
3426 }
fa8d436c 3427 }
f65fd747 3428
a9177ff5 3429 /*
fa8d436c
UD
3430 If this is a large request, consolidate fastbins before continuing.
3431 While it might look excessive to kill all fastbins before
3432 even seeing if there is space available, this avoids
3433 fragmentation problems normally associated with fastbins.
3434 Also, in practice, programs tend to have runs of either small or
a9177ff5 3435 large requests, but less often mixtures, so consolidation is not
fa8d436c
UD
3436 invoked all that often in most programs. And the programs that
3437 it is called frequently in otherwise tend to fragment.
6c8dbf00 3438 */
7799b7b3 3439
6c8dbf00
OB
3440 else
3441 {
3442 idx = largebin_index (nb);
3443 if (have_fastchunks (av))
3444 malloc_consolidate (av);
3445 }
f65fd747 3446
fa8d436c 3447 /*
6c8dbf00
OB
3448 Process recently freed or remaindered chunks, taking one only if
3449 it is exact fit, or, if this a small request, the chunk is remainder from
3450 the most recent non-exact fit. Place other traversed chunks in
3451 bins. Note that this step is the only place in any routine where
3452 chunks are placed in bins.
3453
3454 The outer loop here is needed because we might not realize until
3455 near the end of malloc that we should have consolidated, so must
3456 do so and retry. This happens at most once, and only when we would
3457 otherwise need to expand memory to service a "small" request.
3458 */
3459
3460 for (;; )
3461 {
3462 int iters = 0;
3463 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3464 {
3465 bck = victim->bk;
3466 if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0)
3467 || __builtin_expect (victim->size > av->system_mem, 0))
3468 malloc_printerr (check_action, "malloc(): memory corruption",
fff94fa2 3469 chunk2mem (victim), av);
6c8dbf00
OB
3470 size = chunksize (victim);
3471
3472 /*
3473 If a small request, try to use last remainder if it is the
3474 only chunk in unsorted bin. This helps promote locality for
3475 runs of consecutive small requests. This is the only
3476 exception to best-fit, and applies only when there is
3477 no exact fit for a small chunk.
3478 */
3479
3480 if (in_smallbin_range (nb) &&
3481 bck == unsorted_chunks (av) &&
3482 victim == av->last_remainder &&
3483 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
3484 {
3485 /* split and reattach remainder */
3486 remainder_size = size - nb;
3487 remainder = chunk_at_offset (victim, nb);
3488 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
3489 av->last_remainder = remainder;
3490 remainder->bk = remainder->fd = unsorted_chunks (av);
3491 if (!in_smallbin_range (remainder_size))
3492 {
3493 remainder->fd_nextsize = NULL;
3494 remainder->bk_nextsize = NULL;
3495 }
3496
3497 set_head (victim, nb | PREV_INUSE |
3498 (av != &main_arena ? NON_MAIN_ARENA : 0));
3499 set_head (remainder, remainder_size | PREV_INUSE);
3500 set_foot (remainder, remainder_size);
3501
3502 check_malloced_chunk (av, victim, nb);
3503 void *p = chunk2mem (victim);
3504 alloc_perturb (p, bytes);
3505 return p;
3506 }
3507
3508 /* remove from unsorted list */
3509 unsorted_chunks (av)->bk = bck;
3510 bck->fd = unsorted_chunks (av);
3511
3512 /* Take now instead of binning if exact fit */
3513
3514 if (size == nb)
3515 {
3516 set_inuse_bit_at_offset (victim, size);
3517 if (av != &main_arena)
3518 victim->size |= NON_MAIN_ARENA;
3519 check_malloced_chunk (av, victim, nb);
3520 void *p = chunk2mem (victim);
3521 alloc_perturb (p, bytes);
3522 return p;
3523 }
3524
3525 /* place chunk in bin */
3526
3527 if (in_smallbin_range (size))
3528 {
3529 victim_index = smallbin_index (size);
3530 bck = bin_at (av, victim_index);
3531 fwd = bck->fd;
3532 }
3533 else
3534 {
3535 victim_index = largebin_index (size);
3536 bck = bin_at (av, victim_index);
3537 fwd = bck->fd;
3538
3539 /* maintain large bins in sorted order */
3540 if (fwd != bck)
3541 {
3542 /* Or with inuse bit to speed comparisons */
3543 size |= PREV_INUSE;
3544 /* if smaller than smallest, bypass loop below */
3545 assert ((bck->bk->size & NON_MAIN_ARENA) == 0);
3546 if ((unsigned long) (size) < (unsigned long) (bck->bk->size))
3547 {
3548 fwd = bck;
3549 bck = bck->bk;
3550
3551 victim->fd_nextsize = fwd->fd;
3552 victim->bk_nextsize = fwd->fd->bk_nextsize;
3553 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
3554 }
3555 else
3556 {
3557 assert ((fwd->size & NON_MAIN_ARENA) == 0);
3558 while ((unsigned long) size < fwd->size)
3559 {
3560 fwd = fwd->fd_nextsize;
3561 assert ((fwd->size & NON_MAIN_ARENA) == 0);
3562 }
3563
3564 if ((unsigned long) size == (unsigned long) fwd->size)
3565 /* Always insert in the second position. */
3566 fwd = fwd->fd;
3567 else
3568 {
3569 victim->fd_nextsize = fwd;
3570 victim->bk_nextsize = fwd->bk_nextsize;
3571 fwd->bk_nextsize = victim;
3572 victim->bk_nextsize->fd_nextsize = victim;
3573 }
3574 bck = fwd->bk;
3575 }
3576 }
3577 else
3578 victim->fd_nextsize = victim->bk_nextsize = victim;
3579 }
3580
3581 mark_bin (av, victim_index);
3582 victim->bk = bck;
3583 victim->fd = fwd;
3584 fwd->bk = victim;
3585 bck->fd = victim;
3586
3587#define MAX_ITERS 10000
3588 if (++iters >= MAX_ITERS)
3589 break;
3590 }
fa8d436c 3591
a9177ff5 3592 /*
6c8dbf00
OB
3593 If a large request, scan through the chunks of current bin in
3594 sorted order to find smallest that fits. Use the skip list for this.
3595 */
3596
3597 if (!in_smallbin_range (nb))
3598 {
3599 bin = bin_at (av, idx);
3600
3601 /* skip scan if empty or largest chunk is too small */
3602 if ((victim = first (bin)) != bin &&
3603 (unsigned long) (victim->size) >= (unsigned long) (nb))
3604 {
3605 victim = victim->bk_nextsize;
3606 while (((unsigned long) (size = chunksize (victim)) <
3607 (unsigned long) (nb)))
3608 victim = victim->bk_nextsize;
3609
3610 /* Avoid removing the first entry for a size so that the skip
3611 list does not have to be rerouted. */
3612 if (victim != last (bin) && victim->size == victim->fd->size)
3613 victim = victim->fd;
3614
3615 remainder_size = size - nb;
fff94fa2 3616 unlink (av, victim, bck, fwd);
6c8dbf00
OB
3617
3618 /* Exhaust */
3619 if (remainder_size < MINSIZE)
3620 {
3621 set_inuse_bit_at_offset (victim, size);
3622 if (av != &main_arena)
3623 victim->size |= NON_MAIN_ARENA;
3624 }
3625 /* Split */
3626 else
3627 {
3628 remainder = chunk_at_offset (victim, nb);
3629 /* We cannot assume the unsorted list is empty and therefore
3630 have to perform a complete insert here. */
3631 bck = unsorted_chunks (av);
3632 fwd = bck->fd;
a1ffb40e 3633 if (__glibc_unlikely (fwd->bk != bck))
6c8dbf00
OB
3634 {
3635 errstr = "malloc(): corrupted unsorted chunks";
3636 goto errout;
3637 }
3638 remainder->bk = bck;
3639 remainder->fd = fwd;
3640 bck->fd = remainder;
3641 fwd->bk = remainder;
3642 if (!in_smallbin_range (remainder_size))
3643 {
3644 remainder->fd_nextsize = NULL;
3645 remainder->bk_nextsize = NULL;
3646 }
3647 set_head (victim, nb | PREV_INUSE |
3648 (av != &main_arena ? NON_MAIN_ARENA : 0));
3649 set_head (remainder, remainder_size | PREV_INUSE);
3650 set_foot (remainder, remainder_size);
3651 }
3652 check_malloced_chunk (av, victim, nb);
3653 void *p = chunk2mem (victim);
3654 alloc_perturb (p, bytes);
3655 return p;
3656 }
3657 }
f65fd747 3658
6c8dbf00
OB
3659 /*
3660 Search for a chunk by scanning bins, starting with next largest
3661 bin. This search is strictly by best-fit; i.e., the smallest
3662 (with ties going to approximately the least recently used) chunk
3663 that fits is selected.
3664
3665 The bitmap avoids needing to check that most blocks are nonempty.
3666 The particular case of skipping all bins during warm-up phases
3667 when no chunks have been returned yet is faster than it might look.
3668 */
3669
3670 ++idx;
3671 bin = bin_at (av, idx);
3672 block = idx2block (idx);
3673 map = av->binmap[block];
3674 bit = idx2bit (idx);
3675
3676 for (;; )
3677 {
3678 /* Skip rest of block if there are no more set bits in this block. */
3679 if (bit > map || bit == 0)
3680 {
3681 do
3682 {
3683 if (++block >= BINMAPSIZE) /* out of bins */
3684 goto use_top;
3685 }
3686 while ((map = av->binmap[block]) == 0);
3687
3688 bin = bin_at (av, (block << BINMAPSHIFT));
3689 bit = 1;
3690 }
3691
3692 /* Advance to bin with set bit. There must be one. */
3693 while ((bit & map) == 0)
3694 {
3695 bin = next_bin (bin);
3696 bit <<= 1;
3697 assert (bit != 0);
3698 }
3699
3700 /* Inspect the bin. It is likely to be non-empty */
3701 victim = last (bin);
3702
3703 /* If a false alarm (empty bin), clear the bit. */
3704 if (victim == bin)
3705 {
3706 av->binmap[block] = map &= ~bit; /* Write through */
3707 bin = next_bin (bin);
3708 bit <<= 1;
3709 }
3710
3711 else
3712 {
3713 size = chunksize (victim);
3714
3715 /* We know the first chunk in this bin is big enough to use. */
3716 assert ((unsigned long) (size) >= (unsigned long) (nb));
3717
3718 remainder_size = size - nb;
3719
3720 /* unlink */
fff94fa2 3721 unlink (av, victim, bck, fwd);
6c8dbf00
OB
3722
3723 /* Exhaust */
3724 if (remainder_size < MINSIZE)
3725 {
3726 set_inuse_bit_at_offset (victim, size);
3727 if (av != &main_arena)
3728 victim->size |= NON_MAIN_ARENA;
3729 }
3730
3731 /* Split */
3732 else
3733 {
3734 remainder = chunk_at_offset (victim, nb);
3735
3736 /* We cannot assume the unsorted list is empty and therefore
3737 have to perform a complete insert here. */
3738 bck = unsorted_chunks (av);
3739 fwd = bck->fd;
a1ffb40e 3740 if (__glibc_unlikely (fwd->bk != bck))
6c8dbf00
OB
3741 {
3742 errstr = "malloc(): corrupted unsorted chunks 2";
3743 goto errout;
3744 }
3745 remainder->bk = bck;
3746 remainder->fd = fwd;
3747 bck->fd = remainder;
3748 fwd->bk = remainder;
3749
3750 /* advertise as last remainder */
3751 if (in_smallbin_range (nb))
3752 av->last_remainder = remainder;
3753 if (!in_smallbin_range (remainder_size))
3754 {
3755 remainder->fd_nextsize = NULL;
3756 remainder->bk_nextsize = NULL;
3757 }
3758 set_head (victim, nb | PREV_INUSE |
3759 (av != &main_arena ? NON_MAIN_ARENA : 0));
3760 set_head (remainder, remainder_size | PREV_INUSE);
3761 set_foot (remainder, remainder_size);
3762 }
3763 check_malloced_chunk (av, victim, nb);
3764 void *p = chunk2mem (victim);
3765 alloc_perturb (p, bytes);
3766 return p;
3767 }
3768 }
3769
3770 use_top:
3771 /*
3772 If large enough, split off the chunk bordering the end of memory
3773 (held in av->top). Note that this is in accord with the best-fit
3774 search rule. In effect, av->top is treated as larger (and thus
3775 less well fitting) than any other available chunk since it can
3776 be extended to be as large as necessary (up to system
3777 limitations).
3778
3779 We require that av->top always exists (i.e., has size >=
3780 MINSIZE) after initialization, so if it would otherwise be
3781 exhausted by current request, it is replenished. (The main
3782 reason for ensuring it exists is that we may need MINSIZE space
3783 to put in fenceposts in sysmalloc.)
3784 */
3785
3786 victim = av->top;
3787 size = chunksize (victim);
3788
3789 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
3790 {
3791 remainder_size = size - nb;
3792 remainder = chunk_at_offset (victim, nb);
3793 av->top = remainder;
3794 set_head (victim, nb | PREV_INUSE |
3795 (av != &main_arena ? NON_MAIN_ARENA : 0));
3796 set_head (remainder, remainder_size | PREV_INUSE);
3797
3798 check_malloced_chunk (av, victim, nb);
3799 void *p = chunk2mem (victim);
3800 alloc_perturb (p, bytes);
3801 return p;
3802 }
3803
3804 /* When we are using atomic ops to free fast chunks we can get
3805 here for all block sizes. */
3806 else if (have_fastchunks (av))
3807 {
3808 malloc_consolidate (av);
3809 /* restore original bin index */
3810 if (in_smallbin_range (nb))
3811 idx = smallbin_index (nb);
3812 else
3813 idx = largebin_index (nb);
3814 }
f65fd747 3815
6c8dbf00
OB
3816 /*
3817 Otherwise, relay to handle system-dependent cases
3818 */
425ce2ed 3819 else
6c8dbf00
OB
3820 {
3821 void *p = sysmalloc (nb, av);
3822 if (p != NULL)
3823 alloc_perturb (p, bytes);
3824 return p;
3825 }
425ce2ed 3826 }
fa8d436c 3827}
f65fd747 3828
fa8d436c 3829/*
6c8dbf00
OB
3830 ------------------------------ free ------------------------------
3831 */
f65fd747 3832
78ac92ad 3833static void
6c8dbf00 3834_int_free (mstate av, mchunkptr p, int have_lock)
f65fd747 3835{
fa8d436c 3836 INTERNAL_SIZE_T size; /* its size */
6c8dbf00
OB
3837 mfastbinptr *fb; /* associated fastbin */
3838 mchunkptr nextchunk; /* next contiguous chunk */
fa8d436c 3839 INTERNAL_SIZE_T nextsize; /* its size */
6c8dbf00 3840 int nextinuse; /* true if nextchunk is used */
fa8d436c 3841 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
6c8dbf00
OB
3842 mchunkptr bck; /* misc temp for linking */
3843 mchunkptr fwd; /* misc temp for linking */
fa8d436c 3844
37fa1953 3845 const char *errstr = NULL;
425ce2ed 3846 int locked = 0;
f65fd747 3847
6c8dbf00 3848 size = chunksize (p);
f65fd747 3849
37fa1953
UD
3850 /* Little security check which won't hurt performance: the
3851 allocator never wrapps around at the end of the address space.
3852 Therefore we can exclude some size values which might appear
3853 here by accident or by "design" from some intruder. */
dc165f7b 3854 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
073f560e 3855 || __builtin_expect (misaligned_chunk (p), 0))
37fa1953
UD
3856 {
3857 errstr = "free(): invalid pointer";
3858 errout:
6c8dbf00
OB
3859 if (!have_lock && locked)
3860 (void) mutex_unlock (&av->mutex);
fff94fa2 3861 malloc_printerr (check_action, errstr, chunk2mem (p), av);
37fa1953 3862 return;
fa8d436c 3863 }
347c92e9
L
3864 /* We know that each chunk is at least MINSIZE bytes in size or a
3865 multiple of MALLOC_ALIGNMENT. */
a1ffb40e 3866 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
bf589066
UD
3867 {
3868 errstr = "free(): invalid size";
3869 goto errout;
3870 }
f65fd747 3871
37fa1953 3872 check_inuse_chunk(av, p);
f65fd747 3873
37fa1953
UD
3874 /*
3875 If eligible, place chunk on a fastbin so it can be found
3876 and used quickly in malloc.
3877 */
6bf4302e 3878
9bf248c6 3879 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
6bf4302e 3880
37fa1953
UD
3881#if TRIM_FASTBINS
3882 /*
3883 If TRIM_FASTBINS set, don't place chunks
3884 bordering top into fastbins
3885 */
3886 && (chunk_at_offset(p, size) != av->top)
3887#endif
3888 ) {
fa8d436c 3889
893e6098
UD
3890 if (__builtin_expect (chunk_at_offset (p, size)->size <= 2 * SIZE_SZ, 0)
3891 || __builtin_expect (chunksize (chunk_at_offset (p, size))
3892 >= av->system_mem, 0))
3893 {
bec466d9
UD
3894 /* We might not have a lock at this point and concurrent modifications
3895 of system_mem might have let to a false positive. Redo the test
3896 after getting the lock. */
3897 if (have_lock
3898 || ({ assert (locked == 0);
3899 mutex_lock(&av->mutex);
3900 locked = 1;
3901 chunk_at_offset (p, size)->size <= 2 * SIZE_SZ
3902 || chunksize (chunk_at_offset (p, size)) >= av->system_mem;
3903 }))
bec466d9
UD
3904 {
3905 errstr = "free(): invalid next size (fast)";
3906 goto errout;
3907 }
bec466d9
UD
3908 if (! have_lock)
3909 {
3910 (void)mutex_unlock(&av->mutex);
3911 locked = 0;
3912 }
893e6098
UD
3913 }
3914
e8349efd 3915 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
425ce2ed 3916
37fa1953 3917 set_fastchunks(av);
90a3055e
UD
3918 unsigned int idx = fastbin_index(size);
3919 fb = &fastbin (av, idx);
425ce2ed 3920
362b47fe
MK
3921 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
3922 mchunkptr old = *fb, old2;
5f24d53a 3923 unsigned int old_idx = ~0u;
425ce2ed
UD
3924 do
3925 {
362b47fe
MK
3926 /* Check that the top of the bin is not the record we are going to add
3927 (i.e., double free). */
425ce2ed
UD
3928 if (__builtin_expect (old == p, 0))
3929 {
3930 errstr = "double free or corruption (fasttop)";
3931 goto errout;
3932 }
362b47fe
MK
3933 /* Check that size of fastbin chunk at the top is the same as
3934 size of the chunk that we are adding. We can dereference OLD
3935 only if we have the lock, otherwise it might have already been
3936 deallocated. See use of OLD_IDX below for the actual check. */
3937 if (have_lock && old != NULL)
5f24d53a 3938 old_idx = fastbin_index(chunksize(old));
362b47fe 3939 p->fd = old2 = old;
425ce2ed 3940 }
362b47fe 3941 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2)) != old2);
5f24d53a 3942
362b47fe 3943 if (have_lock && old != NULL && __builtin_expect (old_idx != idx, 0))
5f24d53a
UD
3944 {
3945 errstr = "invalid fastbin entry (free)";
3946 goto errout;
3947 }
37fa1953 3948 }
f65fd747 3949
37fa1953
UD
3950 /*
3951 Consolidate other non-mmapped chunks as they arrive.
3952 */
fa8d436c 3953
37fa1953 3954 else if (!chunk_is_mmapped(p)) {
425ce2ed 3955 if (! have_lock) {
425ce2ed 3956 (void)mutex_lock(&av->mutex);
425ce2ed
UD
3957 locked = 1;
3958 }
425ce2ed 3959
37fa1953 3960 nextchunk = chunk_at_offset(p, size);
fa8d436c 3961
37fa1953
UD
3962 /* Lightweight tests: check whether the block is already the
3963 top block. */
a1ffb40e 3964 if (__glibc_unlikely (p == av->top))
37fa1953
UD
3965 {
3966 errstr = "double free or corruption (top)";
3967 goto errout;
3968 }
3969 /* Or whether the next chunk is beyond the boundaries of the arena. */
3970 if (__builtin_expect (contiguous (av)
3971 && (char *) nextchunk
3972 >= ((char *) av->top + chunksize(av->top)), 0))
3973 {
3974 errstr = "double free or corruption (out)";
3975 goto errout;
3976 }
3977 /* Or whether the block is actually not marked used. */
a1ffb40e 3978 if (__glibc_unlikely (!prev_inuse(nextchunk)))
37fa1953
UD
3979 {
3980 errstr = "double free or corruption (!prev)";
3981 goto errout;
3982 }
fa8d436c 3983
37fa1953 3984 nextsize = chunksize(nextchunk);
893e6098
UD
3985 if (__builtin_expect (nextchunk->size <= 2 * SIZE_SZ, 0)
3986 || __builtin_expect (nextsize >= av->system_mem, 0))
3987 {
76761b63 3988 errstr = "free(): invalid next size (normal)";
893e6098
UD
3989 goto errout;
3990 }
fa8d436c 3991
e8349efd 3992 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
854278df 3993
37fa1953
UD
3994 /* consolidate backward */
3995 if (!prev_inuse(p)) {
3996 prevsize = p->prev_size;
3997 size += prevsize;
3998 p = chunk_at_offset(p, -((long) prevsize));
fff94fa2 3999 unlink(av, p, bck, fwd);
37fa1953 4000 }
a9177ff5 4001
37fa1953
UD
4002 if (nextchunk != av->top) {
4003 /* get and clear inuse bit */
4004 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4005
4006 /* consolidate forward */
4007 if (!nextinuse) {
fff94fa2 4008 unlink(av, nextchunk, bck, fwd);
37fa1953
UD
4009 size += nextsize;
4010 } else
4011 clear_inuse_bit_at_offset(nextchunk, 0);
10dc2a90 4012
fa8d436c 4013 /*
37fa1953
UD
4014 Place the chunk in unsorted chunk list. Chunks are
4015 not placed into regular bins until after they have
4016 been given one chance to be used in malloc.
fa8d436c 4017 */
f65fd747 4018
37fa1953
UD
4019 bck = unsorted_chunks(av);
4020 fwd = bck->fd;
a1ffb40e 4021 if (__glibc_unlikely (fwd->bk != bck))
f6887a0d
UD
4022 {
4023 errstr = "free(): corrupted unsorted chunks";
4024 goto errout;
4025 }
37fa1953 4026 p->fd = fwd;
7ecfbd38
UD
4027 p->bk = bck;
4028 if (!in_smallbin_range(size))
4029 {
4030 p->fd_nextsize = NULL;
4031 p->bk_nextsize = NULL;
4032 }
37fa1953
UD
4033 bck->fd = p;
4034 fwd->bk = p;
8a4b65b4 4035
37fa1953
UD
4036 set_head(p, size | PREV_INUSE);
4037 set_foot(p, size);
4038
4039 check_free_chunk(av, p);
4040 }
4041
4042 /*
4043 If the chunk borders the current high end of memory,
4044 consolidate into top
4045 */
4046
4047 else {
4048 size += nextsize;
4049 set_head(p, size | PREV_INUSE);
4050 av->top = p;
4051 check_chunk(av, p);
4052 }
4053
4054 /*
4055 If freeing a large space, consolidate possibly-surrounding
4056 chunks. Then, if the total unused topmost memory exceeds trim
4057 threshold, ask malloc_trim to reduce top.
4058
4059 Unless max_fast is 0, we don't know if there are fastbins
4060 bordering top, so we cannot tell for sure whether threshold
4061 has been reached unless fastbins are consolidated. But we
4062 don't want to consolidate on each free. As a compromise,
4063 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4064 is reached.
4065 */
fa8d436c 4066
37fa1953
UD
4067 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4068 if (have_fastchunks(av))
4069 malloc_consolidate(av);
fa8d436c 4070
37fa1953 4071 if (av == &main_arena) {
a9177ff5 4072#ifndef MORECORE_CANNOT_TRIM
37fa1953
UD
4073 if ((unsigned long)(chunksize(av->top)) >=
4074 (unsigned long)(mp_.trim_threshold))
3b49edc0 4075 systrim(mp_.top_pad, av);
fa8d436c 4076#endif
37fa1953
UD
4077 } else {
4078 /* Always try heap_trim(), even if the top chunk is not
4079 large, because the corresponding heap might go away. */
4080 heap_info *heap = heap_for_ptr(top(av));
fa8d436c 4081
37fa1953
UD
4082 assert(heap->ar_ptr == av);
4083 heap_trim(heap, mp_.top_pad);
fa8d436c 4084 }
fa8d436c 4085 }
10dc2a90 4086
425ce2ed
UD
4087 if (! have_lock) {
4088 assert (locked);
4089 (void)mutex_unlock(&av->mutex);
4090 }
37fa1953
UD
4091 }
4092 /*
22a89187 4093 If the chunk was allocated via mmap, release via munmap().
37fa1953
UD
4094 */
4095
4096 else {
c120d94d 4097 munmap_chunk (p);
fa8d436c 4098 }
10dc2a90
UD
4099}
4100
fa8d436c
UD
4101/*
4102 ------------------------- malloc_consolidate -------------------------
4103
4104 malloc_consolidate is a specialized version of free() that tears
4105 down chunks held in fastbins. Free itself cannot be used for this
4106 purpose since, among other things, it might place chunks back onto
4107 fastbins. So, instead, we need to use a minor variant of the same
4108 code.
a9177ff5 4109
fa8d436c
UD
4110 Also, because this routine needs to be called the first time through
4111 malloc anyway, it turns out to be the perfect place to trigger
4112 initialization code.
4113*/
4114
fa8d436c 4115static void malloc_consolidate(mstate av)
10dc2a90 4116{
fa8d436c
UD
4117 mfastbinptr* fb; /* current fastbin being consolidated */
4118 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4119 mchunkptr p; /* current chunk being consolidated */
4120 mchunkptr nextp; /* next chunk to consolidate */
4121 mchunkptr unsorted_bin; /* bin header */
4122 mchunkptr first_unsorted; /* chunk to link to */
4123
4124 /* These have same use as in free() */
4125 mchunkptr nextchunk;
4126 INTERNAL_SIZE_T size;
4127 INTERNAL_SIZE_T nextsize;
4128 INTERNAL_SIZE_T prevsize;
4129 int nextinuse;
4130 mchunkptr bck;
4131 mchunkptr fwd;
10dc2a90 4132
fa8d436c
UD
4133 /*
4134 If max_fast is 0, we know that av hasn't
4135 yet been initialized, in which case do so below
4136 */
10dc2a90 4137
9bf248c6 4138 if (get_max_fast () != 0) {
fa8d436c 4139 clear_fastchunks(av);
10dc2a90 4140
fa8d436c 4141 unsorted_bin = unsorted_chunks(av);
10dc2a90 4142
fa8d436c
UD
4143 /*
4144 Remove each chunk from fast bin and consolidate it, placing it
4145 then in unsorted bin. Among other reasons for doing this,
4146 placing in unsorted bin avoids needing to calculate actual bins
4147 until malloc is sure that chunks aren't immediately going to be
4148 reused anyway.
4149 */
a9177ff5 4150
425ce2ed 4151 maxfb = &fastbin (av, NFASTBINS - 1);
425ce2ed 4152 fb = &fastbin (av, 0);
fa8d436c 4153 do {
425ce2ed 4154 p = atomic_exchange_acq (fb, 0);
425ce2ed 4155 if (p != 0) {
72f90263
UD
4156 do {
4157 check_inuse_chunk(av, p);
4158 nextp = p->fd;
4159
4160 /* Slightly streamlined version of consolidation code in free() */
4161 size = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
4162 nextchunk = chunk_at_offset(p, size);
4163 nextsize = chunksize(nextchunk);
4164
4165 if (!prev_inuse(p)) {
4166 prevsize = p->prev_size;
4167 size += prevsize;
4168 p = chunk_at_offset(p, -((long) prevsize));
fff94fa2 4169 unlink(av, p, bck, fwd);
72f90263
UD
4170 }
4171
4172 if (nextchunk != av->top) {
4173 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4174
4175 if (!nextinuse) {
4176 size += nextsize;
fff94fa2 4177 unlink(av, nextchunk, bck, fwd);
72f90263 4178 } else
fa8d436c 4179 clear_inuse_bit_at_offset(nextchunk, 0);
a9177ff5 4180
72f90263
UD
4181 first_unsorted = unsorted_bin->fd;
4182 unsorted_bin->fd = p;
4183 first_unsorted->bk = p;
a9177ff5 4184
72f90263 4185 if (!in_smallbin_range (size)) {
7ecfbd38
UD
4186 p->fd_nextsize = NULL;
4187 p->bk_nextsize = NULL;
4188 }
4189
72f90263
UD
4190 set_head(p, size | PREV_INUSE);
4191 p->bk = unsorted_bin;
4192 p->fd = first_unsorted;
4193 set_foot(p, size);
4194 }
a9177ff5 4195
72f90263
UD
4196 else {
4197 size += nextsize;
4198 set_head(p, size | PREV_INUSE);
4199 av->top = p;
4200 }
a9177ff5 4201
72f90263 4202 } while ( (p = nextp) != 0);
a9177ff5 4203
fa8d436c
UD
4204 }
4205 } while (fb++ != maxfb);
4206 }
4207 else {
4208 malloc_init_state(av);
4209 check_malloc_state(av);
4210 }
4211}
10dc2a90 4212
fa8d436c
UD
4213/*
4214 ------------------------------ realloc ------------------------------
4215*/
f65fd747 4216
22a89187 4217void*
4c8b8cc3
UD
4218_int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4219 INTERNAL_SIZE_T nb)
fa8d436c 4220{
fa8d436c
UD
4221 mchunkptr newp; /* chunk to return */
4222 INTERNAL_SIZE_T newsize; /* its size */
22a89187 4223 void* newmem; /* corresponding user mem */
f65fd747 4224
fa8d436c 4225 mchunkptr next; /* next contiguous chunk after oldp */
f65fd747 4226
fa8d436c
UD
4227 mchunkptr remainder; /* extra space at end of newp */
4228 unsigned long remainder_size; /* its size */
f65fd747 4229
fa8d436c
UD
4230 mchunkptr bck; /* misc temp for linking */
4231 mchunkptr fwd; /* misc temp for linking */
2ed5fd9a 4232
fa8d436c
UD
4233 unsigned long copysize; /* bytes to copy */
4234 unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
a9177ff5 4235 INTERNAL_SIZE_T* s; /* copy source */
fa8d436c 4236 INTERNAL_SIZE_T* d; /* copy destination */
f65fd747 4237
76761b63 4238 const char *errstr = NULL;
f65fd747 4239
6dd6a580 4240 /* oldmem size */
76761b63
UD
4241 if (__builtin_expect (oldp->size <= 2 * SIZE_SZ, 0)
4242 || __builtin_expect (oldsize >= av->system_mem, 0))
4243 {
4b04154d 4244 errstr = "realloc(): invalid old size";
4c8b8cc3 4245 errout:
fff94fa2 4246 malloc_printerr (check_action, errstr, chunk2mem (oldp), av);
4c8b8cc3 4247 return NULL;
76761b63
UD
4248 }
4249
6c8dbf00 4250 check_inuse_chunk (av, oldp);
f65fd747 4251
4c8b8cc3 4252 /* All callers already filter out mmap'ed chunks. */
6c8dbf00 4253 assert (!chunk_is_mmapped (oldp));
f65fd747 4254
6c8dbf00
OB
4255 next = chunk_at_offset (oldp, oldsize);
4256 INTERNAL_SIZE_T nextsize = chunksize (next);
22a89187
UD
4257 if (__builtin_expect (next->size <= 2 * SIZE_SZ, 0)
4258 || __builtin_expect (nextsize >= av->system_mem, 0))
4259 {
4260 errstr = "realloc(): invalid next size";
4261 goto errout;
4262 }
4263
6c8dbf00
OB
4264 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4265 {
4266 /* already big enough; split below */
fa8d436c 4267 newp = oldp;
6c8dbf00 4268 newsize = oldsize;
7799b7b3 4269 }
f65fd747 4270
6c8dbf00
OB
4271 else
4272 {
4273 /* Try to expand forward into top */
4274 if (next == av->top &&
4275 (unsigned long) (newsize = oldsize + nextsize) >=
4276 (unsigned long) (nb + MINSIZE))
4277 {
4278 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4279 av->top = chunk_at_offset (oldp, nb);
4280 set_head (av->top, (newsize - nb) | PREV_INUSE);
4281 check_inuse_chunk (av, oldp);
4282 return chunk2mem (oldp);
4283 }
4284
4285 /* Try to expand forward into next chunk; split off remainder below */
4286 else if (next != av->top &&
4287 !inuse (next) &&
4288 (unsigned long) (newsize = oldsize + nextsize) >=
4289 (unsigned long) (nb))
4290 {
4291 newp = oldp;
fff94fa2 4292 unlink (av, next, bck, fwd);
6c8dbf00
OB
4293 }
4294
4295 /* allocate, copy, free */
4296 else
4297 {
4298 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4299 if (newmem == 0)
4300 return 0; /* propagate failure */
4301
4302 newp = mem2chunk (newmem);
4303 newsize = chunksize (newp);
4304
4305 /*
4306 Avoid copy if newp is next chunk after oldp.
4307 */
4308 if (newp == next)
4309 {
4310 newsize += oldsize;
4311 newp = oldp;
4312 }
4313 else
4314 {
4315 /*
4316 Unroll copy of <= 36 bytes (72 if 8byte sizes)
4317 We know that contents have an odd number of
4318 INTERNAL_SIZE_T-sized words; minimally 3.
4319 */
4320
4321 copysize = oldsize - SIZE_SZ;
4322 s = (INTERNAL_SIZE_T *) (chunk2mem (oldp));
4323 d = (INTERNAL_SIZE_T *) (newmem);
4324 ncopies = copysize / sizeof (INTERNAL_SIZE_T);
4325 assert (ncopies >= 3);
4326
4327 if (ncopies > 9)
4328 memcpy (d, s, copysize);
4329
4330 else
4331 {
4332 *(d + 0) = *(s + 0);
4333 *(d + 1) = *(s + 1);
4334 *(d + 2) = *(s + 2);
4335 if (ncopies > 4)
4336 {
4337 *(d + 3) = *(s + 3);
4338 *(d + 4) = *(s + 4);
4339 if (ncopies > 6)
4340 {
4341 *(d + 5) = *(s + 5);
4342 *(d + 6) = *(s + 6);
4343 if (ncopies > 8)
4344 {
4345 *(d + 7) = *(s + 7);
4346 *(d + 8) = *(s + 8);
4347 }
4348 }
4349 }
4350 }
4351
4352 _int_free (av, oldp, 1);
4353 check_inuse_chunk (av, newp);
4354 return chunk2mem (newp);
4355 }
4356 }
fa8d436c 4357 }
f65fd747 4358
22a89187 4359 /* If possible, free extra space in old or extended chunk */
f65fd747 4360
6c8dbf00 4361 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
f65fd747 4362
22a89187 4363 remainder_size = newsize - nb;
10dc2a90 4364
6c8dbf00
OB
4365 if (remainder_size < MINSIZE) /* not enough extra to split off */
4366 {
4367 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4368 set_inuse_bit_at_offset (newp, newsize);
4369 }
4370 else /* split remainder */
4371 {
4372 remainder = chunk_at_offset (newp, nb);
4373 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4374 set_head (remainder, remainder_size | PREV_INUSE |
4375 (av != &main_arena ? NON_MAIN_ARENA : 0));
4376 /* Mark remainder as inuse so free() won't complain */
4377 set_inuse_bit_at_offset (remainder, remainder_size);
4378 _int_free (av, remainder, 1);
4379 }
22a89187 4380
6c8dbf00
OB
4381 check_inuse_chunk (av, newp);
4382 return chunk2mem (newp);
fa8d436c
UD
4383}
4384
4385/*
6c8dbf00
OB
4386 ------------------------------ memalign ------------------------------
4387 */
fa8d436c 4388
6c8dbf00
OB
4389static void *
4390_int_memalign (mstate av, size_t alignment, size_t bytes)
fa8d436c
UD
4391{
4392 INTERNAL_SIZE_T nb; /* padded request size */
6c8dbf00
OB
4393 char *m; /* memory returned by malloc call */
4394 mchunkptr p; /* corresponding chunk */
4395 char *brk; /* alignment point within p */
4396 mchunkptr newp; /* chunk to return */
fa8d436c
UD
4397 INTERNAL_SIZE_T newsize; /* its size */
4398 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
6c8dbf00
OB
4399 mchunkptr remainder; /* spare room at end to split off */
4400 unsigned long remainder_size; /* its size */
fa8d436c 4401 INTERNAL_SIZE_T size;
f65fd747 4402
f65fd747 4403
f65fd747 4404
6c8dbf00 4405 checked_request2size (bytes, nb);
fa8d436c
UD
4406
4407 /*
6c8dbf00
OB
4408 Strategy: find a spot within that chunk that meets the alignment
4409 request, and then possibly free the leading and trailing space.
4410 */
fa8d436c
UD
4411
4412
4413 /* Call malloc with worst case padding to hit alignment. */
4414
6c8dbf00
OB
4415 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4416
4417 if (m == 0)
4418 return 0; /* propagate failure */
4419
4420 p = mem2chunk (m);
4421
4422 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4423
4424 { /*
4425 Find an aligned spot inside chunk. Since we need to give back
4426 leading space in a chunk of at least MINSIZE, if the first
4427 calculation places us at a spot with less than MINSIZE leader,
4428 we can move to the next aligned spot -- we've allocated enough
4429 total room so that this is always possible.
4430 */
4431 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4432 - ((signed long) alignment));
4433 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4434 brk += alignment;
4435
4436 newp = (mchunkptr) brk;
4437 leadsize = brk - (char *) (p);
4438 newsize = chunksize (p) - leadsize;
4439
4440 /* For mmapped chunks, just adjust offset */
4441 if (chunk_is_mmapped (p))
4442 {
4443 newp->prev_size = p->prev_size + leadsize;
4444 set_head (newp, newsize | IS_MMAPPED);
4445 return chunk2mem (newp);
4446 }
4447
4448 /* Otherwise, give back leader, use the rest */
4449 set_head (newp, newsize | PREV_INUSE |
4450 (av != &main_arena ? NON_MAIN_ARENA : 0));
4451 set_inuse_bit_at_offset (newp, newsize);
4452 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4453 _int_free (av, p, 1);
4454 p = newp;
4455
4456 assert (newsize >= nb &&
4457 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
f65fd747 4458 }
f65fd747 4459
f65fd747 4460 /* Also give back spare room at the end */
6c8dbf00
OB
4461 if (!chunk_is_mmapped (p))
4462 {
4463 size = chunksize (p);
4464 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4465 {
4466 remainder_size = size - nb;
4467 remainder = chunk_at_offset (p, nb);
4468 set_head (remainder, remainder_size | PREV_INUSE |
4469 (av != &main_arena ? NON_MAIN_ARENA : 0));
4470 set_head_size (p, nb);
4471 _int_free (av, remainder, 1);
4472 }
fa8d436c 4473 }
f65fd747 4474
6c8dbf00
OB
4475 check_inuse_chunk (av, p);
4476 return chunk2mem (p);
f65fd747
UD
4477}
4478
f65fd747 4479
fa8d436c 4480/*
6c8dbf00
OB
4481 ------------------------------ malloc_trim ------------------------------
4482 */
8a4b65b4 4483
6c8dbf00
OB
4484static int
4485mtrim (mstate av, size_t pad)
f65fd747 4486{
fff94fa2
SP
4487 /* Don't touch corrupt arenas. */
4488 if (arena_is_corrupt (av))
4489 return 0;
4490
fa8d436c 4491 /* Ensure initialization/consolidation */
68631c8e
UD
4492 malloc_consolidate (av);
4493
6c8dbf00 4494 const size_t ps = GLRO (dl_pagesize);
68631c8e
UD
4495 int psindex = bin_index (ps);
4496 const size_t psm1 = ps - 1;
4497
4498 int result = 0;
4499 for (int i = 1; i < NBINS; ++i)
4500 if (i == 1 || i >= psindex)
4501 {
6c8dbf00 4502 mbinptr bin = bin_at (av, i);
68631c8e 4503
6c8dbf00
OB
4504 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4505 {
4506 INTERNAL_SIZE_T size = chunksize (p);
68631c8e 4507
6c8dbf00
OB
4508 if (size > psm1 + sizeof (struct malloc_chunk))
4509 {
4510 /* See whether the chunk contains at least one unused page. */
4511 char *paligned_mem = (char *) (((uintptr_t) p
4512 + sizeof (struct malloc_chunk)
4513 + psm1) & ~psm1);
68631c8e 4514
6c8dbf00
OB
4515 assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
4516 assert ((char *) p + size > paligned_mem);
68631c8e 4517
6c8dbf00
OB
4518 /* This is the size we could potentially free. */
4519 size -= paligned_mem - (char *) p;
68631c8e 4520
6c8dbf00
OB
4521 if (size > psm1)
4522 {
439bda32 4523#if MALLOC_DEBUG
6c8dbf00
OB
4524 /* When debugging we simulate destroying the memory
4525 content. */
4526 memset (paligned_mem, 0x89, size & ~psm1);
68631c8e 4527#endif
6c8dbf00 4528 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
68631c8e 4529
6c8dbf00
OB
4530 result = 1;
4531 }
4532 }
4533 }
68631c8e 4534 }
8a4b65b4 4535
a9177ff5 4536#ifndef MORECORE_CANNOT_TRIM
3b49edc0 4537 return result | (av == &main_arena ? systrim (pad, av) : 0);
6c8dbf00 4538
8a4b65b4 4539#else
68631c8e 4540 return result;
f65fd747 4541#endif
f65fd747
UD
4542}
4543
f65fd747 4544
3b49edc0 4545int
6c8dbf00 4546__malloc_trim (size_t s)
3b49edc0
UD
4547{
4548 int result = 0;
4549
6c8dbf00 4550 if (__malloc_initialized < 0)
3b49edc0
UD
4551 ptmalloc_init ();
4552
4553 mstate ar_ptr = &main_arena;
4554 do
4555 {
4556 (void) mutex_lock (&ar_ptr->mutex);
4557 result |= mtrim (ar_ptr, s);
4558 (void) mutex_unlock (&ar_ptr->mutex);
4559
4560 ar_ptr = ar_ptr->next;
4561 }
4562 while (ar_ptr != &main_arena);
4563
4564 return result;
4565}
4566
4567
f65fd747 4568/*
6c8dbf00
OB
4569 ------------------------- malloc_usable_size -------------------------
4570 */
f65fd747 4571
3b49edc0 4572static size_t
6c8dbf00 4573musable (void *mem)
f65fd747
UD
4574{
4575 mchunkptr p;
6c8dbf00
OB
4576 if (mem != 0)
4577 {
4578 p = mem2chunk (mem);
4579
4580 if (__builtin_expect (using_malloc_checking == 1, 0))
4581 return malloc_check_get_size (p);
4582
4583 if (chunk_is_mmapped (p))
4584 return chunksize (p) - 2 * SIZE_SZ;
4585 else if (inuse (p))
4586 return chunksize (p) - SIZE_SZ;
4587 }
fa8d436c 4588 return 0;
f65fd747
UD
4589}
4590
3b49edc0
UD
4591
4592size_t
6c8dbf00 4593__malloc_usable_size (void *m)
3b49edc0
UD
4594{
4595 size_t result;
4596
6c8dbf00 4597 result = musable (m);
3b49edc0
UD
4598 return result;
4599}
4600
fa8d436c 4601/*
6c8dbf00
OB
4602 ------------------------------ mallinfo ------------------------------
4603 Accumulate malloc statistics for arena AV into M.
4604 */
f65fd747 4605
bedee953 4606static void
6c8dbf00 4607int_mallinfo (mstate av, struct mallinfo *m)
f65fd747 4608{
6dd67bd5 4609 size_t i;
f65fd747
UD
4610 mbinptr b;
4611 mchunkptr p;
f65fd747 4612 INTERNAL_SIZE_T avail;
fa8d436c
UD
4613 INTERNAL_SIZE_T fastavail;
4614 int nblocks;
4615 int nfastblocks;
f65fd747 4616
fa8d436c 4617 /* Ensure initialization */
6c8dbf00
OB
4618 if (av->top == 0)
4619 malloc_consolidate (av);
8a4b65b4 4620
6c8dbf00 4621 check_malloc_state (av);
8a4b65b4 4622
fa8d436c 4623 /* Account for top */
6c8dbf00 4624 avail = chunksize (av->top);
fa8d436c 4625 nblocks = 1; /* top always exists */
f65fd747 4626
fa8d436c
UD
4627 /* traverse fastbins */
4628 nfastblocks = 0;
4629 fastavail = 0;
4630
6c8dbf00
OB
4631 for (i = 0; i < NFASTBINS; ++i)
4632 {
4633 for (p = fastbin (av, i); p != 0; p = p->fd)
4634 {
4635 ++nfastblocks;
4636 fastavail += chunksize (p);
4637 }
fa8d436c 4638 }
fa8d436c
UD
4639
4640 avail += fastavail;
f65fd747 4641
fa8d436c 4642 /* traverse regular bins */
6c8dbf00
OB
4643 for (i = 1; i < NBINS; ++i)
4644 {
4645 b = bin_at (av, i);
4646 for (p = last (b); p != b; p = p->bk)
4647 {
4648 ++nblocks;
4649 avail += chunksize (p);
4650 }
fa8d436c 4651 }
f65fd747 4652
bedee953
PP
4653 m->smblks += nfastblocks;
4654 m->ordblks += nblocks;
4655 m->fordblks += avail;
4656 m->uordblks += av->system_mem - avail;
4657 m->arena += av->system_mem;
4658 m->fsmblks += fastavail;
4659 if (av == &main_arena)
4660 {
4661 m->hblks = mp_.n_mmaps;
4662 m->hblkhd = mp_.mmapped_mem;
4663 m->usmblks = mp_.max_total_mem;
6c8dbf00 4664 m->keepcost = chunksize (av->top);
bedee953 4665 }
fa8d436c 4666}
f65fd747 4667
3b49edc0 4668
6c8dbf00
OB
4669struct mallinfo
4670__libc_mallinfo ()
3b49edc0
UD
4671{
4672 struct mallinfo m;
bedee953 4673 mstate ar_ptr;
3b49edc0 4674
6c8dbf00 4675 if (__malloc_initialized < 0)
3b49edc0 4676 ptmalloc_init ();
bedee953 4677
6c8dbf00 4678 memset (&m, 0, sizeof (m));
bedee953 4679 ar_ptr = &main_arena;
6c8dbf00
OB
4680 do
4681 {
4682 (void) mutex_lock (&ar_ptr->mutex);
4683 int_mallinfo (ar_ptr, &m);
4684 (void) mutex_unlock (&ar_ptr->mutex);
bedee953 4685
6c8dbf00
OB
4686 ar_ptr = ar_ptr->next;
4687 }
4688 while (ar_ptr != &main_arena);
bedee953 4689
3b49edc0
UD
4690 return m;
4691}
4692
fa8d436c 4693/*
6c8dbf00
OB
4694 ------------------------------ malloc_stats ------------------------------
4695 */
f65fd747 4696
3b49edc0 4697void
60d2f8f3 4698__malloc_stats (void)
f65fd747 4699{
8a4b65b4 4700 int i;
fa8d436c 4701 mstate ar_ptr;
fa8d436c 4702 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
8a4b65b4 4703
6c8dbf00 4704 if (__malloc_initialized < 0)
a234e27d 4705 ptmalloc_init ();
8dab36a1
UD
4706 _IO_flockfile (stderr);
4707 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
4708 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
6c8dbf00
OB
4709 for (i = 0, ar_ptr = &main_arena;; i++)
4710 {
4711 struct mallinfo mi;
4712
4713 memset (&mi, 0, sizeof (mi));
4714 (void) mutex_lock (&ar_ptr->mutex);
4715 int_mallinfo (ar_ptr, &mi);
4716 fprintf (stderr, "Arena %d:\n", i);
4717 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
4718 fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
fa8d436c 4719#if MALLOC_DEBUG > 1
6c8dbf00
OB
4720 if (i > 0)
4721 dump_heap (heap_for_ptr (top (ar_ptr)));
fa8d436c 4722#endif
6c8dbf00
OB
4723 system_b += mi.arena;
4724 in_use_b += mi.uordblks;
6c8dbf00
OB
4725 (void) mutex_unlock (&ar_ptr->mutex);
4726 ar_ptr = ar_ptr->next;
4727 if (ar_ptr == &main_arena)
4728 break;
4729 }
4730 fprintf (stderr, "Total (incl. mmap):\n");
4731 fprintf (stderr, "system bytes = %10u\n", system_b);
4732 fprintf (stderr, "in use bytes = %10u\n", in_use_b);
4733 fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
4734 fprintf (stderr, "max mmap bytes = %10lu\n",
4735 (unsigned long) mp_.max_mmapped_mem);
8dab36a1
UD
4736 ((_IO_FILE *) stderr)->_flags2 |= old_flags2;
4737 _IO_funlockfile (stderr);
f65fd747
UD
4738}
4739
f65fd747
UD
4740
4741/*
6c8dbf00
OB
4742 ------------------------------ mallopt ------------------------------
4743 */
f65fd747 4744
6c8dbf00
OB
4745int
4746__libc_mallopt (int param_number, int value)
f65fd747 4747{
fa8d436c
UD
4748 mstate av = &main_arena;
4749 int res = 1;
f65fd747 4750
6c8dbf00 4751 if (__malloc_initialized < 0)
0cb71e02 4752 ptmalloc_init ();
6c8dbf00 4753 (void) mutex_lock (&av->mutex);
fa8d436c 4754 /* Ensure initialization/consolidation */
6c8dbf00 4755 malloc_consolidate (av);
2f6d1f1b 4756
3ea5be54
AO
4757 LIBC_PROBE (memory_mallopt, 2, param_number, value);
4758
6c8dbf00
OB
4759 switch (param_number)
4760 {
4761 case M_MXFAST:
4762 if (value >= 0 && value <= MAX_FAST_SIZE)
4763 {
4764 LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
4765 set_max_fast (value);
4766 }
4767 else
4768 res = 0;
4769 break;
4770
4771 case M_TRIM_THRESHOLD:
4772 LIBC_PROBE (memory_mallopt_trim_threshold, 3, value,
4773 mp_.trim_threshold, mp_.no_dyn_threshold);
4774 mp_.trim_threshold = value;
4775 mp_.no_dyn_threshold = 1;
4776 break;
4777
4778 case M_TOP_PAD:
4779 LIBC_PROBE (memory_mallopt_top_pad, 3, value,
4780 mp_.top_pad, mp_.no_dyn_threshold);
4781 mp_.top_pad = value;
4782 mp_.no_dyn_threshold = 1;
4783 break;
4784
4785 case M_MMAP_THRESHOLD:
4786 /* Forbid setting the threshold too high. */
4787 if ((unsigned long) value > HEAP_MAX_SIZE / 2)
4788 res = 0;
4789 else
4790 {
4791 LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value,
4792 mp_.mmap_threshold, mp_.no_dyn_threshold);
4793 mp_.mmap_threshold = value;
4794 mp_.no_dyn_threshold = 1;
4795 }
4796 break;
4797
4798 case M_MMAP_MAX:
4799 LIBC_PROBE (memory_mallopt_mmap_max, 3, value,
4800 mp_.n_mmaps_max, mp_.no_dyn_threshold);
4801 mp_.n_mmaps_max = value;
4802 mp_.no_dyn_threshold = 1;
4803 break;
4804
4805 case M_CHECK_ACTION:
4806 LIBC_PROBE (memory_mallopt_check_action, 2, value, check_action);
4807 check_action = value;
4808 break;
4809
4810 case M_PERTURB:
4811 LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
4812 perturb_byte = value;
4813 break;
4814
4815 case M_ARENA_TEST:
4816 if (value > 0)
4817 {
4818 LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
4819 mp_.arena_test = value;
4820 }
4821 break;
4822
4823 case M_ARENA_MAX:
4824 if (value > 0)
4825 {
4826 LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
4827 mp_.arena_max = value;
4828 }
4829 break;
4830 }
4831 (void) mutex_unlock (&av->mutex);
fa8d436c 4832 return res;
b22fc5f5 4833}
3b49edc0 4834libc_hidden_def (__libc_mallopt)
b22fc5f5 4835
10dc2a90 4836
a9177ff5 4837/*
6c8dbf00
OB
4838 -------------------- Alternative MORECORE functions --------------------
4839 */
10dc2a90 4840
b22fc5f5 4841
fa8d436c 4842/*
6c8dbf00 4843 General Requirements for MORECORE.
b22fc5f5 4844
6c8dbf00 4845 The MORECORE function must have the following properties:
b22fc5f5 4846
6c8dbf00 4847 If MORECORE_CONTIGUOUS is false:
10dc2a90 4848
6c8dbf00 4849 * MORECORE must allocate in multiples of pagesize. It will
fa8d436c 4850 only be called with arguments that are multiples of pagesize.
10dc2a90 4851
6c8dbf00 4852 * MORECORE(0) must return an address that is at least
fa8d436c 4853 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
10dc2a90 4854
6c8dbf00 4855 else (i.e. If MORECORE_CONTIGUOUS is true):
10dc2a90 4856
6c8dbf00 4857 * Consecutive calls to MORECORE with positive arguments
fa8d436c
UD
4858 return increasing addresses, indicating that space has been
4859 contiguously extended.
10dc2a90 4860
6c8dbf00 4861 * MORECORE need not allocate in multiples of pagesize.
fa8d436c 4862 Calls to MORECORE need not have args of multiples of pagesize.
10dc2a90 4863
6c8dbf00 4864 * MORECORE need not page-align.
10dc2a90 4865
6c8dbf00 4866 In either case:
10dc2a90 4867
6c8dbf00 4868 * MORECORE may allocate more memory than requested. (Or even less,
fa8d436c 4869 but this will generally result in a malloc failure.)
10dc2a90 4870
6c8dbf00 4871 * MORECORE must not allocate memory when given argument zero, but
fa8d436c
UD
4872 instead return one past the end address of memory from previous
4873 nonzero call. This malloc does NOT call MORECORE(0)
4874 until at least one call with positive arguments is made, so
4875 the initial value returned is not important.
10dc2a90 4876
6c8dbf00 4877 * Even though consecutive calls to MORECORE need not return contiguous
fa8d436c
UD
4878 addresses, it must be OK for malloc'ed chunks to span multiple
4879 regions in those cases where they do happen to be contiguous.
10dc2a90 4880
6c8dbf00 4881 * MORECORE need not handle negative arguments -- it may instead
fa8d436c
UD
4882 just return MORECORE_FAILURE when given negative arguments.
4883 Negative arguments are always multiples of pagesize. MORECORE
4884 must not misinterpret negative args as large positive unsigned
4885 args. You can suppress all such calls from even occurring by defining
4886 MORECORE_CANNOT_TRIM,
10dc2a90 4887
6c8dbf00
OB
4888 There is some variation across systems about the type of the
4889 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
4890 actually be size_t, because sbrk supports negative args, so it is
4891 normally the signed type of the same width as size_t (sometimes
4892 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
4893 matter though. Internally, we use "long" as arguments, which should
4894 work across all reasonable possibilities.
4895
4896 Additionally, if MORECORE ever returns failure for a positive
4897 request, then mmap is used as a noncontiguous system allocator. This
4898 is a useful backup strategy for systems with holes in address spaces
4899 -- in this case sbrk cannot contiguously expand the heap, but mmap
4900 may be able to map noncontiguous space.
4901
4902 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
4903 a function that always returns MORECORE_FAILURE.
4904
4905 If you are using this malloc with something other than sbrk (or its
4906 emulation) to supply memory regions, you probably want to set
4907 MORECORE_CONTIGUOUS as false. As an example, here is a custom
4908 allocator kindly contributed for pre-OSX macOS. It uses virtually
4909 but not necessarily physically contiguous non-paged memory (locked
4910 in, present and won't get swapped out). You can use it by
4911 uncommenting this section, adding some #includes, and setting up the
4912 appropriate defines above:
4913
4914 *#define MORECORE osMoreCore
4915 *#define MORECORE_CONTIGUOUS 0
4916
4917 There is also a shutdown routine that should somehow be called for
4918 cleanup upon program exit.
4919
4920 *#define MAX_POOL_ENTRIES 100
4921 *#define MINIMUM_MORECORE_SIZE (64 * 1024)
4922 static int next_os_pool;
4923 void *our_os_pools[MAX_POOL_ENTRIES];
4924
4925 void *osMoreCore(int size)
4926 {
fa8d436c
UD
4927 void *ptr = 0;
4928 static void *sbrk_top = 0;
ca34d7a7 4929
fa8d436c
UD
4930 if (size > 0)
4931 {
4932 if (size < MINIMUM_MORECORE_SIZE)
6c8dbf00 4933 size = MINIMUM_MORECORE_SIZE;
fa8d436c 4934 if (CurrentExecutionLevel() == kTaskLevel)
6c8dbf00 4935 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
fa8d436c
UD
4936 if (ptr == 0)
4937 {
6c8dbf00 4938 return (void *) MORECORE_FAILURE;
fa8d436c
UD
4939 }
4940 // save ptrs so they can be freed during cleanup
4941 our_os_pools[next_os_pool] = ptr;
4942 next_os_pool++;
4943 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
4944 sbrk_top = (char *) ptr + size;
4945 return ptr;
4946 }
4947 else if (size < 0)
4948 {
4949 // we don't currently support shrink behavior
4950 return (void *) MORECORE_FAILURE;
4951 }
4952 else
4953 {
4954 return sbrk_top;
431c33c0 4955 }
6c8dbf00 4956 }
ca34d7a7 4957
6c8dbf00
OB
4958 // cleanup any allocated memory pools
4959 // called as last thing before shutting down driver
ca34d7a7 4960
6c8dbf00
OB
4961 void osCleanupMem(void)
4962 {
fa8d436c 4963 void **ptr;
ca34d7a7 4964
fa8d436c
UD
4965 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
4966 if (*ptr)
4967 {
6c8dbf00
OB
4968 PoolDeallocate(*ptr);
4969 * ptr = 0;
fa8d436c 4970 }
6c8dbf00 4971 }
ee74a442 4972
6c8dbf00 4973 */
f65fd747 4974
7e3be507 4975
3e030bd5
UD
4976/* Helper code. */
4977
ae7f5313
UD
4978extern char **__libc_argv attribute_hidden;
4979
3e030bd5 4980static void
fff94fa2 4981malloc_printerr (int action, const char *str, void *ptr, mstate ar_ptr)
3e030bd5 4982{
fff94fa2
SP
4983 /* Avoid using this arena in future. We do not attempt to synchronize this
4984 with anything else because we minimally want to ensure that __libc_message
4985 gets its resources safely without stumbling on the current corruption. */
4986 if (ar_ptr)
4987 set_arena_corrupt (ar_ptr);
4988
553cc5f9
UD
4989 if ((action & 5) == 5)
4990 __libc_message (action & 2, "%s\n", str);
4991 else if (action & 1)
3e030bd5 4992 {
a9055cab 4993 char buf[2 * sizeof (uintptr_t) + 1];
3e030bd5 4994
a9055cab
UD
4995 buf[sizeof (buf) - 1] = '\0';
4996 char *cp = _itoa_word ((uintptr_t) ptr, &buf[sizeof (buf) - 1], 16, 0);
4997 while (cp > buf)
6c8dbf00 4998 *--cp = '0';
a9055cab 4999
bb9510dc 5000 __libc_message (action & 2, "*** Error in `%s': %s: 0x%s ***\n",
6c8dbf00 5001 __libc_argv[0] ? : "<unknown>", str, cp);
3e030bd5 5002 }
a9055cab 5003 else if (action & 2)
3e030bd5
UD
5004 abort ();
5005}
5006
a204dbb2
UD
5007/* We need a wrapper function for one of the additions of POSIX. */
5008int
5009__posix_memalign (void **memptr, size_t alignment, size_t size)
5010{
5011 void *mem;
5012
5013 /* Test whether the SIZE argument is valid. It must be a power of
5014 two multiple of sizeof (void *). */
de02bd05 5015 if (alignment % sizeof (void *) != 0
fc56e970 5016 || !powerof2 (alignment / sizeof (void *))
de02bd05 5017 || alignment == 0)
a204dbb2
UD
5018 return EINVAL;
5019
10ad46bc
OB
5020
5021 void *address = RETURN_ADDRESS (0);
5022 mem = _mid_memalign (alignment, size, address);
a204dbb2 5023
6c8dbf00
OB
5024 if (mem != NULL)
5025 {
5026 *memptr = mem;
5027 return 0;
5028 }
a204dbb2
UD
5029
5030 return ENOMEM;
5031}
5032weak_alias (__posix_memalign, posix_memalign)
5033
20c13899
OB
5034
5035int
c52ff39e 5036__malloc_info (int options, FILE *fp)
bb066545 5037{
20c13899
OB
5038 /* For now, at least. */
5039 if (options != 0)
5040 return EINVAL;
bb066545 5041
20c13899
OB
5042 int n = 0;
5043 size_t total_nblocks = 0;
5044 size_t total_nfastblocks = 0;
5045 size_t total_avail = 0;
5046 size_t total_fastavail = 0;
5047 size_t total_system = 0;
5048 size_t total_max_system = 0;
5049 size_t total_aspace = 0;
5050 size_t total_aspace_mprotect = 0;
bb066545 5051
6c8dbf00 5052
6c8dbf00 5053
987c0269
OB
5054 if (__malloc_initialized < 0)
5055 ptmalloc_init ();
bb066545 5056
987c0269 5057 fputs ("<malloc version=\"1\">\n", fp);
bb066545 5058
987c0269
OB
5059 /* Iterate over all arenas currently in use. */
5060 mstate ar_ptr = &main_arena;
5061 do
5062 {
5063 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
8b35e35d 5064
987c0269
OB
5065 size_t nblocks = 0;
5066 size_t nfastblocks = 0;
5067 size_t avail = 0;
5068 size_t fastavail = 0;
5069 struct
5070 {
5071 size_t from;
5072 size_t to;
5073 size_t total;
5074 size_t count;
5075 } sizes[NFASTBINS + NBINS - 1];
5076#define nsizes (sizeof (sizes) / sizeof (sizes[0]))
6c8dbf00 5077
987c0269 5078 mutex_lock (&ar_ptr->mutex);
bb066545 5079
987c0269
OB
5080 for (size_t i = 0; i < NFASTBINS; ++i)
5081 {
5082 mchunkptr p = fastbin (ar_ptr, i);
5083 if (p != NULL)
5084 {
5085 size_t nthissize = 0;
5086 size_t thissize = chunksize (p);
5087
5088 while (p != NULL)
5089 {
5090 ++nthissize;
5091 p = p->fd;
5092 }
5093
5094 fastavail += nthissize * thissize;
5095 nfastblocks += nthissize;
5096 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
5097 sizes[i].to = thissize;
5098 sizes[i].count = nthissize;
5099 }
5100 else
5101 sizes[i].from = sizes[i].to = sizes[i].count = 0;
bb066545 5102
987c0269
OB
5103 sizes[i].total = sizes[i].count * sizes[i].to;
5104 }
bb066545 5105
bb066545 5106
987c0269
OB
5107 mbinptr bin;
5108 struct malloc_chunk *r;
bb066545 5109
987c0269
OB
5110 for (size_t i = 1; i < NBINS; ++i)
5111 {
5112 bin = bin_at (ar_ptr, i);
5113 r = bin->fd;
5114 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5115 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5116 = sizes[NFASTBINS - 1 + i].count = 0;
5117
5118 if (r != NULL)
5119 while (r != bin)
5120 {
5121 ++sizes[NFASTBINS - 1 + i].count;
5122 sizes[NFASTBINS - 1 + i].total += r->size;
5123 sizes[NFASTBINS - 1 + i].from
5124 = MIN (sizes[NFASTBINS - 1 + i].from, r->size);
5125 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5126 r->size);
5127
5128 r = r->fd;
5129 }
5130
5131 if (sizes[NFASTBINS - 1 + i].count == 0)
5132 sizes[NFASTBINS - 1 + i].from = 0;
5133 nblocks += sizes[NFASTBINS - 1 + i].count;
5134 avail += sizes[NFASTBINS - 1 + i].total;
5135 }
bb066545 5136
987c0269 5137 mutex_unlock (&ar_ptr->mutex);
da2d2fb6 5138
987c0269
OB
5139 total_nfastblocks += nfastblocks;
5140 total_fastavail += fastavail;
0588a9cb 5141
987c0269
OB
5142 total_nblocks += nblocks;
5143 total_avail += avail;
0588a9cb 5144
987c0269
OB
5145 for (size_t i = 0; i < nsizes; ++i)
5146 if (sizes[i].count != 0 && i != NFASTBINS)
5147 fprintf (fp, " \
5148 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5149 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
fdfd175d 5150
987c0269
OB
5151 if (sizes[NFASTBINS].count != 0)
5152 fprintf (fp, "\
5153 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5154 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5155 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
fdfd175d 5156
987c0269
OB
5157 total_system += ar_ptr->system_mem;
5158 total_max_system += ar_ptr->max_system_mem;
bb066545 5159
987c0269
OB
5160 fprintf (fp,
5161 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5162 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5163 "<system type=\"current\" size=\"%zu\"/>\n"
5164 "<system type=\"max\" size=\"%zu\"/>\n",
5165 nfastblocks, fastavail, nblocks, avail,
5166 ar_ptr->system_mem, ar_ptr->max_system_mem);
346bc35c 5167
987c0269
OB
5168 if (ar_ptr != &main_arena)
5169 {
5170 heap_info *heap = heap_for_ptr (top (ar_ptr));
5171 fprintf (fp,
5172 "<aspace type=\"total\" size=\"%zu\"/>\n"
5173 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5174 heap->size, heap->mprotect_size);
5175 total_aspace += heap->size;
5176 total_aspace_mprotect += heap->mprotect_size;
5177 }
5178 else
5179 {
5180 fprintf (fp,
5181 "<aspace type=\"total\" size=\"%zu\"/>\n"
5182 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5183 ar_ptr->system_mem, ar_ptr->system_mem);
5184 total_aspace += ar_ptr->system_mem;
5185 total_aspace_mprotect += ar_ptr->system_mem;
5186 }
bb066545 5187
987c0269 5188 fputs ("</heap>\n", fp);
bb066545
UD
5189 ar_ptr = ar_ptr->next;
5190 }
5191 while (ar_ptr != &main_arena);
5192
5193 fprintf (fp,
62a58816
SP
5194 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5195 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
9fa76613 5196 "<total type=\"mmap\" count=\"%d\" size=\"%zu\"/>\n"
62a58816
SP
5197 "<system type=\"current\" size=\"%zu\"/>\n"
5198 "<system type=\"max\" size=\"%zu\"/>\n"
5199 "<aspace type=\"total\" size=\"%zu\"/>\n"
5200 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5201 "</malloc>\n",
5202 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
4d653a59 5203 mp_.n_mmaps, mp_.mmapped_mem,
62a58816
SP
5204 total_system, total_max_system,
5205 total_aspace, total_aspace_mprotect);
bb066545
UD
5206
5207 return 0;
5208}
c52ff39e 5209weak_alias (__malloc_info, malloc_info)
bb066545
UD
5210
5211
eba19d2b
UD
5212strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5213strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5214strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5215strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5216strong_alias (__libc_memalign, __memalign)
5217weak_alias (__libc_memalign, memalign)
5218strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5219strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5220strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5221strong_alias (__libc_mallinfo, __mallinfo)
5222weak_alias (__libc_mallinfo, mallinfo)
5223strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
7e3be507
UD
5224
5225weak_alias (__malloc_stats, malloc_stats)
5226weak_alias (__malloc_usable_size, malloc_usable_size)
5227weak_alias (__malloc_trim, malloc_trim)
2f6d1f1b
UD
5228weak_alias (__malloc_get_state, malloc_get_state)
5229weak_alias (__malloc_set_state, malloc_set_state)
7e3be507 5230
f65fd747 5231
fa8d436c 5232/* ------------------------------------------------------------
6c8dbf00 5233 History:
f65fd747 5234
6c8dbf00 5235 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
f65fd747 5236
6c8dbf00 5237 */
fa8d436c
UD
5238/*
5239 * Local variables:
5240 * c-basic-offset: 2
5241 * End:
5242 */