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