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