Replace FSF snail mail address with URLs.
[jlayton/glibc.git] / malloc / malloc.c
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.
6
7    The GNU C Library is free software; you can redistribute it and/or
8    modify it under the terms of the GNU Lesser General Public License as
9    published by the Free Software Foundation; either version 2.1 of the
10    License, or (at your option) any later version.
11
12    The GNU C Library is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    Lesser General Public License for more details.
16
17    You should have received a copy of the GNU Lesser General Public
18    License along with the GNU C Library; see the file COPYING.LIB.  If
19    not, see <http://www.gnu.org/licenses/>.  */
20
21 /*
22   This is a version (aka ptmalloc2) of malloc/free/realloc written by
23   Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
24
25   There have been substantial changesmade after the integration into
26   glibc in all parts of the code.  Do not look for much commonality
27   with the ptmalloc2 version.
28
29 * Version ptmalloc2-20011215
30   based on:
31   VERSION 2.7.0 Sun Mar 11 14:14:06 2001  Doug Lea  (dl at gee)
32
33 * Quickstart
34
35   In order to compile this implementation, a Makefile is provided with
36   the ptmalloc2 distribution, which has pre-defined targets for some
37   popular systems (e.g. "make posix" for Posix threads).  All that is
38   typically required with regard to compiler flags is the selection of
39   the thread package via defining one out of USE_PTHREADS, USE_THR or
40   USE_SPROC.  Check the thread-m.h file for what effects this has.
41   Many/most systems will additionally require USE_TSD_DATA_HACK to be
42   defined, so this is the default for "make posix".
43
44 * Why use this malloc?
45
46   This is not the fastest, most space-conserving, most portable, or
47   most tunable malloc ever written. However it is among the fastest
48   while also being among the most space-conserving, portable and tunable.
49   Consistent balance across these factors results in a good general-purpose
50   allocator for malloc-intensive programs.
51
52   The main properties of the algorithms are:
53   * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
54     with ties normally decided via FIFO (i.e. least recently used).
55   * For small (<= 64 bytes by default) requests, it is a caching
56     allocator, that maintains pools of quickly recycled chunks.
57   * In between, and for combinations of large and small requests, it does
58     the best it can trying to meet both goals at once.
59   * For very large requests (>= 128KB by default), it relies on system
60     memory mapping facilities, if supported.
61
62   For a longer but slightly out of date high-level description, see
63      http://gee.cs.oswego.edu/dl/html/malloc.html
64
65   You may already by default be using a C library containing a malloc
66   that is  based on some version of this malloc (for example in
67   linux). You might still want to use the one in this file in order to
68   customize settings or to avoid overheads associated with library
69   versions.
70
71 * Contents, described in more detail in "description of public routines" below.
72
73   Standard (ANSI/SVID/...)  functions:
74     malloc(size_t n);
75     calloc(size_t n_elements, size_t element_size);
76     free(void* p);
77     realloc(void* p, size_t n);
78     memalign(size_t alignment, size_t n);
79     valloc(size_t n);
80     mallinfo()
81     mallopt(int parameter_number, int parameter_value)
82
83   Additional functions:
84     independent_calloc(size_t n_elements, size_t size, void* chunks[]);
85     independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
86     pvalloc(size_t n);
87     cfree(void* p);
88     malloc_trim(size_t pad);
89     malloc_usable_size(void* p);
90     malloc_stats();
91
92 * Vital statistics:
93
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
98
99   Alignment:                              2 * sizeof(size_t) (default)
100        (i.e., 8 byte alignment with 4byte size_t). This suffices for
101        nearly all current machines and C compilers. However, you can
102        define MALLOC_ALIGNMENT to be wider than this if necessary.
103
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.
107
108   Minimum allocated size: 4-byte ptrs:  16 bytes    (including 4 overhead)
109                           8-byte ptrs:  24/32 bytes (including, 4/8 overhead)
110
111        When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
112        ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
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.
116
117        Even a request for zero bytes (i.e., malloc(0)) returns a
118        pointer to something of the minimum allocatable size.
119
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.
126
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
129
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.
142
143        Requests for sizes outside the allowed range will perform an optional
144        failure action and then return null. (Requests may also
145        also fail because a system is out of memory.)
146
147   Thread-safety: thread-safe
148
149   Compliance: I believe it is compliant with the 1997 Single Unix Specification
150        Also SVID/XPG, ANSI C, and probably others as well.
151
152 * Synopsis of compile-time options:
153
154     People have reported using previous versions of this malloc on all
155     versions of Unix, sometimes by tweaking some of the defines
156     below. It has been tested most extensively on Solaris and Linux.
157     People also report using it in stand-alone embedded systems.
158
159     The implementation is in straight, hand-tuned ANSI C.  It is not
160     at all modular. (Sorry!)  It uses a lot of macros.  To be at all
161     usable, this code should be compiled using an optimizing compiler
162     (for example gcc -O3) that can simplify expressions and control
163     paths. (FAQ: some macros import variables as arguments rather than
164     declare locals because people reported that some debuggers
165     otherwise get confused.)
166
167     OPTION                     DEFAULT VALUE
168
169     Compilation Environment options:
170
171     HAVE_MREMAP                0 unless linux defined
172
173     Changing default word sizes:
174
175     INTERNAL_SIZE_T            size_t
176     MALLOC_ALIGNMENT           MAX (2 * sizeof(INTERNAL_SIZE_T),
177                                     __alignof__ (long double))
178
179     Configuration and functionality options:
180
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
186
187     Options for customizing MORECORE:
188
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)
195
196     Tuning options that are also dynamically changeable via mallopt:
197
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
203
204     There are several other #defined constants and macros that you
205     probably don't want to touch unless you are extending or adapting malloc.  */
206
207 /*
208   void* is the pointer type that malloc should say it returns
209 */
210
211 #ifndef void
212 #define void      void
213 #endif /*void*/
214
215 #include <stddef.h>   /* for size_t */
216 #include <stdlib.h>   /* for getenv(), abort() */
217
218 #include <malloc-machine.h>
219
220 #include <atomic.h>
221 #include <stdio-common/_itoa.h>
222 #include <bits/wordsize.h>
223 #include <sys/sysinfo.h>
224
225 #include <ldsodefs.h>
226
227 #include <unistd.h>
228 #include <stdio.h>    /* needed for malloc_stats */
229 #include <errno.h>
230
231 /* For uintptr_t.  */
232 #include <stdint.h>
233
234 /* For va_arg, va_start, va_end.  */
235 #include <stdarg.h>
236
237
238 /*
239   Debugging:
240
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.
245
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.)
255
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.
259
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.
264 */
265
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__))
273
274 extern const char *__progname;
275
276 static void
277 __malloc_assert (const char *assertion, const char *file, unsigned int line,
278                  const char *function)
279 {
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 ();
287 }
288 #endif
289
290
291 /*
292   INTERNAL_SIZE_T is the word-size used for internal bookkeeping
293   of chunk sizes.
294
295   The default version is the same as size_t.
296
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.
300
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.
308
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.
320 */
321
322 #ifndef INTERNAL_SIZE_T
323 #define INTERNAL_SIZE_T size_t
324 #endif
325
326 /* The corresponding word size */
327 #define SIZE_SZ                (sizeof(INTERNAL_SIZE_T))
328
329
330 /*
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.
336 */
337
338
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.
345
346 #define MALLOC_ALIGNMENT       (2 * SIZE_SZ < __alignof__ (long double) \
347                                 ? __alignof__ (long double) : 2 * SIZE_SZ)
348 */
349 #define MALLOC_ALIGNMENT       (2 * SIZE_SZ)
350 #endif
351
352 /* The corresponding bit mask value */
353 #define MALLOC_ALIGN_MASK      (MALLOC_ALIGNMENT - 1)
354
355
356
357 /*
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).
362 */
363
364 #ifndef REALLOC_ZERO_BYTES_FREES
365 #define REALLOC_ZERO_BYTES_FREES 1
366 #endif
367
368 /*
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.
373
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.
382 */
383
384 #ifndef TRIM_FASTBINS
385 #define TRIM_FASTBINS  0
386 #endif
387
388
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;
394
395
396 #include <string.h>
397
398
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; })
403
404
405 /*
406   MORECORE-related declarations. By default, rely on sbrk
407 */
408
409
410 /*
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.
415 */
416
417 #ifndef MORECORE
418 #define MORECORE sbrk
419 #endif
420
421 /*
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.
426 */
427
428 #ifndef MORECORE_FAILURE
429 #define MORECORE_FAILURE (-1)
430 #endif
431
432 /*
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.
440 */
441
442 #ifndef MORECORE_CONTIGUOUS
443 #define MORECORE_CONTIGUOUS 1
444 #endif
445
446 /*
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.
451 */
452
453 /* #define MORECORE_CANNOT_TRIM */
454
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.
462 */
463
464 #ifndef MORECORE_CLEARS
465 #define MORECORE_CLEARS 1
466 #endif
467
468
469 /*
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.  */
480
481 #ifndef MMAP_AS_MORECORE_SIZE
482 #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
483 #endif
484
485 /*
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.
489 */
490
491 #ifndef HAVE_MREMAP
492 #ifdef linux
493 #define HAVE_MREMAP 1
494 #else
495 #define HAVE_MREMAP 0
496 #endif
497
498 #endif /* HAVE_MREMAP */
499
500
501 /*
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.)
509
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.
515 */
516
517
518 /* ---------- description of public routines ------------ */
519
520 /*
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.
525
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.
533 */
534 void*  __libc_malloc(size_t);
535 libc_hidden_proto (__libc_malloc)
536
537 /*
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.
543
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.
547 */
548 void     __libc_free(void*);
549 libc_hidden_proto (__libc_free)
550
551 /*
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.
555 */
556 void*  __libc_calloc(size_t, size_t);
557
558 /*
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.
563
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.
567
568   If p is null, realloc is equivalent to malloc.
569
570   If space is not available, realloc returns null, errno is set (if on
571   ANSI) and p is NOT freed.
572
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.
577
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).
581
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.
584 */
585 void*  __libc_realloc(void*, size_t);
586 libc_hidden_proto (__libc_realloc)
587
588 /*
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.
592
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.
597
598   Overreliance on memalign is a sure way to fragment space.
599 */
600 void*  __libc_memalign(size_t, size_t);
601 libc_hidden_proto (__libc_memalign)
602
603 /*
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.
607 */
608 void*  __libc_valloc(size_t);
609
610
611
612 /*
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).
625
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)
632 */
633 int      __libc_mallopt(int, int);
634 libc_hidden_proto (__libc_mallopt)
635
636
637 /*
638   mallinfo()
639   Returns (by copy) a struct containing various summary statistics:
640
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.)
655
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.
659 */
660 struct mallinfo __libc_mallinfo(void);
661
662
663 /*
664   pvalloc(size_t n);
665   Equivalent to valloc(minimum-page-that-holds(n)), that is,
666   round up n to nearest pagesize.
667  */
668 void*  __libc_pvalloc(size_t);
669
670 /*
671   malloc_trim(size_t pad);
672
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.
681
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.
689
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.
693 */
694 int      __malloc_trim(size_t);
695
696 /*
697   malloc_usable_size(void* p);
698
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:
706
707   p = malloc(n);
708   assert(malloc_usable_size(p) >= 256);
709
710 */
711 size_t   __malloc_usable_size(void*);
712
713 /*
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.
724
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.
728
729   malloc_stats prints only the most commonly interesting statistics.
730   More information can be obtained by calling mallinfo.
731
732 */
733 void     __malloc_stats(void);
734
735 /*
736   malloc_get_state(void);
737
738   Returns the state of all malloc variables in an opaque data
739   structure.
740 */
741 void*  __malloc_get_state(void);
742
743 /*
744   malloc_set_state(void* state);
745
746   Restore the state of all malloc variables from data obtained with
747   malloc_get_state().
748 */
749 int      __malloc_set_state(void*);
750
751 /*
752   posix_memalign(void **memptr, size_t alignment, size_t size);
753
754   POSIX wrapper like memalign(), checking for validity of size.
755 */
756 int      __posix_memalign(void **, size_t, size_t);
757
758 /* mallopt tuning options */
759
760 /*
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.
766
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.
776
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.
783 */
784
785
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
790
791 #ifndef DEFAULT_MXFAST
792 #define DEFAULT_MXFAST     (64 * SIZE_SZ / 4)
793 #endif
794
795
796 /*
797   M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
798   to keep before releasing via malloc_trim in free().
799
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.
806
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.
816
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.
829
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.
836
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)
840
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.
846
847   Also, trimming is not generally possible in cases where
848   the main arena is obtained via mmap.
849
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.
854 */
855
856 #define M_TRIM_THRESHOLD       -1
857
858 #ifndef DEFAULT_TRIM_THRESHOLD
859 #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
860 #endif
861
862 /*
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:
865
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.
869
870   * When malloc_trim is called automatically from free(),
871   it is used as the `pad' argument.
872
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.
875
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.
881
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.
887 */
888
889 #define M_TOP_PAD              -2
890
891 #ifndef DEFAULT_TOP_PAD
892 #define DEFAULT_TOP_PAD        (0)
893 #endif
894
895 /*
896   MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
897   adjusted MMAP_THRESHOLD.
898 */
899
900 #ifndef DEFAULT_MMAP_THRESHOLD_MIN
901 #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
902 #endif
903
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
915
916 /*
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.)
921
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).
927
928   Segregating space in this way has the benefits that:
929
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.
938
939   However, it has the disadvantages that:
940
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.
950
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.
955
956
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.
961
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.
966
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.
973
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.
979
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
988
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.
992
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).
997
998   The upperbound on the threshold satisfies requirement 2)
999
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.
1005
1006 */
1007
1008 #define M_MMAP_THRESHOLD      -3
1009
1010 #ifndef DEFAULT_MMAP_THRESHOLD
1011 #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
1012 #endif
1013
1014 /*
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.
1020
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.
1023 */
1024
1025 #define M_MMAP_MAX             -4
1026
1027 #ifndef DEFAULT_MMAP_MAX
1028 #define DEFAULT_MMAP_MAX       (65536)
1029 #endif
1030
1031 #include <malloc.h>
1032
1033 #ifndef RETURN_ADDRESS
1034 #define RETURN_ADDRESS(X_) (NULL)
1035 #endif
1036
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
1043
1044 /* Forward declarations.  */
1045 struct malloc_chunk;
1046 typedef struct malloc_chunk* mchunkptr;
1047
1048 /* Internal routines.  */
1049
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);
1058
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
1065
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);
1075
1076
1077 /* ------------- Optional versions of memcopy ---------------- */
1078
1079
1080 /*
1081   Note: memcpy is ONLY invoked with non-overlapping regions,
1082   so the (usually slower) memmove is not needed.
1083 */
1084
1085 #define MALLOC_COPY(dest, src, nbytes)  memcpy(dest, src, nbytes)
1086 #define MALLOC_ZERO(dest, nbytes)       memset(dest, 0,   nbytes)
1087
1088
1089 /* ------------------ MMAP support ------------------  */
1090
1091
1092 #include <fcntl.h>
1093 #include <sys/mman.h>
1094
1095 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1096 # define MAP_ANONYMOUS MAP_ANON
1097 #endif
1098
1099 #ifndef MAP_NORESERVE
1100 # define MAP_NORESERVE 0
1101 #endif
1102
1103 #define MMAP(addr, size, prot, flags) \
1104  __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1105
1106
1107 /*
1108   -----------------------  Chunk representations -----------------------
1109 */
1110
1111
1112 /*
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.
1116 */
1117
1118 struct malloc_chunk {
1119
1120   INTERNAL_SIZE_T      prev_size;  /* Size of previous chunk (if free).  */
1121   INTERNAL_SIZE_T      size;       /* Size in bytes, including overhead. */
1122
1123   struct malloc_chunk* fd;         /* double links -- used only if free. */
1124   struct malloc_chunk* bk;
1125
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;
1129 };
1130
1131
1132 /*
1133    malloc_chunk details:
1134
1135     (The following includes lightly edited explanations by Colin Plumb.)
1136
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.
1145
1146     An allocated chunk looks like this:
1147
1148
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...                          .
1155             .                                                               .
1156             .             (malloc_usable_size() bytes)                      .
1157             .                                                               |
1158 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1159             |             Size of chunk                                     |
1160             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1161
1162
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.
1166
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.
1170
1171     Free chunks are stored in circular doubly-linked lists, and look like this:
1172
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)                .
1183             .                                                               .
1184             .                                                               |
1185 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1186     `foot:' |             Size of chunk, in bytes                           |
1187             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1188
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.
1199
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.
1204
1205     The two exceptions to all this are
1206
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.
1212
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.
1216
1217 */
1218
1219 /*
1220   ---------- Size and alignment checks and conversions ----------
1221 */
1222
1223 /* conversion from malloc headers to user pointers, and back */
1224
1225 #define chunk2mem(p)   ((void*)((char*)(p) + 2*SIZE_SZ))
1226 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1227
1228 /* The smallest possible chunk */
1229 #define MIN_CHUNK_SIZE        (offsetof(struct malloc_chunk, fd_nextsize))
1230
1231 /* The smallest size we can malloc is an aligned minimal chunk */
1232
1233 #define MINSIZE  \
1234   (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1235
1236 /* Check if m has acceptable alignment */
1237
1238 #define aligned_OK(m)  (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1239
1240 #define misaligned_chunk(p) \
1241   ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
1242    & MALLOC_ALIGN_MASK)
1243
1244
1245 /*
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.
1249 */
1250
1251 #define REQUEST_OUT_OF_RANGE(req)                                 \
1252   ((unsigned long)(req) >=                                        \
1253    (unsigned long)(INTERNAL_SIZE_T)(-2 * MINSIZE))
1254
1255 /* pad request bytes into a usable size -- internal version */
1256
1257 #define request2size(req)                                         \
1258   (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE)  ?             \
1259    MINSIZE :                                                      \
1260    ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1261
1262 /*  Same, except also perform argument check */
1263
1264 #define checked_request2size(req, sz)                             \
1265   if (REQUEST_OUT_OF_RANGE(req)) {                                \
1266     __set_errno (ENOMEM);                                         \
1267     return 0;                                                     \
1268   }                                                               \
1269   (sz) = request2size(req);
1270
1271 /*
1272   --------------- Physical chunk operations ---------------
1273 */
1274
1275
1276 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1277 #define PREV_INUSE 0x1
1278
1279 /* extract inuse bit of previous chunk */
1280 #define prev_inuse(p)       ((p)->size & PREV_INUSE)
1281
1282
1283 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1284 #define IS_MMAPPED 0x2
1285
1286 /* check for mmap()'ed chunk */
1287 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
1288
1289
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
1294
1295 /* check for chunk from non-main arena */
1296 #define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)
1297
1298
1299 /*
1300   Bits to mask off when extracting size
1301
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.
1306 */
1307 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED|NON_MAIN_ARENA)
1308
1309 /* Get size, ignoring use bits */
1310 #define chunksize(p)         ((p)->size & ~(SIZE_BITS))
1311
1312
1313 /* Ptr to next physical malloc_chunk. */
1314 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~SIZE_BITS) ))
1315
1316 /* Ptr to previous physical malloc_chunk */
1317 #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
1318
1319 /* Treat space at ptr + offset as a chunk */
1320 #define chunk_at_offset(p, s)  ((mchunkptr)(((char*)(p)) + (s)))
1321
1322 /* extract p's inuse bit */
1323 #define inuse(p)\
1324 ((((mchunkptr)(((char*)(p))+((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)
1325
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
1329
1330 #define clear_inuse(p)\
1331 ((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)
1332
1333
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)
1337
1338 #define set_inuse_bit_at_offset(p, s)\
1339  (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
1340
1341 #define clear_inuse_bit_at_offset(p, s)\
1342  (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
1343
1344
1345 /* Set size at head, without disturbing its use bit */
1346 #define set_head_size(p, s)  ((p)->size = (((p)->size & SIZE_BITS) | (s)))
1347
1348 /* Set size/use field */
1349 #define set_head(p, s)       ((p)->size = (s))
1350
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))
1353
1354
1355 /*
1356   -------------------- Internal data structures --------------------
1357
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.
1364
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.)
1368 */
1369
1370 /*
1371   Bins
1372
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.
1383
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.
1391
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.
1398
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*.
1404 */
1405
1406 typedef struct malloc_chunk* mbinptr;
1407
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))
1412
1413 /* analog of ++bin */
1414 #define next_bin(b)  ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1)))
1415
1416 /* Reminders about list directionality within bins */
1417 #define first(b)     ((b)->fd)
1418 #define last(b)      ((b)->bk)
1419
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;                            \
1441         }                                                              \
1442       } else {                                                         \
1443         P->fd_nextsize->bk_nextsize = P->bk_nextsize;                  \
1444         P->bk_nextsize->fd_nextsize = P->fd_nextsize;                  \
1445       }                                                                \
1446     }                                                                  \
1447   }                                                                    \
1448 }
1449
1450 /*
1451   Indexing
1452
1453     Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1454     8 bytes apart. Larger bins are approximately logarithmically spaced:
1455
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
1463
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.
1466
1467     The bins top out around 1MB because we expect to service large
1468     requests via mmap.
1469 */
1470
1471 #define NBINS             128
1472 #define NSMALLBINS         64
1473 #define SMALLBIN_WIDTH    MALLOC_ALIGNMENT
1474 #define MIN_LARGE_SIZE    (NSMALLBINS * SMALLBIN_WIDTH)
1475
1476 #define in_smallbin_range(sz)  \
1477   ((unsigned long)(sz) < (unsigned long)MIN_LARGE_SIZE)
1478
1479 #define smallbin_index(sz) \
1480   (SMALLBIN_WIDTH == 16 ? (((unsigned)(sz)) >> 4) : (((unsigned)(sz)) >> 3))
1481
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)
1489
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)
1500
1501 #define largebin_index(sz) \
1502   (SIZE_SZ == 8 ? largebin_index_64 (sz) : largebin_index_32 (sz))
1503
1504 #define bin_index(sz) \
1505  ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz))
1506
1507
1508 /*
1509   Unsorted chunks
1510
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.
1517
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.
1520 */
1521
1522 /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1523 #define unsorted_chunks(M)          (bin_at(M, 1))
1524
1525 /*
1526   Top
1527
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.)
1541 */
1542
1543 /* Conveniently, the unsorted bin can be used as dummy top on first call */
1544 #define initial_top(M)              (unsorted_chunks(M))
1545
1546 /*
1547   Binmap
1548
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.
1555 */
1556
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)
1561
1562 #define idx2block(i)     ((i) >> BINMAPSHIFT)
1563 #define idx2bit(i)       ((1U << ((i) & ((1U << BINMAPSHIFT)-1))))
1564
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))
1568
1569 /*
1570   Fastbins
1571
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.
1579
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.
1584 */
1585
1586 typedef struct malloc_chunk* mfastbinptr;
1587 #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1588
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)
1592
1593
1594 /* The maximum fastbin request size we support */
1595 #define MAX_FAST_SIZE     (80 * SIZE_SZ / 4)
1596
1597 #define NFASTBINS  (fastbin_index(request2size(MAX_FAST_SIZE))+1)
1598
1599 /*
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.
1608 */
1609
1610 #define FASTBIN_CONSOLIDATION_THRESHOLD  (65536UL)
1611
1612 /*
1613   Since the lowest 2 bits in max_fast don't matter in size comparisons,
1614   they are used as flags.
1615 */
1616
1617 /*
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.
1621
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.
1625 */
1626
1627 #define FASTCHUNKS_BIT        (1U)
1628
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)
1632
1633 /*
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.
1637
1638   The initial value comes from MORECORE_CONTIGUOUS, but is
1639   changed dynamically if mmap is ever used as an sbrk substitute.
1640 */
1641
1642 #define NONCONTIGUOUS_BIT     (2U)
1643
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)
1648
1649 /*
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.
1654 */
1655
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
1660
1661
1662 /*
1663    ----------- Internal state representation and initialization -----------
1664 */
1665
1666 struct malloc_state {
1667   /* Serialize access.  */
1668   mutex_t mutex;
1669
1670   /* Flags (formerly in max_fast).  */
1671   int flags;
1672
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
1677
1678   /* Fastbins */
1679   mfastbinptr      fastbinsY[NFASTBINS];
1680
1681   /* Base of the topmost chunk -- not otherwise kept in a bin */
1682   mchunkptr        top;
1683
1684   /* The remainder from the most recent split of a small request */
1685   mchunkptr        last_remainder;
1686
1687   /* Normal bins packed as described above */
1688   mchunkptr        bins[NBINS * 2 - 2];
1689
1690   /* Bitmap of bins */
1691   unsigned int     binmap[BINMAPSIZE];
1692
1693   /* Linked list */
1694   struct malloc_state *next;
1695
1696 #ifdef PER_THREAD
1697   /* Linked list for free arenas.  */
1698   struct malloc_state *next_free;
1699 #endif
1700
1701   /* Memory allocated from the system in this arena.  */
1702   INTERNAL_SIZE_T system_mem;
1703   INTERNAL_SIZE_T max_system_mem;
1704 };
1705
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
1715
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;
1724
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 */
1731
1732   /* First address handed out by MORECORE/sbrk.  */
1733   char*            sbrk_base;
1734 };
1735
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).  */
1741
1742 static struct malloc_state main_arena =
1743   {
1744     .mutex = MUTEX_INITIALIZER,
1745     .next = &main_arena
1746   };
1747
1748 /* There is only one instance of the malloc parameters.  */
1749
1750 static struct malloc_par mp_ =
1751   {
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
1760   };
1761
1762
1763 #ifdef PER_THREAD
1764 /*  Non public mallopt parameters.  */
1765 #define M_ARENA_TEST -7
1766 #define M_ARENA_MAX  -8
1767 #endif
1768
1769
1770 /* Maximum size of memory handled in fastbins.  */
1771 static INTERNAL_SIZE_T global_max_fast;
1772
1773 /*
1774   Initialize a malloc_state struct.
1775
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.)
1781 */
1782
1783 static void malloc_init_state(mstate av)
1784 {
1785   int     i;
1786   mbinptr bin;
1787
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;
1792   }
1793
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;
1801
1802   av->top            = initial_top(av);
1803 }
1804
1805 /*
1806    Other internal utilities operating on mstates
1807 */
1808
1809 static void*  sysmalloc(INTERNAL_SIZE_T, mstate);
1810 static int      systrim(size_t, mstate);
1811 static void     malloc_consolidate(mstate);
1812
1813
1814 /* -------------- Early definitions for debugging hooks ---------------- */
1815
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
1823
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));
1831
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;
1844
1845
1846 /* ---------------- Error behavior ------------------------------------ */
1847
1848 #ifndef DEFAULT_CHECK_ACTION
1849 #define DEFAULT_CHECK_ACTION 3
1850 #endif
1851
1852 static int check_action = DEFAULT_CHECK_ACTION;
1853
1854
1855 /* ------------------ Testing support ----------------------------------*/
1856
1857 static int perturb_byte;
1858
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)
1861
1862
1863 /* ------------------- Support for multiple arenas -------------------- */
1864 #include "arena.c"
1865
1866 /*
1867   Debugging support
1868
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!)
1874 */
1875
1876 #if ! MALLOC_DEBUG
1877
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)
1884
1885 #else
1886
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)
1893
1894 /*
1895   Properties of all chunks
1896 */
1897
1898 static void do_check_chunk(mstate av, mchunkptr p)
1899 {
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;
1904
1905   if (!chunk_is_mmapped(p)) {
1906
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)));
1912       }
1913     }
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));
1919     }
1920
1921   }
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);
1926     }
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)));
1931   }
1932 }
1933
1934 /*
1935   Properties of free chunks
1936 */
1937
1938 static void do_check_free_chunk(mstate av, mchunkptr p)
1939 {
1940   INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
1941   mchunkptr next = chunk_at_offset(p, sz);
1942
1943   do_check_chunk(av, p);
1944
1945   /* Chunk must claim to be free ... */
1946   assert(!inuse(p));
1947   assert (!chunk_is_mmapped(p));
1948
1949   /* Unless a special marker, must have OK fields */
1950   if ((unsigned long)(sz) >= MINSIZE)
1951   {
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));
1959
1960     /* ... and has minimally sane links */
1961     assert(p->fd->bk == p);
1962     assert(p->bk->fd == p);
1963   }
1964   else /* markers are always of size SIZE_SZ */
1965     assert(sz == SIZE_SZ);
1966 }
1967
1968 /*
1969   Properties of inuse chunks
1970 */
1971
1972 static void do_check_inuse_chunk(mstate av, mchunkptr p)
1973 {
1974   mchunkptr next;
1975
1976   do_check_chunk(av, p);
1977
1978   if (chunk_is_mmapped(p))
1979     return; /* mmapped chunks have no next/prev */
1980
1981   /* Check whether it claims to be in use ... */
1982   assert(inuse(p));
1983
1984   next = next_chunk(p);
1985
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.
1989   */
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);
1995   }
1996
1997   if (next == av->top) {
1998     assert(prev_inuse(next));
1999     assert(chunksize(next) >= MINSIZE);
2000   }
2001   else if (!inuse(next))
2002     do_check_free_chunk(av, next);
2003 }
2004
2005 /*
2006   Properties of chunks recycled from fastbins
2007 */
2008
2009 static void do_check_remalloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2010 {
2011   INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
2012
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);
2019   }
2020
2021   do_check_inuse_chunk(av, p);
2022
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);
2031 }
2032
2033 /*
2034   Properties of nonrecycled chunks at the point they are malloced
2035 */
2036
2037 static void do_check_malloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2038 {
2039   /* same as recycled case ... */
2040   do_check_remalloced_chunk(av, p, s);
2041
2042   /*
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.
2050   */
2051
2052   assert(prev_inuse(p));
2053 }
2054
2055
2056 /*
2057   Properties of malloc_state.
2058
2059   This may be useful for debugging malloc, as well as detecting user
2060   programmer errors that somehow write into malloc_state.
2061
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.
2065 */
2066
2067 static void do_check_malloc_state(mstate av)
2068 {
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;
2077
2078   /* internal size_t must be no wider than pointer type */
2079   assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*));
2080
2081   /* alignment is a power of 2 */
2082   assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0);
2083
2084   /* cannot run remaining checks until fully initialized */
2085   if (av->top == 0 || av->top == initial_top(av))
2086     return;
2087
2088   /* pagesize is a power of 2 */
2089   assert((GLRO(dl_pagesize) & (GLRO(dl_pagesize)-1)) == 0);
2090
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));
2095
2096   /* properties of fastbins */
2097
2098   /* max_fast is in allowed range */
2099   assert((get_max_fast () & ~1) <= request2size(MAX_FAST_SIZE));
2100
2101   max_fast_bin = fastbin_index(get_max_fast ());
2102
2103   for (i = 0; i < NFASTBINS; ++i) {
2104     p = fastbin (av, i);
2105
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.  */
2116
2117     /* all bins past max_fast are empty */
2118     if (av == &main_arena && i > max_fast_bin)
2119       assert(p == 0);
2120
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;
2128     }
2129   }
2130
2131   if (total != 0)
2132     assert(have_fastchunks(av));
2133   else if (!have_fastchunks(av))
2134     assert(total == 0);
2135
2136   /* check normal bins */
2137   for (i = 1; i < NBINS; ++i) {
2138     b = bin_at(av,i);
2139
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);
2148     }
2149
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));
2162
2163         if (!in_smallbin_range(size))
2164           {
2165             if (p->fd_nextsize != NULL)
2166               {
2167                 if (p->fd_nextsize == p)
2168                   assert (p->bk_nextsize == p);
2169                 else
2170                   {
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));
2175
2176                     if (p == first (b))
2177                       assert (chunksize (p) > chunksize (p->bk_nextsize));
2178                     else
2179                       assert (chunksize (p) < chunksize (p->bk_nextsize));
2180                   }
2181               }
2182             else
2183               assert (p->bk_nextsize == NULL);
2184           }
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);
2193     }
2194   }
2195
2196   /* top chunk is OK */
2197   check_chunk(av, av->top);
2198
2199   /* sanity checks for statistics */
2200
2201   assert(mp_.n_mmaps <= mp_.max_n_mmaps);
2202
2203   assert((unsigned long)(av->system_mem) <=
2204          (unsigned long)(av->max_system_mem));
2205
2206   assert((unsigned long)(mp_.mmapped_mem) <=
2207          (unsigned long)(mp_.max_mmapped_mem));
2208 }
2209 #endif
2210
2211
2212 /* ----------------- Support for debugging hooks -------------------- */
2213 #include "hooks.c"
2214
2215
2216 /* ----------- Routines dealing with system allocation -------------- */
2217
2218 /*
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.
2223 */
2224
2225 static void* sysmalloc(INTERNAL_SIZE_T nb, mstate av)
2226 {
2227   mchunkptr       old_top;        /* incoming value of av->top */
2228   INTERNAL_SIZE_T old_size;       /* its size */
2229   char*           old_end;        /* its end address */
2230
2231   long            size;           /* arg to first MORECORE or mmap call */
2232   char*           brk;            /* return value from MORECORE */
2233
2234   long            correction;     /* arg to 2nd MORECORE call */
2235   char*           snd_brk;        /* 2nd return val */
2236
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 */
2240
2241   mchunkptr       p;              /* the allocated/returned chunk */
2242   mchunkptr       remainder;      /* remainder from allocation */
2243   unsigned long   remainder_size; /* its size */
2244
2245   unsigned long   sum;            /* for updating stats */
2246
2247   size_t          pagemask  = GLRO(dl_pagesize) - 1;
2248   bool            tried_mmap = false;
2249
2250
2251   /*
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.
2256   */
2257
2258   if ((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) &&
2259       (mp_.n_mmaps < mp_.n_mmaps_max)) {
2260
2261     char* mm;             /* return value from mmap call*/
2262
2263   try_mmap:
2264     /*
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.
2268
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;
2273
2274     /* Don't try if size wraps around 0 */
2275     if ((unsigned long)(size) > (unsigned long)(nb)) {
2276
2277       mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, 0));
2278
2279       if (mm != MAP_FAILED) {
2280
2281         /*
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().
2287
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);
2292
2293         p = (mchunkptr)mm;
2294         set_head(p, size|IS_MMAPPED);
2295
2296         /* update statistics */
2297
2298         if (++mp_.n_mmaps > mp_.max_n_mmaps)
2299           mp_.max_n_mmaps = mp_.n_mmaps;
2300
2301         sum = mp_.mmapped_mem += size;
2302         if (sum > (unsigned long)(mp_.max_mmapped_mem))
2303           mp_.max_mmapped_mem = sum;
2304
2305         check_chunk(av, p);
2306
2307         return chunk2mem(p);
2308       }
2309     }
2310   }
2311
2312   /* Record incoming configuration of top */
2313
2314   old_top  = av->top;
2315   old_size = chunksize(old_top);
2316   old_end  = (char*)(chunk_at_offset(old_top, old_size));
2317
2318   brk = snd_brk = (char*)(MORECORE_FAILURE);
2319
2320   /*
2321      If not the first time through, we require old_size to be
2322      at least MINSIZE and to have prev_inuse set.
2323   */
2324
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));
2329
2330   /* Precondition: not enough current space to satisfy nb request */
2331   assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE));
2332
2333
2334   if (av != &main_arena) {
2335
2336     heap_info *old_heap, *heap;
2337     size_t old_heap_size;
2338
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);
2348     }
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);
2358
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));
2373       }
2374     }
2375     else if (!tried_mmap)
2376       /* We can at least try to use to mmap memory.  */
2377       goto try_mmap;
2378
2379   } else { /* av == main_arena */
2380
2381
2382   /* Request enough space for nb + pad + overhead */
2383
2384   size = nb + mp_.top_pad + MINSIZE;
2385
2386   /*
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.
2390   */
2391
2392   if (contiguous(av))
2393     size -= old_size;
2394
2395   /*
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.
2401   */
2402
2403   size = (size + pagemask) & ~pagemask;
2404
2405   /*
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.
2409   */
2410
2411   if (size > 0)
2412     brk = (char*)(MORECORE(size));
2413
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 {
2420   /*
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.
2427   */
2428
2429     /* Cannot merge with old top, so add its size back in */
2430     if (contiguous(av))
2431       size = (size + old_size + pagemask) & ~pagemask;
2432
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;
2436
2437     /* Don't try if size wraps around 0 */
2438     if ((unsigned long)(size) > (unsigned long)(nb)) {
2439
2440       char *mbrk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, 0));
2441
2442       if (mbrk != MAP_FAILED) {
2443
2444         /* We do not need, and cannot use, another sbrk call to find end */
2445         brk = mbrk;
2446         snd_brk = brk + size;
2447
2448         /*
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.
2453         */
2454         set_noncontiguous(av);
2455       }
2456     }
2457   }
2458
2459   if (brk != (char*)(MORECORE_FAILURE)) {
2460     if (mp_.sbrk_base == 0)
2461       mp_.sbrk_base = brk;
2462     av->system_mem += size;
2463
2464     /*
2465       If MORECORE extends previous space, we can likewise extend top size.
2466     */
2467
2468     if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE))
2469       set_head(old_top, (size + old_size) | PREV_INUSE);
2470
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);
2474     }
2475
2476     /*
2477       Otherwise, make adjustments:
2478
2479       * If the first time through or noncontiguous, we need to call sbrk
2480         just to find out where the end of memory lies.
2481
2482       * We need to ensure that all returned chunks from malloc will meet
2483         MALLOC_ALIGNMENT
2484
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.
2488
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.
2493     */
2494
2495     else {
2496       front_misalign = 0;
2497       end_misalign = 0;
2498       correction = 0;
2499       aligned_brk = brk;
2500
2501       /* handle contiguous cases */
2502       if (contiguous(av)) {
2503
2504         /* Count foreign sbrk as system_mem.  */
2505         if (old_size)
2506           av->system_mem += brk - old_end;
2507
2508         /* Guarantee alignment of first new chunk made from this space */
2509
2510         front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;
2511         if (front_misalign > 0) {
2512
2513           /*
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.
2519           */
2520
2521           correction = MALLOC_ALIGNMENT - front_misalign;
2522           aligned_brk += correction;
2523         }
2524
2525         /*
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.
2528         */
2529
2530         correction += old_size;
2531
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;
2535
2536         assert(correction >= 0);
2537         snd_brk = (char*)(MORECORE(correction));
2538
2539         /*
2540           If can't allocate correction, try to at least find out current
2541           brk.  It might be enough to proceed without failing.
2542
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.
2547         */
2548
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) ();
2557         }
2558       }
2559
2560       /* handle non-contiguous cases */
2561       else {
2562         /* MORECORE/mmap must correctly align */
2563         assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0);
2564
2565         /* Find out current end of memory */
2566         if (snd_brk == (char*)(MORECORE_FAILURE)) {
2567           snd_brk = (char*)(MORECORE(0));
2568         }
2569       }
2570
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;
2576
2577         /*
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.
2584         */
2585
2586         if (old_size != 0) {
2587           /*
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.
2591           */
2592           old_size = (old_size - 4*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
2593           set_head(old_top, old_size | PREV_INUSE);
2594
2595           /*
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.
2600           */
2601           chunk_at_offset(old_top, old_size            )->size =
2602             (2*SIZE_SZ)|PREV_INUSE;
2603
2604           chunk_at_offset(old_top, old_size + 2*SIZE_SZ)->size =
2605             (2*SIZE_SZ)|PREV_INUSE;
2606
2607           /* If possible, release the rest. */
2608           if (old_size >= MINSIZE) {
2609             _int_free(av, old_top, 1);
2610           }
2611
2612         }
2613       }
2614     }
2615   }
2616
2617   } /* if (av !=  &main_arena) */
2618
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);
2622
2623   /* finally, do the allocation */
2624   p = av->top;
2625   size = chunksize(p);
2626
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);
2636   }
2637
2638   /* catch all failure paths */
2639   __set_errno (ENOMEM);
2640   return 0;
2641 }
2642
2643
2644 /*
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.
2651 */
2652
2653 static int systrim(size_t pad, mstate av)
2654 {
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;
2661
2662   pagesz = GLRO(dl_pagesize);
2663   top_size = chunksize(av->top);
2664
2665   /* Release in pagesize units, keeping at least one page */
2666   extra = (top_size - pad - MINSIZE - 1) & ~(pagesz - 1);
2667
2668   if (extra > 0) {
2669
2670     /*
2671       Only proceed if end of memory is where we last set it.
2672       This avoids problems if there were foreign sbrk calls.
2673     */
2674     current_brk = (char*)(MORECORE(0));
2675     if (current_brk == (char*)(av->top) + top_size) {
2676
2677       /*
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.)
2685       */
2686
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));
2693
2694       if (new_brk != (char*)MORECORE_FAILURE) {
2695         released = (long)(current_brk - new_brk);
2696
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;
2703         }
2704       }
2705     }
2706   }
2707   return 0;
2708 }
2709
2710 static void
2711 internal_function
2712 munmap_chunk(mchunkptr p)
2713 {
2714   INTERNAL_SIZE_T size = chunksize(p);
2715
2716   assert (chunk_is_mmapped(p));
2717
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))
2726     {
2727       malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
2728                        chunk2mem (p));
2729       return;
2730     }
2731
2732   mp_.n_mmaps--;
2733   mp_.mmapped_mem -= total_size;
2734
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);
2739 }
2740
2741 #if HAVE_MREMAP
2742
2743 static mchunkptr
2744 internal_function
2745 mremap_chunk(mchunkptr p, size_t new_size)
2746 {
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;
2751
2752   assert (chunk_is_mmapped(p));
2753   assert(((size + offset) & (GLRO(dl_pagesize)-1)) == 0);
2754
2755   /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2756   new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
2757
2758   /* No need to remap if the number of pages does not change.  */
2759   if (size + offset == new_size)
2760     return p;
2761
2762   cp = (char *)__mremap((char *)p - offset, size + offset, new_size,
2763                         MREMAP_MAYMOVE);
2764
2765   if (cp == MAP_FAILED) return 0;
2766
2767   p = (mchunkptr)(cp + offset);
2768
2769   assert(aligned_OK(chunk2mem(p)));
2770
2771   assert((p->prev_size == offset));
2772   set_head(p, (new_size - offset)|IS_MMAPPED);
2773
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;
2779 }
2780
2781 #endif /* HAVE_MREMAP */
2782
2783 /*------------------------ Public wrappers. --------------------------------*/
2784
2785 void*
2786 __libc_malloc(size_t bytes)
2787 {
2788   mstate ar_ptr;
2789   void *victim;
2790
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));
2795
2796   arena_lookup(ar_ptr);
2797
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);
2817       }
2818     }
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;
2824 }
2825 libc_hidden_def(__libc_malloc)
2826
2827 void
2828 __libc_free(void* mem)
2829 {
2830   mstate ar_ptr;
2831   mchunkptr p;                          /* chunk corresponding to mem */
2832
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;
2838   }
2839
2840   if (mem == 0)                              /* free(0) has no effect */
2841     return;
2842
2843   p = mem2chunk(mem);
2844
2845   if (chunk_is_mmapped(p))                       /* release mmapped memory. */
2846   {
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)
2851       {
2852         mp_.mmap_threshold = chunksize (p);
2853         mp_.trim_threshold = 2 * mp_.mmap_threshold;
2854       }
2855     munmap_chunk(p);
2856     return;
2857   }
2858
2859   ar_ptr = arena_for_chunk(p);
2860   _int_free(ar_ptr, p, 0);
2861 }
2862 libc_hidden_def (__libc_free)
2863
2864 void*
2865 __libc_realloc(void* oldmem, size_t bytes)
2866 {
2867   mstate ar_ptr;
2868   INTERNAL_SIZE_T    nb;      /* padded request size */
2869
2870   void* newp;             /* chunk to return */
2871
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));
2876
2877 #if REALLOC_ZERO_BYTES_FREES
2878   if (bytes == 0 && oldmem != NULL) { __libc_free(oldmem); return 0; }
2879 #endif
2880
2881   /* realloc of null is supposed to be same as malloc */
2882   if (oldmem == 0) return __libc_malloc(bytes);
2883
2884   /* chunk corresponding to oldmem */
2885   const mchunkptr oldp    = mem2chunk(oldmem);
2886   /* its size */
2887   const INTERNAL_SIZE_T oldsize = chunksize(oldp);
2888
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))
2895     {
2896       malloc_printerr (check_action, "realloc(): invalid pointer", oldmem);
2897       return NULL;
2898     }
2899
2900   checked_request2size(bytes, nb);
2901
2902   if (chunk_is_mmapped(oldp))
2903   {
2904     void* newmem;
2905
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;
2918   }
2919
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);
2927   }
2928 #else
2929   (void)mutex_lock(&ar_ptr->mutex);
2930 #endif
2931
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
2936
2937   newp = _int_realloc(ar_ptr, oldp, oldsize, nb);
2938
2939   (void)mutex_unlock(&ar_ptr->mutex);
2940   assert(!newp || chunk_is_mmapped(mem2chunk(newp)) ||
2941          ar_ptr == arena_for_chunk(mem2chunk(newp)));
2942
2943   if (newp == NULL)
2944     {
2945       /* Try harder to allocate memory in other arenas.  */
2946       newp = __libc_malloc(bytes);
2947       if (newp != NULL)
2948         {
2949           MALLOC_COPY (newp, oldmem, oldsize - SIZE_SZ);
2950           _int_free(ar_ptr, oldp, 0);
2951         }
2952     }
2953
2954   return newp;
2955 }
2956 libc_hidden_def (__libc_realloc)
2957
2958 void*
2959 __libc_memalign(size_t alignment, size_t bytes)
2960 {
2961   mstate ar_ptr;
2962   void *p;
2963
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));
2969
2970   /* If need less alignment than we give anyway, just relay to malloc */
2971   if (alignment <= MALLOC_ALIGNMENT) return __libc_malloc(bytes);
2972
2973   /* Otherwise, ensure that it is at least a minimum chunk size */
2974   if (alignment <  MINSIZE) alignment = MINSIZE;
2975
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);
2996       }
2997     }
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;
3003 }
3004 /* For ISO C11.  */
3005 weak_alias (__libc_memalign, aligned_alloc)
3006 libc_hidden_def (__libc_memalign)
3007
3008 void*
3009 __libc_valloc(size_t bytes)
3010 {
3011   mstate ar_ptr;
3012   void *p;
3013
3014   if(__malloc_initialized < 0)
3015     ptmalloc_init ();
3016
3017   size_t pagesz = GLRO(dl_pagesize);
3018
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));
3024
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);
3043       }
3044     }
3045   }
3046   assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3047          ar_ptr == arena_for_chunk(mem2chunk(p)));
3048
3049   return p;
3050 }
3051
3052 void*
3053 __libc_pvalloc(size_t bytes)
3054 {
3055   mstate ar_ptr;
3056   void *p;
3057
3058   if(__malloc_initialized < 0)
3059     ptmalloc_init ();
3060
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);
3064
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));
3070
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);
3088       }
3089     }
3090   }
3091   assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3092          ar_ptr == arena_for_chunk(mem2chunk(p)));
3093
3094   return p;
3095 }
3096
3097 void*
3098 __libc_calloc(size_t n, size_t elem_size)
3099 {
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;
3107
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;
3116     }
3117   }
3118
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);
3127   }
3128
3129   sz = bytes;
3130
3131   arena_get(av, sz);
3132   if(!av)
3133     return 0;
3134
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)
3147     {
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;
3151     }
3152 #endif
3153   mem = _int_malloc(av, sz);
3154
3155   /* Only clearing follows, so we can unlock early. */
3156   (void)mutex_unlock(&av->mutex);
3157
3158   assert(!mem || chunk_is_mmapped(mem2chunk(mem)) ||
3159          av == arena_for_chunk(mem2chunk(mem)));
3160
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);
3175       }
3176     }
3177     if (mem == 0) return 0;
3178   }
3179   p = mem2chunk(mem);
3180
3181   /* Two optional cases in which clearing not necessary */
3182   if (chunk_is_mmapped (p))
3183     {
3184       if (__builtin_expect (perturb_byte, 0))
3185         MALLOC_ZERO (mem, sz);
3186       return mem;
3187     }
3188
3189   csz = chunksize(p);
3190
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;
3195   }
3196 #endif
3197
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);
3205
3206   if (nclears > 9)
3207     MALLOC_ZERO(d, clearsize);
3208
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;
3222         }
3223       }
3224     }
3225   }
3226
3227   return mem;
3228 }
3229
3230 /*
3231   ------------------------------ malloc ------------------------------
3232 */
3233
3234 static void*
3235 _int_malloc(mstate av, size_t bytes)
3236 {
3237   INTERNAL_SIZE_T nb;               /* normalized request size */
3238   unsigned int    idx;              /* associated bin index */
3239   mbinptr         bin;              /* associated bin */
3240
3241   mchunkptr       victim;           /* inspected/selected chunk */
3242   INTERNAL_SIZE_T size;             /* its size */
3243   int             victim_index;     /* its bin index */
3244
3245   mchunkptr       remainder;        /* remainder from a split */
3246   unsigned long   remainder_size;   /* its size */
3247
3248   unsigned int    block;            /* bit map traverser */
3249   unsigned int    bit;              /* bit map traverser */
3250   unsigned int    map;              /* current word of binmap */
3251
3252   mchunkptr       fwd;              /* misc temp for linking */
3253   mchunkptr       bck;              /* misc temp for linking */
3254
3255   const char *errstr = NULL;
3256
3257   /*
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.
3264   */
3265
3266   checked_request2size(bytes, nb);
3267
3268   /*
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.
3272   */
3273
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;
3278     do
3279       {
3280         victim = pp;
3281         if (victim == NULL)
3282           break;
3283       }
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))
3288         {
3289           errstr = "malloc(): memory corruption (fast)";
3290         errout:
3291           malloc_printerr (check_action, errstr, chunk2mem (victim));
3292           return NULL;
3293         }
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;
3299     }
3300   }
3301
3302   /*
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.)
3308   */
3309
3310   if (in_smallbin_range(nb)) {
3311     idx = smallbin_index(nb);
3312     bin = bin_at(av,idx);
3313
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))
3320           {
3321             errstr = "malloc(): smallbin double linked list corrupted";
3322             goto errout;
3323           }
3324         set_inuse_bit_at_offset(victim, nb);
3325         bin->bk = bck;
3326         bck->fd = bin;
3327
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;
3335       }
3336     }
3337   }
3338
3339   /*
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.
3348   */
3349
3350   else {
3351     idx = largebin_index(nb);
3352     if (have_fastchunks(av))
3353       malloc_consolidate(av);
3354   }
3355
3356   /*
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.
3362
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.
3367   */
3368
3369   for(;;) {
3370
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);
3379
3380       /*
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.
3386       */
3387
3388       if (in_smallbin_range(nb) &&
3389           bck == unsorted_chunks(av) &&
3390           victim == av->last_remainder &&
3391           (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
3392
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))
3400           {
3401             remainder->fd_nextsize = NULL;
3402             remainder->bk_nextsize = NULL;
3403           }
3404
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);
3409
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;
3415       }
3416
3417       /* remove from unsorted list */
3418       unsorted_chunks(av)->bk = bck;
3419       bck->fd = unsorted_chunks(av);
3420
3421       /* Take now instead of binning if exact fit */
3422
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;
3432       }
3433
3434       /* place chunk in bin */
3435
3436       if (in_smallbin_range(size)) {
3437         victim_index = smallbin_index(size);
3438         bck = bin_at(av, victim_index);
3439         fwd = bck->fd;
3440       }
3441       else {
3442         victim_index = largebin_index(size);
3443         bck = bin_at(av, victim_index);
3444         fwd = bck->fd;
3445
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;
3455
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;
3459           }
3460           else {
3461             assert((fwd->size & NON_MAIN_ARENA) == 0);
3462             while ((unsigned long) size < fwd->size)
3463               {
3464                 fwd = fwd->fd_nextsize;
3465                 assert((fwd->size & NON_MAIN_ARENA) == 0);
3466               }
3467
3468             if ((unsigned long) size == (unsigned long) fwd->size)
3469               /* Always insert in the second position.  */
3470               fwd = fwd->fd;
3471             else
3472               {
3473                 victim->fd_nextsize = fwd;
3474                 victim->bk_nextsize = fwd->bk_nextsize;
3475                 fwd->bk_nextsize = victim;
3476                 victim->bk_nextsize->fd_nextsize = victim;
3477               }
3478             bck = fwd->bk;
3479           }
3480         } else
3481           victim->fd_nextsize = victim->bk_nextsize = victim;
3482       }
3483
3484       mark_bin(av, victim_index);
3485       victim->bk = bck;
3486       victim->fd = fwd;
3487       fwd->bk = victim;
3488       bck->fd = victim;
3489
3490 #define MAX_ITERS       10000
3491       if (++iters >= MAX_ITERS)
3492         break;
3493     }
3494
3495     /*
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.
3498     */
3499
3500     if (!in_smallbin_range(nb)) {
3501       bin = bin_at(av, idx);
3502
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)) {
3506
3507         victim = victim->bk_nextsize;
3508         while (((unsigned long)(size = chunksize(victim)) <
3509                 (unsigned long)(nb)))
3510           victim = victim->bk_nextsize;
3511
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;
3516
3517         remainder_size = size - nb;
3518         unlink(victim, bck, fwd);
3519
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;
3525         }
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))
3534             {
3535               errstr = "malloc(): corrupted unsorted chunks";
3536               goto errout;
3537             }
3538           remainder->bk = bck;
3539           remainder->fd = fwd;
3540           bck->fd = remainder;
3541           fwd->bk = remainder;
3542           if (!in_smallbin_range(remainder_size))
3543             {
3544               remainder->fd_nextsize = NULL;
3545               remainder->bk_nextsize = NULL;
3546             }
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);
3551         }
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;
3557       }
3558     }
3559
3560     /*
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.
3565
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.
3569     */
3570
3571     ++idx;
3572     bin = bin_at(av,idx);
3573     block = idx2block(idx);
3574     map = av->binmap[block];
3575     bit = idx2bit(idx);
3576
3577     for (;;) {
3578
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);
3585
3586         bin = bin_at(av, (block << BINMAPSHIFT));
3587         bit = 1;
3588       }
3589
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);
3595       }
3596
3597       /* Inspect the bin. It is likely to be non-empty */
3598       victim = last(bin);
3599
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;
3605       }
3606
3607       else {
3608         size = chunksize(victim);
3609
3610         /*  We know the first chunk in this bin is big enough to use. */
3611         assert((unsigned long)(size) >= (unsigned long)(nb));
3612
3613         remainder_size = size - nb;
3614
3615         /* unlink */
3616         unlink(victim, bck, fwd);
3617
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;
3623         }
3624
3625         /* Split */
3626         else {
3627           remainder = chunk_at_offset(victim, nb);
3628
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))
3634             {
3635               errstr = "malloc(): corrupted unsorted chunks 2";
3636               goto errout;
3637             }
3638           remainder->bk = bck;
3639           remainder->fd = fwd;
3640           bck->fd = remainder;
3641           fwd->bk = remainder;
3642
3643           /* advertise as last remainder */
3644           if (in_smallbin_range(nb))
3645             av->last_remainder = remainder;
3646           if (!in_smallbin_range(remainder_size))
3647             {
3648               remainder->fd_nextsize = NULL;
3649               remainder->bk_nextsize = NULL;
3650             }
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);
3655         }
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;
3661       }
3662     }
3663
3664   use_top:
3665     /*
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).
3672
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.)
3678     */
3679
3680     victim = av->top;
3681     size = chunksize(victim);
3682
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);
3690
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;
3696     }
3697
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);
3707     }
3708
3709     /*
3710        Otherwise, relay to handle system-dependent cases
3711     */
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;
3717     }
3718   }
3719 }
3720
3721 /*
3722   ------------------------------ free ------------------------------
3723 */
3724
3725 static void
3726 _int_free(mstate av, mchunkptr p, int have_lock)
3727 {
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 */
3736
3737   const char *errstr = NULL;
3738   int locked = 0;
3739
3740   size = chunksize(p);
3741
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))
3748     {
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;
3755     }
3756   /* We know that each chunk is at least MINSIZE bytes in size.  */
3757   if (__builtin_expect (size < MINSIZE, 0))
3758     {
3759       errstr = "free(): invalid size";
3760       goto errout;
3761     }
3762
3763   check_inuse_chunk(av, p);
3764
3765   /*
3766     If eligible, place chunk on a fastbin so it can be found
3767     and used quickly in malloc.
3768   */
3769
3770   if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
3771
3772 #if TRIM_FASTBINS
3773       /*
3774         If TRIM_FASTBINS set, don't place chunks
3775         bordering top into fastbins
3776       */
3777       && (chunk_at_offset(p, size) != av->top)
3778 #endif
3779       ) {
3780
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))
3784       {
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;
3794               }))
3795           {
3796             errstr = "free(): invalid next size (fast)";
3797             goto errout;
3798           }
3799         if (! have_lock)
3800           {
3801             (void)mutex_unlock(&av->mutex);
3802             locked = 0;
3803           }
3804       }
3805
3806     if (__builtin_expect (perturb_byte, 0))
3807       free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3808
3809     set_fastchunks(av);
3810     unsigned int idx = fastbin_index(size);
3811     fb = &fastbin (av, idx);
3812
3813     mchunkptr fd;
3814     mchunkptr old = *fb;
3815     unsigned int old_idx = ~0u;
3816     do
3817       {
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))
3821           {
3822             errstr = "double free or corruption (fasttop)";
3823             goto errout;
3824           }
3825         if (old != NULL)
3826           old_idx = fastbin_index(chunksize(old));
3827         p->fd = fd = old;
3828       }
3829     while ((old = catomic_compare_and_exchange_val_rel (fb, p, fd)) != fd);
3830
3831     if (fd != NULL && __builtin_expect (old_idx != idx, 0))
3832       {
3833         errstr = "invalid fastbin entry (free)";
3834         goto errout;
3835       }
3836   }
3837
3838   /*
3839     Consolidate other non-mmapped chunks as they arrive.
3840   */
3841
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);
3850       }
3851 #else
3852       (void)mutex_lock(&av->mutex);
3853 #endif
3854       locked = 1;
3855     }
3856
3857     nextchunk = chunk_at_offset(p, size);
3858
3859     /* Lightweight tests: check whether the block is already the
3860        top block.  */
3861     if (__builtin_expect (p == av->top, 0))
3862       {
3863         errstr = "double free or corruption (top)";
3864         goto errout;
3865       }
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))
3870       {
3871         errstr = "double free or corruption (out)";
3872         goto errout;
3873       }
3874     /* Or whether the block is actually not marked used.  */
3875     if (__builtin_expect (!prev_inuse(nextchunk), 0))
3876       {
3877         errstr = "double free or corruption (!prev)";
3878         goto errout;
3879       }
3880
3881     nextsize = chunksize(nextchunk);
3882     if (__builtin_expect (nextchunk->size <= 2 * SIZE_SZ, 0)
3883         || __builtin_expect (nextsize >= av->system_mem, 0))
3884       {
3885         errstr = "free(): invalid next size (normal)";
3886         goto errout;
3887       }
3888
3889     if (__builtin_expect (perturb_byte, 0))
3890       free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3891
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);
3898     }
3899
3900     if (nextchunk != av->top) {
3901       /* get and clear inuse bit */
3902       nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
3903
3904       /* consolidate forward */
3905       if (!nextinuse) {
3906         unlink(nextchunk, bck, fwd);
3907         size += nextsize;
3908       } else
3909         clear_inuse_bit_at_offset(nextchunk, 0);
3910
3911       /*
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.
3915       */
3916
3917       bck = unsorted_chunks(av);
3918       fwd = bck->fd;
3919       if (__builtin_expect (fwd->bk != bck, 0))
3920         {
3921           errstr = "free(): corrupted unsorted chunks";
3922           goto errout;
3923         }
3924       p->fd = fwd;
3925       p->bk = bck;
3926       if (!in_smallbin_range(size))
3927         {
3928           p->fd_nextsize = NULL;
3929           p->bk_nextsize = NULL;
3930         }
3931       bck->fd = p;
3932       fwd->bk = p;
3933
3934       set_head(p, size | PREV_INUSE);
3935       set_foot(p, size);
3936
3937       check_free_chunk(av, p);
3938     }
3939
3940     /*
3941       If the chunk borders the current high end of memory,
3942       consolidate into top
3943     */
3944
3945     else {
3946       size += nextsize;
3947       set_head(p, size | PREV_INUSE);
3948       av->top = p;
3949       check_chunk(av, p);
3950     }
3951
3952     /*
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.
3956
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.
3963     */
3964
3965     if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
3966       if (have_fastchunks(av))
3967         malloc_consolidate(av);
3968
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));
3979
3980         assert(heap->ar_ptr == av);
3981         heap_trim(heap, mp_.top_pad);
3982       }
3983     }
3984
3985     if (! have_lock) {
3986       assert (locked);
3987       (void)mutex_unlock(&av->mutex);
3988     }
3989   }
3990   /*
3991     If the chunk was allocated via mmap, release via munmap().
3992   */
3993
3994   else {
3995     munmap_chunk (p);
3996   }
3997 }
3998
3999 /*
4000   ------------------------- malloc_consolidate -------------------------
4001
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.
4007
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.
4011 */
4012
4013 static void malloc_consolidate(mstate av)
4014 {
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 */
4021
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;
4030
4031   /*
4032     If max_fast is 0, we know that av hasn't
4033     yet been initialized, in which case do so below
4034   */
4035
4036   if (get_max_fast () != 0) {
4037     clear_fastchunks(av);
4038
4039     unsorted_bin = unsorted_chunks(av);
4040
4041     /*
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.
4047     */
4048
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;
4057
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);
4062
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);
4068           }
4069
4070           if (nextchunk != av->top) {
4071             nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4072
4073             if (!nextinuse) {
4074               size += nextsize;
4075               unlink(nextchunk, bck, fwd);
4076             } else
4077               clear_inuse_bit_at_offset(nextchunk, 0);
4078
4079             first_unsorted = unsorted_bin->fd;
4080             unsorted_bin->fd = p;
4081             first_unsorted->bk = p;
4082
4083             if (!in_smallbin_range (size)) {
4084               p->fd_nextsize = NULL;
4085               p->bk_nextsize = NULL;
4086             }
4087
4088             set_head(p, size | PREV_INUSE);
4089             p->bk = unsorted_bin;
4090             p->fd = first_unsorted;
4091             set_foot(p, size);
4092           }
4093
4094           else {
4095             size += nextsize;
4096             set_head(p, size | PREV_INUSE);
4097             av->top = p;
4098           }
4099
4100         } while ( (p = nextp) != 0);
4101
4102       }
4103     } while (fb++ != maxfb);
4104   }
4105   else {
4106     malloc_init_state(av);
4107     check_malloc_state(av);
4108   }
4109 }
4110
4111 /*
4112   ------------------------------ realloc ------------------------------
4113 */
4114
4115 void*
4116 _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4117              INTERNAL_SIZE_T nb)
4118 {
4119   mchunkptr        newp;            /* chunk to return */
4120   INTERNAL_SIZE_T  newsize;         /* its size */
4121   void*          newmem;          /* corresponding user mem */
4122
4123   mchunkptr        next;            /* next contiguous chunk after oldp */
4124
4125   mchunkptr        remainder;       /* extra space at end of newp */
4126   unsigned long    remainder_size;  /* its size */
4127
4128   mchunkptr        bck;             /* misc temp for linking */
4129   mchunkptr        fwd;             /* misc temp for linking */
4130
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 */
4135
4136   const char *errstr = NULL;
4137
4138   /* oldmem size */
4139   if (__builtin_expect (oldp->size <= 2 * SIZE_SZ, 0)
4140       || __builtin_expect (oldsize >= av->system_mem, 0))
4141     {
4142       errstr = "realloc(): invalid old size";
4143     errout:
4144       malloc_printerr (check_action, errstr, chunk2mem(oldp));
4145       return NULL;
4146     }
4147
4148   check_inuse_chunk(av, oldp);
4149
4150   /* All callers already filter out mmap'ed chunks.  */
4151   assert (!chunk_is_mmapped(oldp));
4152
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))
4157     {
4158       errstr = "realloc(): invalid next size";
4159       goto errout;
4160     }
4161
4162   if ((unsigned long)(oldsize) >= (unsigned long)(nb)) {
4163     /* already big enough; split below */
4164     newp = oldp;
4165     newsize = oldsize;
4166   }
4167
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);
4178     }
4179
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);
4187     }
4188
4189     /* allocate, copy, free */
4190     else {
4191       newmem = _int_malloc(av, nb - MALLOC_ALIGN_MASK);
4192       if (newmem == 0)
4193         return 0; /* propagate failure */
4194
4195       newp = mem2chunk(newmem);
4196       newsize = chunksize(newp);
4197
4198       /*
4199         Avoid copy if newp is next chunk after oldp.
4200       */
4201       if (newp == next) {
4202         newsize += oldsize;
4203         newp = oldp;
4204       }
4205       else {
4206         /*
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.
4210         */
4211
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);
4217
4218         if (ncopies > 9)
4219           MALLOC_COPY(d, s, copysize);
4220
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);
4234               }
4235             }
4236           }
4237         }
4238
4239         _int_free(av, oldp, 1);
4240         check_inuse_chunk(av, newp);
4241         return chunk2mem(newp);
4242       }
4243     }
4244   }
4245
4246   /* If possible, free extra space in old or extended chunk */
4247
4248   assert((unsigned long)(newsize) >= (unsigned long)(nb));
4249
4250   remainder_size = newsize - nb;
4251
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);
4255   }
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);
4264   }
4265
4266   check_inuse_chunk(av, newp);
4267   return chunk2mem(newp);
4268 }
4269
4270 /*
4271   ------------------------------ memalign ------------------------------
4272 */
4273
4274 static void*
4275 _int_memalign(mstate av, size_t alignment, size_t bytes)
4276 {
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;
4287
4288   /* If need less alignment than we give anyway, just relay to malloc */
4289
4290   if (alignment <= MALLOC_ALIGNMENT) return _int_malloc(av, bytes);
4291
4292   /* Otherwise, ensure that it is at least a minimum chunk size */
4293
4294   if (alignment <  MINSIZE) alignment = MINSIZE;
4295
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;
4301   }
4302
4303   checked_request2size(bytes, nb);
4304
4305   /*
4306     Strategy: find a spot within that chunk that meets the alignment
4307     request, and then possibly free the leading and trailing space.
4308   */
4309
4310
4311   /* Call malloc with worst case padding to hit alignment. */
4312
4313   m  = (char*)(_int_malloc(av, nb + alignment + MINSIZE));
4314
4315   if (m == 0) return 0; /* propagate failure */
4316
4317   p = mem2chunk(m);
4318
4319   if ((((unsigned long)(m)) % alignment) != 0) { /* misaligned */
4320
4321     /*
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.
4327     */
4328
4329     brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) &
4330                            -((signed long) alignment));
4331     if ((unsigned long)(brk - (char*)(p)) < MINSIZE)
4332       brk += alignment;
4333
4334     newp = (mchunkptr)brk;
4335     leadsize = brk - (char*)(p);
4336     newsize = chunksize(p) - leadsize;
4337
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);
4343     }
4344
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;
4352
4353     assert (newsize >= nb &&
4354             (((unsigned long)(chunk2mem(p))) % alignment) == 0);
4355   }
4356
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);
4367     }
4368   }
4369
4370   check_inuse_chunk(av, p);
4371   return chunk2mem(p);
4372 }
4373
4374
4375 /*
4376   ------------------------------ valloc ------------------------------
4377 */
4378
4379 static void*
4380 _int_valloc(mstate av, size_t bytes)
4381 {
4382   /* Ensure initialization/consolidation */
4383   if (have_fastchunks(av)) malloc_consolidate(av);
4384   return _int_memalign(av, GLRO(dl_pagesize), bytes);
4385 }
4386
4387 /*
4388   ------------------------------ pvalloc ------------------------------
4389 */
4390
4391
4392 static void*
4393 _int_pvalloc(mstate av, size_t bytes)
4394 {
4395   size_t pagesz;
4396
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));
4401 }
4402
4403
4404 /*
4405   ------------------------------ malloc_trim ------------------------------
4406 */
4407
4408 static int mtrim(mstate av, size_t pad)
4409 {
4410   /* Ensure initialization/consolidation */
4411   malloc_consolidate (av);
4412
4413   const size_t ps = GLRO(dl_pagesize);
4414   int psindex = bin_index (ps);
4415   const size_t psm1 = ps - 1;
4416
4417   int result = 0;
4418   for (int i = 1; i < NBINS; ++i)
4419     if (i == 1 || i >= psindex)
4420       {
4421         mbinptr bin = bin_at (av, i);
4422
4423         for (mchunkptr p = last (bin); p != bin; p = p->bk)
4424           {
4425             INTERNAL_SIZE_T size = chunksize (p);
4426
4427             if (size > psm1 + sizeof (struct malloc_chunk))
4428               {
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);
4433
4434                 assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
4435                 assert ((char *) p + size > paligned_mem);
4436
4437                 /* This is the size we could potentially free.  */
4438                 size -= paligned_mem - (char *) p;
4439
4440                 if (size > psm1)
4441                   {
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);
4448
4449                     result = 1;
4450                   }
4451               }
4452           }
4453       }
4454
4455 #ifndef MORECORE_CANNOT_TRIM
4456   return result | (av == &main_arena ? systrim (pad, av) : 0);
4457 #else
4458   return result;
4459 #endif
4460 }
4461
4462
4463 int
4464 __malloc_trim(size_t s)
4465 {
4466   int result = 0;
4467
4468   if(__malloc_initialized < 0)
4469     ptmalloc_init ();
4470
4471   mstate ar_ptr = &main_arena;
4472   do
4473     {
4474       (void) mutex_lock (&ar_ptr->mutex);
4475       result |= mtrim (ar_ptr, s);
4476       (void) mutex_unlock (&ar_ptr->mutex);
4477
4478       ar_ptr = ar_ptr->next;
4479     }
4480   while (ar_ptr != &main_arena);
4481
4482   return result;
4483 }
4484
4485
4486 /*
4487   ------------------------- malloc_usable_size -------------------------
4488 */
4489
4490 static size_t
4491 musable(void* mem)
4492 {
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;
4500   }
4501   return 0;
4502 }
4503
4504
4505 size_t
4506 __malloc_usable_size(void* m)
4507 {
4508   size_t result;
4509
4510   result = musable(m);
4511   return result;
4512 }
4513
4514 /*
4515   ------------------------------ mallinfo ------------------------------
4516 */
4517
4518 static struct mallinfo
4519 int_mallinfo(mstate av)
4520 {
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;
4529
4530   /* Ensure initialization */
4531   if (av->top == 0)  malloc_consolidate(av);
4532
4533   check_malloc_state(av);
4534
4535   /* Account for top */
4536   avail = chunksize(av->top);
4537   nblocks = 1;  /* top always exists */
4538
4539   /* traverse fastbins */
4540   nfastblocks = 0;
4541   fastavail = 0;
4542
4543   for (i = 0; i < NFASTBINS; ++i) {
4544     for (p = fastbin (av, i); p != 0; p = p->fd) {
4545       ++nfastblocks;
4546       fastavail += chunksize(p);
4547     }
4548   }
4549
4550   avail += fastavail;
4551
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);
4558     }
4559   }
4560
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;
4572 }
4573
4574
4575 struct mallinfo __libc_mallinfo()
4576 {
4577   struct mallinfo m;
4578
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;
4585 }
4586
4587 /*
4588   ------------------------------ malloc_stats ------------------------------
4589 */
4590
4591 void
4592 __malloc_stats()
4593 {
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
4601
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;
4627   }
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);
4644 }
4645
4646
4647 /*
4648   ------------------------------ mallopt ------------------------------
4649 */
4650
4651 int __libc_mallopt(int param_number, int value)
4652 {
4653   mstate av = &main_arena;
4654   int res = 1;
4655
4656   if(__malloc_initialized < 0)
4657     ptmalloc_init ();
4658   (void)mutex_lock(&av->mutex);
4659   /* Ensure initialization/consolidation */
4660   malloc_consolidate(av);
4661
4662   switch(param_number) {
4663   case M_MXFAST:
4664     if (value >= 0 && value <= MAX_FAST_SIZE) {
4665       set_max_fast(value);
4666     }
4667     else
4668       res = 0;
4669     break;
4670
4671   case M_TRIM_THRESHOLD:
4672     mp_.trim_threshold = value;
4673     mp_.no_dyn_threshold = 1;
4674     break;
4675
4676   case M_TOP_PAD:
4677     mp_.top_pad = value;
4678     mp_.no_dyn_threshold = 1;
4679     break;
4680
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;
4689
4690   case M_MMAP_MAX:
4691       mp_.n_mmaps_max = value;
4692       mp_.no_dyn_threshold = 1;
4693     break;
4694
4695   case M_CHECK_ACTION:
4696     check_action = value;
4697     break;
4698
4699   case M_PERTURB:
4700     perturb_byte = value;
4701     break;
4702
4703 #ifdef PER_THREAD
4704   case M_ARENA_TEST:
4705     if (value > 0)
4706       mp_.arena_test = value;
4707     break;
4708
4709   case M_ARENA_MAX:
4710     if (value > 0)
4711       mp_.arena_max = value;
4712     break;
4713 #endif
4714   }
4715   (void)mutex_unlock(&av->mutex);
4716   return res;
4717 }
4718 libc_hidden_def (__libc_mallopt)
4719
4720
4721 /*
4722   -------------------- Alternative MORECORE functions --------------------
4723 */
4724
4725
4726 /*
4727   General Requirements for MORECORE.
4728
4729   The MORECORE function must have the following properties:
4730
4731   If MORECORE_CONTIGUOUS is false:
4732
4733     * MORECORE must allocate in multiples of pagesize. It will
4734       only be called with arguments that are multiples of pagesize.
4735
4736     * MORECORE(0) must return an address that is at least
4737       MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
4738
4739   else (i.e. If MORECORE_CONTIGUOUS is true):
4740
4741     * Consecutive calls to MORECORE with positive arguments
4742       return increasing addresses, indicating that space has been
4743       contiguously extended.
4744
4745     * MORECORE need not allocate in multiples of pagesize.
4746       Calls to MORECORE need not have args of multiples of pagesize.
4747
4748     * MORECORE need not page-align.
4749
4750   In either case:
4751
4752     * MORECORE may allocate more memory than requested. (Or even less,
4753       but this will generally result in a malloc failure.)
4754
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.
4760
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.
4764
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,
4771
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.
4779
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.
4785
4786   If you'd like mmap to ALWAYS be used, you can define MORECORE to be
4787   a function that always returns MORECORE_FAILURE.
4788
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:
4797
4798       #define MORECORE osMoreCore
4799       #define MORECORE_CONTIGUOUS 0
4800
4801   There is also a shutdown routine that should somehow be called for
4802   cleanup upon program exit.
4803
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];
4808
4809   void *osMoreCore(int size)
4810   {
4811     void *ptr = 0;
4812     static void *sbrk_top = 0;
4813
4814     if (size > 0)
4815     {
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)
4821       {
4822         return (void *) MORECORE_FAILURE;
4823       }
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;
4830     }
4831     else if (size < 0)
4832     {
4833       // we don't currently support shrink behavior
4834       return (void *) MORECORE_FAILURE;
4835     }
4836     else
4837     {
4838       return sbrk_top;
4839     }
4840   }
4841
4842   // cleanup any allocated memory pools
4843   // called as last thing before shutting down driver
4844
4845   void osCleanupMem(void)
4846   {
4847     void **ptr;
4848
4849     for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
4850       if (*ptr)
4851       {
4852          PoolDeallocate(*ptr);
4853          *ptr = 0;
4854       }
4855   }
4856
4857 */
4858
4859
4860 /* Helper code.  */
4861
4862 extern char **__libc_argv attribute_hidden;
4863
4864 static void
4865 malloc_printerr(int action, const char *str, void *ptr)
4866 {
4867   if ((action & 5) == 5)
4868     __libc_message (action & 2, "%s\n", str);
4869   else if (action & 1)
4870     {
4871       char buf[2 * sizeof (uintptr_t) + 1];
4872
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';
4877
4878       __libc_message (action & 2,
4879                       "*** glibc detected *** %s: %s: 0x%s ***\n",
4880                       __libc_argv[0] ?: "<unknown>", str, cp);
4881     }
4882   else if (action & 2)
4883     abort ();
4884 }
4885
4886 #include <sys/param.h>
4887
4888 /* We need a wrapper function for one of the additions of POSIX.  */
4889 int
4890 __posix_memalign (void **memptr, size_t alignment, size_t size)
4891 {
4892   void *mem;
4893
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;
4900
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);
4910
4911   if (mem != NULL) {
4912     *memptr = mem;
4913     return 0;
4914   }
4915
4916   return ENOMEM;
4917 }
4918 weak_alias (__posix_memalign, posix_memalign)
4919
4920
4921 int
4922 malloc_info (int options, FILE *fp)
4923 {
4924   /* For now, at least.  */
4925   if (options != 0)
4926     return EINVAL;
4927
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;
4937
4938   void mi_arena (mstate ar_ptr)
4939   {
4940     fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
4941
4942     size_t nblocks = 0;
4943     size_t nfastblocks = 0;
4944     size_t avail = 0;
4945     size_t fastavail = 0;
4946     struct
4947     {
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]))
4954
4955     mutex_lock (&ar_ptr->mutex);
4956
4957     for (size_t i = 0; i < NFASTBINS; ++i)
4958       {
4959         mchunkptr p = fastbin (ar_ptr, i);
4960         if (p != NULL)
4961           {
4962             size_t nthissize = 0;
4963             size_t thissize = chunksize (p);
4964
4965             while (p != NULL)
4966               {
4967                 ++nthissize;
4968                 p = p->fd;
4969               }
4970
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;
4976           }
4977         else
4978           sizes[i].from = sizes[i].to = sizes[i].count = 0;
4979
4980         sizes[i].total = sizes[i].count * sizes[i].to;
4981       }
4982
4983     mbinptr bin = bin_at (ar_ptr, 1);
4984     struct malloc_chunk *r = bin->fd;
4985     if (r != NULL)
4986       {
4987         while (r != bin)
4988           {
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;
4994           }
4995         nblocks += sizes[NFASTBINS].count;
4996         avail += sizes[NFASTBINS].total;
4997       }
4998
4999     for (size_t i = 2; i < NBINS; ++i)
5000       {
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;
5006
5007         if (r != NULL)
5008           while (r != bin)
5009             {
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);
5016
5017               r = r->fd;
5018             }
5019
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;
5024       }
5025
5026     mutex_unlock (&ar_ptr->mutex);
5027
5028     total_nfastblocks += nfastblocks;
5029     total_fastavail += fastavail;
5030
5031     total_nblocks += nblocks;
5032     total_avail += avail;
5033
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);
5039
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);
5045
5046     total_system += ar_ptr->system_mem;
5047     total_max_system += ar_ptr->max_system_mem;
5048
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);
5056
5057     if (ar_ptr != &main_arena)
5058       {
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;
5066       }
5067     else
5068       {
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;
5075       }
5076
5077     fputs ("</heap>\n", fp);
5078   }
5079
5080   if(__malloc_initialized < 0)
5081     ptmalloc_init ();
5082
5083   fputs ("<malloc version=\"1\">\n", fp);
5084
5085   /* Iterate over all arenas currently in use.  */
5086   mstate ar_ptr = &main_arena;
5087   do
5088     {
5089       mi_arena (ar_ptr);
5090       ar_ptr = ar_ptr->next;
5091     }
5092   while (ar_ptr != &main_arena);
5093
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);
5105
5106   return 0;
5107 }
5108
5109
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)
5122
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)
5128
5129
5130 /* ------------------------------------------------------------
5131 History:
5132
5133 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
5134
5135 */
5136 /*
5137  * Local variables:
5138  * c-basic-offset: 2
5139  * End:
5140  */