Correct powerpc64 s_floorl edge cases (bug 13886).
[glibc.git] / malloc / malloc.c
blob79cdc52330d970cb0a113b882020adb079c94d6f
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2009, 2010, 2011, 2012 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/>. */
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 changesmade 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 unless linux defined
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. */
208 void* is the pointer type that malloc should say it returns
211 #ifndef void
212 #define void void
213 #endif /*void*/
215 #include <stddef.h> /* for size_t */
216 #include <stdlib.h> /* for getenv(), abort() */
218 #include <malloc-machine.h>
220 #include <atomic.h>
221 #include <_itoa.h>
222 #include <bits/wordsize.h>
223 #include <sys/sysinfo.h>
225 #include <ldsodefs.h>
227 #include <unistd.h>
228 #include <stdio.h> /* needed for malloc_stats */
229 #include <errno.h>
231 /* For uintptr_t. */
232 #include <stdint.h>
234 /* For va_arg, va_start, va_end. */
235 #include <stdarg.h>
239 Debugging:
241 Because freed chunks may be overwritten with bookkeeping fields, this
242 malloc will often die when freed memory is overwritten by user
243 programs. This can be very effective (albeit in an annoying way)
244 in helping track down dangling pointers.
246 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
247 enabled that will catch more memory errors. You probably won't be
248 able to make much sense of the actual assertion errors, but they
249 should help you locate incorrectly overwritten memory. The checking
250 is fairly extensive, and will slow down execution
251 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
252 will attempt to check every non-mmapped allocated and free chunk in
253 the course of computing the summmaries. (By nature, mmapped regions
254 cannot be checked very much automatically.)
256 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
257 this code. The assertions in the check routines spell out in more
258 detail the assumptions and invariants underlying the algorithms.
260 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
261 checking that all accesses to malloced memory stay within their
262 bounds. However, there are several add-ons and adaptations of this
263 or other mallocs available that do this.
266 #ifdef NDEBUG
267 # define assert(expr) ((void) 0)
268 #else
269 # define assert(expr) \
270 ((expr) \
271 ? ((void) 0) \
272 : __malloc_assert (__STRING (expr), __FILE__, __LINE__, __func__))
274 extern const char *__progname;
276 static void
277 __malloc_assert (const char *assertion, const char *file, unsigned int line,
278 const char *function)
280 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
281 __progname, __progname[0] ? ": " : "",
282 file, line,
283 function ? function : "", function ? ": " : "",
284 assertion);
285 fflush (stderr);
286 abort ();
288 #endif
292 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
293 of chunk sizes.
295 The default version is the same as size_t.
297 While not strictly necessary, it is best to define this as an
298 unsigned type, even if size_t is a signed type. This may avoid some
299 artificial size limitations on some systems.
301 On a 64-bit machine, you may be able to reduce malloc overhead by
302 defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
303 expense of not being able to handle more than 2^32 of malloced
304 space. If this limitation is acceptable, you are encouraged to set
305 this unless you are on a platform requiring 16byte alignments. In
306 this case the alignment requirements turn out to negate any
307 potential advantages of decreasing size_t word size.
309 Implementors: Beware of the possible combinations of:
310 - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
311 and might be the same width as int or as long
312 - size_t might have different width and signedness as INTERNAL_SIZE_T
313 - int and long might be 32 or 64 bits, and might be the same width
314 To deal with this, most comparisons and difference computations
315 among INTERNAL_SIZE_Ts should cast them to unsigned long, being
316 aware of the fact that casting an unsigned int to a wider long does
317 not sign-extend. (This also makes checking for negative numbers
318 awkward.) Some of these casts result in harmless compiler warnings
319 on some systems.
322 #ifndef INTERNAL_SIZE_T
323 #define INTERNAL_SIZE_T size_t
324 #endif
326 /* The corresponding word size */
327 #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
331 MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
332 It must be a power of two at least 2 * SIZE_SZ, even on machines
333 for which smaller alignments would suffice. It may be defined as
334 larger than this though. Note however that code and data structures
335 are optimized for the case of 8-byte alignment.
339 #ifndef MALLOC_ALIGNMENT
340 /* XXX This is the correct definition. It differs from 2*SIZE_SZ only on
341 powerpc32. For the time being, changing this is causing more
342 compatibility problems due to malloc_get_state/malloc_set_state than
343 will returning blocks not adequately aligned for long double objects
344 under -mlong-double-128.
346 #define MALLOC_ALIGNMENT (2 * SIZE_SZ < __alignof__ (long double) \
347 ? __alignof__ (long double) : 2 * SIZE_SZ)
349 #define MALLOC_ALIGNMENT (2 * SIZE_SZ)
350 #endif
352 /* The corresponding bit mask value */
353 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
358 REALLOC_ZERO_BYTES_FREES should be set if a call to
359 realloc with zero bytes should be the same as a call to free.
360 This is required by the C standard. Otherwise, since this malloc
361 returns a unique pointer for malloc(0), so does realloc(p, 0).
364 #ifndef REALLOC_ZERO_BYTES_FREES
365 #define REALLOC_ZERO_BYTES_FREES 1
366 #endif
369 TRIM_FASTBINS controls whether free() of a very small chunk can
370 immediately lead to trimming. Setting to true (1) can reduce memory
371 footprint, but will almost always slow down programs that use a lot
372 of small chunks.
374 Define this only if you are willing to give up some speed to more
375 aggressively reduce system-level memory footprint when releasing
376 memory in programs that use many small chunks. You can get
377 essentially the same effect by setting MXFAST to 0, but this can
378 lead to even greater slowdowns in programs using many small chunks.
379 TRIM_FASTBINS is an in-between compile-time option, that disables
380 only those chunks bordering topmost memory from being placed in
381 fastbins.
384 #ifndef TRIM_FASTBINS
385 #define TRIM_FASTBINS 0
386 #endif
389 /* Definition for getting more memory from the OS. */
390 #define MORECORE (*__morecore)
391 #define MORECORE_FAILURE 0
392 void * __default_morecore (ptrdiff_t);
393 void *(*__morecore)(ptrdiff_t) = __default_morecore;
396 #include <string.h>
399 /* Force a value to be in a register and stop the compiler referring
400 to the source (mostly memory location) again. */
401 #define force_reg(val) \
402 ({ __typeof (val) _v; asm ("" : "=r" (_v) : "0" (val)); _v; })
406 MORECORE-related declarations. By default, rely on sbrk
411 MORECORE is the name of the routine to call to obtain more memory
412 from the system. See below for general guidance on writing
413 alternative MORECORE functions, as well as a version for WIN32 and a
414 sample version for pre-OSX macos.
417 #ifndef MORECORE
418 #define MORECORE sbrk
419 #endif
422 MORECORE_FAILURE is the value returned upon failure of MORECORE
423 as well as mmap. Since it cannot be an otherwise valid memory address,
424 and must reflect values of standard sys calls, you probably ought not
425 try to redefine it.
428 #ifndef MORECORE_FAILURE
429 #define MORECORE_FAILURE (-1)
430 #endif
433 If MORECORE_CONTIGUOUS is true, take advantage of fact that
434 consecutive calls to MORECORE with positive arguments always return
435 contiguous increasing addresses. This is true of unix sbrk. Even
436 if not defined, when regions happen to be contiguous, malloc will
437 permit allocations spanning regions obtained from different
438 calls. But defining this when applicable enables some stronger
439 consistency checks and space efficiencies.
442 #ifndef MORECORE_CONTIGUOUS
443 #define MORECORE_CONTIGUOUS 1
444 #endif
447 Define MORECORE_CANNOT_TRIM if your version of MORECORE
448 cannot release space back to the system when given negative
449 arguments. This is generally necessary only if you are using
450 a hand-crafted MORECORE function that cannot handle negative arguments.
453 /* #define MORECORE_CANNOT_TRIM */
455 /* MORECORE_CLEARS (default 1)
456 The degree to which the routine mapped to MORECORE zeroes out
457 memory: never (0), only for newly allocated space (1) or always
458 (2). The distinction between (1) and (2) is necessary because on
459 some systems, if the application first decrements and then
460 increments the break value, the contents of the reallocated space
461 are unspecified.
464 #ifndef MORECORE_CLEARS
465 #define MORECORE_CLEARS 1
466 #endif
470 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
471 sbrk fails, and mmap is used as a backup. The value must be a
472 multiple of page size. This backup strategy generally applies only
473 when systems have "holes" in address space, so sbrk cannot perform
474 contiguous expansion, but there is still space available on system.
475 On systems for which this is known to be useful (i.e. most linux
476 kernels), this occurs only when programs allocate huge amounts of
477 memory. Between this, and the fact that mmap regions tend to be
478 limited, the size should be large, to avoid too many mmap calls and
479 thus avoid running out of kernel resources. */
481 #ifndef MMAP_AS_MORECORE_SIZE
482 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
483 #endif
486 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
487 large blocks. This is currently only possible on Linux with
488 kernel versions newer than 1.3.77.
491 #ifndef HAVE_MREMAP
492 #ifdef linux
493 #define HAVE_MREMAP 1
494 #else
495 #define HAVE_MREMAP 0
496 #endif
498 #endif /* HAVE_MREMAP */
502 This version of malloc supports the standard SVID/XPG mallinfo
503 routine that returns a struct containing usage properties and
504 statistics. It should work on any SVID/XPG compliant system that has
505 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
506 install such a thing yourself, cut out the preliminary declarations
507 as described above and below and save them in a malloc.h file. But
508 there's no compelling reason to bother to do this.)
510 The main declaration needed is the mallinfo struct that is returned
511 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
512 bunch of fields that are not even meaningful in this version of
513 malloc. These fields are are instead filled by mallinfo() with
514 other numbers that might be of interest.
518 /* ---------- description of public routines ------------ */
521 malloc(size_t n)
522 Returns a pointer to a newly allocated chunk of at least n bytes, or null
523 if no space is available. Additionally, on failure, errno is
524 set to ENOMEM on ANSI C systems.
526 If n is zero, malloc returns a minumum-sized chunk. (The minimum
527 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
528 systems.) On most systems, size_t is an unsigned type, so calls
529 with negative arguments are interpreted as requests for huge amounts
530 of space, which will often fail. The maximum supported value of n
531 differs across systems, but is in all cases less than the maximum
532 representable value of a size_t.
534 void* __libc_malloc(size_t);
535 libc_hidden_proto (__libc_malloc)
538 free(void* p)
539 Releases the chunk of memory pointed to by p, that had been previously
540 allocated using malloc or a related routine such as realloc.
541 It has no effect if p is null. It can have arbitrary (i.e., bad!)
542 effects if p has already been freed.
544 Unless disabled (using mallopt), freeing very large spaces will
545 when possible, automatically trigger operations that give
546 back unused memory to the system, thus reducing program footprint.
548 void __libc_free(void*);
549 libc_hidden_proto (__libc_free)
552 calloc(size_t n_elements, size_t element_size);
553 Returns a pointer to n_elements * element_size bytes, with all locations
554 set to zero.
556 void* __libc_calloc(size_t, size_t);
559 realloc(void* p, size_t n)
560 Returns a pointer to a chunk of size n that contains the same data
561 as does chunk p up to the minimum of (n, p's size) bytes, or null
562 if no space is available.
564 The returned pointer may or may not be the same as p. The algorithm
565 prefers extending p when possible, otherwise it employs the
566 equivalent of a malloc-copy-free sequence.
568 If p is null, realloc is equivalent to malloc.
570 If space is not available, realloc returns null, errno is set (if on
571 ANSI) and p is NOT freed.
573 if n is for fewer bytes than already held by p, the newly unused
574 space is lopped off and freed if possible. Unless the #define
575 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
576 zero (re)allocates a minimum-sized chunk.
578 Large chunks that were internally obtained via mmap will always
579 be reallocated using malloc-copy-free sequences unless
580 the system supports MREMAP (currently only linux).
582 The old unix realloc convention of allowing the last-free'd chunk
583 to be used as an argument to realloc is not supported.
585 void* __libc_realloc(void*, size_t);
586 libc_hidden_proto (__libc_realloc)
589 memalign(size_t alignment, size_t n);
590 Returns a pointer to a newly allocated chunk of n bytes, aligned
591 in accord with the alignment argument.
593 The alignment argument should be a power of two. If the argument is
594 not a power of two, the nearest greater power is used.
595 8-byte alignment is guaranteed by normal malloc calls, so don't
596 bother calling memalign with an argument of 8 or less.
598 Overreliance on memalign is a sure way to fragment space.
600 void* __libc_memalign(size_t, size_t);
601 libc_hidden_proto (__libc_memalign)
604 valloc(size_t n);
605 Equivalent to memalign(pagesize, n), where pagesize is the page
606 size of the system. If the pagesize is unknown, 4096 is used.
608 void* __libc_valloc(size_t);
613 mallopt(int parameter_number, int parameter_value)
614 Sets tunable parameters The format is to provide a
615 (parameter-number, parameter-value) pair. mallopt then sets the
616 corresponding parameter to the argument value if it can (i.e., so
617 long as the value is meaningful), and returns 1 if successful else
618 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
619 normally defined in malloc.h. Only one of these (M_MXFAST) is used
620 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
621 so setting them has no effect. But this malloc also supports four
622 other options in mallopt. See below for details. Briefly, supported
623 parameters are as follows (listed defaults are for "typical"
624 configurations).
626 Symbol param # default allowed param values
627 M_MXFAST 1 64 0-80 (0 disables fastbins)
628 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
629 M_TOP_PAD -2 0 any
630 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
631 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
633 int __libc_mallopt(int, int);
634 libc_hidden_proto (__libc_mallopt)
638 mallinfo()
639 Returns (by copy) a struct containing various summary statistics:
641 arena: current total non-mmapped bytes allocated from system
642 ordblks: the number of free chunks
643 smblks: the number of fastbin blocks (i.e., small chunks that
644 have been freed but not use resused or consolidated)
645 hblks: current number of mmapped regions
646 hblkhd: total bytes held in mmapped regions
647 usmblks: the maximum total allocated space. This will be greater
648 than current total if trimming has occurred.
649 fsmblks: total bytes held in fastbin blocks
650 uordblks: current total allocated space (normal or mmapped)
651 fordblks: total free space
652 keepcost: the maximum number of bytes that could ideally be released
653 back to system via malloc_trim. ("ideally" means that
654 it ignores page restrictions etc.)
656 Because these fields are ints, but internal bookkeeping may
657 be kept as longs, the reported values may wrap around zero and
658 thus be inaccurate.
660 struct mallinfo __libc_mallinfo(void);
664 pvalloc(size_t n);
665 Equivalent to valloc(minimum-page-that-holds(n)), that is,
666 round up n to nearest pagesize.
668 void* __libc_pvalloc(size_t);
671 malloc_trim(size_t pad);
673 If possible, gives memory back to the system (via negative
674 arguments to sbrk) if there is unused memory at the `high' end of
675 the malloc pool. You can call this after freeing large blocks of
676 memory to potentially reduce the system-level memory requirements
677 of a program. However, it cannot guarantee to reduce memory. Under
678 some allocation patterns, some large free blocks of memory will be
679 locked between two used chunks, so they cannot be given back to
680 the system.
682 The `pad' argument to malloc_trim represents the amount of free
683 trailing space to leave untrimmed. If this argument is zero,
684 only the minimum amount of memory to maintain internal data
685 structures will be left (one page or less). Non-zero arguments
686 can be supplied to maintain enough trailing space to service
687 future expected allocations without having to re-obtain memory
688 from the system.
690 Malloc_trim returns 1 if it actually released any memory, else 0.
691 On systems that do not support "negative sbrks", it will always
692 return 0.
694 int __malloc_trim(size_t);
697 malloc_usable_size(void* p);
699 Returns the number of bytes you can actually use in
700 an allocated chunk, which may be more than you requested (although
701 often not) due to alignment and minimum size constraints.
702 You can use this many bytes without worrying about
703 overwriting other allocated objects. This is not a particularly great
704 programming practice. malloc_usable_size can be more useful in
705 debugging and assertions, for example:
707 p = malloc(n);
708 assert(malloc_usable_size(p) >= 256);
711 size_t __malloc_usable_size(void*);
714 malloc_stats();
715 Prints on stderr the amount of space obtained from the system (both
716 via sbrk and mmap), the maximum amount (which may be more than
717 current if malloc_trim and/or munmap got called), and the current
718 number of bytes allocated via malloc (or realloc, etc) but not yet
719 freed. Note that this is the number of bytes allocated, not the
720 number requested. It will be larger than the number requested
721 because of alignment and bookkeeping overhead. Because it includes
722 alignment wastage as being in use, this figure may be greater than
723 zero even when no user-level chunks are allocated.
725 The reported current and maximum system memory can be inaccurate if
726 a program makes other calls to system memory allocation functions
727 (normally sbrk) outside of malloc.
729 malloc_stats prints only the most commonly interesting statistics.
730 More information can be obtained by calling mallinfo.
733 void __malloc_stats(void);
736 malloc_get_state(void);
738 Returns the state of all malloc variables in an opaque data
739 structure.
741 void* __malloc_get_state(void);
744 malloc_set_state(void* state);
746 Restore the state of all malloc variables from data obtained with
747 malloc_get_state().
749 int __malloc_set_state(void*);
752 posix_memalign(void **memptr, size_t alignment, size_t size);
754 POSIX wrapper like memalign(), checking for validity of size.
756 int __posix_memalign(void **, size_t, size_t);
758 /* mallopt tuning options */
761 M_MXFAST is the maximum request size used for "fastbins", special bins
762 that hold returned chunks without consolidating their spaces. This
763 enables future requests for chunks of the same size to be handled
764 very quickly, but can increase fragmentation, and thus increase the
765 overall memory footprint of a program.
767 This malloc manages fastbins very conservatively yet still
768 efficiently, so fragmentation is rarely a problem for values less
769 than or equal to the default. The maximum supported value of MXFAST
770 is 80. You wouldn't want it any higher than this anyway. Fastbins
771 are designed especially for use with many small structs, objects or
772 strings -- the default handles structs/objects/arrays with sizes up
773 to 8 4byte fields, or small strings representing words, tokens,
774 etc. Using fastbins for larger objects normally worsens
775 fragmentation without improving speed.
777 M_MXFAST is set in REQUEST size units. It is internally used in
778 chunksize units, which adds padding and alignment. You can reduce
779 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
780 algorithm to be a closer approximation of fifo-best-fit in all cases,
781 not just for larger requests, but will generally cause it to be
782 slower.
786 /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
787 #ifndef M_MXFAST
788 #define M_MXFAST 1
789 #endif
791 #ifndef DEFAULT_MXFAST
792 #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
793 #endif
797 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
798 to keep before releasing via malloc_trim in free().
800 Automatic trimming is mainly useful in long-lived programs.
801 Because trimming via sbrk can be slow on some systems, and can
802 sometimes be wasteful (in cases where programs immediately
803 afterward allocate more large chunks) the value should be high
804 enough so that your overall system performance would improve by
805 releasing this much memory.
807 The trim threshold and the mmap control parameters (see below)
808 can be traded off with one another. Trimming and mmapping are
809 two different ways of releasing unused memory back to the
810 system. Between these two, it is often possible to keep
811 system-level demands of a long-lived program down to a bare
812 minimum. For example, in one test suite of sessions measuring
813 the XF86 X server on Linux, using a trim threshold of 128K and a
814 mmap threshold of 192K led to near-minimal long term resource
815 consumption.
817 If you are using this malloc in a long-lived program, it should
818 pay to experiment with these values. As a rough guide, you
819 might set to a value close to the average size of a process
820 (program) running on your system. Releasing this much memory
821 would allow such a process to run in memory. Generally, it's
822 worth it to tune for trimming rather tham memory mapping when a
823 program undergoes phases where several large chunks are
824 allocated and released in ways that can reuse each other's
825 storage, perhaps mixed with phases where there are no such
826 chunks at all. And in well-behaved long-lived programs,
827 controlling release of large blocks via trimming versus mapping
828 is usually faster.
830 However, in most programs, these parameters serve mainly as
831 protection against the system-level effects of carrying around
832 massive amounts of unneeded memory. Since frequent calls to
833 sbrk, mmap, and munmap otherwise degrade performance, the default
834 parameters are set to relatively high values that serve only as
835 safeguards.
837 The trim value It must be greater than page size to have any useful
838 effect. To disable trimming completely, you can set to
839 (unsigned long)(-1)
841 Trim settings interact with fastbin (MXFAST) settings: Unless
842 TRIM_FASTBINS is defined, automatic trimming never takes place upon
843 freeing a chunk with size less than or equal to MXFAST. Trimming is
844 instead delayed until subsequent freeing of larger chunks. However,
845 you can still force an attempted trim by calling malloc_trim.
847 Also, trimming is not generally possible in cases where
848 the main arena is obtained via mmap.
850 Note that the trick some people use of mallocing a huge space and
851 then freeing it at program startup, in an attempt to reserve system
852 memory, doesn't have the intended effect under automatic trimming,
853 since that memory will immediately be returned to the system.
856 #define M_TRIM_THRESHOLD -1
858 #ifndef DEFAULT_TRIM_THRESHOLD
859 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
860 #endif
863 M_TOP_PAD is the amount of extra `padding' space to allocate or
864 retain whenever sbrk is called. It is used in two ways internally:
866 * When sbrk is called to extend the top of the arena to satisfy
867 a new malloc request, this much padding is added to the sbrk
868 request.
870 * When malloc_trim is called automatically from free(),
871 it is used as the `pad' argument.
873 In both cases, the actual amount of padding is rounded
874 so that the end of the arena is always a system page boundary.
876 The main reason for using padding is to avoid calling sbrk so
877 often. Having even a small pad greatly reduces the likelihood
878 that nearly every malloc request during program start-up (or
879 after trimming) will invoke sbrk, which needlessly wastes
880 time.
882 Automatic rounding-up to page-size units is normally sufficient
883 to avoid measurable overhead, so the default is 0. However, in
884 systems where sbrk is relatively slow, it can pay to increase
885 this value, at the expense of carrying around more memory than
886 the program needs.
889 #define M_TOP_PAD -2
891 #ifndef DEFAULT_TOP_PAD
892 #define DEFAULT_TOP_PAD (0)
893 #endif
896 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
897 adjusted MMAP_THRESHOLD.
900 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
901 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
902 #endif
904 #ifndef DEFAULT_MMAP_THRESHOLD_MAX
905 /* For 32-bit platforms we cannot increase the maximum mmap
906 threshold much because it is also the minimum value for the
907 maximum heap size and its alignment. Going above 512k (i.e., 1M
908 for new heaps) wastes too much address space. */
909 # if __WORDSIZE == 32
910 # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
911 # else
912 # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
913 # endif
914 #endif
917 M_MMAP_THRESHOLD is the request size threshold for using mmap()
918 to service a request. Requests of at least this size that cannot
919 be allocated using already-existing space will be serviced via mmap.
920 (If enough normal freed space already exists it is used instead.)
922 Using mmap segregates relatively large chunks of memory so that
923 they can be individually obtained and released from the host
924 system. A request serviced through mmap is never reused by any
925 other request (at least not directly; the system may just so
926 happen to remap successive requests to the same locations).
928 Segregating space in this way has the benefits that:
930 1. Mmapped space can ALWAYS be individually released back
931 to the system, which helps keep the system level memory
932 demands of a long-lived program low.
933 2. Mapped memory can never become `locked' between
934 other chunks, as can happen with normally allocated chunks, which
935 means that even trimming via malloc_trim would not release them.
936 3. On some systems with "holes" in address spaces, mmap can obtain
937 memory that sbrk cannot.
939 However, it has the disadvantages that:
941 1. The space cannot be reclaimed, consolidated, and then
942 used to service later requests, as happens with normal chunks.
943 2. It can lead to more wastage because of mmap page alignment
944 requirements
945 3. It causes malloc performance to be more dependent on host
946 system memory management support routines which may vary in
947 implementation quality and may impose arbitrary
948 limitations. Generally, servicing a request via normal
949 malloc steps is faster than going through a system's mmap.
951 The advantages of mmap nearly always outweigh disadvantages for
952 "large" chunks, but the value of "large" varies across systems. The
953 default is an empirically derived value that works well in most
954 systems.
957 Update in 2006:
958 The above was written in 2001. Since then the world has changed a lot.
959 Memory got bigger. Applications got bigger. The virtual address space
960 layout in 32 bit linux changed.
962 In the new situation, brk() and mmap space is shared and there are no
963 artificial limits on brk size imposed by the kernel. What is more,
964 applications have started using transient allocations larger than the
965 128Kb as was imagined in 2001.
967 The price for mmap is also high now; each time glibc mmaps from the
968 kernel, the kernel is forced to zero out the memory it gives to the
969 application. Zeroing memory is expensive and eats a lot of cache and
970 memory bandwidth. This has nothing to do with the efficiency of the
971 virtual memory system, by doing mmap the kernel just has no choice but
972 to zero.
974 In 2001, the kernel had a maximum size for brk() which was about 800
975 megabytes on 32 bit x86, at that point brk() would hit the first
976 mmaped shared libaries and couldn't expand anymore. With current 2.6
977 kernels, the VA space layout is different and brk() and mmap
978 both can span the entire heap at will.
980 Rather than using a static threshold for the brk/mmap tradeoff,
981 we are now using a simple dynamic one. The goal is still to avoid
982 fragmentation. The old goals we kept are
983 1) try to get the long lived large allocations to use mmap()
984 2) really large allocations should always use mmap()
985 and we're adding now:
986 3) transient allocations should use brk() to avoid forcing the kernel
987 having to zero memory over and over again
989 The implementation works with a sliding threshold, which is by default
990 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
991 out at 128Kb as per the 2001 default.
993 This allows us to satisfy requirement 1) under the assumption that long
994 lived allocations are made early in the process' lifespan, before it has
995 started doing dynamic allocations of the same size (which will
996 increase the threshold).
998 The upperbound on the threshold satisfies requirement 2)
1000 The threshold goes up in value when the application frees memory that was
1001 allocated with the mmap allocator. The idea is that once the application
1002 starts freeing memory of a certain size, it's highly probable that this is
1003 a size the application uses for transient allocations. This estimator
1004 is there to satisfy the new third requirement.
1008 #define M_MMAP_THRESHOLD -3
1010 #ifndef DEFAULT_MMAP_THRESHOLD
1011 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1012 #endif
1015 M_MMAP_MAX is the maximum number of requests to simultaneously
1016 service using mmap. This parameter exists because
1017 some systems have a limited number of internal tables for
1018 use by mmap, and using more than a few of them may degrade
1019 performance.
1021 The default is set to a value that serves only as a safeguard.
1022 Setting to 0 disables use of mmap for servicing large requests.
1025 #define M_MMAP_MAX -4
1027 #ifndef DEFAULT_MMAP_MAX
1028 #define DEFAULT_MMAP_MAX (65536)
1029 #endif
1031 #include <malloc.h>
1033 #ifndef RETURN_ADDRESS
1034 #define RETURN_ADDRESS(X_) (NULL)
1035 #endif
1037 /* On some platforms we can compile internal, not exported functions better.
1038 Let the environment provide a macro and define it to be empty if it
1039 is not available. */
1040 #ifndef internal_function
1041 # define internal_function
1042 #endif
1044 /* Forward declarations. */
1045 struct malloc_chunk;
1046 typedef struct malloc_chunk* mchunkptr;
1048 /* Internal routines. */
1050 static void* _int_malloc(mstate, size_t);
1051 static void _int_free(mstate, mchunkptr, int);
1052 static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
1053 INTERNAL_SIZE_T);
1054 static void* _int_memalign(mstate, size_t, size_t);
1055 static void* _int_valloc(mstate, size_t);
1056 static void* _int_pvalloc(mstate, size_t);
1057 static void malloc_printerr(int action, const char *str, void *ptr);
1059 static void* internal_function mem2mem_check(void *p, size_t sz);
1060 static int internal_function top_check(void);
1061 static void internal_function munmap_chunk(mchunkptr p);
1062 #if HAVE_MREMAP
1063 static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
1064 #endif
1066 static void* malloc_check(size_t sz, const void *caller);
1067 static void free_check(void* mem, const void *caller);
1068 static void* realloc_check(void* oldmem, size_t bytes,
1069 const void *caller);
1070 static void* memalign_check(size_t alignment, size_t bytes,
1071 const void *caller);
1072 /* These routines are never needed in this configuration. */
1073 static void* malloc_atfork(size_t sz, const void *caller);
1074 static void free_atfork(void* mem, const void *caller);
1077 /* ------------- Optional versions of memcopy ---------------- */
1081 Note: memcpy is ONLY invoked with non-overlapping regions,
1082 so the (usually slower) memmove is not needed.
1085 #define MALLOC_COPY(dest, src, nbytes) memcpy(dest, src, nbytes)
1086 #define MALLOC_ZERO(dest, nbytes) memset(dest, 0, nbytes)
1089 /* ------------------ MMAP support ------------------ */
1092 #include <fcntl.h>
1093 #include <sys/mman.h>
1095 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1096 # define MAP_ANONYMOUS MAP_ANON
1097 #endif
1099 #ifndef MAP_NORESERVE
1100 # define MAP_NORESERVE 0
1101 #endif
1103 #define MMAP(addr, size, prot, flags) \
1104 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1108 ----------------------- Chunk representations -----------------------
1113 This struct declaration is misleading (but accurate and necessary).
1114 It declares a "view" into memory allowing access to necessary
1115 fields at known offsets from a given base. See explanation below.
1118 struct malloc_chunk {
1120 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
1121 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
1123 struct malloc_chunk* fd; /* double links -- used only if free. */
1124 struct malloc_chunk* bk;
1126 /* Only used for large blocks: pointer to next larger size. */
1127 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1128 struct malloc_chunk* bk_nextsize;
1133 malloc_chunk details:
1135 (The following includes lightly edited explanations by Colin Plumb.)
1137 Chunks of memory are maintained using a `boundary tag' method as
1138 described in e.g., Knuth or Standish. (See the paper by Paul
1139 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1140 survey of such techniques.) Sizes of free chunks are stored both
1141 in the front of each chunk and at the end. This makes
1142 consolidating fragmented chunks into bigger chunks very fast. The
1143 size fields also hold bits representing whether chunks are free or
1144 in use.
1146 An allocated chunk looks like this:
1149 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1150 | Size of previous chunk, if allocated | |
1151 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1152 | Size of chunk, in bytes |M|P|
1153 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1154 | User data starts here... .
1156 . (malloc_usable_size() bytes) .
1158 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1159 | Size of chunk |
1160 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1163 Where "chunk" is the front of the chunk for the purpose of most of
1164 the malloc code, but "mem" is the pointer that is returned to the
1165 user. "Nextchunk" is the beginning of the next contiguous chunk.
1167 Chunks always begin on even word boundries, so the mem portion
1168 (which is returned to the user) is also on an even word boundary, and
1169 thus at least double-word aligned.
1171 Free chunks are stored in circular doubly-linked lists, and look like this:
1173 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1174 | Size of previous chunk |
1175 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1176 `head:' | Size of chunk, in bytes |P|
1177 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1178 | Forward pointer to next chunk in list |
1179 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1180 | Back pointer to previous chunk in list |
1181 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1182 | Unused space (may be 0 bytes long) .
1185 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1186 `foot:' | Size of chunk, in bytes |
1187 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1189 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1190 chunk size (which is always a multiple of two words), is an in-use
1191 bit for the *previous* chunk. If that bit is *clear*, then the
1192 word before the current chunk size contains the previous chunk
1193 size, and can be used to find the front of the previous chunk.
1194 The very first chunk allocated always has this bit set,
1195 preventing access to non-existent (or non-owned) memory. If
1196 prev_inuse is set for any given chunk, then you CANNOT determine
1197 the size of the previous chunk, and might even get a memory
1198 addressing fault when trying to do so.
1200 Note that the `foot' of the current chunk is actually represented
1201 as the prev_size of the NEXT chunk. This makes it easier to
1202 deal with alignments etc but can be very confusing when trying
1203 to extend or adapt this code.
1205 The two exceptions to all this are
1207 1. The special chunk `top' doesn't bother using the
1208 trailing size field since there is no next contiguous chunk
1209 that would have to index off it. After initialization, `top'
1210 is forced to always exist. If it would become less than
1211 MINSIZE bytes long, it is replenished.
1213 2. Chunks allocated via mmap, which have the second-lowest-order
1214 bit M (IS_MMAPPED) set in their size fields. Because they are
1215 allocated one-by-one, each must contain its own trailing size field.
1220 ---------- Size and alignment checks and conversions ----------
1223 /* conversion from malloc headers to user pointers, and back */
1225 #define chunk2mem(p) ((void*)((char*)(p) + 2*SIZE_SZ))
1226 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1228 /* The smallest possible chunk */
1229 #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1231 /* The smallest size we can malloc is an aligned minimal chunk */
1233 #define MINSIZE \
1234 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1236 /* Check if m has acceptable alignment */
1238 #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1240 #define misaligned_chunk(p) \
1241 ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
1242 & MALLOC_ALIGN_MASK)
1246 Check if a request is so large that it would wrap around zero when
1247 padded and aligned. To simplify some other code, the bound is made
1248 low enough so that adding MINSIZE will also not wrap around zero.
1251 #define REQUEST_OUT_OF_RANGE(req) \
1252 ((unsigned long)(req) >= \
1253 (unsigned long)(INTERNAL_SIZE_T)(-2 * MINSIZE))
1255 /* pad request bytes into a usable size -- internal version */
1257 #define request2size(req) \
1258 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1259 MINSIZE : \
1260 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1262 /* Same, except also perform argument check */
1264 #define checked_request2size(req, sz) \
1265 if (REQUEST_OUT_OF_RANGE(req)) { \
1266 __set_errno (ENOMEM); \
1267 return 0; \
1269 (sz) = request2size(req);
1272 --------------- Physical chunk operations ---------------
1276 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1277 #define PREV_INUSE 0x1
1279 /* extract inuse bit of previous chunk */
1280 #define prev_inuse(p) ((p)->size & PREV_INUSE)
1283 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1284 #define IS_MMAPPED 0x2
1286 /* check for mmap()'ed chunk */
1287 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1290 /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1291 from a non-main arena. This is only set immediately before handing
1292 the chunk to the user, if necessary. */
1293 #define NON_MAIN_ARENA 0x4
1295 /* check for chunk from non-main arena */
1296 #define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)
1300 Bits to mask off when extracting size
1302 Note: IS_MMAPPED is intentionally not masked off from size field in
1303 macros for which mmapped chunks should never be seen. This should
1304 cause helpful core dumps to occur if it is tried by accident by
1305 people extending or adapting this malloc.
1307 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED|NON_MAIN_ARENA)
1309 /* Get size, ignoring use bits */
1310 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
1313 /* Ptr to next physical malloc_chunk. */
1314 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~SIZE_BITS) ))
1316 /* Ptr to previous physical malloc_chunk */
1317 #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
1319 /* Treat space at ptr + offset as a chunk */
1320 #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
1322 /* extract p's inuse bit */
1323 #define inuse(p)\
1324 ((((mchunkptr)(((char*)(p))+((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)
1326 /* set/clear chunk as being inuse without otherwise disturbing */
1327 #define set_inuse(p)\
1328 ((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE
1330 #define clear_inuse(p)\
1331 ((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)
1334 /* check/set/clear inuse bits in known places */
1335 #define inuse_bit_at_offset(p, s)\
1336 (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
1338 #define set_inuse_bit_at_offset(p, s)\
1339 (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
1341 #define clear_inuse_bit_at_offset(p, s)\
1342 (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
1345 /* Set size at head, without disturbing its use bit */
1346 #define set_head_size(p, s) ((p)->size = (((p)->size & SIZE_BITS) | (s)))
1348 /* Set size/use field */
1349 #define set_head(p, s) ((p)->size = (s))
1351 /* Set size at footer (only when chunk is not in use) */
1352 #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
1356 -------------------- Internal data structures --------------------
1358 All internal state is held in an instance of malloc_state defined
1359 below. There are no other static variables, except in two optional
1360 cases:
1361 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1362 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1363 for mmap.
1365 Beware of lots of tricks that minimize the total bookkeeping space
1366 requirements. The result is a little over 1K bytes (for 4byte
1367 pointers and size_t.)
1371 Bins
1373 An array of bin headers for free chunks. Each bin is doubly
1374 linked. The bins are approximately proportionally (log) spaced.
1375 There are a lot of these bins (128). This may look excessive, but
1376 works very well in practice. Most bins hold sizes that are
1377 unusual as malloc request sizes, but are more usual for fragments
1378 and consolidated sets of chunks, which is what these bins hold, so
1379 they can be found quickly. All procedures maintain the invariant
1380 that no consolidated chunk physically borders another one, so each
1381 chunk in a list is known to be preceeded and followed by either
1382 inuse chunks or the ends of memory.
1384 Chunks in bins are kept in size order, with ties going to the
1385 approximately least recently used chunk. Ordering isn't needed
1386 for the small bins, which all contain the same-sized chunks, but
1387 facilitates best-fit allocation for larger chunks. These lists
1388 are just sequential. Keeping them in order almost never requires
1389 enough traversal to warrant using fancier ordered data
1390 structures.
1392 Chunks of the same size are linked with the most
1393 recently freed at the front, and allocations are taken from the
1394 back. This results in LRU (FIFO) allocation order, which tends
1395 to give each chunk an equal opportunity to be consolidated with
1396 adjacent freed chunks, resulting in larger free chunks and less
1397 fragmentation.
1399 To simplify use in double-linked lists, each bin header acts
1400 as a malloc_chunk. This avoids special-casing for headers.
1401 But to conserve space and improve locality, we allocate
1402 only the fd/bk pointers of bins, and then use repositioning tricks
1403 to treat these as the fields of a malloc_chunk*.
1406 typedef struct malloc_chunk* mbinptr;
1408 /* addressing -- note that bin_at(0) does not exist */
1409 #define bin_at(m, i) \
1410 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1411 - offsetof (struct malloc_chunk, fd))
1413 /* analog of ++bin */
1414 #define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1)))
1416 /* Reminders about list directionality within bins */
1417 #define first(b) ((b)->fd)
1418 #define last(b) ((b)->bk)
1420 /* Take a chunk off a bin list */
1421 #define unlink(P, BK, FD) { \
1422 FD = P->fd; \
1423 BK = P->bk; \
1424 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
1425 malloc_printerr (check_action, "corrupted double-linked list", P); \
1426 else { \
1427 FD->bk = BK; \
1428 BK->fd = FD; \
1429 if (!in_smallbin_range (P->size) \
1430 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \
1431 assert (P->fd_nextsize->bk_nextsize == P); \
1432 assert (P->bk_nextsize->fd_nextsize == P); \
1433 if (FD->fd_nextsize == NULL) { \
1434 if (P->fd_nextsize == P) \
1435 FD->fd_nextsize = FD->bk_nextsize = FD; \
1436 else { \
1437 FD->fd_nextsize = P->fd_nextsize; \
1438 FD->bk_nextsize = P->bk_nextsize; \
1439 P->fd_nextsize->bk_nextsize = FD; \
1440 P->bk_nextsize->fd_nextsize = FD; \
1442 } else { \
1443 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \
1444 P->bk_nextsize->fd_nextsize = P->fd_nextsize; \
1451 Indexing
1453 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1454 8 bytes apart. Larger bins are approximately logarithmically spaced:
1456 64 bins of size 8
1457 32 bins of size 64
1458 16 bins of size 512
1459 8 bins of size 4096
1460 4 bins of size 32768
1461 2 bins of size 262144
1462 1 bin of size what's left
1464 There is actually a little bit of slop in the numbers in bin_index
1465 for the sake of speed. This makes no difference elsewhere.
1467 The bins top out around 1MB because we expect to service large
1468 requests via mmap.
1471 #define NBINS 128
1472 #define NSMALLBINS 64
1473 #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1474 #define MIN_LARGE_SIZE (NSMALLBINS * SMALLBIN_WIDTH)
1476 #define in_smallbin_range(sz) \
1477 ((unsigned long)(sz) < (unsigned long)MIN_LARGE_SIZE)
1479 #define smallbin_index(sz) \
1480 (SMALLBIN_WIDTH == 16 ? (((unsigned)(sz)) >> 4) : (((unsigned)(sz)) >> 3))
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 // XXX It remains to be seen whether it is good to keep the widths of
1491 // XXX the buckets the same or whether it should be scaled by a factor
1492 // XXX of two as well.
1493 #define largebin_index_64(sz) \
1494 (((((unsigned long)(sz)) >> 6) <= 48)? 48 + (((unsigned long)(sz)) >> 6): \
1495 ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \
1496 ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \
1497 ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \
1498 ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \
1499 126)
1501 #define largebin_index(sz) \
1502 (SIZE_SZ == 8 ? largebin_index_64 (sz) : largebin_index_32 (sz))
1504 #define bin_index(sz) \
1505 ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz))
1509 Unsorted chunks
1511 All remainders from chunk splits, as well as all returned chunks,
1512 are first placed in the "unsorted" bin. They are then placed
1513 in regular bins after malloc gives them ONE chance to be used before
1514 binning. So, basically, the unsorted_chunks list acts as a queue,
1515 with chunks being placed on it in free (and malloc_consolidate),
1516 and taken off (to be either used or placed in bins) in malloc.
1518 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1519 does not have to be taken into account in size comparisons.
1522 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1523 #define unsorted_chunks(M) (bin_at(M, 1))
1528 The top-most available chunk (i.e., the one bordering the end of
1529 available memory) is treated specially. It is never included in
1530 any bin, is used only if no other chunk is available, and is
1531 released back to the system if it is very large (see
1532 M_TRIM_THRESHOLD). Because top initially
1533 points to its own bin with initial zero size, thus forcing
1534 extension on the first malloc request, we avoid having any special
1535 code in malloc to check whether it even exists yet. But we still
1536 need to do so when getting memory from system, so we make
1537 initial_top treat the bin as a legal but unusable chunk during the
1538 interval between initialization and the first call to
1539 sysmalloc. (This is somewhat delicate, since it relies on
1540 the 2 preceding words to be zero during this interval as well.)
1543 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1544 #define initial_top(M) (unsorted_chunks(M))
1547 Binmap
1549 To help compensate for the large number of bins, a one-level index
1550 structure is used for bin-by-bin searching. `binmap' is a
1551 bitvector recording whether bins are definitely empty so they can
1552 be skipped over during during traversals. The bits are NOT always
1553 cleared as soon as bins are empty, but instead only
1554 when they are noticed to be empty during traversal in malloc.
1557 /* Conservatively use 32 bits per map word, even if on 64bit system */
1558 #define BINMAPSHIFT 5
1559 #define BITSPERMAP (1U << BINMAPSHIFT)
1560 #define BINMAPSIZE (NBINS / BITSPERMAP)
1562 #define idx2block(i) ((i) >> BINMAPSHIFT)
1563 #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1))))
1565 #define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i))
1566 #define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i)))
1567 #define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i))
1570 Fastbins
1572 An array of lists holding recently freed small chunks. Fastbins
1573 are not doubly linked. It is faster to single-link them, and
1574 since chunks are never removed from the middles of these lists,
1575 double linking is not necessary. Also, unlike regular bins, they
1576 are not even processed in FIFO order (they use faster LIFO) since
1577 ordering doesn't much matter in the transient contexts in which
1578 fastbins are normally used.
1580 Chunks in fastbins keep their inuse bit set, so they cannot
1581 be consolidated with other free chunks. malloc_consolidate
1582 releases all chunks in fastbins and consolidates them with
1583 other free chunks.
1586 typedef struct malloc_chunk* mfastbinptr;
1587 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1589 /* offset 2 to use otherwise unindexable first 2 bins */
1590 #define fastbin_index(sz) \
1591 ((((unsigned int)(sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1594 /* The maximum fastbin request size we support */
1595 #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1597 #define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1)
1600 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1601 that triggers automatic consolidation of possibly-surrounding
1602 fastbin chunks. This is a heuristic, so the exact value should not
1603 matter too much. It is defined at half the default trim threshold as a
1604 compromise heuristic to only attempt consolidation if it is likely
1605 to lead to trimming. However, it is not dynamically tunable, since
1606 consolidation reduces fragmentation surrounding large chunks even
1607 if trimming is not used.
1610 #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1613 Since the lowest 2 bits in max_fast don't matter in size comparisons,
1614 they are used as flags.
1618 FASTCHUNKS_BIT held in max_fast indicates that there are probably
1619 some fastbin chunks. It is set true on entering a chunk into any
1620 fastbin, and cleared only in malloc_consolidate.
1622 The truth value is inverted so that have_fastchunks will be true
1623 upon startup (since statics are zero-filled), simplifying
1624 initialization checks.
1627 #define FASTCHUNKS_BIT (1U)
1629 #define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
1630 #define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT)
1631 #define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT)
1634 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1635 regions. Otherwise, contiguity is exploited in merging together,
1636 when possible, results from consecutive MORECORE calls.
1638 The initial value comes from MORECORE_CONTIGUOUS, but is
1639 changed dynamically if mmap is ever used as an sbrk substitute.
1642 #define NONCONTIGUOUS_BIT (2U)
1644 #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1645 #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1646 #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1647 #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1650 Set value of max_fast.
1651 Use impossibly small value if 0.
1652 Precondition: there are no existing fastbin chunks.
1653 Setting the value clears fastchunk bit but preserves noncontiguous bit.
1656 #define set_max_fast(s) \
1657 global_max_fast = (((s) == 0) \
1658 ? SMALLBIN_WIDTH: ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1659 #define get_max_fast() global_max_fast
1663 ----------- Internal state representation and initialization -----------
1666 struct malloc_state {
1667 /* Serialize access. */
1668 mutex_t mutex;
1670 /* Flags (formerly in max_fast). */
1671 int flags;
1673 #if THREAD_STATS
1674 /* Statistics for locking. Only used if THREAD_STATS is defined. */
1675 long stat_lock_direct, stat_lock_loop, stat_lock_wait;
1676 #endif
1678 /* Fastbins */
1679 mfastbinptr fastbinsY[NFASTBINS];
1681 /* Base of the topmost chunk -- not otherwise kept in a bin */
1682 mchunkptr top;
1684 /* The remainder from the most recent split of a small request */
1685 mchunkptr last_remainder;
1687 /* Normal bins packed as described above */
1688 mchunkptr bins[NBINS * 2 - 2];
1690 /* Bitmap of bins */
1691 unsigned int binmap[BINMAPSIZE];
1693 /* Linked list */
1694 struct malloc_state *next;
1696 #ifdef PER_THREAD
1697 /* Linked list for free arenas. */
1698 struct malloc_state *next_free;
1699 #endif
1701 /* Memory allocated from the system in this arena. */
1702 INTERNAL_SIZE_T system_mem;
1703 INTERNAL_SIZE_T max_system_mem;
1706 struct malloc_par {
1707 /* Tunable parameters */
1708 unsigned long trim_threshold;
1709 INTERNAL_SIZE_T top_pad;
1710 INTERNAL_SIZE_T mmap_threshold;
1711 #ifdef PER_THREAD
1712 INTERNAL_SIZE_T arena_test;
1713 INTERNAL_SIZE_T arena_max;
1714 #endif
1716 /* Memory map support */
1717 int n_mmaps;
1718 int n_mmaps_max;
1719 int max_n_mmaps;
1720 /* the mmap_threshold is dynamic, until the user sets
1721 it manually, at which point we need to disable any
1722 dynamic behavior. */
1723 int no_dyn_threshold;
1725 /* Statistics */
1726 INTERNAL_SIZE_T mmapped_mem;
1727 /*INTERNAL_SIZE_T sbrked_mem;*/
1728 /*INTERNAL_SIZE_T max_sbrked_mem;*/
1729 INTERNAL_SIZE_T max_mmapped_mem;
1730 INTERNAL_SIZE_T max_total_mem; /* only kept for NO_THREADS */
1732 /* First address handed out by MORECORE/sbrk. */
1733 char* sbrk_base;
1736 /* There are several instances of this struct ("arenas") in this
1737 malloc. If you are adapting this malloc in a way that does NOT use
1738 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1739 before using. This malloc relies on the property that malloc_state
1740 is initialized to all zeroes (as is true of C statics). */
1742 static struct malloc_state main_arena =
1744 .mutex = MUTEX_INITIALIZER,
1745 .next = &main_arena
1748 /* There is only one instance of the malloc parameters. */
1750 static struct malloc_par mp_ =
1752 .top_pad = DEFAULT_TOP_PAD,
1753 .n_mmaps_max = DEFAULT_MMAP_MAX,
1754 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1755 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1756 #ifdef PER_THREAD
1757 # define NARENAS_FROM_NCORES(n) ((n) * (sizeof(long) == 4 ? 2 : 8))
1758 .arena_test = NARENAS_FROM_NCORES (1)
1759 #endif
1763 #ifdef PER_THREAD
1764 /* Non public mallopt parameters. */
1765 #define M_ARENA_TEST -7
1766 #define M_ARENA_MAX -8
1767 #endif
1770 /* Maximum size of memory handled in fastbins. */
1771 static INTERNAL_SIZE_T global_max_fast;
1774 Initialize a malloc_state struct.
1776 This is called only from within malloc_consolidate, which needs
1777 be called in the same contexts anyway. It is never called directly
1778 outside of malloc_consolidate because some optimizing compilers try
1779 to inline it at all call points, which turns out not to be an
1780 optimization at all. (Inlining it in malloc_consolidate is fine though.)
1783 static void 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) {
1790 bin = bin_at(av,i);
1791 bin->fd = bin->bk = bin;
1794 #if MORECORE_CONTIGUOUS
1795 if (av != &main_arena)
1796 #endif
1797 set_noncontiguous(av);
1798 if (av == &main_arena)
1799 set_max_fast(DEFAULT_MXFAST);
1800 av->flags |= FASTCHUNKS_BIT;
1802 av->top = initial_top(av);
1806 Other internal utilities operating on mstates
1809 static void* sysmalloc(INTERNAL_SIZE_T, mstate);
1810 static int systrim(size_t, mstate);
1811 static void malloc_consolidate(mstate);
1814 /* -------------- Early definitions for debugging hooks ---------------- */
1816 /* Define and initialize the hook variables. These weak definitions must
1817 appear before any use of the variables in a function (arena.c uses one). */
1818 #ifndef weak_variable
1819 /* In GNU libc we want the hook variables to be weak definitions to
1820 avoid a problem with Emacs. */
1821 # define weak_variable weak_function
1822 #endif
1824 /* Forward declarations. */
1825 static void* malloc_hook_ini __MALLOC_P ((size_t sz,
1826 const __malloc_ptr_t caller));
1827 static void* realloc_hook_ini __MALLOC_P ((void* ptr, size_t sz,
1828 const __malloc_ptr_t caller));
1829 static void* memalign_hook_ini __MALLOC_P ((size_t alignment, size_t sz,
1830 const __malloc_ptr_t caller));
1832 void weak_variable (*__malloc_initialize_hook) (void) = NULL;
1833 void weak_variable (*__free_hook) (__malloc_ptr_t __ptr,
1834 const __malloc_ptr_t) = NULL;
1835 __malloc_ptr_t weak_variable (*__malloc_hook)
1836 (size_t __size, const __malloc_ptr_t) = malloc_hook_ini;
1837 __malloc_ptr_t weak_variable (*__realloc_hook)
1838 (__malloc_ptr_t __ptr, size_t __size, const __malloc_ptr_t)
1839 = realloc_hook_ini;
1840 __malloc_ptr_t weak_variable (*__memalign_hook)
1841 (size_t __alignment, size_t __size, const __malloc_ptr_t)
1842 = memalign_hook_ini;
1843 void weak_variable (*__after_morecore_hook) (void) = NULL;
1846 /* ---------------- Error behavior ------------------------------------ */
1848 #ifndef DEFAULT_CHECK_ACTION
1849 #define DEFAULT_CHECK_ACTION 3
1850 #endif
1852 static int check_action = DEFAULT_CHECK_ACTION;
1855 /* ------------------ Testing support ----------------------------------*/
1857 static int perturb_byte;
1859 #define alloc_perturb(p, n) memset (p, (perturb_byte ^ 0xff) & 0xff, n)
1860 #define free_perturb(p, n) memset (p, perturb_byte & 0xff, n)
1863 /* ------------------- Support for multiple arenas -------------------- */
1864 #include "arena.c"
1867 Debugging support
1869 These routines make a number of assertions about the states
1870 of data structures that should be true at all times. If any
1871 are not true, it's very likely that a user program has somehow
1872 trashed memory. (It's also possible that there is a coding error
1873 in malloc. In which case, please report it!)
1876 #if ! MALLOC_DEBUG
1878 #define check_chunk(A,P)
1879 #define check_free_chunk(A,P)
1880 #define check_inuse_chunk(A,P)
1881 #define check_remalloced_chunk(A,P,N)
1882 #define check_malloced_chunk(A,P,N)
1883 #define check_malloc_state(A)
1885 #else
1887 #define check_chunk(A,P) do_check_chunk(A,P)
1888 #define check_free_chunk(A,P) do_check_free_chunk(A,P)
1889 #define check_inuse_chunk(A,P) do_check_inuse_chunk(A,P)
1890 #define check_remalloced_chunk(A,P,N) do_check_remalloced_chunk(A,P,N)
1891 #define check_malloced_chunk(A,P,N) do_check_malloced_chunk(A,P,N)
1892 #define check_malloc_state(A) do_check_malloc_state(A)
1895 Properties of all chunks
1898 static void do_check_chunk(mstate av, mchunkptr p)
1900 unsigned long sz = chunksize(p);
1901 /* min and max possible addresses assuming contiguous allocation */
1902 char* max_address = (char*)(av->top) + chunksize(av->top);
1903 char* min_address = max_address - av->system_mem;
1905 if (!chunk_is_mmapped(p)) {
1907 /* Has legal address ... */
1908 if (p != av->top) {
1909 if (contiguous(av)) {
1910 assert(((char*)p) >= min_address);
1911 assert(((char*)p + sz) <= ((char*)(av->top)));
1914 else {
1915 /* top size is always at least MINSIZE */
1916 assert((unsigned long)(sz) >= MINSIZE);
1917 /* top predecessor always marked inuse */
1918 assert(prev_inuse(p));
1922 else {
1923 /* address is outside main heap */
1924 if (contiguous(av) && av->top != initial_top(av)) {
1925 assert(((char*)p) < min_address || ((char*)p) >= max_address);
1927 /* chunk is page-aligned */
1928 assert(((p->prev_size + sz) & (GLRO(dl_pagesize)-1)) == 0);
1929 /* mem is aligned */
1930 assert(aligned_OK(chunk2mem(p)));
1935 Properties of free chunks
1938 static void do_check_free_chunk(mstate av, mchunkptr p)
1940 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
1941 mchunkptr next = chunk_at_offset(p, sz);
1943 do_check_chunk(av, p);
1945 /* Chunk must claim to be free ... */
1946 assert(!inuse(p));
1947 assert (!chunk_is_mmapped(p));
1949 /* Unless a special marker, must have OK fields */
1950 if ((unsigned long)(sz) >= MINSIZE)
1952 assert((sz & MALLOC_ALIGN_MASK) == 0);
1953 assert(aligned_OK(chunk2mem(p)));
1954 /* ... matching footer field */
1955 assert(next->prev_size == sz);
1956 /* ... and is fully consolidated */
1957 assert(prev_inuse(p));
1958 assert (next == av->top || inuse(next));
1960 /* ... and has minimally sane links */
1961 assert(p->fd->bk == p);
1962 assert(p->bk->fd == p);
1964 else /* markers are always of size SIZE_SZ */
1965 assert(sz == SIZE_SZ);
1969 Properties of inuse chunks
1972 static void do_check_inuse_chunk(mstate av, mchunkptr p)
1974 mchunkptr next;
1976 do_check_chunk(av, p);
1978 if (chunk_is_mmapped(p))
1979 return; /* mmapped chunks have no next/prev */
1981 /* Check whether it claims to be in use ... */
1982 assert(inuse(p));
1984 next = next_chunk(p);
1986 /* ... and is surrounded by OK chunks.
1987 Since more things can be checked with free chunks than inuse ones,
1988 if an inuse chunk borders them and debug is on, it's worth doing them.
1990 if (!prev_inuse(p)) {
1991 /* Note that we cannot even look at prev unless it is not inuse */
1992 mchunkptr prv = prev_chunk(p);
1993 assert(next_chunk(prv) == p);
1994 do_check_free_chunk(av, prv);
1997 if (next == av->top) {
1998 assert(prev_inuse(next));
1999 assert(chunksize(next) >= MINSIZE);
2001 else if (!inuse(next))
2002 do_check_free_chunk(av, next);
2006 Properties of chunks recycled from fastbins
2009 static void do_check_remalloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2011 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
2013 if (!chunk_is_mmapped(p)) {
2014 assert(av == arena_for_chunk(p));
2015 if (chunk_non_main_arena(p))
2016 assert(av != &main_arena);
2017 else
2018 assert(av == &main_arena);
2021 do_check_inuse_chunk(av, p);
2023 /* Legal size ... */
2024 assert((sz & MALLOC_ALIGN_MASK) == 0);
2025 assert((unsigned long)(sz) >= MINSIZE);
2026 /* ... and alignment */
2027 assert(aligned_OK(chunk2mem(p)));
2028 /* chunk is less than MINSIZE more than request */
2029 assert((long)(sz) - (long)(s) >= 0);
2030 assert((long)(sz) - (long)(s + MINSIZE) < 0);
2034 Properties of nonrecycled chunks at the point they are malloced
2037 static void do_check_malloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2039 /* same as recycled case ... */
2040 do_check_remalloced_chunk(av, p, s);
2043 ... plus, must obey implementation invariant that prev_inuse is
2044 always true of any allocated chunk; i.e., that each allocated
2045 chunk borders either a previously allocated and still in-use
2046 chunk, or the base of its memory arena. This is ensured
2047 by making all allocations from the `lowest' part of any found
2048 chunk. This does not necessarily hold however for chunks
2049 recycled via fastbins.
2052 assert(prev_inuse(p));
2057 Properties of malloc_state.
2059 This may be useful for debugging malloc, as well as detecting user
2060 programmer errors that somehow write into malloc_state.
2062 If you are extending or experimenting with this malloc, you can
2063 probably figure out how to hack this routine to print out or
2064 display chunk addresses, sizes, bins, and other instrumentation.
2067 static void do_check_malloc_state(mstate av)
2069 int i;
2070 mchunkptr p;
2071 mchunkptr q;
2072 mbinptr b;
2073 unsigned int idx;
2074 INTERNAL_SIZE_T size;
2075 unsigned long total = 0;
2076 int max_fast_bin;
2078 /* internal size_t must be no wider than pointer type */
2079 assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*));
2081 /* alignment is a power of 2 */
2082 assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0);
2084 /* cannot run remaining checks until fully initialized */
2085 if (av->top == 0 || av->top == initial_top(av))
2086 return;
2088 /* pagesize is a power of 2 */
2089 assert((GLRO(dl_pagesize) & (GLRO(dl_pagesize)-1)) == 0);
2091 /* A contiguous main_arena is consistent with sbrk_base. */
2092 if (av == &main_arena && contiguous(av))
2093 assert((char*)mp_.sbrk_base + av->system_mem ==
2094 (char*)av->top + chunksize(av->top));
2096 /* properties of fastbins */
2098 /* max_fast is in allowed range */
2099 assert((get_max_fast () & ~1) <= request2size(MAX_FAST_SIZE));
2101 max_fast_bin = fastbin_index(get_max_fast ());
2103 for (i = 0; i < NFASTBINS; ++i) {
2104 p = fastbin (av, i);
2106 /* The following test can only be performed for the main arena.
2107 While mallopt calls malloc_consolidate to get rid of all fast
2108 bins (especially those larger than the new maximum) this does
2109 only happen for the main arena. Trying to do this for any
2110 other arena would mean those arenas have to be locked and
2111 malloc_consolidate be called for them. This is excessive. And
2112 even if this is acceptable to somebody it still cannot solve
2113 the problem completely since if the arena is locked a
2114 concurrent malloc call might create a new arena which then
2115 could use the newly invalid fast bins. */
2117 /* all bins past max_fast are empty */
2118 if (av == &main_arena && i > max_fast_bin)
2119 assert(p == 0);
2121 while (p != 0) {
2122 /* each chunk claims to be inuse */
2123 do_check_inuse_chunk(av, p);
2124 total += chunksize(p);
2125 /* chunk belongs in this bin */
2126 assert(fastbin_index(chunksize(p)) == i);
2127 p = p->fd;
2131 if (total != 0)
2132 assert(have_fastchunks(av));
2133 else if (!have_fastchunks(av))
2134 assert(total == 0);
2136 /* check normal bins */
2137 for (i = 1; i < NBINS; ++i) {
2138 b = bin_at(av,i);
2140 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2141 if (i >= 2) {
2142 unsigned int binbit = get_binmap(av,i);
2143 int empty = last(b) == b;
2144 if (!binbit)
2145 assert(empty);
2146 else if (!empty)
2147 assert(binbit);
2150 for (p = last(b); p != b; p = p->bk) {
2151 /* each chunk claims to be free */
2152 do_check_free_chunk(av, p);
2153 size = chunksize(p);
2154 total += size;
2155 if (i >= 2) {
2156 /* chunk belongs in bin */
2157 idx = bin_index(size);
2158 assert(idx == i);
2159 /* lists are sorted */
2160 assert(p->bk == b ||
2161 (unsigned long)chunksize(p->bk) >= (unsigned long)chunksize(p));
2163 if (!in_smallbin_range(size))
2165 if (p->fd_nextsize != NULL)
2167 if (p->fd_nextsize == p)
2168 assert (p->bk_nextsize == p);
2169 else
2171 if (p->fd_nextsize == first (b))
2172 assert (chunksize (p) < chunksize (p->fd_nextsize));
2173 else
2174 assert (chunksize (p) > chunksize (p->fd_nextsize));
2176 if (p == first (b))
2177 assert (chunksize (p) > chunksize (p->bk_nextsize));
2178 else
2179 assert (chunksize (p) < chunksize (p->bk_nextsize));
2182 else
2183 assert (p->bk_nextsize == NULL);
2185 } else if (!in_smallbin_range(size))
2186 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2187 /* chunk is followed by a legal chain of inuse chunks */
2188 for (q = next_chunk(p);
2189 (q != av->top && inuse(q) &&
2190 (unsigned long)(chunksize(q)) >= MINSIZE);
2191 q = next_chunk(q))
2192 do_check_inuse_chunk(av, q);
2196 /* top chunk is OK */
2197 check_chunk(av, av->top);
2199 /* sanity checks for statistics */
2201 assert(mp_.n_mmaps <= mp_.max_n_mmaps);
2203 assert((unsigned long)(av->system_mem) <=
2204 (unsigned long)(av->max_system_mem));
2206 assert((unsigned long)(mp_.mmapped_mem) <=
2207 (unsigned long)(mp_.max_mmapped_mem));
2209 #endif
2212 /* ----------------- Support for debugging hooks -------------------- */
2213 #include "hooks.c"
2216 /* ----------- Routines dealing with system allocation -------------- */
2219 sysmalloc handles malloc cases requiring more memory from the system.
2220 On entry, it is assumed that av->top does not have enough
2221 space to service request for nb bytes, thus requiring that av->top
2222 be extended or replaced.
2225 static void* sysmalloc(INTERNAL_SIZE_T nb, mstate av)
2227 mchunkptr old_top; /* incoming value of av->top */
2228 INTERNAL_SIZE_T old_size; /* its size */
2229 char* old_end; /* its end address */
2231 long size; /* arg to first MORECORE or mmap call */
2232 char* brk; /* return value from MORECORE */
2234 long correction; /* arg to 2nd MORECORE call */
2235 char* snd_brk; /* 2nd return val */
2237 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2238 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2239 char* aligned_brk; /* aligned offset into brk */
2241 mchunkptr p; /* the allocated/returned chunk */
2242 mchunkptr remainder; /* remainder from allocation */
2243 unsigned long remainder_size; /* its size */
2245 unsigned long sum; /* for updating stats */
2247 size_t pagemask = GLRO(dl_pagesize) - 1;
2248 bool tried_mmap = false;
2252 If have mmap, and the request size meets the mmap threshold, and
2253 the system supports mmap, and there are few enough currently
2254 allocated mmapped regions, try to directly map this request
2255 rather than expanding top.
2258 if ((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) &&
2259 (mp_.n_mmaps < mp_.n_mmaps_max)) {
2261 char* mm; /* return value from mmap call*/
2263 try_mmap:
2265 Round up size to nearest page. For mmapped chunks, the overhead
2266 is one SIZE_SZ unit larger than for normal chunks, because there
2267 is no following chunk whose prev_size field could be used.
2269 See the front_misalign handling below, for glibc there is no
2270 need for further alignments. */
2271 size = (nb + SIZE_SZ + pagemask) & ~pagemask;
2272 tried_mmap = true;
2274 /* Don't try if size wraps around 0 */
2275 if ((unsigned long)(size) > (unsigned long)(nb)) {
2277 mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, 0));
2279 if (mm != MAP_FAILED) {
2282 The offset to the start of the mmapped region is stored
2283 in the prev_size field of the chunk. This allows us to adjust
2284 returned start address to meet alignment requirements here
2285 and in memalign(), and still be able to compute proper
2286 address argument for later munmap in free() and realloc().
2288 For glibc, chunk2mem increases the address by 2*SIZE_SZ and
2289 MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
2290 aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
2291 assert (((INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK) == 0);
2293 p = (mchunkptr)mm;
2294 set_head(p, size|IS_MMAPPED);
2296 /* update statistics */
2298 if (++mp_.n_mmaps > mp_.max_n_mmaps)
2299 mp_.max_n_mmaps = mp_.n_mmaps;
2301 sum = mp_.mmapped_mem += size;
2302 if (sum > (unsigned long)(mp_.max_mmapped_mem))
2303 mp_.max_mmapped_mem = sum;
2305 check_chunk(av, p);
2307 return chunk2mem(p);
2312 /* Record incoming configuration of top */
2314 old_top = av->top;
2315 old_size = chunksize(old_top);
2316 old_end = (char*)(chunk_at_offset(old_top, old_size));
2318 brk = snd_brk = (char*)(MORECORE_FAILURE);
2321 If not the first time through, we require old_size to be
2322 at least MINSIZE and to have prev_inuse set.
2325 assert((old_top == initial_top(av) && old_size == 0) ||
2326 ((unsigned long) (old_size) >= MINSIZE &&
2327 prev_inuse(old_top) &&
2328 ((unsigned long)old_end & pagemask) == 0));
2330 /* Precondition: not enough current space to satisfy nb request */
2331 assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE));
2334 if (av != &main_arena) {
2336 heap_info *old_heap, *heap;
2337 size_t old_heap_size;
2339 /* First try to extend the current heap. */
2340 old_heap = heap_for_ptr(old_top);
2341 old_heap_size = old_heap->size;
2342 if ((long) (MINSIZE + nb - old_size) > 0
2343 && grow_heap(old_heap, MINSIZE + nb - old_size) == 0) {
2344 av->system_mem += old_heap->size - old_heap_size;
2345 arena_mem += old_heap->size - old_heap_size;
2346 set_head(old_top, (((char *)old_heap + old_heap->size) - (char *)old_top)
2347 | PREV_INUSE);
2349 else if ((heap = new_heap(nb + (MINSIZE + sizeof(*heap)), mp_.top_pad))) {
2350 /* Use a newly allocated heap. */
2351 heap->ar_ptr = av;
2352 heap->prev = old_heap;
2353 av->system_mem += heap->size;
2354 arena_mem += heap->size;
2355 /* Set up the new top. */
2356 top(av) = chunk_at_offset(heap, sizeof(*heap));
2357 set_head(top(av), (heap->size - sizeof(*heap)) | PREV_INUSE);
2359 /* Setup fencepost and free the old top chunk. */
2360 /* The fencepost takes at least MINSIZE bytes, because it might
2361 become the top chunk again later. Note that a footer is set
2362 up, too, although the chunk is marked in use. */
2363 old_size -= MINSIZE;
2364 set_head(chunk_at_offset(old_top, old_size + 2*SIZE_SZ), 0|PREV_INUSE);
2365 if (old_size >= MINSIZE) {
2366 set_head(chunk_at_offset(old_top, old_size), (2*SIZE_SZ)|PREV_INUSE);
2367 set_foot(chunk_at_offset(old_top, old_size), (2*SIZE_SZ));
2368 set_head(old_top, old_size|PREV_INUSE|NON_MAIN_ARENA);
2369 _int_free(av, old_top, 1);
2370 } else {
2371 set_head(old_top, (old_size + 2*SIZE_SZ)|PREV_INUSE);
2372 set_foot(old_top, (old_size + 2*SIZE_SZ));
2375 else if (!tried_mmap)
2376 /* We can at least try to use to mmap memory. */
2377 goto try_mmap;
2379 } else { /* av == main_arena */
2382 /* Request enough space for nb + pad + overhead */
2384 size = nb + mp_.top_pad + MINSIZE;
2387 If contiguous, we can subtract out existing space that we hope to
2388 combine with new space. We add it back later only if
2389 we don't actually get contiguous space.
2392 if (contiguous(av))
2393 size -= old_size;
2396 Round to a multiple of page size.
2397 If MORECORE is not contiguous, this ensures that we only call it
2398 with whole-page arguments. And if MORECORE is contiguous and
2399 this is not first time through, this preserves page-alignment of
2400 previous calls. Otherwise, we correct to page-align below.
2403 size = (size + pagemask) & ~pagemask;
2406 Don't try to call MORECORE if argument is so big as to appear
2407 negative. Note that since mmap takes size_t arg, it may succeed
2408 below even if we cannot call MORECORE.
2411 if (size > 0)
2412 brk = (char*)(MORECORE(size));
2414 if (brk != (char*)(MORECORE_FAILURE)) {
2415 /* Call the `morecore' hook if necessary. */
2416 void (*hook) (void) = force_reg (__after_morecore_hook);
2417 if (__builtin_expect (hook != NULL, 0))
2418 (*hook) ();
2419 } else {
2421 If have mmap, try using it as a backup when MORECORE fails or
2422 cannot be used. This is worth doing on systems that have "holes" in
2423 address space, so sbrk cannot extend to give contiguous space, but
2424 space is available elsewhere. Note that we ignore mmap max count
2425 and threshold limits, since the space will not be used as a
2426 segregated mmap region.
2429 /* Cannot merge with old top, so add its size back in */
2430 if (contiguous(av))
2431 size = (size + old_size + pagemask) & ~pagemask;
2433 /* If we are relying on mmap as backup, then use larger units */
2434 if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE))
2435 size = MMAP_AS_MORECORE_SIZE;
2437 /* Don't try if size wraps around 0 */
2438 if ((unsigned long)(size) > (unsigned long)(nb)) {
2440 char *mbrk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, 0));
2442 if (mbrk != MAP_FAILED) {
2444 /* We do not need, and cannot use, another sbrk call to find end */
2445 brk = mbrk;
2446 snd_brk = brk + size;
2449 Record that we no longer have a contiguous sbrk region.
2450 After the first time mmap is used as backup, we do not
2451 ever rely on contiguous space since this could incorrectly
2452 bridge regions.
2454 set_noncontiguous(av);
2459 if (brk != (char*)(MORECORE_FAILURE)) {
2460 if (mp_.sbrk_base == 0)
2461 mp_.sbrk_base = brk;
2462 av->system_mem += size;
2465 If MORECORE extends previous space, we can likewise extend top size.
2468 if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE))
2469 set_head(old_top, (size + old_size) | PREV_INUSE);
2471 else if (contiguous(av) && old_size && brk < old_end) {
2472 /* Oops! Someone else killed our space.. Can't touch anything. */
2473 malloc_printerr (3, "break adjusted to free malloc space", brk);
2477 Otherwise, make adjustments:
2479 * If the first time through or noncontiguous, we need to call sbrk
2480 just to find out where the end of memory lies.
2482 * We need to ensure that all returned chunks from malloc will meet
2483 MALLOC_ALIGNMENT
2485 * If there was an intervening foreign sbrk, we need to adjust sbrk
2486 request size to account for fact that we will not be able to
2487 combine new space with existing space in old_top.
2489 * Almost all systems internally allocate whole pages at a time, in
2490 which case we might as well use the whole last page of request.
2491 So we allocate enough more memory to hit a page boundary now,
2492 which in turn causes future contiguous calls to page-align.
2495 else {
2496 front_misalign = 0;
2497 end_misalign = 0;
2498 correction = 0;
2499 aligned_brk = brk;
2501 /* handle contiguous cases */
2502 if (contiguous(av)) {
2504 /* Count foreign sbrk as system_mem. */
2505 if (old_size)
2506 av->system_mem += brk - old_end;
2508 /* Guarantee alignment of first new chunk made from this space */
2510 front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;
2511 if (front_misalign > 0) {
2514 Skip over some bytes to arrive at an aligned position.
2515 We don't need to specially mark these wasted front bytes.
2516 They will never be accessed anyway because
2517 prev_inuse of av->top (and any chunk created from its start)
2518 is always true after initialization.
2521 correction = MALLOC_ALIGNMENT - front_misalign;
2522 aligned_brk += correction;
2526 If this isn't adjacent to existing space, then we will not
2527 be able to merge with old_top space, so must add to 2nd request.
2530 correction += old_size;
2532 /* Extend the end address to hit a page boundary */
2533 end_misalign = (INTERNAL_SIZE_T)(brk + size + correction);
2534 correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign;
2536 assert(correction >= 0);
2537 snd_brk = (char*)(MORECORE(correction));
2540 If can't allocate correction, try to at least find out current
2541 brk. It might be enough to proceed without failing.
2543 Note that if second sbrk did NOT fail, we assume that space
2544 is contiguous with first sbrk. This is a safe assumption unless
2545 program is multithreaded but doesn't use locks and a foreign sbrk
2546 occurred between our first and second calls.
2549 if (snd_brk == (char*)(MORECORE_FAILURE)) {
2550 correction = 0;
2551 snd_brk = (char*)(MORECORE(0));
2552 } else {
2553 /* Call the `morecore' hook if necessary. */
2554 void (*hook) (void) = force_reg (__after_morecore_hook);
2555 if (__builtin_expect (hook != NULL, 0))
2556 (*hook) ();
2560 /* handle non-contiguous cases */
2561 else {
2562 /* MORECORE/mmap must correctly align */
2563 assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0);
2565 /* Find out current end of memory */
2566 if (snd_brk == (char*)(MORECORE_FAILURE)) {
2567 snd_brk = (char*)(MORECORE(0));
2571 /* Adjust top based on results of second sbrk */
2572 if (snd_brk != (char*)(MORECORE_FAILURE)) {
2573 av->top = (mchunkptr)aligned_brk;
2574 set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2575 av->system_mem += correction;
2578 If not the first time through, we either have a
2579 gap due to foreign sbrk or a non-contiguous region. Insert a
2580 double fencepost at old_top to prevent consolidation with space
2581 we don't own. These fenceposts are artificial chunks that are
2582 marked as inuse and are in any case too small to use. We need
2583 two to make sizes and alignments work out.
2586 if (old_size != 0) {
2588 Shrink old_top to insert fenceposts, keeping size a
2589 multiple of MALLOC_ALIGNMENT. We know there is at least
2590 enough space in old_top to do this.
2592 old_size = (old_size - 4*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
2593 set_head(old_top, old_size | PREV_INUSE);
2596 Note that the following assignments completely overwrite
2597 old_top when old_size was previously MINSIZE. This is
2598 intentional. We need the fencepost, even if old_top otherwise gets
2599 lost.
2601 chunk_at_offset(old_top, old_size )->size =
2602 (2*SIZE_SZ)|PREV_INUSE;
2604 chunk_at_offset(old_top, old_size + 2*SIZE_SZ)->size =
2605 (2*SIZE_SZ)|PREV_INUSE;
2607 /* If possible, release the rest. */
2608 if (old_size >= MINSIZE) {
2609 _int_free(av, old_top, 1);
2617 } /* if (av != &main_arena) */
2619 if ((unsigned long)av->system_mem > (unsigned long)(av->max_system_mem))
2620 av->max_system_mem = av->system_mem;
2621 check_malloc_state(av);
2623 /* finally, do the allocation */
2624 p = av->top;
2625 size = chunksize(p);
2627 /* check that one of the above allocation paths succeeded */
2628 if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
2629 remainder_size = size - nb;
2630 remainder = chunk_at_offset(p, nb);
2631 av->top = remainder;
2632 set_head(p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2633 set_head(remainder, remainder_size | PREV_INUSE);
2634 check_malloced_chunk(av, p, nb);
2635 return chunk2mem(p);
2638 /* catch all failure paths */
2639 __set_errno (ENOMEM);
2640 return 0;
2645 systrim is an inverse of sorts to sysmalloc. It gives memory back
2646 to the system (via negative arguments to sbrk) if there is unused
2647 memory at the `high' end of the malloc pool. It is called
2648 automatically by free() when top space exceeds the trim
2649 threshold. It is also called by the public malloc_trim routine. It
2650 returns 1 if it actually released any memory, else 0.
2653 static int systrim(size_t pad, mstate av)
2655 long top_size; /* Amount of top-most memory */
2656 long extra; /* Amount to release */
2657 long released; /* Amount actually released */
2658 char* current_brk; /* address returned by pre-check sbrk call */
2659 char* new_brk; /* address returned by post-check sbrk call */
2660 size_t pagesz;
2662 pagesz = GLRO(dl_pagesize);
2663 top_size = chunksize(av->top);
2665 /* Release in pagesize units, keeping at least one page */
2666 extra = (top_size - pad - MINSIZE - 1) & ~(pagesz - 1);
2668 if (extra > 0) {
2671 Only proceed if end of memory is where we last set it.
2672 This avoids problems if there were foreign sbrk calls.
2674 current_brk = (char*)(MORECORE(0));
2675 if (current_brk == (char*)(av->top) + top_size) {
2678 Attempt to release memory. We ignore MORECORE return value,
2679 and instead call again to find out where new end of memory is.
2680 This avoids problems if first call releases less than we asked,
2681 of if failure somehow altered brk value. (We could still
2682 encounter problems if it altered brk in some very bad way,
2683 but the only thing we can do is adjust anyway, which will cause
2684 some downstream failure.)
2687 MORECORE(-extra);
2688 /* Call the `morecore' hook if necessary. */
2689 void (*hook) (void) = force_reg (__after_morecore_hook);
2690 if (__builtin_expect (hook != NULL, 0))
2691 (*hook) ();
2692 new_brk = (char*)(MORECORE(0));
2694 if (new_brk != (char*)MORECORE_FAILURE) {
2695 released = (long)(current_brk - new_brk);
2697 if (released != 0) {
2698 /* Success. Adjust top. */
2699 av->system_mem -= released;
2700 set_head(av->top, (top_size - released) | PREV_INUSE);
2701 check_malloc_state(av);
2702 return 1;
2707 return 0;
2710 static void
2711 internal_function
2712 munmap_chunk(mchunkptr p)
2714 INTERNAL_SIZE_T size = chunksize(p);
2716 assert (chunk_is_mmapped(p));
2718 uintptr_t block = (uintptr_t) p - p->prev_size;
2719 size_t total_size = p->prev_size + size;
2720 /* Unfortunately we have to do the compilers job by hand here. Normally
2721 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2722 page size. But gcc does not recognize the optimization possibility
2723 (in the moment at least) so we combine the two values into one before
2724 the bit test. */
2725 if (__builtin_expect (((block | total_size) & (GLRO(dl_pagesize) - 1)) != 0, 0))
2727 malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
2728 chunk2mem (p));
2729 return;
2732 mp_.n_mmaps--;
2733 mp_.mmapped_mem -= total_size;
2735 /* If munmap failed the process virtual memory address space is in a
2736 bad shape. Just leave the block hanging around, the process will
2737 terminate shortly anyway since not much can be done. */
2738 __munmap((char *)block, total_size);
2741 #if HAVE_MREMAP
2743 static mchunkptr
2744 internal_function
2745 mremap_chunk(mchunkptr p, size_t new_size)
2747 size_t page_mask = GLRO(dl_pagesize) - 1;
2748 INTERNAL_SIZE_T offset = p->prev_size;
2749 INTERNAL_SIZE_T size = chunksize(p);
2750 char *cp;
2752 assert (chunk_is_mmapped(p));
2753 assert(((size + offset) & (GLRO(dl_pagesize)-1)) == 0);
2755 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2756 new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
2758 /* No need to remap if the number of pages does not change. */
2759 if (size + offset == new_size)
2760 return p;
2762 cp = (char *)__mremap((char *)p - offset, size + offset, new_size,
2763 MREMAP_MAYMOVE);
2765 if (cp == MAP_FAILED) return 0;
2767 p = (mchunkptr)(cp + offset);
2769 assert(aligned_OK(chunk2mem(p)));
2771 assert((p->prev_size == offset));
2772 set_head(p, (new_size - offset)|IS_MMAPPED);
2774 mp_.mmapped_mem -= size + offset;
2775 mp_.mmapped_mem += new_size;
2776 if ((unsigned long)mp_.mmapped_mem > (unsigned long)mp_.max_mmapped_mem)
2777 mp_.max_mmapped_mem = mp_.mmapped_mem;
2778 return p;
2781 #endif /* HAVE_MREMAP */
2783 /*------------------------ Public wrappers. --------------------------------*/
2785 void*
2786 __libc_malloc(size_t bytes)
2788 mstate ar_ptr;
2789 void *victim;
2791 __malloc_ptr_t (*hook) (size_t, const __malloc_ptr_t)
2792 = force_reg (__malloc_hook);
2793 if (__builtin_expect (hook != NULL, 0))
2794 return (*hook)(bytes, RETURN_ADDRESS (0));
2796 arena_lookup(ar_ptr);
2798 arena_lock(ar_ptr, bytes);
2799 if(!ar_ptr)
2800 return 0;
2801 victim = _int_malloc(ar_ptr, bytes);
2802 if(!victim) {
2803 /* Maybe the failure is due to running out of mmapped areas. */
2804 if(ar_ptr != &main_arena) {
2805 (void)mutex_unlock(&ar_ptr->mutex);
2806 ar_ptr = &main_arena;
2807 (void)mutex_lock(&ar_ptr->mutex);
2808 victim = _int_malloc(ar_ptr, bytes);
2809 (void)mutex_unlock(&ar_ptr->mutex);
2810 } else {
2811 /* ... or sbrk() has failed and there is still a chance to mmap() */
2812 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
2813 (void)mutex_unlock(&main_arena.mutex);
2814 if(ar_ptr) {
2815 victim = _int_malloc(ar_ptr, bytes);
2816 (void)mutex_unlock(&ar_ptr->mutex);
2819 } else
2820 (void)mutex_unlock(&ar_ptr->mutex);
2821 assert(!victim || chunk_is_mmapped(mem2chunk(victim)) ||
2822 ar_ptr == arena_for_chunk(mem2chunk(victim)));
2823 return victim;
2825 libc_hidden_def(__libc_malloc)
2827 void
2828 __libc_free(void* mem)
2830 mstate ar_ptr;
2831 mchunkptr p; /* chunk corresponding to mem */
2833 void (*hook) (__malloc_ptr_t, const __malloc_ptr_t)
2834 = force_reg (__free_hook);
2835 if (__builtin_expect (hook != NULL, 0)) {
2836 (*hook)(mem, RETURN_ADDRESS (0));
2837 return;
2840 if (mem == 0) /* free(0) has no effect */
2841 return;
2843 p = mem2chunk(mem);
2845 if (chunk_is_mmapped(p)) /* release mmapped memory. */
2847 /* see if the dynamic brk/mmap threshold needs adjusting */
2848 if (!mp_.no_dyn_threshold
2849 && p->size > mp_.mmap_threshold
2850 && p->size <= DEFAULT_MMAP_THRESHOLD_MAX)
2852 mp_.mmap_threshold = chunksize (p);
2853 mp_.trim_threshold = 2 * mp_.mmap_threshold;
2855 munmap_chunk(p);
2856 return;
2859 ar_ptr = arena_for_chunk(p);
2860 _int_free(ar_ptr, p, 0);
2862 libc_hidden_def (__libc_free)
2864 void*
2865 __libc_realloc(void* oldmem, size_t bytes)
2867 mstate ar_ptr;
2868 INTERNAL_SIZE_T nb; /* padded request size */
2870 void* newp; /* chunk to return */
2872 __malloc_ptr_t (*hook) (__malloc_ptr_t, size_t, const __malloc_ptr_t) =
2873 force_reg (__realloc_hook);
2874 if (__builtin_expect (hook != NULL, 0))
2875 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
2877 #if REALLOC_ZERO_BYTES_FREES
2878 if (bytes == 0 && oldmem != NULL) { __libc_free(oldmem); return 0; }
2879 #endif
2881 /* realloc of null is supposed to be same as malloc */
2882 if (oldmem == 0) return __libc_malloc(bytes);
2884 /* chunk corresponding to oldmem */
2885 const mchunkptr oldp = mem2chunk(oldmem);
2886 /* its size */
2887 const INTERNAL_SIZE_T oldsize = chunksize(oldp);
2889 /* Little security check which won't hurt performance: the
2890 allocator never wrapps around at the end of the address space.
2891 Therefore we can exclude some size values which might appear
2892 here by accident or by "design" from some intruder. */
2893 if (__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
2894 || __builtin_expect (misaligned_chunk (oldp), 0))
2896 malloc_printerr (check_action, "realloc(): invalid pointer", oldmem);
2897 return NULL;
2900 checked_request2size(bytes, nb);
2902 if (chunk_is_mmapped(oldp))
2904 void* newmem;
2906 #if HAVE_MREMAP
2907 newp = mremap_chunk(oldp, nb);
2908 if(newp) return chunk2mem(newp);
2909 #endif
2910 /* Note the extra SIZE_SZ overhead. */
2911 if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
2912 /* Must alloc, copy, free. */
2913 newmem = __libc_malloc(bytes);
2914 if (newmem == 0) return 0; /* propagate failure */
2915 MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
2916 munmap_chunk(oldp);
2917 return newmem;
2920 ar_ptr = arena_for_chunk(oldp);
2921 #if THREAD_STATS
2922 if(!mutex_trylock(&ar_ptr->mutex))
2923 ++(ar_ptr->stat_lock_direct);
2924 else {
2925 (void)mutex_lock(&ar_ptr->mutex);
2926 ++(ar_ptr->stat_lock_wait);
2928 #else
2929 (void)mutex_lock(&ar_ptr->mutex);
2930 #endif
2932 #if !defined PER_THREAD
2933 /* As in malloc(), remember this arena for the next allocation. */
2934 tsd_setspecific(arena_key, (void *)ar_ptr);
2935 #endif
2937 newp = _int_realloc(ar_ptr, oldp, oldsize, nb);
2939 (void)mutex_unlock(&ar_ptr->mutex);
2940 assert(!newp || chunk_is_mmapped(mem2chunk(newp)) ||
2941 ar_ptr == arena_for_chunk(mem2chunk(newp)));
2943 if (newp == NULL)
2945 /* Try harder to allocate memory in other arenas. */
2946 newp = __libc_malloc(bytes);
2947 if (newp != NULL)
2949 MALLOC_COPY (newp, oldmem, oldsize - SIZE_SZ);
2950 _int_free(ar_ptr, oldp, 0);
2954 return newp;
2956 libc_hidden_def (__libc_realloc)
2958 void*
2959 __libc_memalign(size_t alignment, size_t bytes)
2961 mstate ar_ptr;
2962 void *p;
2964 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
2965 const __malloc_ptr_t)) =
2966 force_reg (__memalign_hook);
2967 if (__builtin_expect (hook != NULL, 0))
2968 return (*hook)(alignment, bytes, RETURN_ADDRESS (0));
2970 /* If need less alignment than we give anyway, just relay to malloc */
2971 if (alignment <= MALLOC_ALIGNMENT) return __libc_malloc(bytes);
2973 /* Otherwise, ensure that it is at least a minimum chunk size */
2974 if (alignment < MINSIZE) alignment = MINSIZE;
2976 arena_get(ar_ptr, bytes + alignment + MINSIZE);
2977 if(!ar_ptr)
2978 return 0;
2979 p = _int_memalign(ar_ptr, alignment, bytes);
2980 if(!p) {
2981 /* Maybe the failure is due to running out of mmapped areas. */
2982 if(ar_ptr != &main_arena) {
2983 (void)mutex_unlock(&ar_ptr->mutex);
2984 ar_ptr = &main_arena;
2985 (void)mutex_lock(&ar_ptr->mutex);
2986 p = _int_memalign(ar_ptr, alignment, bytes);
2987 (void)mutex_unlock(&ar_ptr->mutex);
2988 } else {
2989 /* ... or sbrk() has failed and there is still a chance to mmap() */
2990 mstate prev = ar_ptr->next ? ar_ptr : 0;
2991 (void)mutex_unlock(&ar_ptr->mutex);
2992 ar_ptr = arena_get2(prev, bytes);
2993 if(ar_ptr) {
2994 p = _int_memalign(ar_ptr, alignment, bytes);
2995 (void)mutex_unlock(&ar_ptr->mutex);
2998 } else
2999 (void)mutex_unlock(&ar_ptr->mutex);
3000 assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3001 ar_ptr == arena_for_chunk(mem2chunk(p)));
3002 return p;
3004 /* For ISO C11. */
3005 weak_alias (__libc_memalign, aligned_alloc)
3006 libc_hidden_def (__libc_memalign)
3008 void*
3009 __libc_valloc(size_t bytes)
3011 mstate ar_ptr;
3012 void *p;
3014 if(__malloc_initialized < 0)
3015 ptmalloc_init ();
3017 size_t pagesz = GLRO(dl_pagesize);
3019 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
3020 const __malloc_ptr_t)) =
3021 force_reg (__memalign_hook);
3022 if (__builtin_expect (hook != NULL, 0))
3023 return (*hook)(pagesz, bytes, RETURN_ADDRESS (0));
3025 arena_get(ar_ptr, bytes + pagesz + MINSIZE);
3026 if(!ar_ptr)
3027 return 0;
3028 p = _int_valloc(ar_ptr, bytes);
3029 (void)mutex_unlock(&ar_ptr->mutex);
3030 if(!p) {
3031 /* Maybe the failure is due to running out of mmapped areas. */
3032 if(ar_ptr != &main_arena) {
3033 ar_ptr = &main_arena;
3034 (void)mutex_lock(&ar_ptr->mutex);
3035 p = _int_memalign(ar_ptr, pagesz, bytes);
3036 (void)mutex_unlock(&ar_ptr->mutex);
3037 } else {
3038 /* ... or sbrk() has failed and there is still a chance to mmap() */
3039 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
3040 if(ar_ptr) {
3041 p = _int_memalign(ar_ptr, pagesz, bytes);
3042 (void)mutex_unlock(&ar_ptr->mutex);
3046 assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3047 ar_ptr == arena_for_chunk(mem2chunk(p)));
3049 return p;
3052 void*
3053 __libc_pvalloc(size_t bytes)
3055 mstate ar_ptr;
3056 void *p;
3058 if(__malloc_initialized < 0)
3059 ptmalloc_init ();
3061 size_t pagesz = GLRO(dl_pagesize);
3062 size_t page_mask = GLRO(dl_pagesize) - 1;
3063 size_t rounded_bytes = (bytes + page_mask) & ~(page_mask);
3065 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
3066 const __malloc_ptr_t)) =
3067 force_reg (__memalign_hook);
3068 if (__builtin_expect (hook != NULL, 0))
3069 return (*hook)(pagesz, rounded_bytes, RETURN_ADDRESS (0));
3071 arena_get(ar_ptr, bytes + 2*pagesz + MINSIZE);
3072 p = _int_pvalloc(ar_ptr, bytes);
3073 (void)mutex_unlock(&ar_ptr->mutex);
3074 if(!p) {
3075 /* Maybe the failure is due to running out of mmapped areas. */
3076 if(ar_ptr != &main_arena) {
3077 ar_ptr = &main_arena;
3078 (void)mutex_lock(&ar_ptr->mutex);
3079 p = _int_memalign(ar_ptr, pagesz, rounded_bytes);
3080 (void)mutex_unlock(&ar_ptr->mutex);
3081 } else {
3082 /* ... or sbrk() has failed and there is still a chance to mmap() */
3083 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0,
3084 bytes + 2*pagesz + MINSIZE);
3085 if(ar_ptr) {
3086 p = _int_memalign(ar_ptr, pagesz, rounded_bytes);
3087 (void)mutex_unlock(&ar_ptr->mutex);
3091 assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3092 ar_ptr == arena_for_chunk(mem2chunk(p)));
3094 return p;
3097 void*
3098 __libc_calloc(size_t n, size_t elem_size)
3100 mstate av;
3101 mchunkptr oldtop, p;
3102 INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
3103 void* mem;
3104 unsigned long clearsize;
3105 unsigned long nclears;
3106 INTERNAL_SIZE_T* d;
3108 /* size_t is unsigned so the behavior on overflow is defined. */
3109 bytes = n * elem_size;
3110 #define HALF_INTERNAL_SIZE_T \
3111 (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
3112 if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) {
3113 if (elem_size != 0 && bytes / elem_size != n) {
3114 __set_errno (ENOMEM);
3115 return 0;
3119 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, const __malloc_ptr_t)) =
3120 force_reg (__malloc_hook);
3121 if (__builtin_expect (hook != NULL, 0)) {
3122 sz = bytes;
3123 mem = (*hook)(sz, RETURN_ADDRESS (0));
3124 if(mem == 0)
3125 return 0;
3126 return memset(mem, 0, sz);
3129 sz = bytes;
3131 arena_get(av, sz);
3132 if(!av)
3133 return 0;
3135 /* Check if we hand out the top chunk, in which case there may be no
3136 need to clear. */
3137 #if MORECORE_CLEARS
3138 oldtop = top(av);
3139 oldtopsize = chunksize(top(av));
3140 #if MORECORE_CLEARS < 2
3141 /* Only newly allocated memory is guaranteed to be cleared. */
3142 if (av == &main_arena &&
3143 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *)oldtop)
3144 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *)oldtop);
3145 #endif
3146 if (av != &main_arena)
3148 heap_info *heap = heap_for_ptr (oldtop);
3149 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3150 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3152 #endif
3153 mem = _int_malloc(av, sz);
3155 /* Only clearing follows, so we can unlock early. */
3156 (void)mutex_unlock(&av->mutex);
3158 assert(!mem || chunk_is_mmapped(mem2chunk(mem)) ||
3159 av == arena_for_chunk(mem2chunk(mem)));
3161 if (mem == 0) {
3162 /* Maybe the failure is due to running out of mmapped areas. */
3163 if(av != &main_arena) {
3164 (void)mutex_lock(&main_arena.mutex);
3165 mem = _int_malloc(&main_arena, sz);
3166 (void)mutex_unlock(&main_arena.mutex);
3167 } else {
3168 /* ... or sbrk() has failed and there is still a chance to mmap() */
3169 (void)mutex_lock(&main_arena.mutex);
3170 av = arena_get2(av->next ? av : 0, sz);
3171 (void)mutex_unlock(&main_arena.mutex);
3172 if(av) {
3173 mem = _int_malloc(av, sz);
3174 (void)mutex_unlock(&av->mutex);
3177 if (mem == 0) return 0;
3179 p = mem2chunk(mem);
3181 /* Two optional cases in which clearing not necessary */
3182 if (chunk_is_mmapped (p))
3184 if (__builtin_expect (perturb_byte, 0))
3185 MALLOC_ZERO (mem, sz);
3186 return mem;
3189 csz = chunksize(p);
3191 #if MORECORE_CLEARS
3192 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize)) {
3193 /* clear only the bytes from non-freshly-sbrked memory */
3194 csz = oldtopsize;
3196 #endif
3198 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3199 contents have an odd number of INTERNAL_SIZE_T-sized words;
3200 minimally 3. */
3201 d = (INTERNAL_SIZE_T*)mem;
3202 clearsize = csz - SIZE_SZ;
3203 nclears = clearsize / sizeof(INTERNAL_SIZE_T);
3204 assert(nclears >= 3);
3206 if (nclears > 9)
3207 MALLOC_ZERO(d, clearsize);
3209 else {
3210 *(d+0) = 0;
3211 *(d+1) = 0;
3212 *(d+2) = 0;
3213 if (nclears > 4) {
3214 *(d+3) = 0;
3215 *(d+4) = 0;
3216 if (nclears > 6) {
3217 *(d+5) = 0;
3218 *(d+6) = 0;
3219 if (nclears > 8) {
3220 *(d+7) = 0;
3221 *(d+8) = 0;
3227 return mem;
3231 ------------------------------ malloc ------------------------------
3234 static void*
3235 _int_malloc(mstate av, size_t bytes)
3237 INTERNAL_SIZE_T nb; /* normalized request size */
3238 unsigned int idx; /* associated bin index */
3239 mbinptr bin; /* associated bin */
3241 mchunkptr victim; /* inspected/selected chunk */
3242 INTERNAL_SIZE_T size; /* its size */
3243 int victim_index; /* its bin index */
3245 mchunkptr remainder; /* remainder from a split */
3246 unsigned long remainder_size; /* its size */
3248 unsigned int block; /* bit map traverser */
3249 unsigned int bit; /* bit map traverser */
3250 unsigned int map; /* current word of binmap */
3252 mchunkptr fwd; /* misc temp for linking */
3253 mchunkptr bck; /* misc temp for linking */
3255 const char *errstr = NULL;
3258 Convert request size to internal form by adding SIZE_SZ bytes
3259 overhead plus possibly more to obtain necessary alignment and/or
3260 to obtain a size of at least MINSIZE, the smallest allocatable
3261 size. Also, checked_request2size traps (returning 0) request sizes
3262 that are so large that they wrap around zero when padded and
3263 aligned.
3266 checked_request2size(bytes, nb);
3269 If the size qualifies as a fastbin, first check corresponding bin.
3270 This code is safe to execute even if av is not yet initialized, so we
3271 can try it without checking, which saves some time on this fast path.
3274 if ((unsigned long)(nb) <= (unsigned long)(get_max_fast ())) {
3275 idx = fastbin_index(nb);
3276 mfastbinptr* fb = &fastbin (av, idx);
3277 mchunkptr pp = *fb;
3280 victim = pp;
3281 if (victim == NULL)
3282 break;
3284 while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim))
3285 != victim);
3286 if (victim != 0) {
3287 if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
3289 errstr = "malloc(): memory corruption (fast)";
3290 errout:
3291 malloc_printerr (check_action, errstr, chunk2mem (victim));
3292 return NULL;
3294 check_remalloced_chunk(av, victim, nb);
3295 void *p = chunk2mem(victim);
3296 if (__builtin_expect (perturb_byte, 0))
3297 alloc_perturb (p, bytes);
3298 return p;
3303 If a small request, check regular bin. Since these "smallbins"
3304 hold one size each, no searching within bins is necessary.
3305 (For a large request, we need to wait until unsorted chunks are
3306 processed to find best fit. But for small ones, fits are exact
3307 anyway, so we can check now, which is faster.)
3310 if (in_smallbin_range(nb)) {
3311 idx = smallbin_index(nb);
3312 bin = bin_at(av,idx);
3314 if ( (victim = last(bin)) != bin) {
3315 if (victim == 0) /* initialization check */
3316 malloc_consolidate(av);
3317 else {
3318 bck = victim->bk;
3319 if (__builtin_expect (bck->fd != victim, 0))
3321 errstr = "malloc(): smallbin double linked list corrupted";
3322 goto errout;
3324 set_inuse_bit_at_offset(victim, nb);
3325 bin->bk = bck;
3326 bck->fd = bin;
3328 if (av != &main_arena)
3329 victim->size |= NON_MAIN_ARENA;
3330 check_malloced_chunk(av, victim, nb);
3331 void *p = chunk2mem(victim);
3332 if (__builtin_expect (perturb_byte, 0))
3333 alloc_perturb (p, bytes);
3334 return p;
3340 If this is a large request, consolidate fastbins before continuing.
3341 While it might look excessive to kill all fastbins before
3342 even seeing if there is space available, this avoids
3343 fragmentation problems normally associated with fastbins.
3344 Also, in practice, programs tend to have runs of either small or
3345 large requests, but less often mixtures, so consolidation is not
3346 invoked all that often in most programs. And the programs that
3347 it is called frequently in otherwise tend to fragment.
3350 else {
3351 idx = largebin_index(nb);
3352 if (have_fastchunks(av))
3353 malloc_consolidate(av);
3357 Process recently freed or remaindered chunks, taking one only if
3358 it is exact fit, or, if this a small request, the chunk is remainder from
3359 the most recent non-exact fit. Place other traversed chunks in
3360 bins. Note that this step is the only place in any routine where
3361 chunks are placed in bins.
3363 The outer loop here is needed because we might not realize until
3364 near the end of malloc that we should have consolidated, so must
3365 do so and retry. This happens at most once, and only when we would
3366 otherwise need to expand memory to service a "small" request.
3369 for(;;) {
3371 int iters = 0;
3372 while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
3373 bck = victim->bk;
3374 if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0)
3375 || __builtin_expect (victim->size > av->system_mem, 0))
3376 malloc_printerr (check_action, "malloc(): memory corruption",
3377 chunk2mem (victim));
3378 size = chunksize(victim);
3381 If a small request, try to use last remainder if it is the
3382 only chunk in unsorted bin. This helps promote locality for
3383 runs of consecutive small requests. This is the only
3384 exception to best-fit, and applies only when there is
3385 no exact fit for a small chunk.
3388 if (in_smallbin_range(nb) &&
3389 bck == unsorted_chunks(av) &&
3390 victim == av->last_remainder &&
3391 (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
3393 /* split and reattach remainder */
3394 remainder_size = size - nb;
3395 remainder = chunk_at_offset(victim, nb);
3396 unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
3397 av->last_remainder = remainder;
3398 remainder->bk = remainder->fd = unsorted_chunks(av);
3399 if (!in_smallbin_range(remainder_size))
3401 remainder->fd_nextsize = NULL;
3402 remainder->bk_nextsize = NULL;
3405 set_head(victim, nb | PREV_INUSE |
3406 (av != &main_arena ? NON_MAIN_ARENA : 0));
3407 set_head(remainder, remainder_size | PREV_INUSE);
3408 set_foot(remainder, remainder_size);
3410 check_malloced_chunk(av, victim, nb);
3411 void *p = chunk2mem(victim);
3412 if (__builtin_expect (perturb_byte, 0))
3413 alloc_perturb (p, bytes);
3414 return p;
3417 /* remove from unsorted list */
3418 unsorted_chunks(av)->bk = bck;
3419 bck->fd = unsorted_chunks(av);
3421 /* Take now instead of binning if exact fit */
3423 if (size == nb) {
3424 set_inuse_bit_at_offset(victim, size);
3425 if (av != &main_arena)
3426 victim->size |= NON_MAIN_ARENA;
3427 check_malloced_chunk(av, victim, nb);
3428 void *p = chunk2mem(victim);
3429 if (__builtin_expect (perturb_byte, 0))
3430 alloc_perturb (p, bytes);
3431 return p;
3434 /* place chunk in bin */
3436 if (in_smallbin_range(size)) {
3437 victim_index = smallbin_index(size);
3438 bck = bin_at(av, victim_index);
3439 fwd = bck->fd;
3441 else {
3442 victim_index = largebin_index(size);
3443 bck = bin_at(av, victim_index);
3444 fwd = bck->fd;
3446 /* maintain large bins in sorted order */
3447 if (fwd != bck) {
3448 /* Or with inuse bit to speed comparisons */
3449 size |= PREV_INUSE;
3450 /* if smaller than smallest, bypass loop below */
3451 assert((bck->bk->size & NON_MAIN_ARENA) == 0);
3452 if ((unsigned long)(size) < (unsigned long)(bck->bk->size)) {
3453 fwd = bck;
3454 bck = bck->bk;
3456 victim->fd_nextsize = fwd->fd;
3457 victim->bk_nextsize = fwd->fd->bk_nextsize;
3458 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
3460 else {
3461 assert((fwd->size & NON_MAIN_ARENA) == 0);
3462 while ((unsigned long) size < fwd->size)
3464 fwd = fwd->fd_nextsize;
3465 assert((fwd->size & NON_MAIN_ARENA) == 0);
3468 if ((unsigned long) size == (unsigned long) fwd->size)
3469 /* Always insert in the second position. */
3470 fwd = fwd->fd;
3471 else
3473 victim->fd_nextsize = fwd;
3474 victim->bk_nextsize = fwd->bk_nextsize;
3475 fwd->bk_nextsize = victim;
3476 victim->bk_nextsize->fd_nextsize = victim;
3478 bck = fwd->bk;
3480 } else
3481 victim->fd_nextsize = victim->bk_nextsize = victim;
3484 mark_bin(av, victim_index);
3485 victim->bk = bck;
3486 victim->fd = fwd;
3487 fwd->bk = victim;
3488 bck->fd = victim;
3490 #define MAX_ITERS 10000
3491 if (++iters >= MAX_ITERS)
3492 break;
3496 If a large request, scan through the chunks of current bin in
3497 sorted order to find smallest that fits. Use the skip list for this.
3500 if (!in_smallbin_range(nb)) {
3501 bin = bin_at(av, idx);
3503 /* skip scan if empty or largest chunk is too small */
3504 if ((victim = first(bin)) != bin &&
3505 (unsigned long)(victim->size) >= (unsigned long)(nb)) {
3507 victim = victim->bk_nextsize;
3508 while (((unsigned long)(size = chunksize(victim)) <
3509 (unsigned long)(nb)))
3510 victim = victim->bk_nextsize;
3512 /* Avoid removing the first entry for a size so that the skip
3513 list does not have to be rerouted. */
3514 if (victim != last(bin) && victim->size == victim->fd->size)
3515 victim = victim->fd;
3517 remainder_size = size - nb;
3518 unlink(victim, bck, fwd);
3520 /* Exhaust */
3521 if (remainder_size < MINSIZE) {
3522 set_inuse_bit_at_offset(victim, size);
3523 if (av != &main_arena)
3524 victim->size |= NON_MAIN_ARENA;
3526 /* Split */
3527 else {
3528 remainder = chunk_at_offset(victim, nb);
3529 /* We cannot assume the unsorted list is empty and therefore
3530 have to perform a complete insert here. */
3531 bck = unsorted_chunks(av);
3532 fwd = bck->fd;
3533 if (__builtin_expect (fwd->bk != bck, 0))
3535 errstr = "malloc(): corrupted unsorted chunks";
3536 goto errout;
3538 remainder->bk = bck;
3539 remainder->fd = fwd;
3540 bck->fd = remainder;
3541 fwd->bk = remainder;
3542 if (!in_smallbin_range(remainder_size))
3544 remainder->fd_nextsize = NULL;
3545 remainder->bk_nextsize = NULL;
3547 set_head(victim, nb | PREV_INUSE |
3548 (av != &main_arena ? NON_MAIN_ARENA : 0));
3549 set_head(remainder, remainder_size | PREV_INUSE);
3550 set_foot(remainder, remainder_size);
3552 check_malloced_chunk(av, victim, nb);
3553 void *p = chunk2mem(victim);
3554 if (__builtin_expect (perturb_byte, 0))
3555 alloc_perturb (p, bytes);
3556 return p;
3561 Search for a chunk by scanning bins, starting with next largest
3562 bin. This search is strictly by best-fit; i.e., the smallest
3563 (with ties going to approximately the least recently used) chunk
3564 that fits is selected.
3566 The bitmap avoids needing to check that most blocks are nonempty.
3567 The particular case of skipping all bins during warm-up phases
3568 when no chunks have been returned yet is faster than it might look.
3571 ++idx;
3572 bin = bin_at(av,idx);
3573 block = idx2block(idx);
3574 map = av->binmap[block];
3575 bit = idx2bit(idx);
3577 for (;;) {
3579 /* Skip rest of block if there are no more set bits in this block. */
3580 if (bit > map || bit == 0) {
3581 do {
3582 if (++block >= BINMAPSIZE) /* out of bins */
3583 goto use_top;
3584 } while ( (map = av->binmap[block]) == 0);
3586 bin = bin_at(av, (block << BINMAPSHIFT));
3587 bit = 1;
3590 /* Advance to bin with set bit. There must be one. */
3591 while ((bit & map) == 0) {
3592 bin = next_bin(bin);
3593 bit <<= 1;
3594 assert(bit != 0);
3597 /* Inspect the bin. It is likely to be non-empty */
3598 victim = last(bin);
3600 /* If a false alarm (empty bin), clear the bit. */
3601 if (victim == bin) {
3602 av->binmap[block] = map &= ~bit; /* Write through */
3603 bin = next_bin(bin);
3604 bit <<= 1;
3607 else {
3608 size = chunksize(victim);
3610 /* We know the first chunk in this bin is big enough to use. */
3611 assert((unsigned long)(size) >= (unsigned long)(nb));
3613 remainder_size = size - nb;
3615 /* unlink */
3616 unlink(victim, bck, fwd);
3618 /* Exhaust */
3619 if (remainder_size < MINSIZE) {
3620 set_inuse_bit_at_offset(victim, size);
3621 if (av != &main_arena)
3622 victim->size |= NON_MAIN_ARENA;
3625 /* Split */
3626 else {
3627 remainder = chunk_at_offset(victim, nb);
3629 /* We cannot assume the unsorted list is empty and therefore
3630 have to perform a complete insert here. */
3631 bck = unsorted_chunks(av);
3632 fwd = bck->fd;
3633 if (__builtin_expect (fwd->bk != bck, 0))
3635 errstr = "malloc(): corrupted unsorted chunks 2";
3636 goto errout;
3638 remainder->bk = bck;
3639 remainder->fd = fwd;
3640 bck->fd = remainder;
3641 fwd->bk = remainder;
3643 /* advertise as last remainder */
3644 if (in_smallbin_range(nb))
3645 av->last_remainder = remainder;
3646 if (!in_smallbin_range(remainder_size))
3648 remainder->fd_nextsize = NULL;
3649 remainder->bk_nextsize = NULL;
3651 set_head(victim, nb | PREV_INUSE |
3652 (av != &main_arena ? NON_MAIN_ARENA : 0));
3653 set_head(remainder, remainder_size | PREV_INUSE);
3654 set_foot(remainder, remainder_size);
3656 check_malloced_chunk(av, victim, nb);
3657 void *p = chunk2mem(victim);
3658 if (__builtin_expect (perturb_byte, 0))
3659 alloc_perturb (p, bytes);
3660 return p;
3664 use_top:
3666 If large enough, split off the chunk bordering the end of memory
3667 (held in av->top). Note that this is in accord with the best-fit
3668 search rule. In effect, av->top is treated as larger (and thus
3669 less well fitting) than any other available chunk since it can
3670 be extended to be as large as necessary (up to system
3671 limitations).
3673 We require that av->top always exists (i.e., has size >=
3674 MINSIZE) after initialization, so if it would otherwise be
3675 exhausted by current request, it is replenished. (The main
3676 reason for ensuring it exists is that we may need MINSIZE space
3677 to put in fenceposts in sysmalloc.)
3680 victim = av->top;
3681 size = chunksize(victim);
3683 if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
3684 remainder_size = size - nb;
3685 remainder = chunk_at_offset(victim, nb);
3686 av->top = remainder;
3687 set_head(victim, nb | PREV_INUSE |
3688 (av != &main_arena ? NON_MAIN_ARENA : 0));
3689 set_head(remainder, remainder_size | PREV_INUSE);
3691 check_malloced_chunk(av, victim, nb);
3692 void *p = chunk2mem(victim);
3693 if (__builtin_expect (perturb_byte, 0))
3694 alloc_perturb (p, bytes);
3695 return p;
3698 /* When we are using atomic ops to free fast chunks we can get
3699 here for all block sizes. */
3700 else if (have_fastchunks(av)) {
3701 malloc_consolidate(av);
3702 /* restore original bin index */
3703 if (in_smallbin_range(nb))
3704 idx = smallbin_index(nb);
3705 else
3706 idx = largebin_index(nb);
3710 Otherwise, relay to handle system-dependent cases
3712 else {
3713 void *p = sysmalloc(nb, av);
3714 if (p != NULL && __builtin_expect (perturb_byte, 0))
3715 alloc_perturb (p, bytes);
3716 return p;
3722 ------------------------------ free ------------------------------
3725 static void
3726 _int_free(mstate av, mchunkptr p, int have_lock)
3728 INTERNAL_SIZE_T size; /* its size */
3729 mfastbinptr* fb; /* associated fastbin */
3730 mchunkptr nextchunk; /* next contiguous chunk */
3731 INTERNAL_SIZE_T nextsize; /* its size */
3732 int nextinuse; /* true if nextchunk is used */
3733 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
3734 mchunkptr bck; /* misc temp for linking */
3735 mchunkptr fwd; /* misc temp for linking */
3737 const char *errstr = NULL;
3738 int locked = 0;
3740 size = chunksize(p);
3742 /* Little security check which won't hurt performance: the
3743 allocator never wrapps around at the end of the address space.
3744 Therefore we can exclude some size values which might appear
3745 here by accident or by "design" from some intruder. */
3746 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
3747 || __builtin_expect (misaligned_chunk (p), 0))
3749 errstr = "free(): invalid pointer";
3750 errout:
3751 if (! have_lock && locked)
3752 (void)mutex_unlock(&av->mutex);
3753 malloc_printerr (check_action, errstr, chunk2mem(p));
3754 return;
3756 /* We know that each chunk is at least MINSIZE bytes in size. */
3757 if (__builtin_expect (size < MINSIZE, 0))
3759 errstr = "free(): invalid size";
3760 goto errout;
3763 check_inuse_chunk(av, p);
3766 If eligible, place chunk on a fastbin so it can be found
3767 and used quickly in malloc.
3770 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
3772 #if TRIM_FASTBINS
3774 If TRIM_FASTBINS set, don't place chunks
3775 bordering top into fastbins
3777 && (chunk_at_offset(p, size) != av->top)
3778 #endif
3781 if (__builtin_expect (chunk_at_offset (p, size)->size <= 2 * SIZE_SZ, 0)
3782 || __builtin_expect (chunksize (chunk_at_offset (p, size))
3783 >= av->system_mem, 0))
3785 /* We might not have a lock at this point and concurrent modifications
3786 of system_mem might have let to a false positive. Redo the test
3787 after getting the lock. */
3788 if (have_lock
3789 || ({ assert (locked == 0);
3790 mutex_lock(&av->mutex);
3791 locked = 1;
3792 chunk_at_offset (p, size)->size <= 2 * SIZE_SZ
3793 || chunksize (chunk_at_offset (p, size)) >= av->system_mem;
3796 errstr = "free(): invalid next size (fast)";
3797 goto errout;
3799 if (! have_lock)
3801 (void)mutex_unlock(&av->mutex);
3802 locked = 0;
3806 if (__builtin_expect (perturb_byte, 0))
3807 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3809 set_fastchunks(av);
3810 unsigned int idx = fastbin_index(size);
3811 fb = &fastbin (av, idx);
3813 mchunkptr fd;
3814 mchunkptr old = *fb;
3815 unsigned int old_idx = ~0u;
3818 /* Another simple check: make sure the top of the bin is not the
3819 record we are going to add (i.e., double free). */
3820 if (__builtin_expect (old == p, 0))
3822 errstr = "double free or corruption (fasttop)";
3823 goto errout;
3825 if (old != NULL)
3826 old_idx = fastbin_index(chunksize(old));
3827 p->fd = fd = old;
3829 while ((old = catomic_compare_and_exchange_val_rel (fb, p, fd)) != fd);
3831 if (fd != NULL && __builtin_expect (old_idx != idx, 0))
3833 errstr = "invalid fastbin entry (free)";
3834 goto errout;
3839 Consolidate other non-mmapped chunks as they arrive.
3842 else if (!chunk_is_mmapped(p)) {
3843 if (! have_lock) {
3844 #if THREAD_STATS
3845 if(!mutex_trylock(&av->mutex))
3846 ++(av->stat_lock_direct);
3847 else {
3848 (void)mutex_lock(&av->mutex);
3849 ++(av->stat_lock_wait);
3851 #else
3852 (void)mutex_lock(&av->mutex);
3853 #endif
3854 locked = 1;
3857 nextchunk = chunk_at_offset(p, size);
3859 /* Lightweight tests: check whether the block is already the
3860 top block. */
3861 if (__builtin_expect (p == av->top, 0))
3863 errstr = "double free or corruption (top)";
3864 goto errout;
3866 /* Or whether the next chunk is beyond the boundaries of the arena. */
3867 if (__builtin_expect (contiguous (av)
3868 && (char *) nextchunk
3869 >= ((char *) av->top + chunksize(av->top)), 0))
3871 errstr = "double free or corruption (out)";
3872 goto errout;
3874 /* Or whether the block is actually not marked used. */
3875 if (__builtin_expect (!prev_inuse(nextchunk), 0))
3877 errstr = "double free or corruption (!prev)";
3878 goto errout;
3881 nextsize = chunksize(nextchunk);
3882 if (__builtin_expect (nextchunk->size <= 2 * SIZE_SZ, 0)
3883 || __builtin_expect (nextsize >= av->system_mem, 0))
3885 errstr = "free(): invalid next size (normal)";
3886 goto errout;
3889 if (__builtin_expect (perturb_byte, 0))
3890 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3892 /* consolidate backward */
3893 if (!prev_inuse(p)) {
3894 prevsize = p->prev_size;
3895 size += prevsize;
3896 p = chunk_at_offset(p, -((long) prevsize));
3897 unlink(p, bck, fwd);
3900 if (nextchunk != av->top) {
3901 /* get and clear inuse bit */
3902 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
3904 /* consolidate forward */
3905 if (!nextinuse) {
3906 unlink(nextchunk, bck, fwd);
3907 size += nextsize;
3908 } else
3909 clear_inuse_bit_at_offset(nextchunk, 0);
3912 Place the chunk in unsorted chunk list. Chunks are
3913 not placed into regular bins until after they have
3914 been given one chance to be used in malloc.
3917 bck = unsorted_chunks(av);
3918 fwd = bck->fd;
3919 if (__builtin_expect (fwd->bk != bck, 0))
3921 errstr = "free(): corrupted unsorted chunks";
3922 goto errout;
3924 p->fd = fwd;
3925 p->bk = bck;
3926 if (!in_smallbin_range(size))
3928 p->fd_nextsize = NULL;
3929 p->bk_nextsize = NULL;
3931 bck->fd = p;
3932 fwd->bk = p;
3934 set_head(p, size | PREV_INUSE);
3935 set_foot(p, size);
3937 check_free_chunk(av, p);
3941 If the chunk borders the current high end of memory,
3942 consolidate into top
3945 else {
3946 size += nextsize;
3947 set_head(p, size | PREV_INUSE);
3948 av->top = p;
3949 check_chunk(av, p);
3953 If freeing a large space, consolidate possibly-surrounding
3954 chunks. Then, if the total unused topmost memory exceeds trim
3955 threshold, ask malloc_trim to reduce top.
3957 Unless max_fast is 0, we don't know if there are fastbins
3958 bordering top, so we cannot tell for sure whether threshold
3959 has been reached unless fastbins are consolidated. But we
3960 don't want to consolidate on each free. As a compromise,
3961 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
3962 is reached.
3965 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
3966 if (have_fastchunks(av))
3967 malloc_consolidate(av);
3969 if (av == &main_arena) {
3970 #ifndef MORECORE_CANNOT_TRIM
3971 if ((unsigned long)(chunksize(av->top)) >=
3972 (unsigned long)(mp_.trim_threshold))
3973 systrim(mp_.top_pad, av);
3974 #endif
3975 } else {
3976 /* Always try heap_trim(), even if the top chunk is not
3977 large, because the corresponding heap might go away. */
3978 heap_info *heap = heap_for_ptr(top(av));
3980 assert(heap->ar_ptr == av);
3981 heap_trim(heap, mp_.top_pad);
3985 if (! have_lock) {
3986 assert (locked);
3987 (void)mutex_unlock(&av->mutex);
3991 If the chunk was allocated via mmap, release via munmap().
3994 else {
3995 munmap_chunk (p);
4000 ------------------------- malloc_consolidate -------------------------
4002 malloc_consolidate is a specialized version of free() that tears
4003 down chunks held in fastbins. Free itself cannot be used for this
4004 purpose since, among other things, it might place chunks back onto
4005 fastbins. So, instead, we need to use a minor variant of the same
4006 code.
4008 Also, because this routine needs to be called the first time through
4009 malloc anyway, it turns out to be the perfect place to trigger
4010 initialization code.
4013 static void malloc_consolidate(mstate av)
4015 mfastbinptr* fb; /* current fastbin being consolidated */
4016 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4017 mchunkptr p; /* current chunk being consolidated */
4018 mchunkptr nextp; /* next chunk to consolidate */
4019 mchunkptr unsorted_bin; /* bin header */
4020 mchunkptr first_unsorted; /* chunk to link to */
4022 /* These have same use as in free() */
4023 mchunkptr nextchunk;
4024 INTERNAL_SIZE_T size;
4025 INTERNAL_SIZE_T nextsize;
4026 INTERNAL_SIZE_T prevsize;
4027 int nextinuse;
4028 mchunkptr bck;
4029 mchunkptr fwd;
4032 If max_fast is 0, we know that av hasn't
4033 yet been initialized, in which case do so below
4036 if (get_max_fast () != 0) {
4037 clear_fastchunks(av);
4039 unsorted_bin = unsorted_chunks(av);
4042 Remove each chunk from fast bin and consolidate it, placing it
4043 then in unsorted bin. Among other reasons for doing this,
4044 placing in unsorted bin avoids needing to calculate actual bins
4045 until malloc is sure that chunks aren't immediately going to be
4046 reused anyway.
4049 maxfb = &fastbin (av, NFASTBINS - 1);
4050 fb = &fastbin (av, 0);
4051 do {
4052 p = atomic_exchange_acq (fb, 0);
4053 if (p != 0) {
4054 do {
4055 check_inuse_chunk(av, p);
4056 nextp = p->fd;
4058 /* Slightly streamlined version of consolidation code in free() */
4059 size = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
4060 nextchunk = chunk_at_offset(p, size);
4061 nextsize = chunksize(nextchunk);
4063 if (!prev_inuse(p)) {
4064 prevsize = p->prev_size;
4065 size += prevsize;
4066 p = chunk_at_offset(p, -((long) prevsize));
4067 unlink(p, bck, fwd);
4070 if (nextchunk != av->top) {
4071 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4073 if (!nextinuse) {
4074 size += nextsize;
4075 unlink(nextchunk, bck, fwd);
4076 } else
4077 clear_inuse_bit_at_offset(nextchunk, 0);
4079 first_unsorted = unsorted_bin->fd;
4080 unsorted_bin->fd = p;
4081 first_unsorted->bk = p;
4083 if (!in_smallbin_range (size)) {
4084 p->fd_nextsize = NULL;
4085 p->bk_nextsize = NULL;
4088 set_head(p, size | PREV_INUSE);
4089 p->bk = unsorted_bin;
4090 p->fd = first_unsorted;
4091 set_foot(p, size);
4094 else {
4095 size += nextsize;
4096 set_head(p, size | PREV_INUSE);
4097 av->top = p;
4100 } while ( (p = nextp) != 0);
4103 } while (fb++ != maxfb);
4105 else {
4106 malloc_init_state(av);
4107 check_malloc_state(av);
4112 ------------------------------ realloc ------------------------------
4115 void*
4116 _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4117 INTERNAL_SIZE_T nb)
4119 mchunkptr newp; /* chunk to return */
4120 INTERNAL_SIZE_T newsize; /* its size */
4121 void* newmem; /* corresponding user mem */
4123 mchunkptr next; /* next contiguous chunk after oldp */
4125 mchunkptr remainder; /* extra space at end of newp */
4126 unsigned long remainder_size; /* its size */
4128 mchunkptr bck; /* misc temp for linking */
4129 mchunkptr fwd; /* misc temp for linking */
4131 unsigned long copysize; /* bytes to copy */
4132 unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
4133 INTERNAL_SIZE_T* s; /* copy source */
4134 INTERNAL_SIZE_T* d; /* copy destination */
4136 const char *errstr = NULL;
4138 /* oldmem size */
4139 if (__builtin_expect (oldp->size <= 2 * SIZE_SZ, 0)
4140 || __builtin_expect (oldsize >= av->system_mem, 0))
4142 errstr = "realloc(): invalid old size";
4143 errout:
4144 malloc_printerr (check_action, errstr, chunk2mem(oldp));
4145 return NULL;
4148 check_inuse_chunk(av, oldp);
4150 /* All callers already filter out mmap'ed chunks. */
4151 assert (!chunk_is_mmapped(oldp));
4153 next = chunk_at_offset(oldp, oldsize);
4154 INTERNAL_SIZE_T nextsize = chunksize(next);
4155 if (__builtin_expect (next->size <= 2 * SIZE_SZ, 0)
4156 || __builtin_expect (nextsize >= av->system_mem, 0))
4158 errstr = "realloc(): invalid next size";
4159 goto errout;
4162 if ((unsigned long)(oldsize) >= (unsigned long)(nb)) {
4163 /* already big enough; split below */
4164 newp = oldp;
4165 newsize = oldsize;
4168 else {
4169 /* Try to expand forward into top */
4170 if (next == av->top &&
4171 (unsigned long)(newsize = oldsize + nextsize) >=
4172 (unsigned long)(nb + MINSIZE)) {
4173 set_head_size(oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4174 av->top = chunk_at_offset(oldp, nb);
4175 set_head(av->top, (newsize - nb) | PREV_INUSE);
4176 check_inuse_chunk(av, oldp);
4177 return chunk2mem(oldp);
4180 /* Try to expand forward into next chunk; split off remainder below */
4181 else if (next != av->top &&
4182 !inuse(next) &&
4183 (unsigned long)(newsize = oldsize + nextsize) >=
4184 (unsigned long)(nb)) {
4185 newp = oldp;
4186 unlink(next, bck, fwd);
4189 /* allocate, copy, free */
4190 else {
4191 newmem = _int_malloc(av, nb - MALLOC_ALIGN_MASK);
4192 if (newmem == 0)
4193 return 0; /* propagate failure */
4195 newp = mem2chunk(newmem);
4196 newsize = chunksize(newp);
4199 Avoid copy if newp is next chunk after oldp.
4201 if (newp == next) {
4202 newsize += oldsize;
4203 newp = oldp;
4205 else {
4207 Unroll copy of <= 36 bytes (72 if 8byte sizes)
4208 We know that contents have an odd number of
4209 INTERNAL_SIZE_T-sized words; minimally 3.
4212 copysize = oldsize - SIZE_SZ;
4213 s = (INTERNAL_SIZE_T*)(chunk2mem(oldp));
4214 d = (INTERNAL_SIZE_T*)(newmem);
4215 ncopies = copysize / sizeof(INTERNAL_SIZE_T);
4216 assert(ncopies >= 3);
4218 if (ncopies > 9)
4219 MALLOC_COPY(d, s, copysize);
4221 else {
4222 *(d+0) = *(s+0);
4223 *(d+1) = *(s+1);
4224 *(d+2) = *(s+2);
4225 if (ncopies > 4) {
4226 *(d+3) = *(s+3);
4227 *(d+4) = *(s+4);
4228 if (ncopies > 6) {
4229 *(d+5) = *(s+5);
4230 *(d+6) = *(s+6);
4231 if (ncopies > 8) {
4232 *(d+7) = *(s+7);
4233 *(d+8) = *(s+8);
4239 _int_free(av, oldp, 1);
4240 check_inuse_chunk(av, newp);
4241 return chunk2mem(newp);
4246 /* If possible, free extra space in old or extended chunk */
4248 assert((unsigned long)(newsize) >= (unsigned long)(nb));
4250 remainder_size = newsize - nb;
4252 if (remainder_size < MINSIZE) { /* not enough extra to split off */
4253 set_head_size(newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4254 set_inuse_bit_at_offset(newp, newsize);
4256 else { /* split remainder */
4257 remainder = chunk_at_offset(newp, nb);
4258 set_head_size(newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4259 set_head(remainder, remainder_size | PREV_INUSE |
4260 (av != &main_arena ? NON_MAIN_ARENA : 0));
4261 /* Mark remainder as inuse so free() won't complain */
4262 set_inuse_bit_at_offset(remainder, remainder_size);
4263 _int_free(av, remainder, 1);
4266 check_inuse_chunk(av, newp);
4267 return chunk2mem(newp);
4271 ------------------------------ memalign ------------------------------
4274 static void*
4275 _int_memalign(mstate av, size_t alignment, size_t bytes)
4277 INTERNAL_SIZE_T nb; /* padded request size */
4278 char* m; /* memory returned by malloc call */
4279 mchunkptr p; /* corresponding chunk */
4280 char* brk; /* alignment point within p */
4281 mchunkptr newp; /* chunk to return */
4282 INTERNAL_SIZE_T newsize; /* its size */
4283 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4284 mchunkptr remainder; /* spare room at end to split off */
4285 unsigned long remainder_size; /* its size */
4286 INTERNAL_SIZE_T size;
4288 /* If need less alignment than we give anyway, just relay to malloc */
4290 if (alignment <= MALLOC_ALIGNMENT) return _int_malloc(av, bytes);
4292 /* Otherwise, ensure that it is at least a minimum chunk size */
4294 if (alignment < MINSIZE) alignment = MINSIZE;
4296 /* Make sure alignment is power of 2 (in case MINSIZE is not). */
4297 if ((alignment & (alignment - 1)) != 0) {
4298 size_t a = MALLOC_ALIGNMENT * 2;
4299 while ((unsigned long)a < (unsigned long)alignment) a <<= 1;
4300 alignment = a;
4303 checked_request2size(bytes, nb);
4306 Strategy: find a spot within that chunk that meets the alignment
4307 request, and then possibly free the leading and trailing space.
4311 /* Call malloc with worst case padding to hit alignment. */
4313 m = (char*)(_int_malloc(av, nb + alignment + MINSIZE));
4315 if (m == 0) return 0; /* propagate failure */
4317 p = mem2chunk(m);
4319 if ((((unsigned long)(m)) % alignment) != 0) { /* misaligned */
4322 Find an aligned spot inside chunk. Since we need to give back
4323 leading space in a chunk of at least MINSIZE, if the first
4324 calculation places us at a spot with less than MINSIZE leader,
4325 we can move to the next aligned spot -- we've allocated enough
4326 total room so that this is always possible.
4329 brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) &
4330 -((signed long) alignment));
4331 if ((unsigned long)(brk - (char*)(p)) < MINSIZE)
4332 brk += alignment;
4334 newp = (mchunkptr)brk;
4335 leadsize = brk - (char*)(p);
4336 newsize = chunksize(p) - leadsize;
4338 /* For mmapped chunks, just adjust offset */
4339 if (chunk_is_mmapped(p)) {
4340 newp->prev_size = p->prev_size + leadsize;
4341 set_head(newp, newsize|IS_MMAPPED);
4342 return chunk2mem(newp);
4345 /* Otherwise, give back leader, use the rest */
4346 set_head(newp, newsize | PREV_INUSE |
4347 (av != &main_arena ? NON_MAIN_ARENA : 0));
4348 set_inuse_bit_at_offset(newp, newsize);
4349 set_head_size(p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4350 _int_free(av, p, 1);
4351 p = newp;
4353 assert (newsize >= nb &&
4354 (((unsigned long)(chunk2mem(p))) % alignment) == 0);
4357 /* Also give back spare room at the end */
4358 if (!chunk_is_mmapped(p)) {
4359 size = chunksize(p);
4360 if ((unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
4361 remainder_size = size - nb;
4362 remainder = chunk_at_offset(p, nb);
4363 set_head(remainder, remainder_size | PREV_INUSE |
4364 (av != &main_arena ? NON_MAIN_ARENA : 0));
4365 set_head_size(p, nb);
4366 _int_free(av, remainder, 1);
4370 check_inuse_chunk(av, p);
4371 return chunk2mem(p);
4376 ------------------------------ valloc ------------------------------
4379 static void*
4380 _int_valloc(mstate av, size_t bytes)
4382 /* Ensure initialization/consolidation */
4383 if (have_fastchunks(av)) malloc_consolidate(av);
4384 return _int_memalign(av, GLRO(dl_pagesize), bytes);
4388 ------------------------------ pvalloc ------------------------------
4392 static void*
4393 _int_pvalloc(mstate av, size_t bytes)
4395 size_t pagesz;
4397 /* Ensure initialization/consolidation */
4398 if (have_fastchunks(av)) malloc_consolidate(av);
4399 pagesz = GLRO(dl_pagesize);
4400 return _int_memalign(av, pagesz, (bytes + pagesz - 1) & ~(pagesz - 1));
4405 ------------------------------ malloc_trim ------------------------------
4408 static int mtrim(mstate av, size_t pad)
4410 /* Ensure initialization/consolidation */
4411 malloc_consolidate (av);
4413 const size_t ps = GLRO(dl_pagesize);
4414 int psindex = bin_index (ps);
4415 const size_t psm1 = ps - 1;
4417 int result = 0;
4418 for (int i = 1; i < NBINS; ++i)
4419 if (i == 1 || i >= psindex)
4421 mbinptr bin = bin_at (av, i);
4423 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4425 INTERNAL_SIZE_T size = chunksize (p);
4427 if (size > psm1 + sizeof (struct malloc_chunk))
4429 /* See whether the chunk contains at least one unused page. */
4430 char *paligned_mem = (char *) (((uintptr_t) p
4431 + sizeof (struct malloc_chunk)
4432 + psm1) & ~psm1);
4434 assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
4435 assert ((char *) p + size > paligned_mem);
4437 /* This is the size we could potentially free. */
4438 size -= paligned_mem - (char *) p;
4440 if (size > psm1)
4442 #ifdef MALLOC_DEBUG
4443 /* When debugging we simulate destroying the memory
4444 content. */
4445 memset (paligned_mem, 0x89, size & ~psm1);
4446 #endif
4447 madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
4449 result = 1;
4455 #ifndef MORECORE_CANNOT_TRIM
4456 return result | (av == &main_arena ? systrim (pad, av) : 0);
4457 #else
4458 return result;
4459 #endif
4464 __malloc_trim(size_t s)
4466 int result = 0;
4468 if(__malloc_initialized < 0)
4469 ptmalloc_init ();
4471 mstate ar_ptr = &main_arena;
4474 (void) mutex_lock (&ar_ptr->mutex);
4475 result |= mtrim (ar_ptr, s);
4476 (void) mutex_unlock (&ar_ptr->mutex);
4478 ar_ptr = ar_ptr->next;
4480 while (ar_ptr != &main_arena);
4482 return result;
4487 ------------------------- malloc_usable_size -------------------------
4490 static size_t
4491 musable(void* mem)
4493 mchunkptr p;
4494 if (mem != 0) {
4495 p = mem2chunk(mem);
4496 if (chunk_is_mmapped(p))
4497 return chunksize(p) - 2*SIZE_SZ;
4498 else if (inuse(p))
4499 return chunksize(p) - SIZE_SZ;
4501 return 0;
4505 size_t
4506 __malloc_usable_size(void* m)
4508 size_t result;
4510 result = musable(m);
4511 return result;
4515 ------------------------------ mallinfo ------------------------------
4518 static struct mallinfo
4519 int_mallinfo(mstate av)
4521 struct mallinfo mi;
4522 size_t i;
4523 mbinptr b;
4524 mchunkptr p;
4525 INTERNAL_SIZE_T avail;
4526 INTERNAL_SIZE_T fastavail;
4527 int nblocks;
4528 int nfastblocks;
4530 /* Ensure initialization */
4531 if (av->top == 0) malloc_consolidate(av);
4533 check_malloc_state(av);
4535 /* Account for top */
4536 avail = chunksize(av->top);
4537 nblocks = 1; /* top always exists */
4539 /* traverse fastbins */
4540 nfastblocks = 0;
4541 fastavail = 0;
4543 for (i = 0; i < NFASTBINS; ++i) {
4544 for (p = fastbin (av, i); p != 0; p = p->fd) {
4545 ++nfastblocks;
4546 fastavail += chunksize(p);
4550 avail += fastavail;
4552 /* traverse regular bins */
4553 for (i = 1; i < NBINS; ++i) {
4554 b = bin_at(av, i);
4555 for (p = last(b); p != b; p = p->bk) {
4556 ++nblocks;
4557 avail += chunksize(p);
4561 mi.smblks = nfastblocks;
4562 mi.ordblks = nblocks;
4563 mi.fordblks = avail;
4564 mi.uordblks = av->system_mem - avail;
4565 mi.arena = av->system_mem;
4566 mi.hblks = mp_.n_mmaps;
4567 mi.hblkhd = mp_.mmapped_mem;
4568 mi.fsmblks = fastavail;
4569 mi.keepcost = chunksize(av->top);
4570 mi.usmblks = mp_.max_total_mem;
4571 return mi;
4575 struct mallinfo __libc_mallinfo()
4577 struct mallinfo m;
4579 if(__malloc_initialized < 0)
4580 ptmalloc_init ();
4581 (void)mutex_lock(&main_arena.mutex);
4582 m = int_mallinfo(&main_arena);
4583 (void)mutex_unlock(&main_arena.mutex);
4584 return m;
4588 ------------------------------ malloc_stats ------------------------------
4591 void
4592 __malloc_stats()
4594 int i;
4595 mstate ar_ptr;
4596 struct mallinfo mi;
4597 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
4598 #if THREAD_STATS
4599 long stat_lock_direct = 0, stat_lock_loop = 0, stat_lock_wait = 0;
4600 #endif
4602 if(__malloc_initialized < 0)
4603 ptmalloc_init ();
4604 _IO_flockfile (stderr);
4605 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
4606 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
4607 for (i=0, ar_ptr = &main_arena;; i++) {
4608 (void)mutex_lock(&ar_ptr->mutex);
4609 mi = int_mallinfo(ar_ptr);
4610 fprintf(stderr, "Arena %d:\n", i);
4611 fprintf(stderr, "system bytes = %10u\n", (unsigned int)mi.arena);
4612 fprintf(stderr, "in use bytes = %10u\n", (unsigned int)mi.uordblks);
4613 #if MALLOC_DEBUG > 1
4614 if (i > 0)
4615 dump_heap(heap_for_ptr(top(ar_ptr)));
4616 #endif
4617 system_b += mi.arena;
4618 in_use_b += mi.uordblks;
4619 #if THREAD_STATS
4620 stat_lock_direct += ar_ptr->stat_lock_direct;
4621 stat_lock_loop += ar_ptr->stat_lock_loop;
4622 stat_lock_wait += ar_ptr->stat_lock_wait;
4623 #endif
4624 (void)mutex_unlock(&ar_ptr->mutex);
4625 ar_ptr = ar_ptr->next;
4626 if(ar_ptr == &main_arena) break;
4628 fprintf(stderr, "Total (incl. mmap):\n");
4629 fprintf(stderr, "system bytes = %10u\n", system_b);
4630 fprintf(stderr, "in use bytes = %10u\n", in_use_b);
4631 fprintf(stderr, "max mmap regions = %10u\n", (unsigned int)mp_.max_n_mmaps);
4632 fprintf(stderr, "max mmap bytes = %10lu\n",
4633 (unsigned long)mp_.max_mmapped_mem);
4634 #if THREAD_STATS
4635 fprintf(stderr, "heaps created = %10d\n", stat_n_heaps);
4636 fprintf(stderr, "locked directly = %10ld\n", stat_lock_direct);
4637 fprintf(stderr, "locked in loop = %10ld\n", stat_lock_loop);
4638 fprintf(stderr, "locked waiting = %10ld\n", stat_lock_wait);
4639 fprintf(stderr, "locked total = %10ld\n",
4640 stat_lock_direct + stat_lock_loop + stat_lock_wait);
4641 #endif
4642 ((_IO_FILE *) stderr)->_flags2 |= old_flags2;
4643 _IO_funlockfile (stderr);
4648 ------------------------------ mallopt ------------------------------
4651 int __libc_mallopt(int param_number, int value)
4653 mstate av = &main_arena;
4654 int res = 1;
4656 if(__malloc_initialized < 0)
4657 ptmalloc_init ();
4658 (void)mutex_lock(&av->mutex);
4659 /* Ensure initialization/consolidation */
4660 malloc_consolidate(av);
4662 switch(param_number) {
4663 case M_MXFAST:
4664 if (value >= 0 && value <= MAX_FAST_SIZE) {
4665 set_max_fast(value);
4667 else
4668 res = 0;
4669 break;
4671 case M_TRIM_THRESHOLD:
4672 mp_.trim_threshold = value;
4673 mp_.no_dyn_threshold = 1;
4674 break;
4676 case M_TOP_PAD:
4677 mp_.top_pad = value;
4678 mp_.no_dyn_threshold = 1;
4679 break;
4681 case M_MMAP_THRESHOLD:
4682 /* Forbid setting the threshold too high. */
4683 if((unsigned long)value > HEAP_MAX_SIZE/2)
4684 res = 0;
4685 else
4686 mp_.mmap_threshold = value;
4687 mp_.no_dyn_threshold = 1;
4688 break;
4690 case M_MMAP_MAX:
4691 mp_.n_mmaps_max = value;
4692 mp_.no_dyn_threshold = 1;
4693 break;
4695 case M_CHECK_ACTION:
4696 check_action = value;
4697 break;
4699 case M_PERTURB:
4700 perturb_byte = value;
4701 break;
4703 #ifdef PER_THREAD
4704 case M_ARENA_TEST:
4705 if (value > 0)
4706 mp_.arena_test = value;
4707 break;
4709 case M_ARENA_MAX:
4710 if (value > 0)
4711 mp_.arena_max = value;
4712 break;
4713 #endif
4715 (void)mutex_unlock(&av->mutex);
4716 return res;
4718 libc_hidden_def (__libc_mallopt)
4722 -------------------- Alternative MORECORE functions --------------------
4727 General Requirements for MORECORE.
4729 The MORECORE function must have the following properties:
4731 If MORECORE_CONTIGUOUS is false:
4733 * MORECORE must allocate in multiples of pagesize. It will
4734 only be called with arguments that are multiples of pagesize.
4736 * MORECORE(0) must return an address that is at least
4737 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
4739 else (i.e. If MORECORE_CONTIGUOUS is true):
4741 * Consecutive calls to MORECORE with positive arguments
4742 return increasing addresses, indicating that space has been
4743 contiguously extended.
4745 * MORECORE need not allocate in multiples of pagesize.
4746 Calls to MORECORE need not have args of multiples of pagesize.
4748 * MORECORE need not page-align.
4750 In either case:
4752 * MORECORE may allocate more memory than requested. (Or even less,
4753 but this will generally result in a malloc failure.)
4755 * MORECORE must not allocate memory when given argument zero, but
4756 instead return one past the end address of memory from previous
4757 nonzero call. This malloc does NOT call MORECORE(0)
4758 until at least one call with positive arguments is made, so
4759 the initial value returned is not important.
4761 * Even though consecutive calls to MORECORE need not return contiguous
4762 addresses, it must be OK for malloc'ed chunks to span multiple
4763 regions in those cases where they do happen to be contiguous.
4765 * MORECORE need not handle negative arguments -- it may instead
4766 just return MORECORE_FAILURE when given negative arguments.
4767 Negative arguments are always multiples of pagesize. MORECORE
4768 must not misinterpret negative args as large positive unsigned
4769 args. You can suppress all such calls from even occurring by defining
4770 MORECORE_CANNOT_TRIM,
4772 There is some variation across systems about the type of the
4773 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
4774 actually be size_t, because sbrk supports negative args, so it is
4775 normally the signed type of the same width as size_t (sometimes
4776 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
4777 matter though. Internally, we use "long" as arguments, which should
4778 work across all reasonable possibilities.
4780 Additionally, if MORECORE ever returns failure for a positive
4781 request, then mmap is used as a noncontiguous system allocator. This
4782 is a useful backup strategy for systems with holes in address spaces
4783 -- in this case sbrk cannot contiguously expand the heap, but mmap
4784 may be able to map noncontiguous space.
4786 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
4787 a function that always returns MORECORE_FAILURE.
4789 If you are using this malloc with something other than sbrk (or its
4790 emulation) to supply memory regions, you probably want to set
4791 MORECORE_CONTIGUOUS as false. As an example, here is a custom
4792 allocator kindly contributed for pre-OSX macOS. It uses virtually
4793 but not necessarily physically contiguous non-paged memory (locked
4794 in, present and won't get swapped out). You can use it by
4795 uncommenting this section, adding some #includes, and setting up the
4796 appropriate defines above:
4798 #define MORECORE osMoreCore
4799 #define MORECORE_CONTIGUOUS 0
4801 There is also a shutdown routine that should somehow be called for
4802 cleanup upon program exit.
4804 #define MAX_POOL_ENTRIES 100
4805 #define MINIMUM_MORECORE_SIZE (64 * 1024)
4806 static int next_os_pool;
4807 void *our_os_pools[MAX_POOL_ENTRIES];
4809 void *osMoreCore(int size)
4811 void *ptr = 0;
4812 static void *sbrk_top = 0;
4814 if (size > 0)
4816 if (size < MINIMUM_MORECORE_SIZE)
4817 size = MINIMUM_MORECORE_SIZE;
4818 if (CurrentExecutionLevel() == kTaskLevel)
4819 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
4820 if (ptr == 0)
4822 return (void *) MORECORE_FAILURE;
4824 // save ptrs so they can be freed during cleanup
4825 our_os_pools[next_os_pool] = ptr;
4826 next_os_pool++;
4827 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
4828 sbrk_top = (char *) ptr + size;
4829 return ptr;
4831 else if (size < 0)
4833 // we don't currently support shrink behavior
4834 return (void *) MORECORE_FAILURE;
4836 else
4838 return sbrk_top;
4842 // cleanup any allocated memory pools
4843 // called as last thing before shutting down driver
4845 void osCleanupMem(void)
4847 void **ptr;
4849 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
4850 if (*ptr)
4852 PoolDeallocate(*ptr);
4853 *ptr = 0;
4860 /* Helper code. */
4862 extern char **__libc_argv attribute_hidden;
4864 static void
4865 malloc_printerr(int action, const char *str, void *ptr)
4867 if ((action & 5) == 5)
4868 __libc_message (action & 2, "%s\n", str);
4869 else if (action & 1)
4871 char buf[2 * sizeof (uintptr_t) + 1];
4873 buf[sizeof (buf) - 1] = '\0';
4874 char *cp = _itoa_word ((uintptr_t) ptr, &buf[sizeof (buf) - 1], 16, 0);
4875 while (cp > buf)
4876 *--cp = '0';
4878 __libc_message (action & 2,
4879 "*** glibc detected *** %s: %s: 0x%s ***\n",
4880 __libc_argv[0] ?: "<unknown>", str, cp);
4882 else if (action & 2)
4883 abort ();
4886 #include <sys/param.h>
4888 /* We need a wrapper function for one of the additions of POSIX. */
4890 __posix_memalign (void **memptr, size_t alignment, size_t size)
4892 void *mem;
4894 /* Test whether the SIZE argument is valid. It must be a power of
4895 two multiple of sizeof (void *). */
4896 if (alignment % sizeof (void *) != 0
4897 || !powerof2 (alignment / sizeof (void *)) != 0
4898 || alignment == 0)
4899 return EINVAL;
4901 /* Call the hook here, so that caller is posix_memalign's caller
4902 and not posix_memalign itself. */
4903 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
4904 const __malloc_ptr_t)) =
4905 force_reg (__memalign_hook);
4906 if (__builtin_expect (hook != NULL, 0))
4907 mem = (*hook)(alignment, size, RETURN_ADDRESS (0));
4908 else
4909 mem = __libc_memalign (alignment, size);
4911 if (mem != NULL) {
4912 *memptr = mem;
4913 return 0;
4916 return ENOMEM;
4918 weak_alias (__posix_memalign, posix_memalign)
4922 malloc_info (int options, FILE *fp)
4924 /* For now, at least. */
4925 if (options != 0)
4926 return EINVAL;
4928 int n = 0;
4929 size_t total_nblocks = 0;
4930 size_t total_nfastblocks = 0;
4931 size_t total_avail = 0;
4932 size_t total_fastavail = 0;
4933 size_t total_system = 0;
4934 size_t total_max_system = 0;
4935 size_t total_aspace = 0;
4936 size_t total_aspace_mprotect = 0;
4938 void mi_arena (mstate ar_ptr)
4940 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
4942 size_t nblocks = 0;
4943 size_t nfastblocks = 0;
4944 size_t avail = 0;
4945 size_t fastavail = 0;
4946 struct
4948 size_t from;
4949 size_t to;
4950 size_t total;
4951 size_t count;
4952 } sizes[NFASTBINS + NBINS - 1];
4953 #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
4955 mutex_lock (&ar_ptr->mutex);
4957 for (size_t i = 0; i < NFASTBINS; ++i)
4959 mchunkptr p = fastbin (ar_ptr, i);
4960 if (p != NULL)
4962 size_t nthissize = 0;
4963 size_t thissize = chunksize (p);
4965 while (p != NULL)
4967 ++nthissize;
4968 p = p->fd;
4971 fastavail += nthissize * thissize;
4972 nfastblocks += nthissize;
4973 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
4974 sizes[i].to = thissize;
4975 sizes[i].count = nthissize;
4977 else
4978 sizes[i].from = sizes[i].to = sizes[i].count = 0;
4980 sizes[i].total = sizes[i].count * sizes[i].to;
4983 mbinptr bin = bin_at (ar_ptr, 1);
4984 struct malloc_chunk *r = bin->fd;
4985 if (r != NULL)
4987 while (r != bin)
4989 ++sizes[NFASTBINS].count;
4990 sizes[NFASTBINS].total += r->size;
4991 sizes[NFASTBINS].from = MIN (sizes[NFASTBINS].from, r->size);
4992 sizes[NFASTBINS].to = MAX (sizes[NFASTBINS].to, r->size);
4993 r = r->fd;
4995 nblocks += sizes[NFASTBINS].count;
4996 avail += sizes[NFASTBINS].total;
4999 for (size_t i = 2; i < NBINS; ++i)
5001 bin = bin_at (ar_ptr, i);
5002 r = bin->fd;
5003 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5004 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5005 = sizes[NFASTBINS - 1 + i].count = 0;
5007 if (r != NULL)
5008 while (r != bin)
5010 ++sizes[NFASTBINS - 1 + i].count;
5011 sizes[NFASTBINS - 1 + i].total += r->size;
5012 sizes[NFASTBINS - 1 + i].from
5013 = MIN (sizes[NFASTBINS - 1 + i].from, r->size);
5014 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5015 r->size);
5017 r = r->fd;
5020 if (sizes[NFASTBINS - 1 + i].count == 0)
5021 sizes[NFASTBINS - 1 + i].from = 0;
5022 nblocks += sizes[NFASTBINS - 1 + i].count;
5023 avail += sizes[NFASTBINS - 1 + i].total;
5026 mutex_unlock (&ar_ptr->mutex);
5028 total_nfastblocks += nfastblocks;
5029 total_fastavail += fastavail;
5031 total_nblocks += nblocks;
5032 total_avail += avail;
5034 for (size_t i = 0; i < nsizes; ++i)
5035 if (sizes[i].count != 0 && i != NFASTBINS)
5036 fprintf (fp, "\
5037 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5038 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
5040 if (sizes[NFASTBINS].count != 0)
5041 fprintf (fp, "\
5042 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5043 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5044 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
5046 total_system += ar_ptr->system_mem;
5047 total_max_system += ar_ptr->max_system_mem;
5049 fprintf (fp,
5050 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5051 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5052 "<system type=\"current\" size=\"%zu\"/>\n"
5053 "<system type=\"max\" size=\"%zu\"/>\n",
5054 nfastblocks, fastavail, nblocks, avail,
5055 ar_ptr->system_mem, ar_ptr->max_system_mem);
5057 if (ar_ptr != &main_arena)
5059 heap_info *heap = heap_for_ptr(top(ar_ptr));
5060 fprintf (fp,
5061 "<aspace type=\"total\" size=\"%zu\"/>\n"
5062 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5063 heap->size, heap->mprotect_size);
5064 total_aspace += heap->size;
5065 total_aspace_mprotect += heap->mprotect_size;
5067 else
5069 fprintf (fp,
5070 "<aspace type=\"total\" size=\"%zu\"/>\n"
5071 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5072 ar_ptr->system_mem, ar_ptr->system_mem);
5073 total_aspace += ar_ptr->system_mem;
5074 total_aspace_mprotect += ar_ptr->system_mem;
5077 fputs ("</heap>\n", fp);
5080 if(__malloc_initialized < 0)
5081 ptmalloc_init ();
5083 fputs ("<malloc version=\"1\">\n", fp);
5085 /* Iterate over all arenas currently in use. */
5086 mstate ar_ptr = &main_arena;
5089 mi_arena (ar_ptr);
5090 ar_ptr = ar_ptr->next;
5092 while (ar_ptr != &main_arena);
5094 fprintf (fp,
5095 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5096 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5097 "<system type=\"current\" size=\"%zu\"/>\n"
5098 "<system type=\"max\" size=\"%zu\"/>\n"
5099 "<aspace type=\"total\" size=\"%zu\"/>\n"
5100 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5101 "</malloc>\n",
5102 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
5103 total_system, total_max_system,
5104 total_aspace, total_aspace_mprotect);
5106 return 0;
5110 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5111 strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5112 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5113 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5114 strong_alias (__libc_memalign, __memalign)
5115 weak_alias (__libc_memalign, memalign)
5116 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5117 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5118 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5119 strong_alias (__libc_mallinfo, __mallinfo)
5120 weak_alias (__libc_mallinfo, mallinfo)
5121 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5123 weak_alias (__malloc_stats, malloc_stats)
5124 weak_alias (__malloc_usable_size, malloc_usable_size)
5125 weak_alias (__malloc_trim, malloc_trim)
5126 weak_alias (__malloc_get_state, malloc_get_state)
5127 weak_alias (__malloc_set_state, malloc_set_state)
5130 /* ------------------------------------------------------------
5131 History:
5133 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
5137 * Local variables:
5138 * c-basic-offset: 2
5139 * End: