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