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