Add more tests of libm functions.
[glibc.git] / malloc / malloc.c
blobf361bad636167cf1680cb75b5098232c9232d771
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2015 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.
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.
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.
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/>. */
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.
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.
29 * Version ptmalloc2-20011215
30 based on:
31 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
33 * Quickstart
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".
44 * Why use this malloc?
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.
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.
62 For a longer but slightly out of date high-level description, see
63 http://gee.cs.oswego.edu/dl/html/malloc.html
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.
71 * Contents, described in more detail in "description of public routines" below.
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)
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 cfree(void* p);
88 malloc_trim(size_t pad);
89 malloc_usable_size(void* p);
90 malloc_stats();
92 * Vital statistics:
94 Supported pointer representation: 4 or 8 bytes
95 Supported size_t representation: 4 or 8 bytes
96 Note that size_t is allowed to be 4 bytes even if pointers are 8.
97 You can adjust this by defining INTERNAL_SIZE_T
99 Alignment: 2 * sizeof(size_t) (default)
100 (i.e., 8 byte alignment with 4byte size_t). This suffices for
101 nearly all current machines and C compilers. However, you can
102 define MALLOC_ALIGNMENT to be wider than this if necessary.
104 Minimum overhead per allocated chunk: 4 or 8 bytes
105 Each malloced chunk has a hidden word of overhead holding size
106 and status information.
108 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
109 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
111 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
112 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
113 needed; 4 (8) for a trailing size field and 8 (16) bytes for
114 free list pointers. Thus, the minimum allocatable size is
115 16/24/32 bytes.
117 Even a request for zero bytes (i.e., malloc(0)) returns a
118 pointer to something of the minimum allocatable size.
120 The maximum overhead wastage (i.e., number of extra bytes
121 allocated than were requested in malloc) is less than or equal
122 to the minimum size, except for requests >= mmap_threshold that
123 are serviced via mmap(), where the worst case wastage is 2 *
124 sizeof(size_t) bytes plus the remainder from a system page (the
125 minimal mmap unit); typically 4096 or 8192 bytes.
127 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
128 8-byte size_t: 2^64 minus about two pages
130 It is assumed that (possibly signed) size_t values suffice to
131 represent chunk sizes. `Possibly signed' is due to the fact
132 that `size_t' may be defined on a system as either a signed or
133 an unsigned type. The ISO C standard says that it must be
134 unsigned, but a few systems are known not to adhere to this.
135 Additionally, even when size_t is unsigned, sbrk (which is by
136 default used to obtain memory from system) accepts signed
137 arguments, and may not be able to handle size_t-wide arguments
138 with negative sign bit. Generally, values that would
139 appear as negative after accounting for overhead and alignment
140 are supported only via mmap(), which does not have this
141 limitation.
143 Requests for sizes outside the allowed range will perform an optional
144 failure action and then return null. (Requests may also
145 also fail because a system is out of memory.)
147 Thread-safety: thread-safe
149 Compliance: I believe it is compliant with the 1997 Single Unix Specification
150 Also SVID/XPG, ANSI C, and probably others as well.
152 * Synopsis of compile-time options:
154 People have reported using previous versions of this malloc on all
155 versions of Unix, sometimes by tweaking some of the defines
156 below. It has been tested most extensively on Solaris and Linux.
157 People also report using it in stand-alone embedded systems.
159 The implementation is in straight, hand-tuned ANSI C. It is not
160 at all modular. (Sorry!) It uses a lot of macros. To be at all
161 usable, this code should be compiled using an optimizing compiler
162 (for example gcc -O3) that can simplify expressions and control
163 paths. (FAQ: some macros import variables as arguments rather than
164 declare locals because people reported that some debuggers
165 otherwise get confused.)
167 OPTION DEFAULT VALUE
169 Compilation Environment options:
171 HAVE_MREMAP 0
173 Changing default word sizes:
175 INTERNAL_SIZE_T size_t
176 MALLOC_ALIGNMENT MAX (2 * sizeof(INTERNAL_SIZE_T),
177 __alignof__ (long double))
179 Configuration and functionality options:
181 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
182 USE_MALLOC_LOCK NOT defined
183 MALLOC_DEBUG NOT defined
184 REALLOC_ZERO_BYTES_FREES 1
185 TRIM_FASTBINS 0
187 Options for customizing MORECORE:
189 MORECORE sbrk
190 MORECORE_FAILURE -1
191 MORECORE_CONTIGUOUS 1
192 MORECORE_CANNOT_TRIM NOT defined
193 MORECORE_CLEARS 1
194 MMAP_AS_MORECORE_SIZE (1024 * 1024)
196 Tuning options that are also dynamically changeable via mallopt:
198 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
199 DEFAULT_TRIM_THRESHOLD 128 * 1024
200 DEFAULT_TOP_PAD 0
201 DEFAULT_MMAP_THRESHOLD 128 * 1024
202 DEFAULT_MMAP_MAX 65536
204 There are several other #defined constants and macros that you
205 probably don't want to touch unless you are extending or adapting malloc. */
207 /*
208 void* is the pointer type that malloc should say it returns
209 */
211 #ifndef void
212 #define void void
213 #endif /*void*/
215 #include <stddef.h> /* for size_t */
216 #include <stdlib.h> /* for getenv(), abort() */
217 #include <unistd.h> /* for __libc_enable_secure */
219 #include <malloc-machine.h>
220 #include <malloc-sysdep.h>
222 #include <atomic.h>
223 #include <_itoa.h>
224 #include <bits/wordsize.h>
225 #include <sys/sysinfo.h>
227 #include <ldsodefs.h>
229 #include <unistd.h>
230 #include <stdio.h> /* needed for malloc_stats */
231 #include <errno.h>
233 #include <shlib-compat.h>
235 /* For uintptr_t. */
236 #include <stdint.h>
238 /* For va_arg, va_start, va_end. */
239 #include <stdarg.h>
241 /* For MIN, MAX, powerof2. */
242 #include <sys/param.h>
244 /* For ALIGN_UP. */
245 #include <libc-internal.h>
248 /*
249 Debugging:
251 Because freed chunks may be overwritten with bookkeeping fields, this
252 malloc will often die when freed memory is overwritten by user
253 programs. This can be very effective (albeit in an annoying way)
254 in helping track down dangling pointers.
256 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
257 enabled that will catch more memory errors. You probably won't be
258 able to make much sense of the actual assertion errors, but they
259 should help you locate incorrectly overwritten memory. The checking
260 is fairly extensive, and will slow down execution
261 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
262 will attempt to check every non-mmapped allocated and free chunk in
263 the course of computing the summmaries. (By nature, mmapped regions
264 cannot be checked very much automatically.)
266 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
267 this code. The assertions in the check routines spell out in more
268 detail the assumptions and invariants underlying the algorithms.
270 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
271 checking that all accesses to malloced memory stay within their
272 bounds. However, there are several add-ons and adaptations of this
273 or other mallocs available that do this.
274 */
276 #ifndef MALLOC_DEBUG
277 #define MALLOC_DEBUG 0
278 #endif
280 #ifdef NDEBUG
281 # define assert(expr) ((void) 0)
282 #else
283 # define assert(expr) \
284 ((expr) \
285 ? ((void) 0) \
286 : __malloc_assert (__STRING (expr), __FILE__, __LINE__, __func__))
288 extern const char *__progname;
290 static void
291 __malloc_assert (const char *assertion, const char *file, unsigned int line,
292 const char *function)
294 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
295 __progname, __progname[0] ? ": " : "",
296 file, line,
297 function ? function : "", function ? ": " : "",
298 assertion);
299 fflush (stderr);
300 abort ();
302 #endif
305 /*
306 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
307 of chunk sizes.
309 The default version is the same as size_t.
311 While not strictly necessary, it is best to define this as an
312 unsigned type, even if size_t is a signed type. This may avoid some
313 artificial size limitations on some systems.
315 On a 64-bit machine, you may be able to reduce malloc overhead by
316 defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
317 expense of not being able to handle more than 2^32 of malloced
318 space. If this limitation is acceptable, you are encouraged to set
319 this unless you are on a platform requiring 16byte alignments. In
320 this case the alignment requirements turn out to negate any
321 potential advantages of decreasing size_t word size.
323 Implementors: Beware of the possible combinations of:
324 - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
325 and might be the same width as int or as long
326 - size_t might have different width and signedness as INTERNAL_SIZE_T
327 - int and long might be 32 or 64 bits, and might be the same width
328 To deal with this, most comparisons and difference computations
329 among INTERNAL_SIZE_Ts should cast them to unsigned long, being
330 aware of the fact that casting an unsigned int to a wider long does
331 not sign-extend. (This also makes checking for negative numbers
332 awkward.) Some of these casts result in harmless compiler warnings
333 on some systems.
334 */
336 #ifndef INTERNAL_SIZE_T
337 #define INTERNAL_SIZE_T size_t
338 #endif
340 /* The corresponding word size */
341 #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
344 /*
345 MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
346 It must be a power of two at least 2 * SIZE_SZ, even on machines
347 for which smaller alignments would suffice. It may be defined as
348 larger than this though. Note however that code and data structures
349 are optimized for the case of 8-byte alignment.
350 */
353 #ifndef MALLOC_ALIGNMENT
354 # if !SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_16)
355 /* This is the correct definition when there is no past ABI to constrain it.
357 Among configurations with a past ABI constraint, it differs from
358 2*SIZE_SZ only on powerpc32. For the time being, changing this is
359 causing more compatibility problems due to malloc_get_state and
360 malloc_set_state than will returning blocks not adequately aligned for
361 long double objects under -mlong-double-128. */
363 # define MALLOC_ALIGNMENT (2 *SIZE_SZ < __alignof__ (long double) \
364 ? __alignof__ (long double) : 2 *SIZE_SZ)
365 # else
366 # define MALLOC_ALIGNMENT (2 *SIZE_SZ)
367 # endif
368 #endif
370 /* The corresponding bit mask value */
371 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
375 /*
376 REALLOC_ZERO_BYTES_FREES should be set if a call to
377 realloc with zero bytes should be the same as a call to free.
378 This is required by the C standard. Otherwise, since this malloc
379 returns a unique pointer for malloc(0), so does realloc(p, 0).
380 */
382 #ifndef REALLOC_ZERO_BYTES_FREES
383 #define REALLOC_ZERO_BYTES_FREES 1
384 #endif
386 /*
387 TRIM_FASTBINS controls whether free() of a very small chunk can
388 immediately lead to trimming. Setting to true (1) can reduce memory
389 footprint, but will almost always slow down programs that use a lot
390 of small chunks.
392 Define this only if you are willing to give up some speed to more
393 aggressively reduce system-level memory footprint when releasing
394 memory in programs that use many small chunks. You can get
395 essentially the same effect by setting MXFAST to 0, but this can
396 lead to even greater slowdowns in programs using many small chunks.
397 TRIM_FASTBINS is an in-between compile-time option, that disables
398 only those chunks bordering topmost memory from being placed in
399 fastbins.
400 */
402 #ifndef TRIM_FASTBINS
403 #define TRIM_FASTBINS 0
404 #endif
407 /* Definition for getting more memory from the OS. */
408 #define MORECORE (*__morecore)
409 #define MORECORE_FAILURE 0
410 void * __default_morecore (ptrdiff_t);
411 void *(*__morecore)(ptrdiff_t) = __default_morecore;
414 #include <string.h>
416 /*
417 MORECORE-related declarations. By default, rely on sbrk
418 */
421 /*
422 MORECORE is the name of the routine to call to obtain more memory
423 from the system. See below for general guidance on writing
424 alternative MORECORE functions, as well as a version for WIN32 and a
425 sample version for pre-OSX macos.
426 */
428 #ifndef MORECORE
429 #define MORECORE sbrk
430 #endif
432 /*
433 MORECORE_FAILURE is the value returned upon failure of MORECORE
434 as well as mmap. Since it cannot be an otherwise valid memory address,
435 and must reflect values of standard sys calls, you probably ought not
436 try to redefine it.
437 */
439 #ifndef MORECORE_FAILURE
440 #define MORECORE_FAILURE (-1)
441 #endif
443 /*
444 If MORECORE_CONTIGUOUS is true, take advantage of fact that
445 consecutive calls to MORECORE with positive arguments always return
446 contiguous increasing addresses. This is true of unix sbrk. Even
447 if not defined, when regions happen to be contiguous, malloc will
448 permit allocations spanning regions obtained from different
449 calls. But defining this when applicable enables some stronger
450 consistency checks and space efficiencies.
451 */
453 #ifndef MORECORE_CONTIGUOUS
454 #define MORECORE_CONTIGUOUS 1
455 #endif
457 /*
458 Define MORECORE_CANNOT_TRIM if your version of MORECORE
459 cannot release space back to the system when given negative
460 arguments. This is generally necessary only if you are using
461 a hand-crafted MORECORE function that cannot handle negative arguments.
462 */
464 /* #define MORECORE_CANNOT_TRIM */
466 /* MORECORE_CLEARS (default 1)
467 The degree to which the routine mapped to MORECORE zeroes out
468 memory: never (0), only for newly allocated space (1) or always
469 (2). The distinction between (1) and (2) is necessary because on
470 some systems, if the application first decrements and then
471 increments the break value, the contents of the reallocated space
472 are unspecified.
473 */
475 #ifndef MORECORE_CLEARS
476 # define MORECORE_CLEARS 1
477 #endif
480 /*
481 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
482 sbrk fails, and mmap is used as a backup. The value must be a
483 multiple of page size. This backup strategy generally applies only
484 when systems have "holes" in address space, so sbrk cannot perform
485 contiguous expansion, but there is still space available on system.
486 On systems for which this is known to be useful (i.e. most linux
487 kernels), this occurs only when programs allocate huge amounts of
488 memory. Between this, and the fact that mmap regions tend to be
489 limited, the size should be large, to avoid too many mmap calls and
490 thus avoid running out of kernel resources. */
492 #ifndef MMAP_AS_MORECORE_SIZE
493 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
494 #endif
496 /*
497 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
498 large blocks.
499 */
501 #ifndef HAVE_MREMAP
502 #define HAVE_MREMAP 0
503 #endif
506 /*
507 This version of malloc supports the standard SVID/XPG mallinfo
508 routine that returns a struct containing usage properties and
509 statistics. It should work on any SVID/XPG compliant system that has
510 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
511 install such a thing yourself, cut out the preliminary declarations
512 as described above and below and save them in a malloc.h file. But
513 there's no compelling reason to bother to do this.)
515 The main declaration needed is the mallinfo struct that is returned
516 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
517 bunch of fields that are not even meaningful in this version of
518 malloc. These fields are are instead filled by mallinfo() with
519 other numbers that might be of interest.
520 */
523 /* ---------- description of public routines ------------ */
525 /*
526 malloc(size_t n)
527 Returns a pointer to a newly allocated chunk of at least n bytes, or null
528 if no space is available. Additionally, on failure, errno is
529 set to ENOMEM on ANSI C systems.
531 If n is zero, malloc returns a minumum-sized chunk. (The minimum
532 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
533 systems.) On most systems, size_t is an unsigned type, so calls
534 with negative arguments are interpreted as requests for huge amounts
535 of space, which will often fail. The maximum supported value of n
536 differs across systems, but is in all cases less than the maximum
537 representable value of a size_t.
538 */
539 void* __libc_malloc(size_t);
540 libc_hidden_proto (__libc_malloc)
542 /*
543 free(void* p)
544 Releases the chunk of memory pointed to by p, that had been previously
545 allocated using malloc or a related routine such as realloc.
546 It has no effect if p is null. It can have arbitrary (i.e., bad!)
547 effects if p has already been freed.
549 Unless disabled (using mallopt), freeing very large spaces will
550 when possible, automatically trigger operations that give
551 back unused memory to the system, thus reducing program footprint.
552 */
553 void __libc_free(void*);
554 libc_hidden_proto (__libc_free)
556 /*
557 calloc(size_t n_elements, size_t element_size);
558 Returns a pointer to n_elements * element_size bytes, with all locations
559 set to zero.
560 */
561 void* __libc_calloc(size_t, size_t);
563 /*
564 realloc(void* p, size_t n)
565 Returns a pointer to a chunk of size n that contains the same data
566 as does chunk p up to the minimum of (n, p's size) bytes, or null
567 if no space is available.
569 The returned pointer may or may not be the same as p. The algorithm
570 prefers extending p when possible, otherwise it employs the
571 equivalent of a malloc-copy-free sequence.
573 If p is null, realloc is equivalent to malloc.
575 If space is not available, realloc returns null, errno is set (if on
576 ANSI) and p is NOT freed.
578 if n is for fewer bytes than already held by p, the newly unused
579 space is lopped off and freed if possible. Unless the #define
580 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
581 zero (re)allocates a minimum-sized chunk.
583 Large chunks that were internally obtained via mmap will always
584 be reallocated using malloc-copy-free sequences unless
585 the system supports MREMAP (currently only linux).
587 The old unix realloc convention of allowing the last-free'd chunk
588 to be used as an argument to realloc is not supported.
589 */
590 void* __libc_realloc(void*, size_t);
591 libc_hidden_proto (__libc_realloc)
593 /*
594 memalign(size_t alignment, size_t n);
595 Returns a pointer to a newly allocated chunk of n bytes, aligned
596 in accord with the alignment argument.
598 The alignment argument should be a power of two. If the argument is
599 not a power of two, the nearest greater power is used.
600 8-byte alignment is guaranteed by normal malloc calls, so don't
601 bother calling memalign with an argument of 8 or less.
603 Overreliance on memalign is a sure way to fragment space.
604 */
605 void* __libc_memalign(size_t, size_t);
606 libc_hidden_proto (__libc_memalign)
608 /*
609 valloc(size_t n);
610 Equivalent to memalign(pagesize, n), where pagesize is the page
611 size of the system. If the pagesize is unknown, 4096 is used.
612 */
613 void* __libc_valloc(size_t);
617 /*
618 mallopt(int parameter_number, int parameter_value)
619 Sets tunable parameters The format is to provide a
620 (parameter-number, parameter-value) pair. mallopt then sets the
621 corresponding parameter to the argument value if it can (i.e., so
622 long as the value is meaningful), and returns 1 if successful else
623 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
624 normally defined in malloc.h. Only one of these (M_MXFAST) is used
625 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
626 so setting them has no effect. But this malloc also supports four
627 other options in mallopt. See below for details. Briefly, supported
628 parameters are as follows (listed defaults are for "typical"
629 configurations).
631 Symbol param # default allowed param values
632 M_MXFAST 1 64 0-80 (0 disables fastbins)
633 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
634 M_TOP_PAD -2 0 any
635 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
636 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
637 */
638 int __libc_mallopt(int, int);
639 libc_hidden_proto (__libc_mallopt)
642 /*
643 mallinfo()
644 Returns (by copy) a struct containing various summary statistics:
646 arena: current total non-mmapped bytes allocated from system
647 ordblks: the number of free chunks
648 smblks: the number of fastbin blocks (i.e., small chunks that
649 have been freed but not use resused or consolidated)
650 hblks: current number of mmapped regions
651 hblkhd: total bytes held in mmapped regions
652 usmblks: the maximum total allocated space. This will be greater
653 than current total if trimming has occurred.
654 fsmblks: total bytes held in fastbin blocks
655 uordblks: current total allocated space (normal or mmapped)
656 fordblks: total free space
657 keepcost: the maximum number of bytes that could ideally be released
658 back to system via malloc_trim. ("ideally" means that
659 it ignores page restrictions etc.)
661 Because these fields are ints, but internal bookkeeping may
662 be kept as longs, the reported values may wrap around zero and
663 thus be inaccurate.
664 */
665 struct mallinfo __libc_mallinfo(void);
668 /*
669 pvalloc(size_t n);
670 Equivalent to valloc(minimum-page-that-holds(n)), that is,
671 round up n to nearest pagesize.
672 */
673 void* __libc_pvalloc(size_t);
675 /*
676 malloc_trim(size_t pad);
678 If possible, gives memory back to the system (via negative
679 arguments to sbrk) if there is unused memory at the `high' end of
680 the malloc pool. You can call this after freeing large blocks of
681 memory to potentially reduce the system-level memory requirements
682 of a program. However, it cannot guarantee to reduce memory. Under
683 some allocation patterns, some large free blocks of memory will be
684 locked between two used chunks, so they cannot be given back to
685 the system.
687 The `pad' argument to malloc_trim represents the amount of free
688 trailing space to leave untrimmed. If this argument is zero,
689 only the minimum amount of memory to maintain internal data
690 structures will be left (one page or less). Non-zero arguments
691 can be supplied to maintain enough trailing space to service
692 future expected allocations without having to re-obtain memory
693 from the system.
695 Malloc_trim returns 1 if it actually released any memory, else 0.
696 On systems that do not support "negative sbrks", it will always
697 return 0.
698 */
699 int __malloc_trim(size_t);
701 /*
702 malloc_usable_size(void* p);
704 Returns the number of bytes you can actually use in
705 an allocated chunk, which may be more than you requested (although
706 often not) due to alignment and minimum size constraints.
707 You can use this many bytes without worrying about
708 overwriting other allocated objects. This is not a particularly great
709 programming practice. malloc_usable_size can be more useful in
710 debugging and assertions, for example:
712 p = malloc(n);
713 assert(malloc_usable_size(p) >= 256);
715 */
716 size_t __malloc_usable_size(void*);
718 /*
719 malloc_stats();
720 Prints on stderr the amount of space obtained from the system (both
721 via sbrk and mmap), the maximum amount (which may be more than
722 current if malloc_trim and/or munmap got called), and the current
723 number of bytes allocated via malloc (or realloc, etc) but not yet
724 freed. Note that this is the number of bytes allocated, not the
725 number requested. It will be larger than the number requested
726 because of alignment and bookkeeping overhead. Because it includes
727 alignment wastage as being in use, this figure may be greater than
728 zero even when no user-level chunks are allocated.
730 The reported current and maximum system memory can be inaccurate if
731 a program makes other calls to system memory allocation functions
732 (normally sbrk) outside of malloc.
734 malloc_stats prints only the most commonly interesting statistics.
735 More information can be obtained by calling mallinfo.
737 */
738 void __malloc_stats(void);
740 /*
741 malloc_get_state(void);
743 Returns the state of all malloc variables in an opaque data
744 structure.
745 */
746 void* __malloc_get_state(void);
748 /*
749 malloc_set_state(void* state);
751 Restore the state of all malloc variables from data obtained with
752 malloc_get_state().
753 */
754 int __malloc_set_state(void*);
756 /*
757 posix_memalign(void **memptr, size_t alignment, size_t size);
759 POSIX wrapper like memalign(), checking for validity of size.
760 */
761 int __posix_memalign(void **, size_t, size_t);
763 /* mallopt tuning options */
765 /*
766 M_MXFAST is the maximum request size used for "fastbins", special bins
767 that hold returned chunks without consolidating their spaces. This
768 enables future requests for chunks of the same size to be handled
769 very quickly, but can increase fragmentation, and thus increase the
770 overall memory footprint of a program.
772 This malloc manages fastbins very conservatively yet still
773 efficiently, so fragmentation is rarely a problem for values less
774 than or equal to the default. The maximum supported value of MXFAST
775 is 80. You wouldn't want it any higher than this anyway. Fastbins
776 are designed especially for use with many small structs, objects or
777 strings -- the default handles structs/objects/arrays with sizes up
778 to 8 4byte fields, or small strings representing words, tokens,
779 etc. Using fastbins for larger objects normally worsens
780 fragmentation without improving speed.
782 M_MXFAST is set in REQUEST size units. It is internally used in
783 chunksize units, which adds padding and alignment. You can reduce
784 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
785 algorithm to be a closer approximation of fifo-best-fit in all cases,
786 not just for larger requests, but will generally cause it to be
787 slower.
788 */
791 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
792 #ifndef M_MXFAST
793 #define M_MXFAST 1
794 #endif
796 #ifndef DEFAULT_MXFAST
797 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
798 #endif
801 /*
802 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
803 to keep before releasing via malloc_trim in free().
805 Automatic trimming is mainly useful in long-lived programs.
806 Because trimming via sbrk can be slow on some systems, and can
807 sometimes be wasteful (in cases where programs immediately
808 afterward allocate more large chunks) the value should be high
809 enough so that your overall system performance would improve by
810 releasing this much memory.
812 The trim threshold and the mmap control parameters (see below)
813 can be traded off with one another. Trimming and mmapping are
814 two different ways of releasing unused memory back to the
815 system. Between these two, it is often possible to keep
816 system-level demands of a long-lived program down to a bare
817 minimum. For example, in one test suite of sessions measuring
818 the XF86 X server on Linux, using a trim threshold of 128K and a
819 mmap threshold of 192K led to near-minimal long term resource
820 consumption.
822 If you are using this malloc in a long-lived program, it should
823 pay to experiment with these values. As a rough guide, you
824 might set to a value close to the average size of a process
825 (program) running on your system. Releasing this much memory
826 would allow such a process to run in memory. Generally, it's
827 worth it to tune for trimming rather tham memory mapping when a
828 program undergoes phases where several large chunks are
829 allocated and released in ways that can reuse each other's
830 storage, perhaps mixed with phases where there are no such
831 chunks at all. And in well-behaved long-lived programs,
832 controlling release of large blocks via trimming versus mapping
833 is usually faster.
835 However, in most programs, these parameters serve mainly as
836 protection against the system-level effects of carrying around
837 massive amounts of unneeded memory. Since frequent calls to
838 sbrk, mmap, and munmap otherwise degrade performance, the default
839 parameters are set to relatively high values that serve only as
840 safeguards.
842 The trim value It must be greater than page size to have any useful
843 effect. To disable trimming completely, you can set to
844 (unsigned long)(-1)
846 Trim settings interact with fastbin (MXFAST) settings: Unless
847 TRIM_FASTBINS is defined, automatic trimming never takes place upon
848 freeing a chunk with size less than or equal to MXFAST. Trimming is
849 instead delayed until subsequent freeing of larger chunks. However,
850 you can still force an attempted trim by calling malloc_trim.
852 Also, trimming is not generally possible in cases where
853 the main arena is obtained via mmap.
855 Note that the trick some people use of mallocing a huge space and
856 then freeing it at program startup, in an attempt to reserve system
857 memory, doesn't have the intended effect under automatic trimming,
858 since that memory will immediately be returned to the system.
859 */
861 #define M_TRIM_THRESHOLD -1
863 #ifndef DEFAULT_TRIM_THRESHOLD
864 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
865 #endif
867 /*
868 M_TOP_PAD is the amount of extra `padding' space to allocate or
869 retain whenever sbrk is called. It is used in two ways internally:
871 * When sbrk is called to extend the top of the arena to satisfy
872 a new malloc request, this much padding is added to the sbrk
873 request.
875 * When malloc_trim is called automatically from free(),
876 it is used as the `pad' argument.
878 In both cases, the actual amount of padding is rounded
879 so that the end of the arena is always a system page boundary.
881 The main reason for using padding is to avoid calling sbrk so
882 often. Having even a small pad greatly reduces the likelihood
883 that nearly every malloc request during program start-up (or
884 after trimming) will invoke sbrk, which needlessly wastes
885 time.
887 Automatic rounding-up to page-size units is normally sufficient
888 to avoid measurable overhead, so the default is 0. However, in
889 systems where sbrk is relatively slow, it can pay to increase
890 this value, at the expense of carrying around more memory than
891 the program needs.
892 */
894 #define M_TOP_PAD -2
896 #ifndef DEFAULT_TOP_PAD
897 #define DEFAULT_TOP_PAD (0)
898 #endif
900 /*
901 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
902 adjusted MMAP_THRESHOLD.
903 */
905 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
906 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
907 #endif
909 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
910 /* For 32-bit platforms we cannot increase the maximum mmap
911 threshold much because it is also the minimum value for the
912 maximum heap size and its alignment. Going above 512k (i.e., 1M
913 for new heaps) wastes too much address space. */
914 # if __WORDSIZE == 32
915 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
916 # else
917 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
918 # endif
919 #endif
921 /*
922 M_MMAP_THRESHOLD is the request size threshold for using mmap()
923 to service a request. Requests of at least this size that cannot
924 be allocated using already-existing space will be serviced via mmap.
925 (If enough normal freed space already exists it is used instead.)
927 Using mmap segregates relatively large chunks of memory so that
928 they can be individually obtained and released from the host
929 system. A request serviced through mmap is never reused by any
930 other request (at least not directly; the system may just so
931 happen to remap successive requests to the same locations).
933 Segregating space in this way has the benefits that:
935 1. Mmapped space can ALWAYS be individually released back
936 to the system, which helps keep the system level memory
937 demands of a long-lived program low.
938 2. Mapped memory can never become `locked' between
939 other chunks, as can happen with normally allocated chunks, which
940 means that even trimming via malloc_trim would not release them.
941 3. On some systems with "holes" in address spaces, mmap can obtain
942 memory that sbrk cannot.
944 However, it has the disadvantages that:
946 1. The space cannot be reclaimed, consolidated, and then
947 used to service later requests, as happens with normal chunks.
948 2. It can lead to more wastage because of mmap page alignment
949 requirements
950 3. It causes malloc performance to be more dependent on host
951 system memory management support routines which may vary in
952 implementation quality and may impose arbitrary
953 limitations. Generally, servicing a request via normal
954 malloc steps is faster than going through a system's mmap.
956 The advantages of mmap nearly always outweigh disadvantages for
957 "large" chunks, but the value of "large" varies across systems. The
958 default is an empirically derived value that works well in most
959 systems.
962 Update in 2006:
963 The above was written in 2001. Since then the world has changed a lot.
964 Memory got bigger. Applications got bigger. The virtual address space
965 layout in 32 bit linux changed.
967 In the new situation, brk() and mmap space is shared and there are no
968 artificial limits on brk size imposed by the kernel. What is more,
969 applications have started using transient allocations larger than the
970 128Kb as was imagined in 2001.
972 The price for mmap is also high now; each time glibc mmaps from the
973 kernel, the kernel is forced to zero out the memory it gives to the
974 application. Zeroing memory is expensive and eats a lot of cache and
975 memory bandwidth. This has nothing to do with the efficiency of the
976 virtual memory system, by doing mmap the kernel just has no choice but
977 to zero.
979 In 2001, the kernel had a maximum size for brk() which was about 800
980 megabytes on 32 bit x86, at that point brk() would hit the first
981 mmaped shared libaries and couldn't expand anymore. With current 2.6
982 kernels, the VA space layout is different and brk() and mmap
983 both can span the entire heap at will.
985 Rather than using a static threshold for the brk/mmap tradeoff,
986 we are now using a simple dynamic one. The goal is still to avoid
987 fragmentation. The old goals we kept are
988 1) try to get the long lived large allocations to use mmap()
989 2) really large allocations should always use mmap()
990 and we're adding now:
991 3) transient allocations should use brk() to avoid forcing the kernel
992 having to zero memory over and over again
994 The implementation works with a sliding threshold, which is by default
995 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
996 out at 128Kb as per the 2001 default.
998 This allows us to satisfy requirement 1) under the assumption that long
999 lived allocations are made early in the process' lifespan, before it has
1000 started doing dynamic allocations of the same size (which will
1001 increase the threshold).
1003 The upperbound on the threshold satisfies requirement 2)
1005 The threshold goes up in value when the application frees memory that was
1006 allocated with the mmap allocator. The idea is that once the application
1007 starts freeing memory of a certain size, it's highly probable that this is
1008 a size the application uses for transient allocations. This estimator
1009 is there to satisfy the new third requirement.
1011 */
1013 #define M_MMAP_THRESHOLD -3
1015 #ifndef DEFAULT_MMAP_THRESHOLD
1016 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1017 #endif
1019 /*
1020 M_MMAP_MAX is the maximum number of requests to simultaneously
1021 service using mmap. This parameter exists because
1022 some systems have a limited number of internal tables for
1023 use by mmap, and using more than a few of them may degrade
1024 performance.
1026 The default is set to a value that serves only as a safeguard.
1027 Setting to 0 disables use of mmap for servicing large requests.
1028 */
1030 #define M_MMAP_MAX -4
1032 #ifndef DEFAULT_MMAP_MAX
1033 #define DEFAULT_MMAP_MAX (65536)
1034 #endif
1036 #include <malloc.h>
1038 #ifndef RETURN_ADDRESS
1039 #define RETURN_ADDRESS(X_) (NULL)
1040 #endif
1042 /* On some platforms we can compile internal, not exported functions better.
1043 Let the environment provide a macro and define it to be empty if it
1044 is not available. */
1045 #ifndef internal_function
1046 # define internal_function
1047 #endif
1049 /* Forward declarations. */
1050 struct malloc_chunk;
1051 typedef struct malloc_chunk* mchunkptr;
1053 /* Internal routines. */
1055 static void* _int_malloc(mstate, size_t);
1056 static void _int_free(mstate, mchunkptr, int);
1057 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1058 INTERNAL_SIZE_T);
1059 static void* _int_memalign(mstate, size_t, size_t);
1060 static void* _mid_memalign(size_t, size_t, void *);
1062 static void malloc_printerr(int action, const char *str, void *ptr);
1064 static void* internal_function mem2mem_check(void *p, size_t sz);
1065 static int internal_function top_check(void);
1066 static void internal_function munmap_chunk(mchunkptr p);
1067 #if HAVE_MREMAP
1068 static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
1069 #endif
1071 static void* malloc_check(size_t sz, const void *caller);
1072 static void free_check(void* mem, const void *caller);
1073 static void* realloc_check(void* oldmem, size_t bytes,
1074 const void *caller);
1075 static void* memalign_check(size_t alignment, size_t bytes,
1076 const void *caller);
1077 #ifndef NO_THREADS
1078 static void* malloc_atfork(size_t sz, const void *caller);
1079 static void free_atfork(void* mem, const void *caller);
1080 #endif
1082 /* ------------------ MMAP support ------------------ */
1085 #include <fcntl.h>
1086 #include <sys/mman.h>
1088 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1089 # define MAP_ANONYMOUS MAP_ANON
1090 #endif
1092 #ifndef MAP_NORESERVE
1093 # define MAP_NORESERVE 0
1094 #endif
1096 #define MMAP(addr, size, prot, flags) \
1097 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1100 /*
1101 ----------------------- Chunk representations -----------------------
1102 */
1105 /*
1106 This struct declaration is misleading (but accurate and necessary).
1107 It declares a "view" into memory allowing access to necessary
1108 fields at known offsets from a given base. See explanation below.
1109 */
1111 struct malloc_chunk {
1113 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
1114 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
1116 struct malloc_chunk* fd; /* double links -- used only if free. */
1117 struct malloc_chunk* bk;
1119 /* Only used for large blocks: pointer to next larger size. */
1120 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1121 struct malloc_chunk* bk_nextsize;
1122 };
1125 /*
1126 malloc_chunk details:
1128 (The following includes lightly edited explanations by Colin Plumb.)
1130 Chunks of memory are maintained using a `boundary tag' method as
1131 described in e.g., Knuth or Standish. (See the paper by Paul
1132 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1133 survey of such techniques.) Sizes of free chunks are stored both
1134 in the front of each chunk and at the end. This makes
1135 consolidating fragmented chunks into bigger chunks very fast. The
1136 size fields also hold bits representing whether chunks are free or
1137 in use.
1139 An allocated chunk looks like this:
1142 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1143 | Size of previous chunk, if allocated | |
1144 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1145 | Size of chunk, in bytes |M|P|
1146 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1147 | User data starts here... .
1148 . .
1149 . (malloc_usable_size() bytes) .
1150 . |
1151 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1152 | Size of chunk |
1153 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1156 Where "chunk" is the front of the chunk for the purpose of most of
1157 the malloc code, but "mem" is the pointer that is returned to the
1158 user. "Nextchunk" is the beginning of the next contiguous chunk.
1160 Chunks always begin on even word boundaries, so the mem portion
1161 (which is returned to the user) is also on an even word boundary, and
1162 thus at least double-word aligned.
1164 Free chunks are stored in circular doubly-linked lists, and look like this:
1166 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1167 | Size of previous chunk |
1168 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1169 `head:' | Size of chunk, in bytes |P|
1170 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1171 | Forward pointer to next chunk in list |
1172 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1173 | Back pointer to previous chunk in list |
1174 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1175 | Unused space (may be 0 bytes long) .
1176 . .
1177 . |
1178 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1179 `foot:' | Size of chunk, in bytes |
1180 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1182 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1183 chunk size (which is always a multiple of two words), is an in-use
1184 bit for the *previous* chunk. If that bit is *clear*, then the
1185 word before the current chunk size contains the previous chunk
1186 size, and can be used to find the front of the previous chunk.
1187 The very first chunk allocated always has this bit set,
1188 preventing access to non-existent (or non-owned) memory. If
1189 prev_inuse is set for any given chunk, then you CANNOT determine
1190 the size of the previous chunk, and might even get a memory
1191 addressing fault when trying to do so.
1193 Note that the `foot' of the current chunk is actually represented
1194 as the prev_size of the NEXT chunk. This makes it easier to
1195 deal with alignments etc but can be very confusing when trying
1196 to extend or adapt this code.
1198 The two exceptions to all this are
1200 1. The special chunk `top' doesn't bother using the
1201 trailing size field since there is no next contiguous chunk
1202 that would have to index off it. After initialization, `top'
1203 is forced to always exist. If it would become less than
1204 MINSIZE bytes long, it is replenished.
1206 2. Chunks allocated via mmap, which have the second-lowest-order
1207 bit M (IS_MMAPPED) set in their size fields. Because they are
1208 allocated one-by-one, each must contain its own trailing size field.
1210 */
1212 /*
1213 ---------- Size and alignment checks and conversions ----------
1214 */
1216 /* conversion from malloc headers to user pointers, and back */
1218 #define chunk2mem(p) ((void*)((char*)(p) + 2*SIZE_SZ))
1219 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1221 /* The smallest possible chunk */
1222 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1224 /* The smallest size we can malloc is an aligned minimal chunk */
1226 #define MINSIZE \
1227 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1229 /* Check if m has acceptable alignment */
1231 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1233 #define misaligned_chunk(p) \
1234 ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
1235 & MALLOC_ALIGN_MASK)
1238 /*
1239 Check if a request is so large that it would wrap around zero when
1240 padded and aligned. To simplify some other code, the bound is made
1241 low enough so that adding MINSIZE will also not wrap around zero.
1242 */
1244 #define REQUEST_OUT_OF_RANGE(req) \
1245 ((unsigned long) (req) >= \
1246 (unsigned long) (INTERNAL_SIZE_T) (-2 * MINSIZE))
1248 /* pad request bytes into a usable size -- internal version */
1250 #define request2size(req) \
1251 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1252 MINSIZE : \
1253 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1255 /* Same, except also perform argument check */
1257 #define checked_request2size(req, sz) \
1258 if (REQUEST_OUT_OF_RANGE (req)) { \
1259 __set_errno (ENOMEM); \
1260 return 0; \
1261 } \
1262 (sz) = request2size (req);
1264 /*
1265 --------------- Physical chunk operations ---------------
1266 */
1269 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1270 #define PREV_INUSE 0x1
1272 /* extract inuse bit of previous chunk */
1273 #define prev_inuse(p) ((p)->size & PREV_INUSE)
1276 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1277 #define IS_MMAPPED 0x2
1279 /* check for mmap()'ed chunk */
1280 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1283 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1284 from a non-main arena. This is only set immediately before handing
1285 the chunk to the user, if necessary. */
1286 #define NON_MAIN_ARENA 0x4
1288 /* check for chunk from non-main arena */
1289 #define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)
1292 /*
1293 Bits to mask off when extracting size
1295 Note: IS_MMAPPED is intentionally not masked off from size field in
1296 macros for which mmapped chunks should never be seen. This should
1297 cause helpful core dumps to occur if it is tried by accident by
1298 people extending or adapting this malloc.
1299 */
1300 #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1302 /* Get size, ignoring use bits */
1303 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
1306 /* Ptr to next physical malloc_chunk. */
1307 #define next_chunk(p) ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))
1309 /* Ptr to previous physical malloc_chunk */
1310 #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - ((p)->prev_size)))
1312 /* Treat space at ptr + offset as a chunk */
1313 #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1315 /* extract p's inuse bit */
1316 #define inuse(p) \
1317 ((((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)
1319 /* set/clear chunk as being inuse without otherwise disturbing */
1320 #define set_inuse(p) \
1321 ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE
1323 #define clear_inuse(p) \
1324 ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)
1327 /* check/set/clear inuse bits in known places */
1328 #define inuse_bit_at_offset(p, s) \
1329 (((mchunkptr) (((char *) (p)) + (s)))->size & PREV_INUSE)
1331 #define set_inuse_bit_at_offset(p, s) \
1332 (((mchunkptr) (((char *) (p)) + (s)))->size |= PREV_INUSE)
1334 #define clear_inuse_bit_at_offset(p, s) \
1335 (((mchunkptr) (((char *) (p)) + (s)))->size &= ~(PREV_INUSE))
1338 /* Set size at head, without disturbing its use bit */
1339 #define set_head_size(p, s) ((p)->size = (((p)->size & SIZE_BITS) | (s)))
1341 /* Set size/use field */
1342 #define set_head(p, s) ((p)->size = (s))
1344 /* Set size at footer (only when chunk is not in use) */
1345 #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->prev_size = (s))
1348 /*
1349 -------------------- Internal data structures --------------------
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.
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 */
1363 /*
1364 Bins
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.
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.
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.
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 */
1399 typedef struct malloc_chunk *mbinptr;
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))
1406 /* analog of ++bin */
1407 #define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
1409 /* Reminders about list directionality within bins */
1410 #define first(b) ((b)->fd)
1411 #define last(b) ((b)->bk)
1413 /* Take a chunk off a bin list */
1414 #define unlink(P, BK, FD) { \
1415 FD = P->fd; \
1416 BK = P->bk; \
1417 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
1418 malloc_printerr (check_action, "corrupted double-linked list", P); \
1419 else { \
1420 FD->bk = BK; \
1421 BK->fd = FD; \
1422 if (!in_smallbin_range (P->size) \
1423 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \
1424 if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \
1425 || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \
1426 malloc_printerr (check_action, \
1427 "corrupted double-linked list (not small)", P);\
1428 if (FD->fd_nextsize == NULL) { \
1429 if (P->fd_nextsize == P) \
1430 FD->fd_nextsize = FD->bk_nextsize = FD; \
1431 else { \
1432 FD->fd_nextsize = P->fd_nextsize; \
1433 FD->bk_nextsize = P->bk_nextsize; \
1434 P->fd_nextsize->bk_nextsize = FD; \
1435 P->bk_nextsize->fd_nextsize = FD; \
1436 } \
1437 } else { \
1438 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \
1439 P->bk_nextsize->fd_nextsize = P->fd_nextsize; \
1440 } \
1441 } \
1442 } \
1445 /*
1446 Indexing
1448 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1449 8 bytes apart. Larger bins are approximately logarithmically spaced:
1451 64 bins of size 8
1452 32 bins of size 64
1453 16 bins of size 512
1454 8 bins of size 4096
1455 4 bins of size 32768
1456 2 bins of size 262144
1457 1 bin of size what's left
1459 There is actually a little bit of slop in the numbers in bin_index
1460 for the sake of speed. This makes no difference elsewhere.
1462 The bins top out around 1MB because we expect to service large
1463 requests via mmap.
1465 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1466 a valid chunk size the small bins are bumped up one.
1467 */
1469 #define NBINS 128
1470 #define NSMALLBINS 64
1471 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1472 #define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > 2 * SIZE_SZ)
1473 #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
1475 #define in_smallbin_range(sz) \
1476 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
1478 #define smallbin_index(sz) \
1479 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
1480 + SMALLBIN_CORRECTION)
1482 #define largebin_index_32(sz) \
1483 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1484 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1485 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1486 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1487 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1488 126)
1490 #define largebin_index_32_big(sz) \
1491 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1492 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1493 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1494 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1495 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1496 126)
1498 // XXX It remains to be seen whether it is good to keep the widths of
1499 // XXX the buckets the same or whether it should be scaled by a factor
1500 // XXX of two as well.
1501 #define largebin_index_64(sz) \
1502 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1503 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1504 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1505 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1506 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1507 126)
1509 #define largebin_index(sz) \
1510 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1511 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1512 : largebin_index_32 (sz))
1514 #define bin_index(sz) \
1515 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
1518 /*
1519 Unsorted chunks
1521 All remainders from chunk splits, as well as all returned chunks,
1522 are first placed in the "unsorted" bin. They are then placed
1523 in regular bins after malloc gives them ONE chance to be used before
1524 binning. So, basically, the unsorted_chunks list acts as a queue,
1525 with chunks being placed on it in free (and malloc_consolidate),
1526 and taken off (to be either used or placed in bins) in malloc.
1528 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1529 does not have to be taken into account in size comparisons.
1530 */
1532 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1533 #define unsorted_chunks(M) (bin_at (M, 1))
1535 /*
1536 Top
1538 The top-most available chunk (i.e., the one bordering the end of
1539 available memory) is treated specially. It is never included in
1540 any bin, is used only if no other chunk is available, and is
1541 released back to the system if it is very large (see
1542 M_TRIM_THRESHOLD). Because top initially
1543 points to its own bin with initial zero size, thus forcing
1544 extension on the first malloc request, we avoid having any special
1545 code in malloc to check whether it even exists yet. But we still
1546 need to do so when getting memory from system, so we make
1547 initial_top treat the bin as a legal but unusable chunk during the
1548 interval between initialization and the first call to
1549 sysmalloc. (This is somewhat delicate, since it relies on
1550 the 2 preceding words to be zero during this interval as well.)
1551 */
1553 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1554 #define initial_top(M) (unsorted_chunks (M))
1556 /*
1557 Binmap
1559 To help compensate for the large number of bins, a one-level index
1560 structure is used for bin-by-bin searching. `binmap' is a
1561 bitvector recording whether bins are definitely empty so they can
1562 be skipped over during during traversals. The bits are NOT always
1563 cleared as soon as bins are empty, but instead only
1564 when they are noticed to be empty during traversal in malloc.
1565 */
1567 /* Conservatively use 32 bits per map word, even if on 64bit system */
1568 #define BINMAPSHIFT 5
1569 #define BITSPERMAP (1U << BINMAPSHIFT)
1570 #define BINMAPSIZE (NBINS / BITSPERMAP)
1572 #define idx2block(i) ((i) >> BINMAPSHIFT)
1573 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
1575 #define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1576 #define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1577 #define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
1579 /*
1580 Fastbins
1582 An array of lists holding recently freed small chunks. Fastbins
1583 are not doubly linked. It is faster to single-link them, and
1584 since chunks are never removed from the middles of these lists,
1585 double linking is not necessary. Also, unlike regular bins, they
1586 are not even processed in FIFO order (they use faster LIFO) since
1587 ordering doesn't much matter in the transient contexts in which
1588 fastbins are normally used.
1590 Chunks in fastbins keep their inuse bit set, so they cannot
1591 be consolidated with other free chunks. malloc_consolidate
1592 releases all chunks in fastbins and consolidates them with
1593 other free chunks.
1594 */
1596 typedef struct malloc_chunk *mfastbinptr;
1597 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1599 /* offset 2 to use otherwise unindexable first 2 bins */
1600 #define fastbin_index(sz) \
1601 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1604 /* The maximum fastbin request size we support */
1605 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1607 #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
1609 /*
1610 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1611 that triggers automatic consolidation of possibly-surrounding
1612 fastbin chunks. This is a heuristic, so the exact value should not
1613 matter too much. It is defined at half the default trim threshold as a
1614 compromise heuristic to only attempt consolidation if it is likely
1615 to lead to trimming. However, it is not dynamically tunable, since
1616 consolidation reduces fragmentation surrounding large chunks even
1617 if trimming is not used.
1618 */
1620 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1622 /*
1623 Since the lowest 2 bits in max_fast don't matter in size comparisons,
1624 they are used as flags.
1625 */
1627 /*
1628 FASTCHUNKS_BIT held in max_fast indicates that there are probably
1629 some fastbin chunks. It is set true on entering a chunk into any
1630 fastbin, and cleared only in malloc_consolidate.
1632 The truth value is inverted so that have_fastchunks will be true
1633 upon startup (since statics are zero-filled), simplifying
1634 initialization checks.
1635 */
1637 #define FASTCHUNKS_BIT (1U)
1639 #define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
1640 #define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT)
1641 #define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT)
1643 /*
1644 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1645 regions. Otherwise, contiguity is exploited in merging together,
1646 when possible, results from consecutive MORECORE calls.
1648 The initial value comes from MORECORE_CONTIGUOUS, but is
1649 changed dynamically if mmap is ever used as an sbrk substitute.
1650 */
1652 #define NONCONTIGUOUS_BIT (2U)
1654 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1655 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1656 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1657 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1659 /*
1660 Set value of max_fast.
1661 Use impossibly small value if 0.
1662 Precondition: there are no existing fastbin chunks.
1663 Setting the value clears fastchunk bit but preserves noncontiguous bit.
1664 */
1666 #define set_max_fast(s) \
1667 global_max_fast = (((s) == 0) \
1668 ? SMALLBIN_WIDTH : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1669 #define get_max_fast() global_max_fast
1672 /*
1673 ----------- Internal state representation and initialization -----------
1674 */
1676 struct malloc_state
1678 /* Serialize access. */
1679 mutex_t mutex;
1681 /* Flags (formerly in max_fast). */
1682 int flags;
1684 /* Fastbins */
1685 mfastbinptr fastbinsY[NFASTBINS];
1687 /* Base of the topmost chunk -- not otherwise kept in a bin */
1688 mchunkptr top;
1690 /* The remainder from the most recent split of a small request */
1691 mchunkptr last_remainder;
1693 /* Normal bins packed as described above */
1694 mchunkptr bins[NBINS * 2 - 2];
1696 /* Bitmap of bins */
1697 unsigned int binmap[BINMAPSIZE];
1699 /* Linked list */
1700 struct malloc_state *next;
1702 /* Linked list for free arenas. */
1703 struct malloc_state *next_free;
1705 /* Memory allocated from the system in this arena. */
1706 INTERNAL_SIZE_T system_mem;
1707 INTERNAL_SIZE_T max_system_mem;
1708 };
1710 struct malloc_par
1712 /* Tunable parameters */
1713 unsigned long trim_threshold;
1714 INTERNAL_SIZE_T top_pad;
1715 INTERNAL_SIZE_T mmap_threshold;
1716 INTERNAL_SIZE_T arena_test;
1717 INTERNAL_SIZE_T arena_max;
1719 /* Memory map support */
1720 int n_mmaps;
1721 int n_mmaps_max;
1722 int max_n_mmaps;
1723 /* the mmap_threshold is dynamic, until the user sets
1724 it manually, at which point we need to disable any
1725 dynamic behavior. */
1726 int no_dyn_threshold;
1728 /* Statistics */
1729 INTERNAL_SIZE_T mmapped_mem;
1730 /*INTERNAL_SIZE_T sbrked_mem;*/
1731 /*INTERNAL_SIZE_T max_sbrked_mem;*/
1732 INTERNAL_SIZE_T max_mmapped_mem;
1733 INTERNAL_SIZE_T max_total_mem; /* only kept for NO_THREADS */
1735 /* First address handed out by MORECORE/sbrk. */
1736 char *sbrk_base;
1737 };
1739 /* There are several instances of this struct ("arenas") in this
1740 malloc. If you are adapting this malloc in a way that does NOT use
1741 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1742 before using. This malloc relies on the property that malloc_state
1743 is initialized to all zeroes (as is true of C statics). */
1745 static struct malloc_state main_arena =
1747 .mutex = MUTEX_INITIALIZER,
1748 .next = &main_arena
1749 };
1751 /* There is only one instance of the malloc parameters. */
1753 static struct malloc_par mp_ =
1755 .top_pad = DEFAULT_TOP_PAD,
1756 .n_mmaps_max = DEFAULT_MMAP_MAX,
1757 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1758 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1759 #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1760 .arena_test = NARENAS_FROM_NCORES (1)
1761 };
1764 /* Non public mallopt parameters. */
1765 #define M_ARENA_TEST -7
1766 #define M_ARENA_MAX -8
1769 /* Maximum size of memory handled in fastbins. */
1770 static INTERNAL_SIZE_T global_max_fast;
1772 /*
1773 Initialize a malloc_state struct.
1775 This is called only from within malloc_consolidate, which needs
1776 be called in the same contexts anyway. It is never called directly
1777 outside of malloc_consolidate because some optimizing compilers try
1778 to inline it at all call points, which turns out not to be an
1779 optimization at all. (Inlining it in malloc_consolidate is fine though.)
1780 */
1782 static void
1783 malloc_init_state (mstate av)
1785 int i;
1786 mbinptr bin;
1788 /* Establish circular links for normal bins */
1789 for (i = 1; i < NBINS; ++i)
1791 bin = bin_at (av, i);
1792 bin->fd = bin->bk = bin;
1795 #if MORECORE_CONTIGUOUS
1796 if (av != &main_arena)
1797 #endif
1798 set_noncontiguous (av);
1799 if (av == &main_arena)
1800 set_max_fast (DEFAULT_MXFAST);
1801 av->flags |= FASTCHUNKS_BIT;
1803 av->top = initial_top (av);
1806 /*
1807 Other internal utilities operating on mstates
1808 */
1810 static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1811 static int systrim (size_t, mstate);
1812 static void malloc_consolidate (mstate);
1815 /* -------------- Early definitions for debugging hooks ---------------- */
1817 /* Define and initialize the hook variables. These weak definitions must
1818 appear before any use of the variables in a function (arena.c uses one). */
1819 #ifndef weak_variable
1820 /* In GNU libc we want the hook variables to be weak definitions to
1821 avoid a problem with Emacs. */
1822 # define weak_variable weak_function
1823 #endif
1825 /* Forward declarations. */
1826 static void *malloc_hook_ini (size_t sz,
1827 const void *caller) __THROW;
1828 static void *realloc_hook_ini (void *ptr, size_t sz,
1829 const void *caller) __THROW;
1830 static void *memalign_hook_ini (size_t alignment, size_t sz,
1831 const void *caller) __THROW;
1833 void weak_variable (*__malloc_initialize_hook) (void) = NULL;
1834 void weak_variable (*__free_hook) (void *__ptr,
1835 const void *) = NULL;
1836 void *weak_variable (*__malloc_hook)
1837 (size_t __size, const void *) = malloc_hook_ini;
1838 void *weak_variable (*__realloc_hook)
1839 (void *__ptr, size_t __size, const void *)
1840 = realloc_hook_ini;
1841 void *weak_variable (*__memalign_hook)
1842 (size_t __alignment, size_t __size, const void *)
1843 = memalign_hook_ini;
1844 void weak_variable (*__after_morecore_hook) (void) = NULL;
1847 /* ---------------- Error behavior ------------------------------------ */
1849 #ifndef DEFAULT_CHECK_ACTION
1850 # define DEFAULT_CHECK_ACTION 3
1851 #endif
1853 static int check_action = DEFAULT_CHECK_ACTION;
1856 /* ------------------ Testing support ----------------------------------*/
1858 static int perturb_byte;
1860 static void
1861 alloc_perturb (char *p, size_t n)
1863 if (__glibc_unlikely (perturb_byte))
1864 memset (p, perturb_byte ^ 0xff, n);
1867 static void
1868 free_perturb (char *p, size_t n)
1870 if (__glibc_unlikely (perturb_byte))
1871 memset (p, perturb_byte, n);
1876 #include <stap-probe.h>
1878 /* ------------------- Support for multiple arenas -------------------- */
1879 #include "arena.c"
1881 /*
1882 Debugging support
1884 These routines make a number of assertions about the states
1885 of data structures that should be true at all times. If any
1886 are not true, it's very likely that a user program has somehow
1887 trashed memory. (It's also possible that there is a coding error
1888 in malloc. In which case, please report it!)
1889 */
1891 #if !MALLOC_DEBUG
1893 # define check_chunk(A, P)
1894 # define check_free_chunk(A, P)
1895 # define check_inuse_chunk(A, P)
1896 # define check_remalloced_chunk(A, P, N)
1897 # define check_malloced_chunk(A, P, N)
1898 # define check_malloc_state(A)
1900 #else
1902 # define check_chunk(A, P) do_check_chunk (A, P)
1903 # define check_free_chunk(A, P) do_check_free_chunk (A, P)
1904 # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
1905 # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
1906 # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
1907 # define check_malloc_state(A) do_check_malloc_state (A)
1909 /*
1910 Properties of all chunks
1911 */
1913 static void
1914 do_check_chunk (mstate av, mchunkptr p)
1916 unsigned long sz = chunksize (p);
1917 /* min and max possible addresses assuming contiguous allocation */
1918 char *max_address = (char *) (av->top) + chunksize (av->top);
1919 char *min_address = max_address - av->system_mem;
1921 if (!chunk_is_mmapped (p))
1923 /* Has legal address ... */
1924 if (p != av->top)
1926 if (contiguous (av))
1928 assert (((char *) p) >= min_address);
1929 assert (((char *) p + sz) <= ((char *) (av->top)));
1932 else
1934 /* top size is always at least MINSIZE */
1935 assert ((unsigned long) (sz) >= MINSIZE);
1936 /* top predecessor always marked inuse */
1937 assert (prev_inuse (p));
1940 else
1942 /* address is outside main heap */
1943 if (contiguous (av) && av->top != initial_top (av))
1945 assert (((char *) p) < min_address || ((char *) p) >= max_address);
1947 /* chunk is page-aligned */
1948 assert (((p->prev_size + sz) & (GLRO (dl_pagesize) - 1)) == 0);
1949 /* mem is aligned */
1950 assert (aligned_OK (chunk2mem (p)));
1954 /*
1955 Properties of free chunks
1956 */
1958 static void
1959 do_check_free_chunk (mstate av, mchunkptr p)
1961 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
1962 mchunkptr next = chunk_at_offset (p, sz);
1964 do_check_chunk (av, p);
1966 /* Chunk must claim to be free ... */
1967 assert (!inuse (p));
1968 assert (!chunk_is_mmapped (p));
1970 /* Unless a special marker, must have OK fields */
1971 if ((unsigned long) (sz) >= MINSIZE)
1973 assert ((sz & MALLOC_ALIGN_MASK) == 0);
1974 assert (aligned_OK (chunk2mem (p)));
1975 /* ... matching footer field */
1976 assert (next->prev_size == sz);
1977 /* ... and is fully consolidated */
1978 assert (prev_inuse (p));
1979 assert (next == av->top || inuse (next));
1981 /* ... and has minimally sane links */
1982 assert (p->fd->bk == p);
1983 assert (p->bk->fd == p);
1985 else /* markers are always of size SIZE_SZ */
1986 assert (sz == SIZE_SZ);
1989 /*
1990 Properties of inuse chunks
1991 */
1993 static void
1994 do_check_inuse_chunk (mstate av, mchunkptr p)
1996 mchunkptr next;
1998 do_check_chunk (av, p);
2000 if (chunk_is_mmapped (p))
2001 return; /* mmapped chunks have no next/prev */
2003 /* Check whether it claims to be in use ... */
2004 assert (inuse (p));
2006 next = next_chunk (p);
2008 /* ... and is surrounded by OK chunks.
2009 Since more things can be checked with free chunks than inuse ones,
2010 if an inuse chunk borders them and debug is on, it's worth doing them.
2011 */
2012 if (!prev_inuse (p))
2014 /* Note that we cannot even look at prev unless it is not inuse */
2015 mchunkptr prv = prev_chunk (p);
2016 assert (next_chunk (prv) == p);
2017 do_check_free_chunk (av, prv);
2020 if (next == av->top)
2022 assert (prev_inuse (next));
2023 assert (chunksize (next) >= MINSIZE);
2025 else if (!inuse (next))
2026 do_check_free_chunk (av, next);
2029 /*
2030 Properties of chunks recycled from fastbins
2031 */
2033 static void
2034 do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2036 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
2038 if (!chunk_is_mmapped (p))
2040 assert (av == arena_for_chunk (p));
2041 if (chunk_non_main_arena (p))
2042 assert (av != &main_arena);
2043 else
2044 assert (av == &main_arena);
2047 do_check_inuse_chunk (av, p);
2049 /* Legal size ... */
2050 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2051 assert ((unsigned long) (sz) >= MINSIZE);
2052 /* ... and alignment */
2053 assert (aligned_OK (chunk2mem (p)));
2054 /* chunk is less than MINSIZE more than request */
2055 assert ((long) (sz) - (long) (s) >= 0);
2056 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2059 /*
2060 Properties of nonrecycled chunks at the point they are malloced
2061 */
2063 static void
2064 do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2066 /* same as recycled case ... */
2067 do_check_remalloced_chunk (av, p, s);
2069 /*
2070 ... plus, must obey implementation invariant that prev_inuse is
2071 always true of any allocated chunk; i.e., that each allocated
2072 chunk borders either a previously allocated and still in-use
2073 chunk, or the base of its memory arena. This is ensured
2074 by making all allocations from the `lowest' part of any found
2075 chunk. This does not necessarily hold however for chunks
2076 recycled via fastbins.
2077 */
2079 assert (prev_inuse (p));
2083 /*
2084 Properties of malloc_state.
2086 This may be useful for debugging malloc, as well as detecting user
2087 programmer errors that somehow write into malloc_state.
2089 If you are extending or experimenting with this malloc, you can
2090 probably figure out how to hack this routine to print out or
2091 display chunk addresses, sizes, bins, and other instrumentation.
2092 */
2094 static void
2095 do_check_malloc_state (mstate av)
2097 int i;
2098 mchunkptr p;
2099 mchunkptr q;
2100 mbinptr b;
2101 unsigned int idx;
2102 INTERNAL_SIZE_T size;
2103 unsigned long total = 0;
2104 int max_fast_bin;
2106 /* internal size_t must be no wider than pointer type */
2107 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2109 /* alignment is a power of 2 */
2110 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2112 /* cannot run remaining checks until fully initialized */
2113 if (av->top == 0 || av->top == initial_top (av))
2114 return;
2116 /* pagesize is a power of 2 */
2117 assert (powerof2(GLRO (dl_pagesize)));
2119 /* A contiguous main_arena is consistent with sbrk_base. */
2120 if (av == &main_arena && contiguous (av))
2121 assert ((char *) mp_.sbrk_base + av->system_mem ==
2122 (char *) av->top + chunksize (av->top));
2124 /* properties of fastbins */
2126 /* max_fast is in allowed range */
2127 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2129 max_fast_bin = fastbin_index (get_max_fast ());
2131 for (i = 0; i < NFASTBINS; ++i)
2133 p = fastbin (av, i);
2135 /* The following test can only be performed for the main arena.
2136 While mallopt calls malloc_consolidate to get rid of all fast
2137 bins (especially those larger than the new maximum) this does
2138 only happen for the main arena. Trying to do this for any
2139 other arena would mean those arenas have to be locked and
2140 malloc_consolidate be called for them. This is excessive. And
2141 even if this is acceptable to somebody it still cannot solve
2142 the problem completely since if the arena is locked a
2143 concurrent malloc call might create a new arena which then
2144 could use the newly invalid fast bins. */
2146 /* all bins past max_fast are empty */
2147 if (av == &main_arena && i > max_fast_bin)
2148 assert (p == 0);
2150 while (p != 0)
2152 /* each chunk claims to be inuse */
2153 do_check_inuse_chunk (av, p);
2154 total += chunksize (p);
2155 /* chunk belongs in this bin */
2156 assert (fastbin_index (chunksize (p)) == i);
2157 p = p->fd;
2161 if (total != 0)
2162 assert (have_fastchunks (av));
2163 else if (!have_fastchunks (av))
2164 assert (total == 0);
2166 /* check normal bins */
2167 for (i = 1; i < NBINS; ++i)
2169 b = bin_at (av, i);
2171 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2172 if (i >= 2)
2174 unsigned int binbit = get_binmap (av, i);
2175 int empty = last (b) == b;
2176 if (!binbit)
2177 assert (empty);
2178 else if (!empty)
2179 assert (binbit);
2182 for (p = last (b); p != b; p = p->bk)
2184 /* each chunk claims to be free */
2185 do_check_free_chunk (av, p);
2186 size = chunksize (p);
2187 total += size;
2188 if (i >= 2)
2190 /* chunk belongs in bin */
2191 idx = bin_index (size);
2192 assert (idx == i);
2193 /* lists are sorted */
2194 assert (p->bk == b ||
2195 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2197 if (!in_smallbin_range (size))
2199 if (p->fd_nextsize != NULL)
2201 if (p->fd_nextsize == p)
2202 assert (p->bk_nextsize == p);
2203 else
2205 if (p->fd_nextsize == first (b))
2206 assert (chunksize (p) < chunksize (p->fd_nextsize));
2207 else
2208 assert (chunksize (p) > chunksize (p->fd_nextsize));
2210 if (p == first (b))
2211 assert (chunksize (p) > chunksize (p->bk_nextsize));
2212 else
2213 assert (chunksize (p) < chunksize (p->bk_nextsize));
2216 else
2217 assert (p->bk_nextsize == NULL);
2220 else if (!in_smallbin_range (size))
2221 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2222 /* chunk is followed by a legal chain of inuse chunks */
2223 for (q = next_chunk (p);
2224 (q != av->top && inuse (q) &&
2225 (unsigned long) (chunksize (q)) >= MINSIZE);
2226 q = next_chunk (q))
2227 do_check_inuse_chunk (av, q);
2231 /* top chunk is OK */
2232 check_chunk (av, av->top);
2234 #endif
2237 /* ----------------- Support for debugging hooks -------------------- */
2238 #include "hooks.c"
2241 /* ----------- Routines dealing with system allocation -------------- */
2243 /*
2244 sysmalloc handles malloc cases requiring more memory from the system.
2245 On entry, it is assumed that av->top does not have enough
2246 space to service request for nb bytes, thus requiring that av->top
2247 be extended or replaced.
2248 */
2250 static void *
2251 sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2253 mchunkptr old_top; /* incoming value of av->top */
2254 INTERNAL_SIZE_T old_size; /* its size */
2255 char *old_end; /* its end address */
2257 long size; /* arg to first MORECORE or mmap call */
2258 char *brk; /* return value from MORECORE */
2260 long correction; /* arg to 2nd MORECORE call */
2261 char *snd_brk; /* 2nd return val */
2263 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2264 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2265 char *aligned_brk; /* aligned offset into brk */
2267 mchunkptr p; /* the allocated/returned chunk */
2268 mchunkptr remainder; /* remainder from allocation */
2269 unsigned long remainder_size; /* its size */
2272 size_t pagesize = GLRO (dl_pagesize);
2273 bool tried_mmap = false;
2276 /*
2277 If have mmap, and the request size meets the mmap threshold, and
2278 the system supports mmap, and there are few enough currently
2279 allocated mmapped regions, try to directly map this request
2280 rather than expanding top.
2281 */
2283 if ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold) &&
2284 (mp_.n_mmaps < mp_.n_mmaps_max))
2286 char *mm; /* return value from mmap call*/
2288 try_mmap:
2289 /*
2290 Round up size to nearest page. For mmapped chunks, the overhead
2291 is one SIZE_SZ unit larger than for normal chunks, because there
2292 is no following chunk whose prev_size field could be used.
2294 See the front_misalign handling below, for glibc there is no
2295 need for further alignments unless we have have high alignment.
2296 */
2297 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2298 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2299 else
2300 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2301 tried_mmap = true;
2303 /* Don't try if size wraps around 0 */
2304 if ((unsigned long) (size) > (unsigned long) (nb))
2306 mm = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2308 if (mm != MAP_FAILED)
2310 /*
2311 The offset to the start of the mmapped region is stored
2312 in the prev_size field of the chunk. This allows us to adjust
2313 returned start address to meet alignment requirements here
2314 and in memalign(), and still be able to compute proper
2315 address argument for later munmap in free() and realloc().
2316 */
2318 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2320 /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and
2321 MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
2322 aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
2323 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2324 front_misalign = 0;
2326 else
2327 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2328 if (front_misalign > 0)
2330 correction = MALLOC_ALIGNMENT - front_misalign;
2331 p = (mchunkptr) (mm + correction);
2332 p->prev_size = correction;
2333 set_head (p, (size - correction) | IS_MMAPPED);
2335 else
2337 p = (mchunkptr) mm;
2338 set_head (p, size | IS_MMAPPED);
2341 /* update statistics */
2343 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2344 atomic_max (&mp_.max_n_mmaps, new);
2346 unsigned long sum;
2347 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2348 atomic_max (&mp_.max_mmapped_mem, sum);
2350 check_chunk (av, p);
2352 return chunk2mem (p);
2357 /* Record incoming configuration of top */
2359 old_top = av->top;
2360 old_size = chunksize (old_top);
2361 old_end = (char *) (chunk_at_offset (old_top, old_size));
2363 brk = snd_brk = (char *) (MORECORE_FAILURE);
2365 /*
2366 If not the first time through, we require old_size to be
2367 at least MINSIZE and to have prev_inuse set.
2368 */
2370 assert ((old_top == initial_top (av) && old_size == 0) ||
2371 ((unsigned long) (old_size) >= MINSIZE &&
2372 prev_inuse (old_top) &&
2373 ((unsigned long) old_end & (pagesize - 1)) == 0));
2375 /* Precondition: not enough current space to satisfy nb request */
2376 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2379 if (av != &main_arena)
2381 heap_info *old_heap, *heap;
2382 size_t old_heap_size;
2384 /* First try to extend the current heap. */
2385 old_heap = heap_for_ptr (old_top);
2386 old_heap_size = old_heap->size;
2387 if ((long) (MINSIZE + nb - old_size) > 0
2388 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2390 av->system_mem += old_heap->size - old_heap_size;
2391 arena_mem += old_heap->size - old_heap_size;
2392 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2393 | PREV_INUSE);
2395 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2397 /* Use a newly allocated heap. */
2398 heap->ar_ptr = av;
2399 heap->prev = old_heap;
2400 av->system_mem += heap->size;
2401 arena_mem += heap->size;
2402 /* Set up the new top. */
2403 top (av) = chunk_at_offset (heap, sizeof (*heap));
2404 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2406 /* Setup fencepost and free the old top chunk with a multiple of
2407 MALLOC_ALIGNMENT in size. */
2408 /* The fencepost takes at least MINSIZE bytes, because it might
2409 become the top chunk again later. Note that a footer is set
2410 up, too, although the chunk is marked in use. */
2411 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2412 set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ), 0 | PREV_INUSE);
2413 if (old_size >= MINSIZE)
2415 set_head (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE);
2416 set_foot (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ));
2417 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2418 _int_free (av, old_top, 1);
2420 else
2422 set_head (old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE);
2423 set_foot (old_top, (old_size + 2 * SIZE_SZ));
2426 else if (!tried_mmap)
2427 /* We can at least try to use to mmap memory. */
2428 goto try_mmap;
2430 else /* av == main_arena */
2433 { /* Request enough space for nb + pad + overhead */
2434 size = nb + mp_.top_pad + MINSIZE;
2436 /*
2437 If contiguous, we can subtract out existing space that we hope to
2438 combine with new space. We add it back later only if
2439 we don't actually get contiguous space.
2440 */
2442 if (contiguous (av))
2443 size -= old_size;
2445 /*
2446 Round to a multiple of page size.
2447 If MORECORE is not contiguous, this ensures that we only call it
2448 with whole-page arguments. And if MORECORE is contiguous and
2449 this is not first time through, this preserves page-alignment of
2450 previous calls. Otherwise, we correct to page-align below.
2451 */
2453 size = ALIGN_UP (size, pagesize);
2455 /*
2456 Don't try to call MORECORE if argument is so big as to appear
2457 negative. Note that since mmap takes size_t arg, it may succeed
2458 below even if we cannot call MORECORE.
2459 */
2461 if (size > 0)
2463 brk = (char *) (MORECORE (size));
2464 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2467 if (brk != (char *) (MORECORE_FAILURE))
2469 /* Call the `morecore' hook if necessary. */
2470 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2471 if (__builtin_expect (hook != NULL, 0))
2472 (*hook)();
2474 else
2476 /*
2477 If have mmap, try using it as a backup when MORECORE fails or
2478 cannot be used. This is worth doing on systems that have "holes" in
2479 address space, so sbrk cannot extend to give contiguous space, but
2480 space is available elsewhere. Note that we ignore mmap max count
2481 and threshold limits, since the space will not be used as a
2482 segregated mmap region.
2483 */
2485 /* Cannot merge with old top, so add its size back in */
2486 if (contiguous (av))
2487 size = ALIGN_UP (size + old_size, pagesize);
2489 /* If we are relying on mmap as backup, then use larger units */
2490 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2491 size = MMAP_AS_MORECORE_SIZE;
2493 /* Don't try if size wraps around 0 */
2494 if ((unsigned long) (size) > (unsigned long) (nb))
2496 char *mbrk = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2498 if (mbrk != MAP_FAILED)
2500 /* We do not need, and cannot use, another sbrk call to find end */
2501 brk = mbrk;
2502 snd_brk = brk + size;
2504 /*
2505 Record that we no longer have a contiguous sbrk region.
2506 After the first time mmap is used as backup, we do not
2507 ever rely on contiguous space since this could incorrectly
2508 bridge regions.
2509 */
2510 set_noncontiguous (av);
2515 if (brk != (char *) (MORECORE_FAILURE))
2517 if (mp_.sbrk_base == 0)
2518 mp_.sbrk_base = brk;
2519 av->system_mem += size;
2521 /*
2522 If MORECORE extends previous space, we can likewise extend top size.
2523 */
2525 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2526 set_head (old_top, (size + old_size) | PREV_INUSE);
2528 else if (contiguous (av) && old_size && brk < old_end)
2530 /* Oops! Someone else killed our space.. Can't touch anything. */
2531 malloc_printerr (3, "break adjusted to free malloc space", brk);
2534 /*
2535 Otherwise, make adjustments:
2537 * If the first time through or noncontiguous, we need to call sbrk
2538 just to find out where the end of memory lies.
2540 * We need to ensure that all returned chunks from malloc will meet
2541 MALLOC_ALIGNMENT
2543 * If there was an intervening foreign sbrk, we need to adjust sbrk
2544 request size to account for fact that we will not be able to
2545 combine new space with existing space in old_top.
2547 * Almost all systems internally allocate whole pages at a time, in
2548 which case we might as well use the whole last page of request.
2549 So we allocate enough more memory to hit a page boundary now,
2550 which in turn causes future contiguous calls to page-align.
2551 */
2553 else
2555 front_misalign = 0;
2556 end_misalign = 0;
2557 correction = 0;
2558 aligned_brk = brk;
2560 /* handle contiguous cases */
2561 if (contiguous (av))
2563 /* Count foreign sbrk as system_mem. */
2564 if (old_size)
2565 av->system_mem += brk - old_end;
2567 /* Guarantee alignment of first new chunk made from this space */
2569 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2570 if (front_misalign > 0)
2572 /*
2573 Skip over some bytes to arrive at an aligned position.
2574 We don't need to specially mark these wasted front bytes.
2575 They will never be accessed anyway because
2576 prev_inuse of av->top (and any chunk created from its start)
2577 is always true after initialization.
2578 */
2580 correction = MALLOC_ALIGNMENT - front_misalign;
2581 aligned_brk += correction;
2584 /*
2585 If this isn't adjacent to existing space, then we will not
2586 be able to merge with old_top space, so must add to 2nd request.
2587 */
2589 correction += old_size;
2591 /* Extend the end address to hit a page boundary */
2592 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2593 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2595 assert (correction >= 0);
2596 snd_brk = (char *) (MORECORE (correction));
2598 /*
2599 If can't allocate correction, try to at least find out current
2600 brk. It might be enough to proceed without failing.
2602 Note that if second sbrk did NOT fail, we assume that space
2603 is contiguous with first sbrk. This is a safe assumption unless
2604 program is multithreaded but doesn't use locks and a foreign sbrk
2605 occurred between our first and second calls.
2606 */
2608 if (snd_brk == (char *) (MORECORE_FAILURE))
2610 correction = 0;
2611 snd_brk = (char *) (MORECORE (0));
2613 else
2615 /* Call the `morecore' hook if necessary. */
2616 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2617 if (__builtin_expect (hook != NULL, 0))
2618 (*hook)();
2622 /* handle non-contiguous cases */
2623 else
2625 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2626 /* MORECORE/mmap must correctly align */
2627 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2628 else
2630 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2631 if (front_misalign > 0)
2633 /*
2634 Skip over some bytes to arrive at an aligned position.
2635 We don't need to specially mark these wasted front bytes.
2636 They will never be accessed anyway because
2637 prev_inuse of av->top (and any chunk created from its start)
2638 is always true after initialization.
2639 */
2641 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2645 /* Find out current end of memory */
2646 if (snd_brk == (char *) (MORECORE_FAILURE))
2648 snd_brk = (char *) (MORECORE (0));
2652 /* Adjust top based on results of second sbrk */
2653 if (snd_brk != (char *) (MORECORE_FAILURE))
2655 av->top = (mchunkptr) aligned_brk;
2656 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2657 av->system_mem += correction;
2659 /*
2660 If not the first time through, we either have a
2661 gap due to foreign sbrk or a non-contiguous region. Insert a
2662 double fencepost at old_top to prevent consolidation with space
2663 we don't own. These fenceposts are artificial chunks that are
2664 marked as inuse and are in any case too small to use. We need
2665 two to make sizes and alignments work out.
2666 */
2668 if (old_size != 0)
2670 /*
2671 Shrink old_top to insert fenceposts, keeping size a
2672 multiple of MALLOC_ALIGNMENT. We know there is at least
2673 enough space in old_top to do this.
2674 */
2675 old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK;
2676 set_head (old_top, old_size | PREV_INUSE);
2678 /*
2679 Note that the following assignments completely overwrite
2680 old_top when old_size was previously MINSIZE. This is
2681 intentional. We need the fencepost, even if old_top otherwise gets
2682 lost.
2683 */
2684 chunk_at_offset (old_top, old_size)->size =
2685 (2 * SIZE_SZ) | PREV_INUSE;
2687 chunk_at_offset (old_top, old_size + 2 * SIZE_SZ)->size =
2688 (2 * SIZE_SZ) | PREV_INUSE;
2690 /* If possible, release the rest. */
2691 if (old_size >= MINSIZE)
2693 _int_free (av, old_top, 1);
2699 } /* if (av != &main_arena) */
2701 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2702 av->max_system_mem = av->system_mem;
2703 check_malloc_state (av);
2705 /* finally, do the allocation */
2706 p = av->top;
2707 size = chunksize (p);
2709 /* check that one of the above allocation paths succeeded */
2710 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2712 remainder_size = size - nb;
2713 remainder = chunk_at_offset (p, nb);
2714 av->top = remainder;
2715 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2716 set_head (remainder, remainder_size | PREV_INUSE);
2717 check_malloced_chunk (av, p, nb);
2718 return chunk2mem (p);
2721 /* catch all failure paths */
2722 __set_errno (ENOMEM);
2723 return 0;
2727 /*
2728 systrim is an inverse of sorts to sysmalloc. It gives memory back
2729 to the system (via negative arguments to sbrk) if there is unused
2730 memory at the `high' end of the malloc pool. It is called
2731 automatically by free() when top space exceeds the trim
2732 threshold. It is also called by the public malloc_trim routine. It
2733 returns 1 if it actually released any memory, else 0.
2734 */
2736 static int
2737 systrim (size_t pad, mstate av)
2739 long top_size; /* Amount of top-most memory */
2740 long extra; /* Amount to release */
2741 long released; /* Amount actually released */
2742 char *current_brk; /* address returned by pre-check sbrk call */
2743 char *new_brk; /* address returned by post-check sbrk call */
2744 size_t pagesize;
2745 long top_area;
2747 pagesize = GLRO (dl_pagesize);
2748 top_size = chunksize (av->top);
2750 top_area = top_size - MINSIZE - 1;
2751 if (top_area <= pad)
2752 return 0;
2754 /* Release in pagesize units, keeping at least one page */
2755 extra = (top_area - pad) & ~(pagesize - 1);
2757 if (extra == 0)
2758 return 0;
2760 /*
2761 Only proceed if end of memory is where we last set it.
2762 This avoids problems if there were foreign sbrk calls.
2763 */
2764 current_brk = (char *) (MORECORE (0));
2765 if (current_brk == (char *) (av->top) + top_size)
2767 /*
2768 Attempt to release memory. We ignore MORECORE return value,
2769 and instead call again to find out where new end of memory is.
2770 This avoids problems if first call releases less than we asked,
2771 of if failure somehow altered brk value. (We could still
2772 encounter problems if it altered brk in some very bad way,
2773 but the only thing we can do is adjust anyway, which will cause
2774 some downstream failure.)
2775 */
2777 MORECORE (-extra);
2778 /* Call the `morecore' hook if necessary. */
2779 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2780 if (__builtin_expect (hook != NULL, 0))
2781 (*hook)();
2782 new_brk = (char *) (MORECORE (0));
2784 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2786 if (new_brk != (char *) MORECORE_FAILURE)
2788 released = (long) (current_brk - new_brk);
2790 if (released != 0)
2792 /* Success. Adjust top. */
2793 av->system_mem -= released;
2794 set_head (av->top, (top_size - released) | PREV_INUSE);
2795 check_malloc_state (av);
2796 return 1;
2800 return 0;
2803 static void
2804 internal_function
2805 munmap_chunk (mchunkptr p)
2807 INTERNAL_SIZE_T size = chunksize (p);
2809 assert (chunk_is_mmapped (p));
2811 uintptr_t block = (uintptr_t) p - p->prev_size;
2812 size_t total_size = p->prev_size + size;
2813 /* Unfortunately we have to do the compilers job by hand here. Normally
2814 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2815 page size. But gcc does not recognize the optimization possibility
2816 (in the moment at least) so we combine the two values into one before
2817 the bit test. */
2818 if (__builtin_expect (((block | total_size) & (GLRO (dl_pagesize) - 1)) != 0, 0))
2820 malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
2821 chunk2mem (p));
2822 return;
2825 atomic_decrement (&mp_.n_mmaps);
2826 atomic_add (&mp_.mmapped_mem, -total_size);
2828 /* If munmap failed the process virtual memory address space is in a
2829 bad shape. Just leave the block hanging around, the process will
2830 terminate shortly anyway since not much can be done. */
2831 __munmap ((char *) block, total_size);
2834 #if HAVE_MREMAP
2836 static mchunkptr
2837 internal_function
2838 mremap_chunk (mchunkptr p, size_t new_size)
2840 size_t pagesize = GLRO (dl_pagesize);
2841 INTERNAL_SIZE_T offset = p->prev_size;
2842 INTERNAL_SIZE_T size = chunksize (p);
2843 char *cp;
2845 assert (chunk_is_mmapped (p));
2846 assert (((size + offset) & (GLRO (dl_pagesize) - 1)) == 0);
2848 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2849 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
2851 /* No need to remap if the number of pages does not change. */
2852 if (size + offset == new_size)
2853 return p;
2855 cp = (char *) __mremap ((char *) p - offset, size + offset, new_size,
2856 MREMAP_MAYMOVE);
2858 if (cp == MAP_FAILED)
2859 return 0;
2861 p = (mchunkptr) (cp + offset);
2863 assert (aligned_OK (chunk2mem (p)));
2865 assert ((p->prev_size == offset));
2866 set_head (p, (new_size - offset) | IS_MMAPPED);
2868 INTERNAL_SIZE_T new;
2869 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
2870 + new_size - size - offset;
2871 atomic_max (&mp_.max_mmapped_mem, new);
2872 return p;
2874 #endif /* HAVE_MREMAP */
2876 /*------------------------ Public wrappers. --------------------------------*/
2878 void *
2879 __libc_malloc (size_t bytes)
2881 mstate ar_ptr;
2882 void *victim;
2884 void *(*hook) (size_t, const void *)
2885 = atomic_forced_read (__malloc_hook);
2886 if (__builtin_expect (hook != NULL, 0))
2887 return (*hook)(bytes, RETURN_ADDRESS (0));
2889 arena_get (ar_ptr, bytes);
2891 if (!ar_ptr)
2892 return 0;
2894 victim = _int_malloc (ar_ptr, bytes);
2895 if (!victim)
2897 LIBC_PROBE (memory_malloc_retry, 1, bytes);
2898 ar_ptr = arena_get_retry (ar_ptr, bytes);
2899 if (__builtin_expect (ar_ptr != NULL, 1))
2901 victim = _int_malloc (ar_ptr, bytes);
2902 (void) mutex_unlock (&ar_ptr->mutex);
2905 else
2906 (void) mutex_unlock (&ar_ptr->mutex);
2907 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
2908 ar_ptr == arena_for_chunk (mem2chunk (victim)));
2909 return victim;
2911 libc_hidden_def (__libc_malloc)
2913 void
2914 __libc_free (void *mem)
2916 mstate ar_ptr;
2917 mchunkptr p; /* chunk corresponding to mem */
2919 void (*hook) (void *, const void *)
2920 = atomic_forced_read (__free_hook);
2921 if (__builtin_expect (hook != NULL, 0))
2923 (*hook)(mem, RETURN_ADDRESS (0));
2924 return;
2927 if (mem == 0) /* free(0) has no effect */
2928 return;
2930 p = mem2chunk (mem);
2932 if (chunk_is_mmapped (p)) /* release mmapped memory. */
2934 /* see if the dynamic brk/mmap threshold needs adjusting */
2935 if (!mp_.no_dyn_threshold
2936 && p->size > mp_.mmap_threshold
2937 && p->size <= DEFAULT_MMAP_THRESHOLD_MAX)
2939 mp_.mmap_threshold = chunksize (p);
2940 mp_.trim_threshold = 2 * mp_.mmap_threshold;
2941 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
2942 mp_.mmap_threshold, mp_.trim_threshold);
2944 munmap_chunk (p);
2945 return;
2948 ar_ptr = arena_for_chunk (p);
2949 _int_free (ar_ptr, p, 0);
2951 libc_hidden_def (__libc_free)
2953 void *
2954 __libc_realloc (void *oldmem, size_t bytes)
2956 mstate ar_ptr;
2957 INTERNAL_SIZE_T nb; /* padded request size */
2959 void *newp; /* chunk to return */
2961 void *(*hook) (void *, size_t, const void *) =
2962 atomic_forced_read (__realloc_hook);
2963 if (__builtin_expect (hook != NULL, 0))
2964 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
2966 #if REALLOC_ZERO_BYTES_FREES
2967 if (bytes == 0 && oldmem != NULL)
2969 __libc_free (oldmem); return 0;
2971 #endif
2973 /* realloc of null is supposed to be same as malloc */
2974 if (oldmem == 0)
2975 return __libc_malloc (bytes);
2977 /* chunk corresponding to oldmem */
2978 const mchunkptr oldp = mem2chunk (oldmem);
2979 /* its size */
2980 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
2982 /* Little security check which won't hurt performance: the
2983 allocator never wrapps around at the end of the address space.
2984 Therefore we can exclude some size values which might appear
2985 here by accident or by "design" from some intruder. */
2986 if (__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
2987 || __builtin_expect (misaligned_chunk (oldp), 0))
2989 malloc_printerr (check_action, "realloc(): invalid pointer", oldmem);
2990 return NULL;
2993 checked_request2size (bytes, nb);
2995 if (chunk_is_mmapped (oldp))
2997 void *newmem;
2999 #if HAVE_MREMAP
3000 newp = mremap_chunk (oldp, nb);
3001 if (newp)
3002 return chunk2mem (newp);
3003 #endif
3004 /* Note the extra SIZE_SZ overhead. */
3005 if (oldsize - SIZE_SZ >= nb)
3006 return oldmem; /* do nothing */
3008 /* Must alloc, copy, free. */
3009 newmem = __libc_malloc (bytes);
3010 if (newmem == 0)
3011 return 0; /* propagate failure */
3013 memcpy (newmem, oldmem, oldsize - 2 * SIZE_SZ);
3014 munmap_chunk (oldp);
3015 return newmem;
3018 ar_ptr = arena_for_chunk (oldp);
3019 (void) mutex_lock (&ar_ptr->mutex);
3022 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3024 (void) mutex_unlock (&ar_ptr->mutex);
3025 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3026 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3028 if (newp == NULL)
3030 /* Try harder to allocate memory in other arenas. */
3031 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3032 newp = __libc_malloc (bytes);
3033 if (newp != NULL)
3035 memcpy (newp, oldmem, oldsize - SIZE_SZ);
3036 _int_free (ar_ptr, oldp, 0);
3040 return newp;
3042 libc_hidden_def (__libc_realloc)
3044 void *
3045 __libc_memalign (size_t alignment, size_t bytes)
3047 void *address = RETURN_ADDRESS (0);
3048 return _mid_memalign (alignment, bytes, address);
3051 static void *
3052 _mid_memalign (size_t alignment, size_t bytes, void *address)
3054 mstate ar_ptr;
3055 void *p;
3057 void *(*hook) (size_t, size_t, const void *) =
3058 atomic_forced_read (__memalign_hook);
3059 if (__builtin_expect (hook != NULL, 0))
3060 return (*hook)(alignment, bytes, address);
3062 /* If we need less alignment than we give anyway, just relay to malloc. */
3063 if (alignment <= MALLOC_ALIGNMENT)
3064 return __libc_malloc (bytes);
3066 /* Otherwise, ensure that it is at least a minimum chunk size */
3067 if (alignment < MINSIZE)
3068 alignment = MINSIZE;
3070 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3071 power of 2 and will cause overflow in the check below. */
3072 if (alignment > SIZE_MAX / 2 + 1)
3074 __set_errno (EINVAL);
3075 return 0;
3078 /* Check for overflow. */
3079 if (bytes > SIZE_MAX - alignment - MINSIZE)
3081 __set_errno (ENOMEM);
3082 return 0;
3086 /* Make sure alignment is power of 2. */
3087 if (!powerof2 (alignment))
3089 size_t a = MALLOC_ALIGNMENT * 2;
3090 while (a < alignment)
3091 a <<= 1;
3092 alignment = a;
3095 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3096 if (!ar_ptr)
3097 return 0;
3099 p = _int_memalign (ar_ptr, alignment, bytes);
3100 if (!p)
3102 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3103 ar_ptr = arena_get_retry (ar_ptr, bytes);
3104 if (__builtin_expect (ar_ptr != NULL, 1))
3106 p = _int_memalign (ar_ptr, alignment, bytes);
3107 (void) mutex_unlock (&ar_ptr->mutex);
3110 else
3111 (void) mutex_unlock (&ar_ptr->mutex);
3112 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3113 ar_ptr == arena_for_chunk (mem2chunk (p)));
3114 return p;
3116 /* For ISO C11. */
3117 weak_alias (__libc_memalign, aligned_alloc)
3118 libc_hidden_def (__libc_memalign)
3120 void *
3121 __libc_valloc (size_t bytes)
3123 if (__malloc_initialized < 0)
3124 ptmalloc_init ();
3126 void *address = RETURN_ADDRESS (0);
3127 size_t pagesize = GLRO (dl_pagesize);
3128 return _mid_memalign (pagesize, bytes, address);
3131 void *
3132 __libc_pvalloc (size_t bytes)
3134 if (__malloc_initialized < 0)
3135 ptmalloc_init ();
3137 void *address = RETURN_ADDRESS (0);
3138 size_t pagesize = GLRO (dl_pagesize);
3139 size_t rounded_bytes = ALIGN_UP (bytes, pagesize);
3141 /* Check for overflow. */
3142 if (bytes > SIZE_MAX - 2 * pagesize - MINSIZE)
3144 __set_errno (ENOMEM);
3145 return 0;
3148 return _mid_memalign (pagesize, rounded_bytes, address);
3151 void *
3152 __libc_calloc (size_t n, size_t elem_size)
3154 mstate av;
3155 mchunkptr oldtop, p;
3156 INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
3157 void *mem;
3158 unsigned long clearsize;
3159 unsigned long nclears;
3160 INTERNAL_SIZE_T *d;
3162 /* size_t is unsigned so the behavior on overflow is defined. */
3163 bytes = n * elem_size;
3164 #define HALF_INTERNAL_SIZE_T \
3165 (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
3166 if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0))
3168 if (elem_size != 0 && bytes / elem_size != n)
3170 __set_errno (ENOMEM);
3171 return 0;
3175 void *(*hook) (size_t, const void *) =
3176 atomic_forced_read (__malloc_hook);
3177 if (__builtin_expect (hook != NULL, 0))
3179 sz = bytes;
3180 mem = (*hook)(sz, RETURN_ADDRESS (0));
3181 if (mem == 0)
3182 return 0;
3184 return memset (mem, 0, sz);
3187 sz = bytes;
3189 arena_get (av, sz);
3190 if (!av)
3191 return 0;
3193 /* Check if we hand out the top chunk, in which case there may be no
3194 need to clear. */
3195 #if MORECORE_CLEARS
3196 oldtop = top (av);
3197 oldtopsize = chunksize (top (av));
3198 # if MORECORE_CLEARS < 2
3199 /* Only newly allocated memory is guaranteed to be cleared. */
3200 if (av == &main_arena &&
3201 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3202 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3203 # endif
3204 if (av != &main_arena)
3206 heap_info *heap = heap_for_ptr (oldtop);
3207 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3208 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3210 #endif
3211 mem = _int_malloc (av, sz);
3214 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3215 av == arena_for_chunk (mem2chunk (mem)));
3217 if (mem == 0)
3219 LIBC_PROBE (memory_calloc_retry, 1, sz);
3220 av = arena_get_retry (av, sz);
3221 if (__builtin_expect (av != NULL, 1))
3223 mem = _int_malloc (av, sz);
3224 (void) mutex_unlock (&av->mutex);
3226 if (mem == 0)
3227 return 0;
3229 else
3230 (void) mutex_unlock (&av->mutex);
3231 p = mem2chunk (mem);
3233 /* Two optional cases in which clearing not necessary */
3234 if (chunk_is_mmapped (p))
3236 if (__builtin_expect (perturb_byte, 0))
3237 return memset (mem, 0, sz);
3239 return mem;
3242 csz = chunksize (p);
3244 #if MORECORE_CLEARS
3245 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3247 /* clear only the bytes from non-freshly-sbrked memory */
3248 csz = oldtopsize;
3250 #endif
3252 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3253 contents have an odd number of INTERNAL_SIZE_T-sized words;
3254 minimally 3. */
3255 d = (INTERNAL_SIZE_T *) mem;
3256 clearsize = csz - SIZE_SZ;
3257 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3258 assert (nclears >= 3);
3260 if (nclears > 9)
3261 return memset (d, 0, clearsize);
3263 else
3265 *(d + 0) = 0;
3266 *(d + 1) = 0;
3267 *(d + 2) = 0;
3268 if (nclears > 4)
3270 *(d + 3) = 0;
3271 *(d + 4) = 0;
3272 if (nclears > 6)
3274 *(d + 5) = 0;
3275 *(d + 6) = 0;
3276 if (nclears > 8)
3278 *(d + 7) = 0;
3279 *(d + 8) = 0;
3285 return mem;
3288 /*
3289 ------------------------------ malloc ------------------------------
3290 */
3292 static void *
3293 _int_malloc (mstate av, size_t bytes)
3295 INTERNAL_SIZE_T nb; /* normalized request size */
3296 unsigned int idx; /* associated bin index */
3297 mbinptr bin; /* associated bin */
3299 mchunkptr victim; /* inspected/selected chunk */
3300 INTERNAL_SIZE_T size; /* its size */
3301 int victim_index; /* its bin index */
3303 mchunkptr remainder; /* remainder from a split */
3304 unsigned long remainder_size; /* its size */
3306 unsigned int block; /* bit map traverser */
3307 unsigned int bit; /* bit map traverser */
3308 unsigned int map; /* current word of binmap */
3310 mchunkptr fwd; /* misc temp for linking */
3311 mchunkptr bck; /* misc temp for linking */
3313 const char *errstr = NULL;
3315 /*
3316 Convert request size to internal form by adding SIZE_SZ bytes
3317 overhead plus possibly more to obtain necessary alignment and/or
3318 to obtain a size of at least MINSIZE, the smallest allocatable
3319 size. Also, checked_request2size traps (returning 0) request sizes
3320 that are so large that they wrap around zero when padded and
3321 aligned.
3322 */
3324 checked_request2size (bytes, nb);
3326 /*
3327 If the size qualifies as a fastbin, first check corresponding bin.
3328 This code is safe to execute even if av is not yet initialized, so we
3329 can try it without checking, which saves some time on this fast path.
3330 */
3332 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3334 idx = fastbin_index (nb);
3335 mfastbinptr *fb = &fastbin (av, idx);
3336 mchunkptr pp = *fb;
3337 do
3339 victim = pp;
3340 if (victim == NULL)
3341 break;
3343 while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim))
3344 != victim);
3345 if (victim != 0)
3347 if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
3349 errstr = "malloc(): memory corruption (fast)";
3350 errout:
3351 malloc_printerr (check_action, errstr, chunk2mem (victim));
3352 return NULL;
3354 check_remalloced_chunk (av, victim, nb);
3355 void *p = chunk2mem (victim);
3356 alloc_perturb (p, bytes);
3357 return p;
3361 /*
3362 If a small request, check regular bin. Since these "smallbins"
3363 hold one size each, no searching within bins is necessary.
3364 (For a large request, we need to wait until unsorted chunks are
3365 processed to find best fit. But for small ones, fits are exact
3366 anyway, so we can check now, which is faster.)
3367 */
3369 if (in_smallbin_range (nb))
3371 idx = smallbin_index (nb);
3372 bin = bin_at (av, idx);
3374 if ((victim = last (bin)) != bin)
3376 if (victim == 0) /* initialization check */
3377 malloc_consolidate (av);
3378 else
3380 bck = victim->bk;
3381 if (__glibc_unlikely (bck->fd != victim))
3383 errstr = "malloc(): smallbin double linked list corrupted";
3384 goto errout;
3386 set_inuse_bit_at_offset (victim, nb);
3387 bin->bk = bck;
3388 bck->fd = bin;
3390 if (av != &main_arena)
3391 victim->size |= NON_MAIN_ARENA;
3392 check_malloced_chunk (av, victim, nb);
3393 void *p = chunk2mem (victim);
3394 alloc_perturb (p, bytes);
3395 return p;
3400 /*
3401 If this is a large request, consolidate fastbins before continuing.
3402 While it might look excessive to kill all fastbins before
3403 even seeing if there is space available, this avoids
3404 fragmentation problems normally associated with fastbins.
3405 Also, in practice, programs tend to have runs of either small or
3406 large requests, but less often mixtures, so consolidation is not
3407 invoked all that often in most programs. And the programs that
3408 it is called frequently in otherwise tend to fragment.
3409 */
3411 else
3413 idx = largebin_index (nb);
3414 if (have_fastchunks (av))
3415 malloc_consolidate (av);
3418 /*
3419 Process recently freed or remaindered chunks, taking one only if
3420 it is exact fit, or, if this a small request, the chunk is remainder from
3421 the most recent non-exact fit. Place other traversed chunks in
3422 bins. Note that this step is the only place in any routine where
3423 chunks are placed in bins.
3425 The outer loop here is needed because we might not realize until
3426 near the end of malloc that we should have consolidated, so must
3427 do so and retry. This happens at most once, and only when we would
3428 otherwise need to expand memory to service a "small" request.
3429 */
3431 for (;; )
3433 int iters = 0;
3434 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3436 bck = victim->bk;
3437 if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0)
3438 || __builtin_expect (victim->size > av->system_mem, 0))
3439 malloc_printerr (check_action, "malloc(): memory corruption",
3440 chunk2mem (victim));
3441 size = chunksize (victim);
3443 /*
3444 If a small request, try to use last remainder if it is the
3445 only chunk in unsorted bin. This helps promote locality for
3446 runs of consecutive small requests. This is the only
3447 exception to best-fit, and applies only when there is
3448 no exact fit for a small chunk.
3449 */
3451 if (in_smallbin_range (nb) &&
3452 bck == unsorted_chunks (av) &&
3453 victim == av->last_remainder &&
3454 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
3456 /* split and reattach remainder */
3457 remainder_size = size - nb;
3458 remainder = chunk_at_offset (victim, nb);
3459 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
3460 av->last_remainder = remainder;
3461 remainder->bk = remainder->fd = unsorted_chunks (av);
3462 if (!in_smallbin_range (remainder_size))
3464 remainder->fd_nextsize = NULL;
3465 remainder->bk_nextsize = NULL;
3468 set_head (victim, nb | PREV_INUSE |
3469 (av != &main_arena ? NON_MAIN_ARENA : 0));
3470 set_head (remainder, remainder_size | PREV_INUSE);
3471 set_foot (remainder, remainder_size);
3473 check_malloced_chunk (av, victim, nb);
3474 void *p = chunk2mem (victim);
3475 alloc_perturb (p, bytes);
3476 return p;
3479 /* remove from unsorted list */
3480 unsorted_chunks (av)->bk = bck;
3481 bck->fd = unsorted_chunks (av);
3483 /* Take now instead of binning if exact fit */
3485 if (size == nb)
3487 set_inuse_bit_at_offset (victim, size);
3488 if (av != &main_arena)
3489 victim->size |= NON_MAIN_ARENA;
3490 check_malloced_chunk (av, victim, nb);
3491 void *p = chunk2mem (victim);
3492 alloc_perturb (p, bytes);
3493 return p;
3496 /* place chunk in bin */
3498 if (in_smallbin_range (size))
3500 victim_index = smallbin_index (size);
3501 bck = bin_at (av, victim_index);
3502 fwd = bck->fd;
3504 else
3506 victim_index = largebin_index (size);
3507 bck = bin_at (av, victim_index);
3508 fwd = bck->fd;
3510 /* maintain large bins in sorted order */
3511 if (fwd != bck)
3513 /* Or with inuse bit to speed comparisons */
3514 size |= PREV_INUSE;
3515 /* if smaller than smallest, bypass loop below */
3516 assert ((bck->bk->size & NON_MAIN_ARENA) == 0);
3517 if ((unsigned long) (size) < (unsigned long) (bck->bk->size))
3519 fwd = bck;
3520 bck = bck->bk;
3522 victim->fd_nextsize = fwd->fd;
3523 victim->bk_nextsize = fwd->fd->bk_nextsize;
3524 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
3526 else
3528 assert ((fwd->size & NON_MAIN_ARENA) == 0);
3529 while ((unsigned long) size < fwd->size)
3531 fwd = fwd->fd_nextsize;
3532 assert ((fwd->size & NON_MAIN_ARENA) == 0);
3535 if ((unsigned long) size == (unsigned long) fwd->size)
3536 /* Always insert in the second position. */
3537 fwd = fwd->fd;
3538 else
3540 victim->fd_nextsize = fwd;
3541 victim->bk_nextsize = fwd->bk_nextsize;
3542 fwd->bk_nextsize = victim;
3543 victim->bk_nextsize->fd_nextsize = victim;
3545 bck = fwd->bk;
3548 else
3549 victim->fd_nextsize = victim->bk_nextsize = victim;
3552 mark_bin (av, victim_index);
3553 victim->bk = bck;
3554 victim->fd = fwd;
3555 fwd->bk = victim;
3556 bck->fd = victim;
3558 #define MAX_ITERS 10000
3559 if (++iters >= MAX_ITERS)
3560 break;
3563 /*
3564 If a large request, scan through the chunks of current bin in
3565 sorted order to find smallest that fits. Use the skip list for this.
3566 */
3568 if (!in_smallbin_range (nb))
3570 bin = bin_at (av, idx);
3572 /* skip scan if empty or largest chunk is too small */
3573 if ((victim = first (bin)) != bin &&
3574 (unsigned long) (victim->size) >= (unsigned long) (nb))
3576 victim = victim->bk_nextsize;
3577 while (((unsigned long) (size = chunksize (victim)) <
3578 (unsigned long) (nb)))
3579 victim = victim->bk_nextsize;
3581 /* Avoid removing the first entry for a size so that the skip
3582 list does not have to be rerouted. */
3583 if (victim != last (bin) && victim->size == victim->fd->size)
3584 victim = victim->fd;
3586 remainder_size = size - nb;
3587 unlink (victim, bck, fwd);
3589 /* Exhaust */
3590 if (remainder_size < MINSIZE)
3592 set_inuse_bit_at_offset (victim, size);
3593 if (av != &main_arena)
3594 victim->size |= NON_MAIN_ARENA;
3596 /* Split */
3597 else
3599 remainder = chunk_at_offset (victim, nb);
3600 /* We cannot assume the unsorted list is empty and therefore
3601 have to perform a complete insert here. */
3602 bck = unsorted_chunks (av);
3603 fwd = bck->fd;
3604 if (__glibc_unlikely (fwd->bk != bck))
3606 errstr = "malloc(): corrupted unsorted chunks";
3607 goto errout;
3609 remainder->bk = bck;
3610 remainder->fd = fwd;
3611 bck->fd = remainder;
3612 fwd->bk = remainder;
3613 if (!in_smallbin_range (remainder_size))
3615 remainder->fd_nextsize = NULL;
3616 remainder->bk_nextsize = NULL;
3618 set_head (victim, nb | PREV_INUSE |
3619 (av != &main_arena ? NON_MAIN_ARENA : 0));
3620 set_head (remainder, remainder_size | PREV_INUSE);
3621 set_foot (remainder, remainder_size);
3623 check_malloced_chunk (av, victim, nb);
3624 void *p = chunk2mem (victim);
3625 alloc_perturb (p, bytes);
3626 return p;
3630 /*
3631 Search for a chunk by scanning bins, starting with next largest
3632 bin. This search is strictly by best-fit; i.e., the smallest
3633 (with ties going to approximately the least recently used) chunk
3634 that fits is selected.
3636 The bitmap avoids needing to check that most blocks are nonempty.
3637 The particular case of skipping all bins during warm-up phases
3638 when no chunks have been returned yet is faster than it might look.
3639 */
3641 ++idx;
3642 bin = bin_at (av, idx);
3643 block = idx2block (idx);
3644 map = av->binmap[block];
3645 bit = idx2bit (idx);
3647 for (;; )
3649 /* Skip rest of block if there are no more set bits in this block. */
3650 if (bit > map || bit == 0)
3652 do
3654 if (++block >= BINMAPSIZE) /* out of bins */
3655 goto use_top;
3657 while ((map = av->binmap[block]) == 0);
3659 bin = bin_at (av, (block << BINMAPSHIFT));
3660 bit = 1;
3663 /* Advance to bin with set bit. There must be one. */
3664 while ((bit & map) == 0)
3666 bin = next_bin (bin);
3667 bit <<= 1;
3668 assert (bit != 0);
3671 /* Inspect the bin. It is likely to be non-empty */
3672 victim = last (bin);
3674 /* If a false alarm (empty bin), clear the bit. */
3675 if (victim == bin)
3677 av->binmap[block] = map &= ~bit; /* Write through */
3678 bin = next_bin (bin);
3679 bit <<= 1;
3682 else
3684 size = chunksize (victim);
3686 /* We know the first chunk in this bin is big enough to use. */
3687 assert ((unsigned long) (size) >= (unsigned long) (nb));
3689 remainder_size = size - nb;
3691 /* unlink */
3692 unlink (victim, bck, fwd);
3694 /* Exhaust */
3695 if (remainder_size < MINSIZE)
3697 set_inuse_bit_at_offset (victim, size);
3698 if (av != &main_arena)
3699 victim->size |= NON_MAIN_ARENA;
3702 /* Split */
3703 else
3705 remainder = chunk_at_offset (victim, nb);
3707 /* We cannot assume the unsorted list is empty and therefore
3708 have to perform a complete insert here. */
3709 bck = unsorted_chunks (av);
3710 fwd = bck->fd;
3711 if (__glibc_unlikely (fwd->bk != bck))
3713 errstr = "malloc(): corrupted unsorted chunks 2";
3714 goto errout;
3716 remainder->bk = bck;
3717 remainder->fd = fwd;
3718 bck->fd = remainder;
3719 fwd->bk = remainder;
3721 /* advertise as last remainder */
3722 if (in_smallbin_range (nb))
3723 av->last_remainder = remainder;
3724 if (!in_smallbin_range (remainder_size))
3726 remainder->fd_nextsize = NULL;
3727 remainder->bk_nextsize = NULL;
3729 set_head (victim, nb | PREV_INUSE |
3730 (av != &main_arena ? NON_MAIN_ARENA : 0));
3731 set_head (remainder, remainder_size | PREV_INUSE);
3732 set_foot (remainder, remainder_size);
3734 check_malloced_chunk (av, victim, nb);
3735 void *p = chunk2mem (victim);
3736 alloc_perturb (p, bytes);
3737 return p;
3741 use_top:
3742 /*
3743 If large enough, split off the chunk bordering the end of memory
3744 (held in av->top). Note that this is in accord with the best-fit
3745 search rule. In effect, av->top is treated as larger (and thus
3746 less well fitting) than any other available chunk since it can
3747 be extended to be as large as necessary (up to system
3748 limitations).
3750 We require that av->top always exists (i.e., has size >=
3751 MINSIZE) after initialization, so if it would otherwise be
3752 exhausted by current request, it is replenished. (The main
3753 reason for ensuring it exists is that we may need MINSIZE space
3754 to put in fenceposts in sysmalloc.)
3755 */
3757 victim = av->top;
3758 size = chunksize (victim);
3760 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
3762 remainder_size = size - nb;
3763 remainder = chunk_at_offset (victim, nb);
3764 av->top = remainder;
3765 set_head (victim, nb | PREV_INUSE |
3766 (av != &main_arena ? NON_MAIN_ARENA : 0));
3767 set_head (remainder, remainder_size | PREV_INUSE);
3769 check_malloced_chunk (av, victim, nb);
3770 void *p = chunk2mem (victim);
3771 alloc_perturb (p, bytes);
3772 return p;
3775 /* When we are using atomic ops to free fast chunks we can get
3776 here for all block sizes. */
3777 else if (have_fastchunks (av))
3779 malloc_consolidate (av);
3780 /* restore original bin index */
3781 if (in_smallbin_range (nb))
3782 idx = smallbin_index (nb);
3783 else
3784 idx = largebin_index (nb);
3787 /*
3788 Otherwise, relay to handle system-dependent cases
3789 */
3790 else
3792 void *p = sysmalloc (nb, av);
3793 if (p != NULL)
3794 alloc_perturb (p, bytes);
3795 return p;
3800 /*
3801 ------------------------------ free ------------------------------
3802 */
3804 static void
3805 _int_free (mstate av, mchunkptr p, int have_lock)
3807 INTERNAL_SIZE_T size; /* its size */
3808 mfastbinptr *fb; /* associated fastbin */
3809 mchunkptr nextchunk; /* next contiguous chunk */
3810 INTERNAL_SIZE_T nextsize; /* its size */
3811 int nextinuse; /* true if nextchunk is used */
3812 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
3813 mchunkptr bck; /* misc temp for linking */
3814 mchunkptr fwd; /* misc temp for linking */
3816 const char *errstr = NULL;
3817 int locked = 0;
3819 size = chunksize (p);
3821 /* Little security check which won't hurt performance: the
3822 allocator never wrapps around at the end of the address space.
3823 Therefore we can exclude some size values which might appear
3824 here by accident or by "design" from some intruder. */
3825 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
3826 || __builtin_expect (misaligned_chunk (p), 0))
3828 errstr = "free(): invalid pointer";
3829 errout:
3830 if (!have_lock && locked)
3831 (void) mutex_unlock (&av->mutex);
3832 malloc_printerr (check_action, errstr, chunk2mem (p));
3833 return;
3835 /* We know that each chunk is at least MINSIZE bytes in size or a
3836 multiple of MALLOC_ALIGNMENT. */
3837 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
3839 errstr = "free(): invalid size";
3840 goto errout;
3843 check_inuse_chunk(av, p);
3845 /*
3846 If eligible, place chunk on a fastbin so it can be found
3847 and used quickly in malloc.
3848 */
3850 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
3852 #if TRIM_FASTBINS
3853 /*
3854 If TRIM_FASTBINS set, don't place chunks
3855 bordering top into fastbins
3856 */
3857 && (chunk_at_offset(p, size) != av->top)
3858 #endif
3859 ) {
3861 if (__builtin_expect (chunk_at_offset (p, size)->size <= 2 * SIZE_SZ, 0)
3862 || __builtin_expect (chunksize (chunk_at_offset (p, size))
3863 >= av->system_mem, 0))
3865 /* We might not have a lock at this point and concurrent modifications
3866 of system_mem might have let to a false positive. Redo the test
3867 after getting the lock. */
3868 if (have_lock
3869 || ({ assert (locked == 0);
3870 mutex_lock(&av->mutex);
3871 locked = 1;
3872 chunk_at_offset (p, size)->size <= 2 * SIZE_SZ
3873 || chunksize (chunk_at_offset (p, size)) >= av->system_mem;
3874 }))
3876 errstr = "free(): invalid next size (fast)";
3877 goto errout;
3879 if (! have_lock)
3881 (void)mutex_unlock(&av->mutex);
3882 locked = 0;
3886 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3888 set_fastchunks(av);
3889 unsigned int idx = fastbin_index(size);
3890 fb = &fastbin (av, idx);
3892 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
3893 mchunkptr old = *fb, old2;
3894 unsigned int old_idx = ~0u;
3895 do
3897 /* Check that the top of the bin is not the record we are going to add
3898 (i.e., double free). */
3899 if (__builtin_expect (old == p, 0))
3901 errstr = "double free or corruption (fasttop)";
3902 goto errout;
3904 /* Check that size of fastbin chunk at the top is the same as
3905 size of the chunk that we are adding. We can dereference OLD
3906 only if we have the lock, otherwise it might have already been
3907 deallocated. See use of OLD_IDX below for the actual check. */
3908 if (have_lock && old != NULL)
3909 old_idx = fastbin_index(chunksize(old));
3910 p->fd = old2 = old;
3912 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2)) != old2);
3914 if (have_lock && old != NULL && __builtin_expect (old_idx != idx, 0))
3916 errstr = "invalid fastbin entry (free)";
3917 goto errout;
3921 /*
3922 Consolidate other non-mmapped chunks as they arrive.
3923 */
3925 else if (!chunk_is_mmapped(p)) {
3926 if (! have_lock) {
3927 (void)mutex_lock(&av->mutex);
3928 locked = 1;
3931 nextchunk = chunk_at_offset(p, size);
3933 /* Lightweight tests: check whether the block is already the
3934 top block. */
3935 if (__glibc_unlikely (p == av->top))
3937 errstr = "double free or corruption (top)";
3938 goto errout;
3940 /* Or whether the next chunk is beyond the boundaries of the arena. */
3941 if (__builtin_expect (contiguous (av)
3942 && (char *) nextchunk
3943 >= ((char *) av->top + chunksize(av->top)), 0))
3945 errstr = "double free or corruption (out)";
3946 goto errout;
3948 /* Or whether the block is actually not marked used. */
3949 if (__glibc_unlikely (!prev_inuse(nextchunk)))
3951 errstr = "double free or corruption (!prev)";
3952 goto errout;
3955 nextsize = chunksize(nextchunk);
3956 if (__builtin_expect (nextchunk->size <= 2 * SIZE_SZ, 0)
3957 || __builtin_expect (nextsize >= av->system_mem, 0))
3959 errstr = "free(): invalid next size (normal)";
3960 goto errout;
3963 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3965 /* consolidate backward */
3966 if (!prev_inuse(p)) {
3967 prevsize = p->prev_size;
3968 size += prevsize;
3969 p = chunk_at_offset(p, -((long) prevsize));
3970 unlink(p, bck, fwd);
3973 if (nextchunk != av->top) {
3974 /* get and clear inuse bit */
3975 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
3977 /* consolidate forward */
3978 if (!nextinuse) {
3979 unlink(nextchunk, bck, fwd);
3980 size += nextsize;
3981 } else
3982 clear_inuse_bit_at_offset(nextchunk, 0);
3984 /*
3985 Place the chunk in unsorted chunk list. Chunks are
3986 not placed into regular bins until after they have
3987 been given one chance to be used in malloc.
3988 */
3990 bck = unsorted_chunks(av);
3991 fwd = bck->fd;
3992 if (__glibc_unlikely (fwd->bk != bck))
3994 errstr = "free(): corrupted unsorted chunks";
3995 goto errout;
3997 p->fd = fwd;
3998 p->bk = bck;
3999 if (!in_smallbin_range(size))
4001 p->fd_nextsize = NULL;
4002 p->bk_nextsize = NULL;
4004 bck->fd = p;
4005 fwd->bk = p;
4007 set_head(p, size | PREV_INUSE);
4008 set_foot(p, size);
4010 check_free_chunk(av, p);
4013 /*
4014 If the chunk borders the current high end of memory,
4015 consolidate into top
4016 */
4018 else {
4019 size += nextsize;
4020 set_head(p, size | PREV_INUSE);
4021 av->top = p;
4022 check_chunk(av, p);
4025 /*
4026 If freeing a large space, consolidate possibly-surrounding
4027 chunks. Then, if the total unused topmost memory exceeds trim
4028 threshold, ask malloc_trim to reduce top.
4030 Unless max_fast is 0, we don't know if there are fastbins
4031 bordering top, so we cannot tell for sure whether threshold
4032 has been reached unless fastbins are consolidated. But we
4033 don't want to consolidate on each free. As a compromise,
4034 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4035 is reached.
4036 */
4038 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4039 if (have_fastchunks(av))
4040 malloc_consolidate(av);
4042 if (av == &main_arena) {
4043 #ifndef MORECORE_CANNOT_TRIM
4044 if ((unsigned long)(chunksize(av->top)) >=
4045 (unsigned long)(mp_.trim_threshold))
4046 systrim(mp_.top_pad, av);
4047 #endif
4048 } else {
4049 /* Always try heap_trim(), even if the top chunk is not
4050 large, because the corresponding heap might go away. */
4051 heap_info *heap = heap_for_ptr(top(av));
4053 assert(heap->ar_ptr == av);
4054 heap_trim(heap, mp_.top_pad);
4058 if (! have_lock) {
4059 assert (locked);
4060 (void)mutex_unlock(&av->mutex);
4063 /*
4064 If the chunk was allocated via mmap, release via munmap().
4065 */
4067 else {
4068 munmap_chunk (p);
4072 /*
4073 ------------------------- malloc_consolidate -------------------------
4075 malloc_consolidate is a specialized version of free() that tears
4076 down chunks held in fastbins. Free itself cannot be used for this
4077 purpose since, among other things, it might place chunks back onto
4078 fastbins. So, instead, we need to use a minor variant of the same
4079 code.
4081 Also, because this routine needs to be called the first time through
4082 malloc anyway, it turns out to be the perfect place to trigger
4083 initialization code.
4084 */
4086 static void malloc_consolidate(mstate av)
4088 mfastbinptr* fb; /* current fastbin being consolidated */
4089 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4090 mchunkptr p; /* current chunk being consolidated */
4091 mchunkptr nextp; /* next chunk to consolidate */
4092 mchunkptr unsorted_bin; /* bin header */
4093 mchunkptr first_unsorted; /* chunk to link to */
4095 /* These have same use as in free() */
4096 mchunkptr nextchunk;
4097 INTERNAL_SIZE_T size;
4098 INTERNAL_SIZE_T nextsize;
4099 INTERNAL_SIZE_T prevsize;
4100 int nextinuse;
4101 mchunkptr bck;
4102 mchunkptr fwd;
4104 /*
4105 If max_fast is 0, we know that av hasn't
4106 yet been initialized, in which case do so below
4107 */
4109 if (get_max_fast () != 0) {
4110 clear_fastchunks(av);
4112 unsorted_bin = unsorted_chunks(av);
4114 /*
4115 Remove each chunk from fast bin and consolidate it, placing it
4116 then in unsorted bin. Among other reasons for doing this,
4117 placing in unsorted bin avoids needing to calculate actual bins
4118 until malloc is sure that chunks aren't immediately going to be
4119 reused anyway.
4120 */
4122 maxfb = &fastbin (av, NFASTBINS - 1);
4123 fb = &fastbin (av, 0);
4124 do {
4125 p = atomic_exchange_acq (fb, 0);
4126 if (p != 0) {
4127 do {
4128 check_inuse_chunk(av, p);
4129 nextp = p->fd;
4131 /* Slightly streamlined version of consolidation code in free() */
4132 size = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
4133 nextchunk = chunk_at_offset(p, size);
4134 nextsize = chunksize(nextchunk);
4136 if (!prev_inuse(p)) {
4137 prevsize = p->prev_size;
4138 size += prevsize;
4139 p = chunk_at_offset(p, -((long) prevsize));
4140 unlink(p, bck, fwd);
4143 if (nextchunk != av->top) {
4144 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4146 if (!nextinuse) {
4147 size += nextsize;
4148 unlink(nextchunk, bck, fwd);
4149 } else
4150 clear_inuse_bit_at_offset(nextchunk, 0);
4152 first_unsorted = unsorted_bin->fd;
4153 unsorted_bin->fd = p;
4154 first_unsorted->bk = p;
4156 if (!in_smallbin_range (size)) {
4157 p->fd_nextsize = NULL;
4158 p->bk_nextsize = NULL;
4161 set_head(p, size | PREV_INUSE);
4162 p->bk = unsorted_bin;
4163 p->fd = first_unsorted;
4164 set_foot(p, size);
4167 else {
4168 size += nextsize;
4169 set_head(p, size | PREV_INUSE);
4170 av->top = p;
4173 } while ( (p = nextp) != 0);
4176 } while (fb++ != maxfb);
4178 else {
4179 malloc_init_state(av);
4180 check_malloc_state(av);
4184 /*
4185 ------------------------------ realloc ------------------------------
4186 */
4188 void*
4189 _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4190 INTERNAL_SIZE_T nb)
4192 mchunkptr newp; /* chunk to return */
4193 INTERNAL_SIZE_T newsize; /* its size */
4194 void* newmem; /* corresponding user mem */
4196 mchunkptr next; /* next contiguous chunk after oldp */
4198 mchunkptr remainder; /* extra space at end of newp */
4199 unsigned long remainder_size; /* its size */
4201 mchunkptr bck; /* misc temp for linking */
4202 mchunkptr fwd; /* misc temp for linking */
4204 unsigned long copysize; /* bytes to copy */
4205 unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
4206 INTERNAL_SIZE_T* s; /* copy source */
4207 INTERNAL_SIZE_T* d; /* copy destination */
4209 const char *errstr = NULL;
4211 /* oldmem size */
4212 if (__builtin_expect (oldp->size <= 2 * SIZE_SZ, 0)
4213 || __builtin_expect (oldsize >= av->system_mem, 0))
4215 errstr = "realloc(): invalid old size";
4216 errout:
4217 malloc_printerr (check_action, errstr, chunk2mem (oldp));
4218 return NULL;
4221 check_inuse_chunk (av, oldp);
4223 /* All callers already filter out mmap'ed chunks. */
4224 assert (!chunk_is_mmapped (oldp));
4226 next = chunk_at_offset (oldp, oldsize);
4227 INTERNAL_SIZE_T nextsize = chunksize (next);
4228 if (__builtin_expect (next->size <= 2 * SIZE_SZ, 0)
4229 || __builtin_expect (nextsize >= av->system_mem, 0))
4231 errstr = "realloc(): invalid next size";
4232 goto errout;
4235 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4237 /* already big enough; split below */
4238 newp = oldp;
4239 newsize = oldsize;
4242 else
4244 /* Try to expand forward into top */
4245 if (next == av->top &&
4246 (unsigned long) (newsize = oldsize + nextsize) >=
4247 (unsigned long) (nb + MINSIZE))
4249 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4250 av->top = chunk_at_offset (oldp, nb);
4251 set_head (av->top, (newsize - nb) | PREV_INUSE);
4252 check_inuse_chunk (av, oldp);
4253 return chunk2mem (oldp);
4256 /* Try to expand forward into next chunk; split off remainder below */
4257 else if (next != av->top &&
4258 !inuse (next) &&
4259 (unsigned long) (newsize = oldsize + nextsize) >=
4260 (unsigned long) (nb))
4262 newp = oldp;
4263 unlink (next, bck, fwd);
4266 /* allocate, copy, free */
4267 else
4269 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4270 if (newmem == 0)
4271 return 0; /* propagate failure */
4273 newp = mem2chunk (newmem);
4274 newsize = chunksize (newp);
4276 /*
4277 Avoid copy if newp is next chunk after oldp.
4278 */
4279 if (newp == next)
4281 newsize += oldsize;
4282 newp = oldp;
4284 else
4286 /*
4287 Unroll copy of <= 36 bytes (72 if 8byte sizes)
4288 We know that contents have an odd number of
4289 INTERNAL_SIZE_T-sized words; minimally 3.
4290 */
4292 copysize = oldsize - SIZE_SZ;
4293 s = (INTERNAL_SIZE_T *) (chunk2mem (oldp));
4294 d = (INTERNAL_SIZE_T *) (newmem);
4295 ncopies = copysize / sizeof (INTERNAL_SIZE_T);
4296 assert (ncopies >= 3);
4298 if (ncopies > 9)
4299 memcpy (d, s, copysize);
4301 else
4303 *(d + 0) = *(s + 0);
4304 *(d + 1) = *(s + 1);
4305 *(d + 2) = *(s + 2);
4306 if (ncopies > 4)
4308 *(d + 3) = *(s + 3);
4309 *(d + 4) = *(s + 4);
4310 if (ncopies > 6)
4312 *(d + 5) = *(s + 5);
4313 *(d + 6) = *(s + 6);
4314 if (ncopies > 8)
4316 *(d + 7) = *(s + 7);
4317 *(d + 8) = *(s + 8);
4323 _int_free (av, oldp, 1);
4324 check_inuse_chunk (av, newp);
4325 return chunk2mem (newp);
4330 /* If possible, free extra space in old or extended chunk */
4332 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
4334 remainder_size = newsize - nb;
4336 if (remainder_size < MINSIZE) /* not enough extra to split off */
4338 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4339 set_inuse_bit_at_offset (newp, newsize);
4341 else /* split remainder */
4343 remainder = chunk_at_offset (newp, nb);
4344 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4345 set_head (remainder, remainder_size | PREV_INUSE |
4346 (av != &main_arena ? NON_MAIN_ARENA : 0));
4347 /* Mark remainder as inuse so free() won't complain */
4348 set_inuse_bit_at_offset (remainder, remainder_size);
4349 _int_free (av, remainder, 1);
4352 check_inuse_chunk (av, newp);
4353 return chunk2mem (newp);
4356 /*
4357 ------------------------------ memalign ------------------------------
4358 */
4360 static void *
4361 _int_memalign (mstate av, size_t alignment, size_t bytes)
4363 INTERNAL_SIZE_T nb; /* padded request size */
4364 char *m; /* memory returned by malloc call */
4365 mchunkptr p; /* corresponding chunk */
4366 char *brk; /* alignment point within p */
4367 mchunkptr newp; /* chunk to return */
4368 INTERNAL_SIZE_T newsize; /* its size */
4369 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4370 mchunkptr remainder; /* spare room at end to split off */
4371 unsigned long remainder_size; /* its size */
4372 INTERNAL_SIZE_T size;
4376 checked_request2size (bytes, nb);
4378 /*
4379 Strategy: find a spot within that chunk that meets the alignment
4380 request, and then possibly free the leading and trailing space.
4381 */
4384 /* Call malloc with worst case padding to hit alignment. */
4386 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4388 if (m == 0)
4389 return 0; /* propagate failure */
4391 p = mem2chunk (m);
4393 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4395 { /*
4396 Find an aligned spot inside chunk. Since we need to give back
4397 leading space in a chunk of at least MINSIZE, if the first
4398 calculation places us at a spot with less than MINSIZE leader,
4399 we can move to the next aligned spot -- we've allocated enough
4400 total room so that this is always possible.
4401 */
4402 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4403 - ((signed long) alignment));
4404 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4405 brk += alignment;
4407 newp = (mchunkptr) brk;
4408 leadsize = brk - (char *) (p);
4409 newsize = chunksize (p) - leadsize;
4411 /* For mmapped chunks, just adjust offset */
4412 if (chunk_is_mmapped (p))
4414 newp->prev_size = p->prev_size + leadsize;
4415 set_head (newp, newsize | IS_MMAPPED);
4416 return chunk2mem (newp);
4419 /* Otherwise, give back leader, use the rest */
4420 set_head (newp, newsize | PREV_INUSE |
4421 (av != &main_arena ? NON_MAIN_ARENA : 0));
4422 set_inuse_bit_at_offset (newp, newsize);
4423 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4424 _int_free (av, p, 1);
4425 p = newp;
4427 assert (newsize >= nb &&
4428 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
4431 /* Also give back spare room at the end */
4432 if (!chunk_is_mmapped (p))
4434 size = chunksize (p);
4435 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4437 remainder_size = size - nb;
4438 remainder = chunk_at_offset (p, nb);
4439 set_head (remainder, remainder_size | PREV_INUSE |
4440 (av != &main_arena ? NON_MAIN_ARENA : 0));
4441 set_head_size (p, nb);
4442 _int_free (av, remainder, 1);
4446 check_inuse_chunk (av, p);
4447 return chunk2mem (p);
4451 /*
4452 ------------------------------ malloc_trim ------------------------------
4453 */
4455 static int
4456 mtrim (mstate av, size_t pad)
4458 /* Ensure initialization/consolidation */
4459 malloc_consolidate (av);
4461 const size_t ps = GLRO (dl_pagesize);
4462 int psindex = bin_index (ps);
4463 const size_t psm1 = ps - 1;
4465 int result = 0;
4466 for (int i = 1; i < NBINS; ++i)
4467 if (i == 1 || i >= psindex)
4469 mbinptr bin = bin_at (av, i);
4471 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4473 INTERNAL_SIZE_T size = chunksize (p);
4475 if (size > psm1 + sizeof (struct malloc_chunk))
4477 /* See whether the chunk contains at least one unused page. */
4478 char *paligned_mem = (char *) (((uintptr_t) p
4479 + sizeof (struct malloc_chunk)
4480 + psm1) & ~psm1);
4482 assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
4483 assert ((char *) p + size > paligned_mem);
4485 /* This is the size we could potentially free. */
4486 size -= paligned_mem - (char *) p;
4488 if (size > psm1)
4490 #if MALLOC_DEBUG
4491 /* When debugging we simulate destroying the memory
4492 content. */
4493 memset (paligned_mem, 0x89, size & ~psm1);
4494 #endif
4495 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
4497 result = 1;
4503 #ifndef MORECORE_CANNOT_TRIM
4504 return result | (av == &main_arena ? systrim (pad, av) : 0);
4506 #else
4507 return result;
4508 #endif
4512 int
4513 __malloc_trim (size_t s)
4515 int result = 0;
4517 if (__malloc_initialized < 0)
4518 ptmalloc_init ();
4520 mstate ar_ptr = &main_arena;
4521 do
4523 (void) mutex_lock (&ar_ptr->mutex);
4524 result |= mtrim (ar_ptr, s);
4525 (void) mutex_unlock (&ar_ptr->mutex);
4527 ar_ptr = ar_ptr->next;
4529 while (ar_ptr != &main_arena);
4531 return result;
4535 /*
4536 ------------------------- malloc_usable_size -------------------------
4537 */
4539 static size_t
4540 musable (void *mem)
4542 mchunkptr p;
4543 if (mem != 0)
4545 p = mem2chunk (mem);
4547 if (__builtin_expect (using_malloc_checking == 1, 0))
4548 return malloc_check_get_size (p);
4550 if (chunk_is_mmapped (p))
4551 return chunksize (p) - 2 * SIZE_SZ;
4552 else if (inuse (p))
4553 return chunksize (p) - SIZE_SZ;
4555 return 0;
4559 size_t
4560 __malloc_usable_size (void *m)
4562 size_t result;
4564 result = musable (m);
4565 return result;
4568 /*
4569 ------------------------------ mallinfo ------------------------------
4570 Accumulate malloc statistics for arena AV into M.
4571 */
4573 static void
4574 int_mallinfo (mstate av, struct mallinfo *m)
4576 size_t i;
4577 mbinptr b;
4578 mchunkptr p;
4579 INTERNAL_SIZE_T avail;
4580 INTERNAL_SIZE_T fastavail;
4581 int nblocks;
4582 int nfastblocks;
4584 /* Ensure initialization */
4585 if (av->top == 0)
4586 malloc_consolidate (av);
4588 check_malloc_state (av);
4590 /* Account for top */
4591 avail = chunksize (av->top);
4592 nblocks = 1; /* top always exists */
4594 /* traverse fastbins */
4595 nfastblocks = 0;
4596 fastavail = 0;
4598 for (i = 0; i < NFASTBINS; ++i)
4600 for (p = fastbin (av, i); p != 0; p = p->fd)
4602 ++nfastblocks;
4603 fastavail += chunksize (p);
4607 avail += fastavail;
4609 /* traverse regular bins */
4610 for (i = 1; i < NBINS; ++i)
4612 b = bin_at (av, i);
4613 for (p = last (b); p != b; p = p->bk)
4615 ++nblocks;
4616 avail += chunksize (p);
4620 m->smblks += nfastblocks;
4621 m->ordblks += nblocks;
4622 m->fordblks += avail;
4623 m->uordblks += av->system_mem - avail;
4624 m->arena += av->system_mem;
4625 m->fsmblks += fastavail;
4626 if (av == &main_arena)
4628 m->hblks = mp_.n_mmaps;
4629 m->hblkhd = mp_.mmapped_mem;
4630 m->usmblks = mp_.max_total_mem;
4631 m->keepcost = chunksize (av->top);
4636 struct mallinfo
4637 __libc_mallinfo ()
4639 struct mallinfo m;
4640 mstate ar_ptr;
4642 if (__malloc_initialized < 0)
4643 ptmalloc_init ();
4645 memset (&m, 0, sizeof (m));
4646 ar_ptr = &main_arena;
4647 do
4649 (void) mutex_lock (&ar_ptr->mutex);
4650 int_mallinfo (ar_ptr, &m);
4651 (void) mutex_unlock (&ar_ptr->mutex);
4653 ar_ptr = ar_ptr->next;
4655 while (ar_ptr != &main_arena);
4657 return m;
4660 /*
4661 ------------------------------ malloc_stats ------------------------------
4662 */
4664 void
4665 __malloc_stats (void)
4667 int i;
4668 mstate ar_ptr;
4669 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
4671 if (__malloc_initialized < 0)
4672 ptmalloc_init ();
4673 _IO_flockfile (stderr);
4674 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
4675 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
4676 for (i = 0, ar_ptr = &main_arena;; i++)
4678 struct mallinfo mi;
4680 memset (&mi, 0, sizeof (mi));
4681 (void) mutex_lock (&ar_ptr->mutex);
4682 int_mallinfo (ar_ptr, &mi);
4683 fprintf (stderr, "Arena %d:\n", i);
4684 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
4685 fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
4686 #if MALLOC_DEBUG > 1
4687 if (i > 0)
4688 dump_heap (heap_for_ptr (top (ar_ptr)));
4689 #endif
4690 system_b += mi.arena;
4691 in_use_b += mi.uordblks;
4692 (void) mutex_unlock (&ar_ptr->mutex);
4693 ar_ptr = ar_ptr->next;
4694 if (ar_ptr == &main_arena)
4695 break;
4697 fprintf (stderr, "Total (incl. mmap):\n");
4698 fprintf (stderr, "system bytes = %10u\n", system_b);
4699 fprintf (stderr, "in use bytes = %10u\n", in_use_b);
4700 fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
4701 fprintf (stderr, "max mmap bytes = %10lu\n",
4702 (unsigned long) mp_.max_mmapped_mem);
4703 ((_IO_FILE *) stderr)->_flags2 |= old_flags2;
4704 _IO_funlockfile (stderr);
4708 /*
4709 ------------------------------ mallopt ------------------------------
4710 */
4712 int
4713 __libc_mallopt (int param_number, int value)
4715 mstate av = &main_arena;
4716 int res = 1;
4718 if (__malloc_initialized < 0)
4719 ptmalloc_init ();
4720 (void) mutex_lock (&av->mutex);
4721 /* Ensure initialization/consolidation */
4722 malloc_consolidate (av);
4724 LIBC_PROBE (memory_mallopt, 2, param_number, value);
4726 switch (param_number)
4728 case M_MXFAST:
4729 if (value >= 0 && value <= MAX_FAST_SIZE)
4731 LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
4732 set_max_fast (value);
4734 else
4735 res = 0;
4736 break;
4738 case M_TRIM_THRESHOLD:
4739 LIBC_PROBE (memory_mallopt_trim_threshold, 3, value,
4740 mp_.trim_threshold, mp_.no_dyn_threshold);
4741 mp_.trim_threshold = value;
4742 mp_.no_dyn_threshold = 1;
4743 break;
4745 case M_TOP_PAD:
4746 LIBC_PROBE (memory_mallopt_top_pad, 3, value,
4747 mp_.top_pad, mp_.no_dyn_threshold);
4748 mp_.top_pad = value;
4749 mp_.no_dyn_threshold = 1;
4750 break;
4752 case M_MMAP_THRESHOLD:
4753 /* Forbid setting the threshold too high. */
4754 if ((unsigned long) value > HEAP_MAX_SIZE / 2)
4755 res = 0;
4756 else
4758 LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value,
4759 mp_.mmap_threshold, mp_.no_dyn_threshold);
4760 mp_.mmap_threshold = value;
4761 mp_.no_dyn_threshold = 1;
4763 break;
4765 case M_MMAP_MAX:
4766 LIBC_PROBE (memory_mallopt_mmap_max, 3, value,
4767 mp_.n_mmaps_max, mp_.no_dyn_threshold);
4768 mp_.n_mmaps_max = value;
4769 mp_.no_dyn_threshold = 1;
4770 break;
4772 case M_CHECK_ACTION:
4773 LIBC_PROBE (memory_mallopt_check_action, 2, value, check_action);
4774 check_action = value;
4775 break;
4777 case M_PERTURB:
4778 LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
4779 perturb_byte = value;
4780 break;
4782 case M_ARENA_TEST:
4783 if (value > 0)
4785 LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
4786 mp_.arena_test = value;
4788 break;
4790 case M_ARENA_MAX:
4791 if (value > 0)
4793 LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
4794 mp_.arena_max = value;
4796 break;
4798 (void) mutex_unlock (&av->mutex);
4799 return res;
4801 libc_hidden_def (__libc_mallopt)
4804 /*
4805 -------------------- Alternative MORECORE functions --------------------
4806 */
4809 /*
4810 General Requirements for MORECORE.
4812 The MORECORE function must have the following properties:
4814 If MORECORE_CONTIGUOUS is false:
4816 * MORECORE must allocate in multiples of pagesize. It will
4817 only be called with arguments that are multiples of pagesize.
4819 * MORECORE(0) must return an address that is at least
4820 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
4822 else (i.e. If MORECORE_CONTIGUOUS is true):
4824 * Consecutive calls to MORECORE with positive arguments
4825 return increasing addresses, indicating that space has been
4826 contiguously extended.
4828 * MORECORE need not allocate in multiples of pagesize.
4829 Calls to MORECORE need not have args of multiples of pagesize.
4831 * MORECORE need not page-align.
4833 In either case:
4835 * MORECORE may allocate more memory than requested. (Or even less,
4836 but this will generally result in a malloc failure.)
4838 * MORECORE must not allocate memory when given argument zero, but
4839 instead return one past the end address of memory from previous
4840 nonzero call. This malloc does NOT call MORECORE(0)
4841 until at least one call with positive arguments is made, so
4842 the initial value returned is not important.
4844 * Even though consecutive calls to MORECORE need not return contiguous
4845 addresses, it must be OK for malloc'ed chunks to span multiple
4846 regions in those cases where they do happen to be contiguous.
4848 * MORECORE need not handle negative arguments -- it may instead
4849 just return MORECORE_FAILURE when given negative arguments.
4850 Negative arguments are always multiples of pagesize. MORECORE
4851 must not misinterpret negative args as large positive unsigned
4852 args. You can suppress all such calls from even occurring by defining
4853 MORECORE_CANNOT_TRIM,
4855 There is some variation across systems about the type of the
4856 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
4857 actually be size_t, because sbrk supports negative args, so it is
4858 normally the signed type of the same width as size_t (sometimes
4859 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
4860 matter though. Internally, we use "long" as arguments, which should
4861 work across all reasonable possibilities.
4863 Additionally, if MORECORE ever returns failure for a positive
4864 request, then mmap is used as a noncontiguous system allocator. This
4865 is a useful backup strategy for systems with holes in address spaces
4866 -- in this case sbrk cannot contiguously expand the heap, but mmap
4867 may be able to map noncontiguous space.
4869 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
4870 a function that always returns MORECORE_FAILURE.
4872 If you are using this malloc with something other than sbrk (or its
4873 emulation) to supply memory regions, you probably want to set
4874 MORECORE_CONTIGUOUS as false. As an example, here is a custom
4875 allocator kindly contributed for pre-OSX macOS. It uses virtually
4876 but not necessarily physically contiguous non-paged memory (locked
4877 in, present and won't get swapped out). You can use it by
4878 uncommenting this section, adding some #includes, and setting up the
4879 appropriate defines above:
4881 *#define MORECORE osMoreCore
4882 *#define MORECORE_CONTIGUOUS 0
4884 There is also a shutdown routine that should somehow be called for
4885 cleanup upon program exit.
4887 *#define MAX_POOL_ENTRIES 100
4888 *#define MINIMUM_MORECORE_SIZE (64 * 1024)
4889 static int next_os_pool;
4890 void *our_os_pools[MAX_POOL_ENTRIES];
4892 void *osMoreCore(int size)
4894 void *ptr = 0;
4895 static void *sbrk_top = 0;
4897 if (size > 0)
4899 if (size < MINIMUM_MORECORE_SIZE)
4900 size = MINIMUM_MORECORE_SIZE;
4901 if (CurrentExecutionLevel() == kTaskLevel)
4902 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
4903 if (ptr == 0)
4905 return (void *) MORECORE_FAILURE;
4907 // save ptrs so they can be freed during cleanup
4908 our_os_pools[next_os_pool] = ptr;
4909 next_os_pool++;
4910 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
4911 sbrk_top = (char *) ptr + size;
4912 return ptr;
4914 else if (size < 0)
4916 // we don't currently support shrink behavior
4917 return (void *) MORECORE_FAILURE;
4919 else
4921 return sbrk_top;
4925 // cleanup any allocated memory pools
4926 // called as last thing before shutting down driver
4928 void osCleanupMem(void)
4930 void **ptr;
4932 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
4933 if (*ptr)
4935 PoolDeallocate(*ptr);
4936 * ptr = 0;
4940 */
4943 /* Helper code. */
4945 extern char **__libc_argv attribute_hidden;
4947 static void
4948 malloc_printerr (int action, const char *str, void *ptr)
4950 if ((action & 5) == 5)
4951 __libc_message (action & 2, "%s\n", str);
4952 else if (action & 1)
4954 char buf[2 * sizeof (uintptr_t) + 1];
4956 buf[sizeof (buf) - 1] = '\0';
4957 char *cp = _itoa_word ((uintptr_t) ptr, &buf[sizeof (buf) - 1], 16, 0);
4958 while (cp > buf)
4959 *--cp = '0';
4961 __libc_message (action & 2, "*** Error in `%s': %s: 0x%s ***\n",
4962 __libc_argv[0] ? : "<unknown>", str, cp);
4964 else if (action & 2)
4965 abort ();
4968 /* We need a wrapper function for one of the additions of POSIX. */
4969 int
4970 __posix_memalign (void **memptr, size_t alignment, size_t size)
4972 void *mem;
4974 /* Test whether the SIZE argument is valid. It must be a power of
4975 two multiple of sizeof (void *). */
4976 if (alignment % sizeof (void *) != 0
4977 || !powerof2 (alignment / sizeof (void *))
4978 || alignment == 0)
4979 return EINVAL;
4982 void *address = RETURN_ADDRESS (0);
4983 mem = _mid_memalign (alignment, size, address);
4985 if (mem != NULL)
4987 *memptr = mem;
4988 return 0;
4991 return ENOMEM;
4993 weak_alias (__posix_memalign, posix_memalign)
4996 int
4997 __malloc_info (int options, FILE *fp)
4999 /* For now, at least. */
5000 if (options != 0)
5001 return EINVAL;
5003 int n = 0;
5004 size_t total_nblocks = 0;
5005 size_t total_nfastblocks = 0;
5006 size_t total_avail = 0;
5007 size_t total_fastavail = 0;
5008 size_t total_system = 0;
5009 size_t total_max_system = 0;
5010 size_t total_aspace = 0;
5011 size_t total_aspace_mprotect = 0;
5015 if (__malloc_initialized < 0)
5016 ptmalloc_init ();
5018 fputs ("<malloc version=\"1\">\n", fp);
5020 /* Iterate over all arenas currently in use. */
5021 mstate ar_ptr = &main_arena;
5022 do
5024 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
5026 size_t nblocks = 0;
5027 size_t nfastblocks = 0;
5028 size_t avail = 0;
5029 size_t fastavail = 0;
5030 struct
5032 size_t from;
5033 size_t to;
5034 size_t total;
5035 size_t count;
5036 } sizes[NFASTBINS + NBINS - 1];
5037 #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
5039 mutex_lock (&ar_ptr->mutex);
5041 for (size_t i = 0; i < NFASTBINS; ++i)
5043 mchunkptr p = fastbin (ar_ptr, i);
5044 if (p != NULL)
5046 size_t nthissize = 0;
5047 size_t thissize = chunksize (p);
5049 while (p != NULL)
5051 ++nthissize;
5052 p = p->fd;
5055 fastavail += nthissize * thissize;
5056 nfastblocks += nthissize;
5057 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
5058 sizes[i].to = thissize;
5059 sizes[i].count = nthissize;
5061 else
5062 sizes[i].from = sizes[i].to = sizes[i].count = 0;
5064 sizes[i].total = sizes[i].count * sizes[i].to;
5068 mbinptr bin;
5069 struct malloc_chunk *r;
5071 for (size_t i = 1; i < NBINS; ++i)
5073 bin = bin_at (ar_ptr, i);
5074 r = bin->fd;
5075 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5076 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5077 = sizes[NFASTBINS - 1 + i].count = 0;
5079 if (r != NULL)
5080 while (r != bin)
5082 ++sizes[NFASTBINS - 1 + i].count;
5083 sizes[NFASTBINS - 1 + i].total += r->size;
5084 sizes[NFASTBINS - 1 + i].from
5085 = MIN (sizes[NFASTBINS - 1 + i].from, r->size);
5086 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5087 r->size);
5089 r = r->fd;
5092 if (sizes[NFASTBINS - 1 + i].count == 0)
5093 sizes[NFASTBINS - 1 + i].from = 0;
5094 nblocks += sizes[NFASTBINS - 1 + i].count;
5095 avail += sizes[NFASTBINS - 1 + i].total;
5098 mutex_unlock (&ar_ptr->mutex);
5100 total_nfastblocks += nfastblocks;
5101 total_fastavail += fastavail;
5103 total_nblocks += nblocks;
5104 total_avail += avail;