开发者社区> 一见蓝天> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

malloc.c

简介: glibc-2.14中的malloc.c源代码,供研究malloc和free实现使用: /* Malloc implementation for multiple threads without lock contention.
+关注继续查看
glibc-2.14中的malloc.c源代码,供研究malloc和free实现使用:

  1. /* Malloc implementation for multiple threads without lock contention.
  2.    Copyright (C) 1996-2009, 2010, 2011 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.    The GNU C Library is free software; you can redistribute it and/or
  7.    modify it under the terms of the GNU Lesser General Public License as
  8.    published by the Free Software Foundation; either version 2.1 of the
  9.    License, or (at your option) any later version.

  10.    The GNU C Library is distributed in the hope that it will be useful,
  11.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13.    Lesser General Public License for more details.

  14.    You should have received a copy of the GNU Lesser General Public
  15.    License along with the GNU C Library; see the file COPYING.LIB. If not,
  16.    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  17.    Boston, MA 02111-1307, USA. */

  18. /*
  19.   This is a version (aka ptmalloc2) of malloc/free/realloc written by
  20.   Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.

  21.   There have been substantial changesmade after the integration into
  22.   glibc in all parts of the code. Do not look for much commonality
  23.   with the ptmalloc2 version.

  24. * Version ptmalloc2-20011215
  25.   based on:
  26.   VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)

  27. * Quickstart

  28.   In order to compile this implementation, a Makefile is provided with
  29.   the ptmalloc2 distribution, which has pre-defined targets for some
  30.   popular systems (e.g. "make posix" for Posix threads). All that is
  31.   typically required with regard to compiler flags is the selection of
  32.   the thread package via defining one out of USE_PTHREADS, USE_THR or
  33.   USE_SPROC. Check the thread-m.h file for what effects this has.
  34.   Many/most systems will additionally require USE_TSD_DATA_HACK to be
  35.   defined, so this is the default for "make posix".

  36. * Why use this malloc?

  37.   This is not the fastest, most space-conserving, most portable, or
  38.   most tunable malloc ever written. However it is among the fastest
  39.   while also being among the most space-conserving, portable and tunable.
  40.   Consistent balance across these factors results in a good general-purpose
  41.   allocator for malloc-intensive programs.

  42.   The main properties of the algorithms are:
  43.   * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
  44.     with ties normally decided via FIFO (i.e. least recently used).
  45.   * For small (<= 64 bytes by default) requests, it is a caching
  46.     allocator, that maintains pools of quickly recycled chunks.
  47.   * In between, and for combinations of large and small requests, it does
  48.     the best it can trying to meet both goals at once.
  49.   * For very large requests (>= 128KB by default), it relies on system
  50.     memory mapping facilities, if supported.

  51.   For a longer but slightly out of date high-level description, see
  52.      http://gee.cs.oswego.edu/dl/html/malloc.html

  53.   You may already by default be using a C library containing a malloc
  54.   that is based on some version of this malloc (for example in
  55.   linux). You might still want to use the one in this file in order to
  56.   customize settings or to avoid overheads associated with library
  57.   versions.

  58. * Contents, described in more detail in "description of public routines" below.

  59.   Standard (ANSI/SVID/...) functions:
  60.     malloc(size_t n);
  61.     calloc(size_t n_elements, size_t element_size);
  62.     free(Void_t* p);
  63.     realloc(Void_t* p, size_t n);
  64.     memalign(size_t alignment, size_t n);
  65.     valloc(size_t n);
  66.     mallinfo()
  67.     mallopt(int parameter_number, int parameter_value)

  68.   Additional functions:
  69.     independent_calloc(size_t n_elements, size_t size, Void_t* chunks[]);
  70.     independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]);
  71.     pvalloc(size_t n);
  72.     cfree(Void_t* p);
  73.     malloc_trim(size_t pad);
  74.     malloc_usable_size(Void_t* p);
  75.     malloc_stats();

  76. * Vital statistics:

  77.   Supported pointer representation: 4 or 8 bytes
  78.   Supported size_t representation: 4 or 8 bytes
  79.        Note that size_t is allowed to be 4 bytes even if pointers are 8.
  80.        You can adjust this by defining INTERNAL_SIZE_T

  81.   Alignment: 2 * sizeof(size_t) (default)
  82.        (i.e., 8 byte alignment with 4byte size_t). This suffices for
  83.        nearly all current machines and C compilers. However, you can
  84.        define MALLOC_ALIGNMENT to be wider than this if necessary.

  85.   Minimum overhead per allocated chunk: 4 or 8 bytes
  86.        Each malloced chunk has a hidden word of overhead holding size
  87.        and status information.

  88.   Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
  89.              8-byte ptrs: 24/32 bytes (including, 4/8 overhead)

  90.        When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
  91.        ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
  92.        needed; 4 (8) for a trailing size field and 8 (16) bytes for
  93.        free list pointers. Thus, the minimum allocatable size is
  94.        16/24/32 bytes.

  95.        Even a request for zero bytes (i.e., malloc(0)) returns a
  96.        pointer to something of the minimum allocatable size.

  97.        The maximum overhead wastage (i.e., number of extra bytes
  98.        allocated than were requested in malloc) is less than or equal
  99.        to the minimum size, except for requests >= mmap_threshold that
  100.        are serviced via mmap(), where the worst case wastage is 2 *
  101.        sizeof(size_t) bytes plus the remainder from a system page (the
  102.        minimal mmap unit); typically 4096 or 8192 bytes.

  103.   Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
  104.              8-byte size_t: 2^64 minus about two pages

  105.        It is assumed that (possibly signed) size_t values suffice to
  106.        represent chunk sizes. `Possibly signed' is due to the fact
  107.        that `size_t' may be defined on a system as either a signed or
  108.        an unsigned type. The ISO C standard says that it must be
  109.        unsigned, but a few systems are known not to adhere to this.
  110.        Additionally, even when size_t is unsigned, sbrk (which is by
  111.        default used to obtain memory from system) accepts signed
  112.        arguments, and may not be able to handle size_t-wide arguments
  113.        with negative sign bit. Generally, values that would
  114.        appear as negative after accounting for overhead and alignment
  115.        are supported only via mmap(), which does not have this
  116.        limitation.

  117.        Requests for sizes outside the allowed range will perform an optional
  118.        failure action and then return null. (Requests may also
  119.        also fail because a system is out of memory.)

  120.   Thread-safety: thread-safe unless NO_THREADS is defined

  121.   Compliance: I believe it is compliant with the 1997 Single Unix Specification
  122.        Also SVID/XPG, ANSI C, and probably others as well.

  123. * Synopsis of compile-time options:

  124.     People have reported using previous versions of this malloc on all
  125.     versions of Unix, sometimes by tweaking some of the defines
  126.     below. It has been tested most extensively on Solaris and
  127.     Linux. It is also reported to work on WIN32 platforms.
  128.     People also report using it in stand-alone embedded systems.

  129.     The implementation is in straight, hand-tuned ANSI C. It is not
  130.     at all modular. ( It uses a lot of macros. To be at all
  131.     usable, this code should be compiled using an optimizing compiler
  132.     (for example gcc -O3) that can simplify expressions and control
  133.     paths. (FAQ: some macros import variables as arguments rather than
  134.     declare locals because people reported that some debuggers
  135.     otherwise get confused.)

  136.     OPTION DEFAULT VALUE

  137.     Compilation Environment options:

  138.     __STD_C derived from C compiler defines
  139.     WIN32 NOT defined
  140.     HAVE_MEMCPY defined
  141.     USE_MEMCPY 1 if HAVE_MEMCPY is defined
  142.     HAVE_MMAP defined as 1
  143.     MMAP_CLEARS 1
  144.     HAVE_MREMAP 0 unless linux defined
  145.     USE_ARENAS the same as HAVE_MMAP
  146.     malloc_getpagesize derived from system #includes, or 4096 if not
  147.     HAVE_USR_INCLUDE_MALLOC_H NOT defined
  148.     LACKS_UNISTD_H NOT defined unless WIN32
  149.     LACKS_SYS_PARAM_H NOT defined unless WIN32
  150.     LACKS_SYS_MMAN_H NOT defined unless WIN32

  151.     Changing default word sizes:

  152.     INTERNAL_SIZE_T size_t
  153.     MALLOC_ALIGNMENT MAX (2 * sizeof(INTERNAL_SIZE_T),
  154.                  __alignof__ (long double))

  155.     Configuration and functionality options:

  156.     USE_DL_PREFIX NOT defined
  157.     USE_PUBLIC_MALLOC_WRAPPERS NOT defined
  158.     USE_MALLOC_LOCK NOT defined
  159.     MALLOC_DEBUG NOT defined
  160.     REALLOC_ZERO_BYTES_FREES 1
  161.     MALLOC_FAILURE_ACTION errno = ENOMEM, if __STD_C defined, else no-op
  162.     TRIM_FASTBINS 0

  163.     Options for customizing MORECORE:

  164.     MORECORE sbrk
  165.     MORECORE_FAILURE -1
  166.     MORECORE_CONTIGUOUS 1
  167.     MORECORE_CANNOT_TRIM NOT defined
  168.     MORECORE_CLEARS 1
  169.     MMAP_AS_MORECORE_SIZE (1024 * 1024)

  170.     Tuning options that are also dynamically changeable via mallopt:

  171.     DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
  172.     DEFAULT_TRIM_THRESHOLD 128 * 1024
  173.     DEFAULT_TOP_PAD 0
  174.     DEFAULT_MMAP_THRESHOLD 128 * 1024
  175.     DEFAULT_MMAP_MAX 65536

  176.     There are several other #defined constants and macros that you
  177.     probably don't want to touch unless you are extending or adapting malloc. */

  178. /*
  179.   __STD_C should be nonzero if using ANSI-standard C compiler, a C++
  180.   compiler, or a C compiler sufficiently close to ANSI to get away
  181.   with it.
  182. */

  183. #ifndef __STD_C
  184. #if defined(__STDC__) || defined(__cplusplus)
  185. #define __STD_C 1
  186. #else
  187. #define __STD_C 0
  188. #endif
  189. #endif /*__STD_C*/


  190. /*
  191.   Void_t* is the pointer type that malloc should say it returns
  192. */

  193. #ifndef Void_t
  194. #if (__STD_C || defined(WIN32))
  195. #define Void_t void
  196. #else
  197. #define Void_t char
  198. #endif
  199. #endif /*Void_t*/

  200. #if __STD_C
  201. #include <stddef.h> /* for size_t */
  202. #include <stdlib.h> /* for getenv(), abort() */
  203. #else
  204. #include <sys/types.h>
  205. #endif

  206. #include <malloc-machine.h>

  207. #ifdef _LIBC
  208. #ifdef ATOMIC_FASTBINS
  209. #include <atomic.h>
  210. #endif
  211. #include <stdio-common/_itoa.h>
  212. #include <bits/wordsize.h>
  213. #include <sys/sysinfo.h>
  214. #endif

  215. #ifdef __cplusplus
  216. extern "C" {
  217. #endif

  218. /* define LACKS_UNISTD_H if your system does not have a <unistd.h>. */

  219. /* #define LACKS_UNISTD_H */

  220. #ifndef LACKS_UNISTD_H
  221. #include <unistd.h>
  222. #endif

  223. /* define LACKS_SYS_PARAM_H if your system does not have a <sys/param.h>. */

  224. /* #define LACKS_SYS_PARAM_H */


  225. #include <stdio.h> /* needed for malloc_stats */
  226. #include <errno.h> /* needed for optional MALLOC_FAILURE_ACTION */

  227. /* For uintptr_t. */
  228. #include <stdint.h>

  229. /* For va_arg, va_start, va_end. */
  230. #include <stdarg.h>

  231. /* For writev and struct iovec. */
  232. #include <sys/uio.h>
  233. /* For syslog. */
  234. #include <sys/syslog.h>

  235. /* For various dynamic linking things. */
  236. #include <dlfcn.h>


  237. /*
  238.   Debugging:

  239.   Because freed chunks may be overwritten with bookkeeping fields, this
  240.   malloc will often die when freed memory is overwritten by user
  241.   programs. This can be very effective (albeit in an annoying way)
  242.   in helping track down dangling pointers.

  243.   If you compile with -DMALLOC_DEBUG, a number of assertion checks are
  244.   enabled that will catch more memory errors. You probably won't be
  245.   able to make much sense of the actual assertion errors, but they
  246.   should help you locate incorrectly overwritten memory. The checking
  247.   is fairly extensive, and will slow down execution
  248.   noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
  249.   will attempt to check every non-mmapped allocated and free chunk in
  250.   the course of computing the summmaries. (By nature, mmapped regions
  251.   cannot be checked very much automatically.)

  252.   Setting MALLOC_DEBUG may also be helpful if you are trying to modify
  253.   this code. The assertions in the check routines spell out in more
  254.   detail the assumptions and invariants underlying the algorithms.

  255.   Setting MALLOC_DEBUG does NOT provide an automated mechanism for
  256.   checking that all accesses to malloced memory stay within their
  257.   bounds. However, there are several add-ons and adaptations of this
  258.   or other mallocs available that do this.
  259. */

  260. #ifdef NDEBUG
  261. # define assert(expr) ((void) 0)
  262. #else
  263. # define assert(expr) \
  264.   ((expr)                                 \
  265.    ? ((void) 0)                                 \
  266.    : __malloc_assert (__STRING (expr), __FILE__, __LINE__, __func__))

  267. extern const char *__progname;

  268. static void
  269. __malloc_assert (const char *assertion, const char *file, unsigned int line,
  270.          const char *function)
  271. {
  272.   (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
  273.          __progname, __progname[0] ? ": " : "",
  274.          file, line,
  275.          function ? function : "", function ? ": " : "",
  276.          assertion);
  277.   fflush (stderr);
  278.   abort ();
  279. }
  280. #endif


  281. /*
  282.   INTERNAL_SIZE_T is the word-size used for internal bookkeeping
  283.   of chunk sizes.

  284.   The default version is the same as size_t.

  285.   While not strictly necessary, it is best to define this as an
  286.   unsigned type, even if size_t is a signed type. This may avoid some
  287.   artificial size limitations on some systems.

  288.   On a 64-bit machine, you may be able to reduce malloc overhead by
  289.   defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
  290.   expense of not being able to handle more than 2^32 of malloced
  291.   space. If this limitation is acceptable, you are encouraged to set
  292.   this unless you are on a platform requiring 16byte alignments. In
  293.   this case the alignment requirements turn out to negate any
  294.   potential advantages of decreasing size_t word size.

  295.   Implementors: Beware of the possible combinations of:
  296.      - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
  297.        and might be the same width as int or as long
  298.      - size_t might have different width and signedness as INTERNAL_SIZE_T
  299.      - int and long might be 32 or 64 bits, and might be the same width
  300.   To deal with this, most comparisons and difference computations
  301.   among INTERNAL_SIZE_Ts should cast them to unsigned long, being
  302.   aware of the fact that casting an unsigned int to a wider long does
  303.   not sign-extend. (This also makes checking for negative numbers
  304.   awkward.) Some of these casts result in harmless compiler warnings
  305.   on some systems.
  306. */

  307. #ifndef INTERNAL_SIZE_T
  308. #define INTERNAL_SIZE_T size_t
  309. #endif

  310. /* The corresponding word size */
  311. #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))


  312. /*
  313.   MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
  314.   It must be a power of two at least 2 * SIZE_SZ, even on machines
  315.   for which smaller alignments would suffice. It may be defined as
  316.   larger than this though. Note however that code and data structures
  317.   are optimized for the case of 8-byte alignment.
  318. */


  319. #ifndef MALLOC_ALIGNMENT
  320. /* XXX This is the correct definition. It differs from 2*SIZE_SZ only on
  321.    powerpc32. For the time being, changing this is causing more
  322.    compatibility problems due to malloc_get_state/malloc_set_state than
  323.    will returning blocks not adequately aligned for long double objects
  324.    under -mlong-double-128.

  325. #define MALLOC_ALIGNMENT (2 * SIZE_SZ < __alignof__ (long double) \
  326.                 ? __alignof__ (long double) : 2 * SIZE_SZ)
  327. */
  328. #define MALLOC_ALIGNMENT (2 * SIZE_SZ)
  329. #endif

  330. /* The corresponding bit mask value */
  331. #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)



  332. /*
  333.   REALLOC_ZERO_BYTES_FREES should be set if a call to
  334.   realloc with zero bytes should be the same as a call to free.
  335.   This is required by the C standard. Otherwise, since this malloc
  336.   returns a unique pointer for malloc(0), so does realloc(p, 0).
  337. */

  338. #ifndef REALLOC_ZERO_BYTES_FREES
  339. #define REALLOC_ZERO_BYTES_FREES 1
  340. #endif

  341. /*
  342.   TRIM_FASTBINS controls whether free() of a very small chunk can
  343.   immediately lead to trimming. Setting to true (1) can reduce memory
  344.   footprint, but will almost always slow down programs that use a lot
  345.   of small chunks.

  346.   Define this only if you are willing to give up some speed to more
  347.   aggressively reduce system-level memory footprint when releasing
  348.   memory in programs that use many small chunks. You can get
  349.   essentially the same effect by setting MXFAST to 0, but this can
  350.   lead to even greater slowdowns in programs using many small chunks.
  351.   TRIM_FASTBINS is an in-between compile-time option, that disables
  352.   only those chunks bordering topmost memory from being placed in
  353.   fastbins.
  354. */

  355. #ifndef TRIM_FASTBINS
  356. #define TRIM_FASTBINS 0
  357. #endif


  358. /*
  359.   USE_DL_PREFIX will prefix all public routines with the string 'dl'.
  360.   This is necessary when you only want to use this malloc in one part
  361.   of a program, using your regular system malloc elsewhere.
  362. */

  363. /* #define USE_DL_PREFIX */


  364. /*
  365.    Two-phase name translation.
  366.    All of the actual routines are given mangled names.
  367.    When wrappers are used, they become the public callable versions.
  368.    When DL_PREFIX is used, the callable names are prefixed.
  369. */

  370. #ifdef USE_DL_PREFIX
  371. #define public_cALLOc dlcalloc
  372. #define public_fREe dlfree
  373. #define public_cFREe dlcfree
  374. #define public_mALLOc dlmalloc
  375. #define public_mEMALIGn dlmemalign
  376. #define public_rEALLOc dlrealloc
  377. #define public_vALLOc dlvalloc
  378. #define public_pVALLOc dlpvalloc
  379. #define public_mALLINFo dlmallinfo
  380. #define public_mALLOPt dlmallopt
  381. #define public_mTRIm dlmalloc_trim
  382. #define public_mSTATs dlmalloc_stats
  383. #define public_mUSABLe dlmalloc_usable_size
  384. #define public_iCALLOc dlindependent_calloc
  385. #define public_iCOMALLOc dlindependent_comalloc
  386. #define public_gET_STATe dlget_state
  387. #define public_sET_STATe dlset_state
  388. #else /* USE_DL_PREFIX */
  389. #ifdef _LIBC

  390. /* Special defines for the GNU C library. */
  391. #define public_cALLOc __libc_calloc
  392. #define public_fREe __libc_free
  393. #define public_cFREe __libc_cfree
  394. #define public_mALLOc __libc_malloc
  395. #define public_mEMALIGn __libc_memalign
  396. #define public_rEALLOc __libc_realloc
  397. #define public_vALLOc __libc_valloc
  398. #define public_pVALLOc __libc_pvalloc
  399. #define public_mALLINFo __libc_mallinfo
  400. #define public_mALLOPt __libc_mallopt
  401. #define public_mTRIm __malloc_trim
  402. #define public_mSTATs __malloc_stats
  403. #define public_mUSABLe __malloc_usable_size
  404. #define public_iCALLOc __libc_independent_calloc
  405. #define public_iCOMALLOc __libc_independent_comalloc
  406. #define public_gET_STATe __malloc_get_state
  407. #define public_sET_STATe __malloc_set_state
  408. #define malloc_getpagesize __getpagesize()
  409. #define open __open
  410. #define mmap __mmap
  411. #define munmap __munmap
  412. #define mremap __mremap
  413. #define mprotect __mprotect
  414. #define MORECORE (*__morecore)
  415. #define MORECORE_FAILURE 0

  416. Void_t * __default_morecore (ptrdiff_t);
  417. Void_t *(*__morecore)(ptrdiff_t) = __default_morecore;

  418. #else /* !_LIBC */
  419. #define public_cALLOc calloc
  420. #define public_fREe free
  421. #define public_cFREe cfree
  422. #define public_mALLOc malloc
  423. #define public_mEMALIGn memalign
  424. #define public_rEALLOc realloc
  425. #define public_vALLOc valloc
  426. #define public_pVALLOc pvalloc
  427. #define public_mALLINFo mallinfo
  428. #define public_mALLOPt mallopt
  429. #define public_mTRIm malloc_trim
  430. #define public_mSTATs malloc_stats
  431. #define public_mUSABLe malloc_usable_size
  432. #define public_iCALLOc independent_calloc
  433. #define public_iCOMALLOc independent_comalloc
  434. #define public_gET_STATe malloc_get_state
  435. #define public_sET_STATe malloc_set_state
  436. #endif /* _LIBC */
  437. #endif /* USE_DL_PREFIX */

  438. #ifndef _LIBC
  439. #define __builtin_expect(expr, val)    (expr)

  440. #define fwrite(buf, size, count, fp) _IO_fwrite (buf, size, count, fp)
  441. #endif

  442. /*
  443.   HAVE_MEMCPY should be defined if you are not otherwise using
  444.   ANSI STD C, but still have memcpy and memset in your C library
  445.   and want to use them in calloc and realloc. Otherwise simple
  446.   macro versions are defined below.

  447.   USE_MEMCPY should be defined as 1 if you actually want to
  448.   have memset and memcpy called. People report that the macro
  449.   versions are faster than libc versions on some systems.

  450.   Even if USE_MEMCPY is set to 1, loops to copy/clear small chunks
  451.   (of <= 36 bytes) are manually unrolled in realloc and calloc.
  452. */

  453. #define HAVE_MEMCPY

  454. #ifndef USE_MEMCPY
  455. #ifdef HAVE_MEMCPY
  456. #define USE_MEMCPY 1
  457. #else
  458. #define USE_MEMCPY 0
  459. #endif
  460. #endif


  461. #if (__STD_C || defined(HAVE_MEMCPY))

  462. #ifdef _LIBC
  463. # include <string.h>
  464. #else
  465. #ifdef WIN32
  466. /* On Win32 memset and memcpy are already declared in windows.h */
  467. #else
  468. #if __STD_C
  469. void* memset(void*, int, size_t);
  470. void* memcpy(void*, const void*, size_t);
  471. #else
  472. Void_t* memset();
  473. Void_t* memcpy();
  474. #endif
  475. #endif
  476. #endif
  477. #endif


  478. /* Force a value to be in a register and stop the compiler referring
  479.    to the source (mostly memory location) again. */
  480. #define force_reg(val) \
  481.   ({ __typeof (val) _v; asm ("" : "=r" (_v) : "0" (val)); _v; })


  482. /*
  483.   MALLOC_FAILURE_ACTION is the action to take before "return 0" when
  484.   malloc fails to be able to return memory, either because memory is
  485.   exhausted or because of illegal arguments.

  486.   By default, sets errno if running on STD_C platform, else does nothing.
  487. */

  488. #ifndef MALLOC_FAILURE_ACTION
  489. #if __STD_C
  490. #define MALLOC_FAILURE_ACTION \
  491.    errno = ENOMEM;

  492. #else
  493. #define MALLOC_FAILURE_ACTION
  494. #endif
  495. #endif

  496. /*
  497.   MORECORE-related declarations. By default, rely on sbrk
  498. */


  499. #ifdef LACKS_UNISTD_H
  500. #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
  501. #if __STD_C
  502. extern Void_t* sbrk(ptrdiff_t);
  503. #else
  504. extern Void_t* sbrk();
  505. #endif
  506. #endif
  507. #endif

  508. /*
  509.   MORECORE is the name of the routine to call to obtain more memory
  510.   from the system. See below for general guidance on writing
  511.   alternative MORECORE functions, as well as a version for WIN32 and a
  512.   sample version for pre-OSX macos.
  513. */

  514. #ifndef MORECORE
  515. #define MORECORE sbrk
  516. #endif

  517. /*
  518.   MORECORE_FAILURE is the value returned upon failure of MORECORE
  519.   as well as mmap. Since it cannot be an otherwise valid memory address,
  520.   and must reflect values of standard sys calls, you probably ought not
  521.   try to redefine it.
  522. */

  523. #ifndef MORECORE_FAILURE
  524. #define MORECORE_FAILURE (-1)
  525. #endif

  526. /*
  527.   If MORECORE_CONTIGUOUS is true, take advantage of fact that
  528.   consecutive calls to MORECORE with positive arguments always return
  529.   contiguous increasing addresses. This is true of unix sbrk. Even
  530.   if not defined, when regions happen to be contiguous, malloc will
  531.   permit allocations spanning regions obtained from different
  532.   calls. But defining this when applicable enables some stronger
  533.   consistency checks and space efficiencies.
  534. */

  535. #ifndef MORECORE_CONTIGUOUS
  536. #define MORECORE_CONTIGUOUS 1
  537. #endif

  538. /*
  539.   Define MORECORE_CANNOT_TRIM if your version of MORECORE
  540.   cannot release space back to the system when given negative
  541.   arguments. This is generally necessary only if you are using
  542.   a hand-crafted MORECORE function that cannot handle negative arguments.
  543. */

  544. /* #define MORECORE_CANNOT_TRIM */

  545. /* MORECORE_CLEARS (default 1)
  546.      The degree to which the routine mapped to MORECORE zeroes out
  547.      memory: never (0), only for newly allocated space (1) or always
  548.      (2). The distinction between (1) and (2) is necessary because on
  549.      some systems, if the application first decrements and then
  550.      increments the break value, the contents of the reallocated space
  551.      are unspecified.
  552. */

  553. #ifndef MORECORE_CLEARS
  554. #define MORECORE_CLEARS 1
  555. #endif


  556. /*
  557.   Define HAVE_MMAP as true to optionally make malloc() use mmap() to
  558.   allocate very large blocks. These will be returned to the
  559.   operating system immediately after a free(). Also, if mmap
  560.   is available, it is used as a backup strategy in cases where
  561.   MORECORE fails to provide space from system.

  562.   This malloc is best tuned to work with mmap for large requests.
  563.   If you do not have mmap, operations involving very large chunks (1MB
  564.   or so) may be slower than you'd like.
  565. */

  566. #ifndef HAVE_MMAP
  567. #define HAVE_MMAP 1

  568. /*
  569.    Standard unix mmap using /dev/zero clears memory so calloc doesn't
  570.    need to.
  571. */

  572. #ifndef MMAP_CLEARS
  573. #define MMAP_CLEARS 1
  574. #endif

  575. #else /* no mmap */
  576. #ifndef MMAP_CLEARS
  577. #define MMAP_CLEARS 0
  578. #endif
  579. #endif


  580. /*
  581.    MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
  582.    sbrk fails, and mmap is used as a backup (which is done only if
  583.    HAVE_MMAP). The value must be a multiple of page size. This
  584.    backup strategy generally applies only when systems have "holes" in
  585.    address space, so sbrk cannot perform contiguous expansion, but
  586.    there is still space available on system. On systems for which
  587.    this is known to be useful (i.e. most linux kernels), this occurs
  588.    only when programs allocate huge amounts of memory. Between this,
  589.    and the fact that mmap regions tend to be limited, the size should
  590.    be large, to avoid too many mmap calls and thus avoid running out
  591.    of kernel resources.
  592. */

  593. #ifndef MMAP_AS_MORECORE_SIZE
  594. #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
  595. #endif

  596. /*
  597.   Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
  598.   large blocks. This is currently only possible on Linux with
  599.   kernel versions newer than 1.3.77.
  600. */

  601. #ifndef HAVE_MREMAP
  602. #ifdef linux
  603. #define HAVE_MREMAP 1
  604. #else
  605. #define HAVE_MREMAP 0
  606. #endif

  607. #endif /* HAVE_MMAP */

  608. /* Define USE_ARENAS to enable support for multiple `arenas'. These
  609.    are allocated using mmap(), are necessary for threads and
  610.    occasionally useful to overcome address space limitations affecting
  611.    sbrk(). */

  612. #ifndef USE_ARENAS
  613. #define USE_ARENAS HAVE_MMAP
  614. #endif


  615. /*
  616.   The system page size. To the extent possible, this malloc manages
  617.   memory from the system in page-size units. Note that this value is
  618.   cached during initialization into a field of malloc_state. So even
  619.   if malloc_getpagesize is a function, it is only called once.

  620.   The following mechanics for getpagesize were adapted from bsd/gnu
  621.   getpagesize.h. If none of the system-probes here apply, a value of
  622.   4096 is used, which should be OK: If they don't apply, then using
  623.   the actual value probably doesn't impact performance.
  624. */


  625. #ifndef malloc_getpagesize

  626. #ifndef LACKS_UNISTD_H
  627. # include <unistd.h>
  628. #endif

  629. # ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
  630. # ifndef _SC_PAGE_SIZE
  631. # define _SC_PAGE_SIZE _SC_PAGESIZE
  632. # endif
  633. # endif

  634. # ifdef _SC_PAGE_SIZE
  635. # define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
  636. # else
  637. # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
  638.        extern size_t getpagesize();
  639. # define malloc_getpagesize getpagesize()
  640. # else
  641. # ifdef WIN32 /* use supplied emulation of getpagesize */
  642. # define malloc_getpagesize getpagesize()
  643. # else
  644. # ifndef LACKS_SYS_PARAM_H
  645. # include <sys/param.h>
  646. # endif
  647. # ifdef EXEC_PAGESIZE
  648. # define malloc_getpagesize EXEC_PAGESIZE
  649. # else
  650. # ifdef NBPG
  651. # ifndef CLSIZE
  652. # define malloc_getpagesize NBPG
  653. # else
  654. # define malloc_getpagesize (NBPG * CLSIZE)
  655. # endif
  656. # else
  657. # ifdef NBPC
  658. # define malloc_getpagesize NBPC
  659. # else
  660. # ifdef PAGESIZE
  661. # define malloc_getpagesize PAGESIZE
  662. # else /* just guess */
  663. # define malloc_getpagesize (4096)
  664. # endif
  665. # endif
  666. # endif
  667. # endif
  668. # endif
  669. # endif
  670. # endif
  671. #endif

  672. /*
  673.   This version of malloc supports the standard SVID/XPG mallinfo
  674.   routine that returns a struct containing usage properties and
  675.   statistics. It should work on any SVID/XPG compliant system that has
  676.   a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
  677.   install such a thing yourself, cut out the preliminary declarations
  678.   as described above and below and save them in a malloc.h file. But
  679.   there's no compelling reason to bother to do this.)

  680.   The main declaration needed is the mallinfo struct that is returned
  681.   (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
  682.   bunch of fields that are not even meaningful in this version of
  683.   malloc. These fields are are instead filled by mallinfo() with
  684.   other numbers that might be of interest.

  685.   HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
  686.   /usr/include/malloc.h file that includes a declaration of struct
  687.   mallinfo. If so, it is included; else an SVID2/XPG2 compliant
  688.   version is declared below. These must be precisely the same for
  689.   mallinfo() to work. The original SVID version of this struct,
  690.   defined on most systems with mallinfo, declares all fields as
  691.   ints. But some others define as unsigned long. If your system
  692.   defines the fields using a type of different width than listed here,
  693.   you must #include your system version and #define
  694.   HAVE_USR_INCLUDE_MALLOC_H.
  695. */

  696. /* #define HAVE_USR_INCLUDE_MALLOC_H */

  697. #ifdef HAVE_USR_INCLUDE_MALLOC_H
  698. #include "/usr/include/malloc.h"
  699. #endif


  700. /* ---------- description of public routines ------------ */

  701. /*
  702.   malloc(size_t n)
  703.   Returns a pointer to a newly allocated chunk of at least n bytes, or null
  704.   if no space is available. Additionally, on failure, errno is
  705.   set to ENOMEM on ANSI C systems.

  706.   If n is zero, malloc returns a minumum-sized chunk. (The minimum
  707.   size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
  708.   systems.) On most systems, size_t is an unsigned type, so calls
  709.   with negative arguments are interpreted as requests for huge amounts
  710.   of space, which will often fail. The maximum supported value of n
  711.   differs across systems, but is in all cases less than the maximum
  712.   representable value of a size_t.
  713. */
  714. #if __STD_C
  715. Void_t* public_mALLOc(size_t);
  716. #else
  717. Void_t* public_mALLOc();
  718. #endif
  719. #ifdef libc_hidden_proto
  720. libc_hidden_proto (public_mALLOc)
  721. #endif

  722. /*
  723.   free(Void_t* p)
  724.   Releases the chunk of memory pointed to by p, that had been previously
  725.   allocated using malloc or a related routine such as realloc.
  726.   It has no effect if p is null. It can have arbitrary (i.e.,
  727.   effects if p has already been freed.

  728.   Unless disabled (using mallopt), freeing very large spaces will
  729.   when possible, automatically trigger operations that give
  730.   back unused memory to the system, thus reducing program footprint.
  731. */
  732. #if __STD_C
  733. void public_fREe(Void_t*);
  734. #else
  735. void public_fREe();
  736. #endif
  737. #ifdef libc_hidden_proto
  738. libc_hidden_proto (public_fREe)
  739. #endif

  740. /*
  741.   calloc(size_t n_elements, size_t element_size);
  742.   Returns a pointer to n_elements * element_size bytes, with all locations
  743.   set to zero.
  744. */
  745. #if __STD_C
  746. Void_t* public_cALLOc(size_t, size_t);
  747. #else
  748. Void_t* public_cALLOc();
  749. #endif

  750. /*
  751.   realloc(Void_t* p, size_t n)
  752.   Returns a pointer to a chunk of size n that contains the same data
  753.   as does chunk p up to the minimum of (n, p's size) bytes, or null
  754.   if no space is available.

  755.   The returned pointer may or may not be the same as p. The algorithm
  756.   prefers extending p when possible, otherwise it employs the
  757.   equivalent of a malloc-copy-free sequence.

  758.   If p is null, realloc is equivalent to malloc.

  759.   If space is not available, realloc returns null, errno is set (if on
  760.   ANSI) and p is NOT freed.

  761.   if n is for fewer bytes than already held by p, the newly unused
  762.   space is lopped off and freed if possible. Unless the #define
  763.   REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
  764.   zero (re)allocates a minimum-sized chunk.

  765.   Large chunks that were internally obtained via mmap will always
  766.   be reallocated using malloc-copy-free sequences unless
  767.   the system supports MREMAP (currently only linux).

  768.   The old unix realloc convention of allowing the last-free'd chunk
  769.   to be used as an argument to realloc is not supported.
  770. */
  771. #if __STD_C
  772. Void_t* public_rEALLOc(Void_t*, size_t);
  773. #else
  774. Void_t* public_rEALLOc();
  775. #endif
  776. #ifdef libc_hidden_proto
  777. libc_hidden_proto (public_rEALLOc)
  778. #endif

  779. /*
  780.   memalign(size_t alignment, size_t n);
  781.   Returns a pointer to a newly allocated chunk of n bytes, aligned
  782.   in accord with the alignment argument.

  783.   The alignment argument should be a power of two. If the argument is
  784.   not a power of two, the nearest greater power is used.
  785.   8-byte alignment is guaranteed by normal malloc calls, so don't
  786.   bother calling memalign with an argument of 8 or less.

  787.   Overreliance on memalign is a sure way to fragment space.
  788. */
  789. #if __STD_C
  790. Void_t* public_mEMALIGn(size_t, size_t);
  791. #else
  792. Void_t* public_mEMALIGn();
  793. #endif
  794. #ifdef libc_hidden_proto
  795. libc_hidden_proto (public_mEMALIGn)
  796. #endif

  797. /*
  798.   valloc(size_t n);
  799.   Equivalent to memalign(pagesize, n), where pagesize is the page
  800.   size of the system. If the pagesize is unknown, 4096 is used.
  801. */
  802. #if __STD_C
  803. Void_t* public_vALLOc(size_t);
  804. #else
  805. Void_t* public_vALLOc();
  806. #endif



  807. /*
  808.   mallopt(int parameter_number, int parameter_value)
  809.   Sets tunable parameters The format is to provide a
  810.   (parameter-number, parameter-value) pair. mallopt then sets the
  811.   corresponding parameter to the argument value if it can (i.e., so
  812.   long as the value is meaningful), and returns 1 if successful else
  813.   0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
  814.   normally defined in malloc.h. Only one of these (M_MXFAST) is used
  815.   in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
  816.   so setting them has no effect. But this malloc also supports four
  817.   other options in mallopt. See below for details. Briefly, supported
  818.   parameters are as follows (listed defaults are for "typical"
  819.   configurations).

  820.   Symbol param # default allowed param values
  821.   M_MXFAST 1 64 0-80 (0 disables fastbins)
  822.   M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
  823.   M_TOP_PAD -2 0 any
  824.   M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
  825.   M_MMAP_MAX -4 65536 any (0 disables use of mmap)
  826. */
  827. #if __STD_C
  828. int public_mALLOPt(int, int);
  829. #else
  830. int public_mALLOPt();
  831. #endif


  832. /*
  833.   mallinfo()
  834.   Returns (by copy) a struct containing various summary statistics:

  835.   arena: current total non-mmapped bytes allocated from system
  836.   ordblks: the number of free chunks
  837.   smblks: the number of fastbin blocks (i.e., small chunks that
  838.      have been freed but not use resused or consolidated)
  839.   hblks: current number of mmapped regions
  840.   hblkhd: total bytes held in mmapped regions
  841.   usmblks: the maximum total allocated space. This will be greater
  842.         than current total if trimming has occurred.
  843.   fsmblks: total bytes held in fastbin blocks
  844.   uordblks: current total allocated space (normal or mmapped)
  845.   fordblks: total free space
  846.   keepcost: the maximum number of bytes that could ideally be released
  847.      back to system via malloc_trim. ("ideally" means that
  848.      it ignores page restrictions etc.)

  849.   Because these fields are ints, but internal bookkeeping may
  850.   be kept as longs, the reported values may wrap around zero and
  851.   thus be inaccurate.
  852. */
  853. #if __STD_C
  854. struct mallinfo public_mALLINFo(void);
  855. #else
  856. struct mallinfo public_mALLINFo();
  857. #endif

  858. #ifndef _LIBC
  859. /*
  860.   independent_calloc(size_t n_elements, size_t element_size, Void_t* chunks[]);

  861.   independent_calloc is similar to calloc, but instead of returning a
  862.   single cleared space, it returns an array of pointers to n_elements
  863.   independent elements that can hold contents of size elem_size, each
  864.   of which starts out cleared, and can be independently freed,
  865.   realloc'ed etc. The elements are guaranteed to be adjacently
  866.   allocated (this is not guaranteed to occur with multiple callocs or
  867.   mallocs), which may also improve cache locality in some
  868.   applications.

  869.   The "chunks" argument is optional (i.e., may be null, which is
  870.   probably the most typical usage). If it is null, the returned array
  871.   is itself dynamically allocated and should also be freed when it is
  872.   no longer needed. Otherwise, the chunks array must be of at least
  873.   n_elements in length. It is filled in with the pointers to the
  874.   chunks.

  875.   In either case, independent_calloc returns this pointer array, or
  876.   null if the allocation failed. If n_elements is zero and "chunks"
  877.   is null, it returns a chunk representing an array with zero elements
  878.   (which should be freed if not wanted).

  879.   Each element must be individually freed when it is no longer
  880.   needed. If you'd like to instead be able to free all at once, you
  881.   should instead use regular calloc and assign pointers into this
  882.   space to represent elements. (In this case though, you cannot
  883.   independently free elements.)

  884.   independent_calloc simplifies and speeds up implementations of many
  885.   kinds of pools. It may also be useful when constructing large data
  886.   structures that initially have a fixed number of fixed-sized nodes,
  887.   but the number is not known at compile time, and some of the nodes
  888.   may later need to be freed. For example:

  889.   struct Node { int item; struct Node* next; };

  890.   struct Node* build_list() {
  891.     struct Node** pool;
  892.     int n = read_number_of_nodes_needed();
  893.     if (n <= 0) return 0;
  894.     pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
  895.     if (pool == 0) die();
  896.     // organize into a linked list...
  897.     struct Node* first = pool[0];
  898.     for (i = 0; i < n-1; ++i)
  899.       pool[i]->next = pool[i+1];
  900.     free(pool); // Can now free the array (or not, if it is needed later)
  901.     return first;
  902.   }
  903. */
  904. #if __STD_C
  905. Void_t** public_iCALLOc(size_t, size_t, Void_t**);
  906. #else
  907. Void_t** public_iCALLOc();
  908. #endif

  909. /*
  910.   independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]);

  911.   independent_comalloc allocates, all at once, a set of n_elements
  912.   chunks with sizes indicated in the "sizes" array. It returns
  913.   an array of pointers to these elements, each of which can be
  914.   independently freed, realloc'ed etc. The elements are guaranteed to
  915.   be adjacently allocated (this is not guaranteed to occur with
  916.   multiple callocs or mallocs), which may also improve cache locality
  917.   in some applications.

  918.   The "chunks" argument is optional (i.e., may be null). If it is null
  919.   the returned array is itself dynamically allocated and should also
  920.   be freed when it is no longer needed. Otherwise, the chunks array
  921.   must be of at least n_elements in length. It is filled in with the
  922.   pointers to the chunks.

  923.   In either case, independent_comalloc returns this pointer array, or
  924.   null if the allocation failed. If n_elements is zero and chunks is
  925.   null, it returns a chunk representing an array with zero elements
  926.   (which should be freed if not wanted).

  927.   Each element must be individually freed when it is no longer
  928.   needed. If you'd like to instead be able to free all at once, you
  929.   should instead use a single regular malloc, and assign pointers at
  930.   particular offsets in the aggregate space. (In this case though, you
  931.   cannot independently free elements.)

  932.   independent_comallac differs from independent_calloc in that each
  933.   element may have a different size, and also that it does not
  934.   automatically clear elements.

  935.   independent_comalloc can be used to speed up allocation in cases
  936.   where several structs or objects must always be allocated at the
  937.   same time. For example:

  938.   struct Head { ... }
  939.   struct Foot { ... }

  940.   void send_message(char* msg) {
  941.     int msglen = strlen(msg);
  942.     size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
  943.     void* chunks[3];
  944.     if (independent_comalloc(3, sizes, chunks) == 0)
  945.       die();
  946.     struct Head* head = (struct Head*)(chunks[0]);
  947.     char* body = (char*)(chunks[1]);
  948.     struct Foot* foot = (struct Foot*)(chunks[2]);
  949.     // ...
  950.   }

  951.   In general though, independent_comalloc is worth using only for
  952.   larger values of n_elements. For small values, you probably won't
  953.   detect enough difference from series of malloc calls to bother.

  954.   Overuse of independent_comalloc can increase overall memory usage,
  955.   since it cannot reuse existing noncontiguous small chunks that
  956.   might be available for some of the elements.
  957. */
  958. #if __STD_C
  959. Void_t** public_iCOMALLOc(size_t, size_t*, Void_t**);
  960. #else
  961. Void_t** public_iCOMALLOc();
  962. #endif

  963. #endif /* _LIBC */


  964. /*
  965.   pvalloc(size_t n);
  966.   Equivalent to valloc(minimum-page-that-holds(n)), that is,
  967.   round up n to nearest pagesize.
  968.  */
  969. #if __STD_C
  970. Void_t* public_pVALLOc(size_t);
  971. #else
  972. Void_t* public_pVALLOc();
  973. #endif

  974. /*
  975.   cfree(Void_t* p);
  976.   Equivalent to free(p).

  977.   cfree is needed/defined on some systems that pair it with calloc,
  978.   for odd historical reasons (such as: cfree is used in example
  979.   code in the first edition of K&R).
  980. */
  981. #if __STD_C
  982. void public_cFREe(Void_t*);
  983. #else
  984. void public_cFREe();
  985. #endif

  986. /*
  987.   malloc_trim(size_t pad);

  988.   If possible, gives memory back to the system (via negative
  989.   arguments to sbrk) if there is unused memory at the `high' end of
  990.   the malloc pool. You can call this after freeing large blocks of
  991.   memory to potentially reduce the system-level memory requirements
  992.   of a program. However, it cannot guarantee to reduce memory. Under
  993.   some allocation patterns, some large free blocks of memory will be
  994.   locked between two used chunks, so they cannot be given back to
  995.   the system.

  996.   The `pad' argument to malloc_trim represents the amount of free
  997.   trailing space to leave untrimmed. If this argument is zero,
  998.   only the minimum amount of memory to maintain internal data
  999.   structures will be left (one page or less). Non-zero arguments
  1000.   can be supplied to maintain enough trailing space to service
  1001.   future expected allocations without having to re-obtain memory
  1002.   from the system.

  1003.   Malloc_trim returns 1 if it actually released any memory, else 0.
  1004.   On systems that do not support "negative sbrks", it will always
  1005.   return 0.
  1006. */
  1007. #if __STD_C
  1008. int public_mTRIm(size_t);
  1009. #else
  1010. int public_mTRIm();
  1011. #endif

  1012. /*
  1013.   malloc_usable_size(Void_t* p);

  1014.   Returns the number of bytes you can actually use in
  1015.   an allocated chunk, which may be more than you requested (although
  1016.   often not) due to alignment and minimum size constraints.
  1017.   You can use this many bytes without worrying about
  1018.   overwriting other allocated objects. This is not a particularly great
  1019.   programming practice. malloc_usable_size can be more useful in
  1020.   debugging and assertions, for example:

  1021.   p = malloc(n);
  1022.   assert(malloc_usable_size(p) >= 256);

  1023. */
  1024. #if __STD_C
  1025. size_t public_mUSABLe(Void_t*);
  1026. #else
  1027. size_t public_mUSABLe();
  1028. #endif

  1029. /*
  1030.   malloc_stats();
  1031.   Prints on stderr the amount of space obtained from the system (both
  1032.   via sbrk and mmap), the maximum amount (which may be more than
  1033.   current if malloc_trim and/or munmap got called), and the current
  1034.   number of bytes allocated via malloc (or realloc, etc) but not yet
  1035.   freed. Note that this is the number of bytes allocated, not the
  1036.   number requested. It will be larger than the number requested
  1037.   because of alignment and bookkeeping overhead. Because it includes
  1038.   alignment wastage as being in use, this figure may be greater than
  1039.   zero even when no user-level chunks are allocated.

  1040.   The reported current and maximum system memory can be inaccurate if
  1041.   a program makes other calls to system memory allocation functions
  1042.   (normally sbrk) outside of malloc.

  1043.   malloc_stats prints only the most commonly interesting statistics.
  1044.   More information can be obtained by calling mallinfo.

  1045. */
  1046. #if __STD_C
  1047. void public_mSTATs(void);
  1048. #else
  1049. void public_mSTATs();
  1050. #endif

  1051. /*
  1052.   malloc_get_state(void);

  1053.   Returns the state of all malloc variables in an opaque data
  1054.   structure.
  1055. */
  1056. #if __STD_C
  1057. Void_t* public_gET_STATe(void);
  1058. #else
  1059. Void_t* public_gET_STATe();
  1060. #endif

  1061. /*
  1062.   malloc_set_state(Void_t* state);

  1063.   Restore the state of all malloc variables from data obtained with
  1064.   malloc_get_state().
  1065. */
  1066. #if __STD_C
  1067. int public_sET_STATe(Void_t*);
  1068. #else
  1069. int public_sET_STATe();
  1070. #endif

  1071. #ifdef _LIBC
  1072. /*
  1073.   posix_memalign(void **memptr, size_t alignment, size_t size);

  1074.   POSIX wrapper like memalign(), checking for validity of size.
  1075. */
  1076. int __posix_memalign(void **, size_t, size_t);
  1077. #endif

  1078. /* mallopt tuning options */

  1079. /*
  1080.   M_MXFAST is the maximum request size used for "fastbins", special bins
  1081.   that hold returned chunks without consolidating their spaces. This
  1082.   enables future requests for chunks of the same size to be handled
  1083.   very quickly, but can increase fragmentation, and thus increase the
  1084.   overall memory footprint of a program.

  1085.   This malloc manages fastbins very conservatively yet still
  1086.   efficiently, so fragmentation is rarely a problem for values less
  1087.   than or equal to the default. The maximum supported value of MXFAST
  1088.   is 80. You wouldn't want it any higher than this anyway. Fastbins
  1089.   are designed especially for use with many small structs, objects or
  1090.   strings -- the default handles structs/objects/arrays with sizes up
  1091.   to 8 4byte fields, or small strings representing words, tokens,
  1092.   etc. Using fastbins for larger objects normally worsens
  1093.   fragmentation without improving speed.

  1094.   M_MXFAST is set in REQUEST size units. It is internally used in
  1095.   chunksize units, which adds padding and alignment. You can reduce
  1096.   M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
  1097.   algorithm to be a closer approximation of fifo-best-fit in all cases,
  1098.   not just for larger requests, but will generally cause it to be
  1099.   slower.
  1100. */


  1101. /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
  1102. #ifndef M_MXFAST
  1103. #define M_MXFAST 1
  1104. #endif

  1105. #ifndef DEFAULT_MXFAST
  1106. #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
  1107. #endif


  1108. /*
  1109.   M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
  1110.   to keep before releasing via malloc_trim in free().

  1111.   Automatic trimming is mainly useful in long-lived programs.
  1112.   Because trimming via sbrk can be slow on some systems, and can
  1113.   sometimes be wasteful (in cases where programs immediately
  1114.   afterward allocate more large chunks) the value should be high
  1115.   enough so that your overall system performance would improve by
  1116.   releasing this much memory.

  1117.   The trim threshold and the mmap control parameters (see below)
  1118.   can be traded off with one another. Trimming and mmapping are
  1119.   two different ways of releasing unused memory back to the
  1120.   system. Between these two, it is often possible to keep
  1121.   system-level demands of a long-lived program down to a bare
  1122.   minimum. For example, in one test suite of sessions measuring
  1123.   the XF86 X server on Linux, using a trim threshold of 128K and a
  1124.   mmap threshold of 192K led to near-minimal long term resource
  1125.   consumption.

  1126.   If you are using this malloc in a long-lived program, it should
  1127.   pay to experiment with these values. As a rough guide, you
  1128.   might set to a value close to the average size of a process
  1129.   (program) running on your system. Releasing this much memory
  1130.   would allow such a process to run in memory. Generally, it's
  1131.   worth it to tune for trimming rather tham memory mapping when a
  1132.   program undergoes phases where several large chunks are
  1133.   allocated and released in ways that can reuse each other's
  1134.   storage, perhaps mixed with phases where there are no such
  1135.   chunks at all. And in well-behaved long-lived programs,
  1136.   controlling release of large blocks via trimming versus mapping
  1137.   is usually faster.

  1138.   However, in most programs, these parameters serve mainly as
  1139.   protection against the system-level effects of carrying around
  1140.   massive amounts of unneeded memory. Since frequent calls to
  1141.   sbrk, mmap, and munmap otherwise degrade performance, the default
  1142.   parameters are set to relatively high values that serve only as
  1143.   safeguards.

  1144.   The trim value It must be greater than page size to have any useful
  1145.   effect. To disable trimming completely, you can set to
  1146.   (unsigned long)(-1)

  1147.   Trim settings interact with fastbin (MXFAST) settings: Unless
  1148.   TRIM_FASTBINS is defined, automatic trimming never takes place upon
  1149.   freeing a chunk with size less than or equal to MXFAST. Trimming is
  1150.   instead delayed until subsequent freeing of larger chunks. However,
  1151.   you can still force an attempted trim by calling malloc_trim.

  1152.   Also, trimming is not generally possible in cases where
  1153.   the main arena is obtained via mmap.

  1154.   Note that the trick some people use of mallocing a huge space and
  1155.   then freeing it at program startup, in an attempt to reserve system
  1156.   memory, doesn't have the intended effect under automatic trimming,
  1157.   since that memory will immediately be returned to the system.
  1158. */

  1159. #define M_TRIM_THRESHOLD -1

  1160. #ifndef DEFAULT_TRIM_THRESHOLD
  1161. #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
  1162. #endif

  1163. /*
  1164.   M_TOP_PAD is the amount of extra `padding' space to allocate or
  1165.   retain whenever sbrk is called. It is used in two ways internally:

  1166.   * When sbrk is called to extend the top of the arena to satisfy
  1167.   a new malloc request, this much padding is added to the sbrk
  1168.   request.

  1169.   * When malloc_trim is called automatically from free(),
  1170.   it is used as the `pad' argument.

  1171.   In both cases, the actual amount of padding is rounded
  1172.   so that the end of the arena is always a system page boundary.

  1173.   The main reason for using padding is to avoid calling sbrk so
  1174.   often. Having even a small pad greatly reduces the likelihood
  1175.   that nearly every malloc request during program start-up (or
  1176.   after trimming) will invoke sbrk, which needlessly wastes
  1177.   time.

  1178.   Automatic rounding-up to page-size units is normally sufficient
  1179.   to avoid measurable overhead, so the default is 0. However, in
  1180.   systems where sbrk is relatively slow, it can pay to increase
  1181.   this value, at the expense of carrying around more memory than
  1182.   the program needs.
  1183. */

  1184. #define M_TOP_PAD -2

  1185. #ifndef DEFAULT_TOP_PAD
  1186. #define DEFAULT_TOP_PAD (0)
  1187. #endif

  1188. /*
  1189.   MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
  1190.   adjusted MMAP_THRESHOLD.
  1191. */

  1192. #ifndef DEFAULT_MMAP_THRESHOLD_MIN
  1193. #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
  1194. #endif

  1195. #ifndef DEFAULT_MMAP_THRESHOLD_MAX
  1196.   /* For 32-bit platforms we cannot increase the maximum mmap
  1197.      threshold much because it is also the minimum value for the
  1198.      maximum heap size and its alignment. Going above 512k (i.e., 1M
  1199.      for new heaps) wastes too much address space. */
  1200. # if __WORDSIZE == 32
  1201. # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
  1202. # else
  1203. # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
  1204. # endif
  1205. #endif

  1206. /*
  1207.   M_MMAP_THRESHOLD is the request size threshold for using mmap()
  1208.   to service a request. Requests of at least this size that cannot
  1209.   be allocated using already-existing space will be serviced via mmap.
  1210.   (If enough normal freed space already exists it is used instead.)

  1211.   Using mmap segregates relatively large chunks of memory so that
  1212.   they can be individually obtained and released from the host
  1213.   system. A request serviced through mmap is never reused by any
  1214.   other request (at least not directly; the system may just so
  1215.   happen to remap successive requests to the same locations).

  1216.   Segregating space in this way has the benefits that:

  1217.    1. Mmapped space can ALWAYS be individually released back
  1218.       to the system, which helps keep the system level memory
  1219.       demands of a long-lived program low.
  1220.    2. Mapped memory can never become `locked' between
  1221.       other chunks, as can happen with normally allocated chunks, which
  1222.       means that even trimming via malloc_trim would not release them.
  1223.    3. On some systems with "holes" in address spaces, mmap can obtain
  1224.       memory that sbrk cannot.

  1225.   However, it has the disadvantages that:

  1226.    1. The space cannot be reclaimed, consolidated, and then
  1227.       used to service later requests, as happens with normal chunks.
  1228.    2. It can lead to more wastage because of mmap page alignment
  1229.       requirements
  1230.    3. It causes malloc performance to be more dependent on host
  1231.       system memory management support routines which may vary in
  1232.       implementation quality and may impose arbitrary
  1233.       limitations. Generally, servicing a request via normal
  1234.       malloc steps is faster than going through a system's mmap.

  1235.   The advantages of mmap nearly always outweigh disadvantages for
  1236.   "large" chunks, but the value of "large" varies across systems. The
  1237.   default is an empirically derived value that works well in most
  1238.   systems.


  1239.   Update in 2006:
  1240.   The above was written in 2001. Since then the world has changed a lot.
  1241.   Memory got bigger. Applications got bigger. The virtual address space
  1242.   layout in 32 bit linux changed.

  1243.   In the new situation, brk() and mmap space is shared and there are no
  1244.   artificial limits on brk size imposed by the kernel. What is more,
  1245.   applications have started using transient allocations larger than the
  1246.   128Kb as was imagined in 2001.

  1247.   The price for mmap is also high now; each time glibc mmaps from the
  1248.   kernel, the kernel is forced to zero out the memory it gives to the
  1249.   application. Zeroing memory is expensive and eats a lot of cache and
  1250.   memory bandwidth. This has nothing to do with the efficiency of the
  1251.   virtual memory system, by doing mmap the kernel just has no choice but
  1252.   to zero.

  1253.   In 2001, the kernel had a maximum size for brk() which was about 800
  1254.   megabytes on 32 bit x86, at that point brk() would hit the first
  1255.   mmaped shared libaries and couldn't expand anymore. With current 2.6
  1256.   kernels, the VA space layout is different and brk() and mmap
  1257.   both can span the entire heap at will.

  1258.   Rather than using a static threshold for the brk/mmap tradeoff,
  1259.   we are now using a simple dynamic one. The goal is still to avoid
  1260.   fragmentation. The old goals we kept are
  1261.   1) try to get the long lived large allocations to use mmap()
  1262.   2) really large allocations should always use mmap()
  1263.   and we're adding now:
  1264.   3) transient allocations should use brk() to avoid forcing the kernel
  1265.      having to zero memory over and over again

  1266.   The implementation works with a sliding threshold, which is by default
  1267.   limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
  1268.   out at 128Kb as per the 2001 default.

  1269.   This allows us to satisfy requirement 1) under the assumption that long
  1270.   lived allocations are made early in the process' lifespan, before it has
  1271.   started doing dynamic allocations of the same size (which will
  1272.   increase the threshold).

  1273.   The upperbound on the threshold satisfies requirement 2)

  1274.   The threshold goes up in value when the application frees memory that was
  1275.   allocated with the mmap allocator. The idea is that once the application
  1276.   starts freeing memory of a certain size, it's highly probable that this is
  1277.   a size the application uses for transient allocations. This estimator
  1278.   is there to satisfy the new third requirement.

  1279. */

  1280. #define M_MMAP_THRESHOLD -3

  1281. #ifndef DEFAULT_MMAP_THRESHOLD
  1282. #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
  1283. #endif

  1284. /*
  1285.   M_MMAP_MAX is the maximum number of requests to simultaneously
  1286.   service using mmap. This parameter exists because
  1287.   some systems have a limited number of internal tables for
  1288.   use by mmap, and using more than a few of them may degrade
  1289.   performance.

  1290.   The default is set to a value that serves only as a safeguard.
  1291.   Setting to 0 disables use of mmap for servicing large requests. If
  1292.   HAVE_MMAP is not set, the default value is 0, and attempts to set it
  1293.   to non-zero values in mallopt will fail.
  1294. */

  1295. #define M_MMAP_MAX -4

  1296. #ifndef DEFAULT_MMAP_MAX
  1297. #if HAVE_MMAP
  1298. #define DEFAULT_MMAP_MAX (65536)
  1299. #else
  1300. #define DEFAULT_MMAP_MAX (0)
  1301. #endif
  1302. #endif

  1303. #ifdef __cplusplus
  1304. } /* end of extern "C" */
  1305. #endif

  1306. #include <malloc.h>

  1307. #ifndef BOUNDED_N
  1308. #define BOUNDED_N(ptr, sz) (ptr)
  1309. #endif
  1310. #ifndef RETURN_ADDRESS
  1311. #define RETURN_ADDRESS(X_) (NULL)
  1312. #endif

  1313. /* On some platforms we can compile internal, not exported functions better.
  1314.    Let the environment provide a macro and define it to be empty if it
  1315.    is not available. */
  1316. #ifndef internal_function
  1317. # define internal_function
  1318. #endif

  1319. /* Forward declarations. */
  1320. struct malloc_chunk;
  1321. typedef struct malloc_chunk* mchunkptr;

  1322. /* Internal routines. */

  1323. #if __STD_C

  1324. static Void_t* _int_malloc(mstate, size_t);
  1325. #ifdef ATOMIC_FASTBINS
  1326. static void _int_free(mstate, mchunkptr, int);
  1327. #else
  1328. static void _int_free(mstate, mchunkptr);
  1329. #endif
  1330. static Void_t* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
  1331.              INTERNAL_SIZE_T);
  1332. static Void_t* _int_memalign(mstate, size_t, size_t);
  1333. static Void_t* _int_valloc(mstate, size_t);
  1334. static Void_t* _int_pvalloc(mstate, size_t);
  1335. /*static Void_t* cALLOc(size_t, size_t);*/
  1336. #ifndef _LIBC
  1337. static Void_t** _int_icalloc(mstate, size_t, size_t, Void_t**);
  1338. static Void_t** _int_icomalloc(mstate, size_t, size_t*, Void_t**);
  1339. #endif
  1340. static int mTRIm(mstate, size_t);
  1341. static size_t mUSABLe(Void_t*);
  1342. static void mSTATs(void);
  1343. static int mALLOPt(int, int);
  1344. static struct mallinfo mALLINFo(mstate);
  1345. static void malloc_printerr(int action, const char *str, void *ptr);

  1346. static Void_t* internal_function mem2mem_check(Void_t *p, size_t sz);
  1347. static int internal_function top_check(void);
  1348. static void internal_function munmap_chunk(mchunkptr p);
  1349. #if HAVE_MREMAP
  1350. static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
  1351. #endif

  1352. static Void_t* malloc_check(size_t sz, const Void_t *caller);
  1353. static void free_check(Void_t* mem, const Void_t *caller);
  1354. static Void_t* realloc_check(Void_t* oldmem, size_t bytes,
  1355.              const Void_t *caller);
  1356. static Void_t* memalign_check(size_t alignment, size_t bytes,
  1357.                 const Void_t *caller);
  1358. #ifndef NO_THREADS
  1359. # ifdef _LIBC
  1360. # if USE___THREAD || !defined SHARED
  1361.     /* These routines are never needed in this configuration. */
  1362. # define NO_STARTER
  1363. # endif
  1364. # endif
  1365. # ifdef NO_STARTER
  1366. # undef NO_STARTER
  1367. # else
  1368. static Void_t* malloc_starter(size_t sz, const Void_t *caller);
  1369. static Void_t* memalign_starter(size_t aln, size_t sz, const Void_t *caller);
  1370. static void free_starter(Void_t* mem, const Void_t *caller);
  1371. # endif
  1372. static Void_t* malloc_atfork(size_t sz, const Void_t *caller);
  1373. static void free_atfork(Void_t* mem, const Void_t *caller);
  1374. #endif

  1375. #else

  1376. static Void_t* _int_malloc();
  1377. static void _int_free();
  1378. static Void_t* _int_realloc();
  1379. static Void_t* _int_memalign();
  1380. static Void_t* _int_valloc();
  1381. static Void_t* _int_pvalloc();
  1382. /*static Void_t* cALLOc();*/
  1383. static Void_t** _int_icalloc();
  1384. static Void_t** _int_icomalloc();
  1385. static int mTRIm();
  1386. static size_t mUSABLe();
  1387. static void mSTATs();
  1388. static int mALLOPt();
  1389. static struct mallinfo mALLINFo();

  1390. #endif




  1391. /* ------------- Optional versions of memcopy ---------------- */


  1392. #if USE_MEMCPY

  1393. /*
  1394.   Note: memcpy is ONLY invoked with non-overlapping regions,
  1395.   so the (usually slower) memmove is not needed.
  1396. */

  1397. #define MALLOC_COPY(dest, src, nbytes) memcpy(dest, src, nbytes)
  1398. #define MALLOC_ZERO(dest, nbytes) memset(dest, 0, nbytes)

  1399. #else /* !USE_MEMCPY */

  1400. /* Use Duff's device for good zeroing/copying performance. */

  1401. #define MALLOC_ZERO(charp, nbytes) \
  1402. do { \
  1403.   INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \
  1404.   unsigned long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \
  1405.   long mcn; \
  1406.   if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
  1407.   switch (mctmp) { \
  1408.     case 0: for(;;) { *mzp++ = 0; \
  1409.     case 7: *mzp++ = 0; \
  1410.     case 6: *mzp++ = 0; \
  1411.     case 5: *mzp++ = 0; \
  1412.     case 4: *mzp++ = 0; \
  1413.     case 3: *mzp++ = 0; \
  1414.     case 2: *mzp++ = 0; \
  1415.     case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \
  1416.   } \
  1417. } while(0)

  1418. #define MALLOC_COPY(dest,src,nbytes) \
  1419. do { \
  1420.   INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \
  1421.   INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \
  1422.   unsigned long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \
  1423.   long mcn; \
  1424.   if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
  1425.   switch (mctmp) { \
  1426.     case 0: for(;;) { *mcdst++ = *mcsrc++; \
  1427.     case 7: *mcdst++ = *mcsrc++; \
  1428.     case 6: *mcdst++ = *mcsrc++; \
  1429.     case 5: *mcdst++ = *mcsrc++; \
  1430.     case 4: *mcdst++ = *mcsrc++; \
  1431.     case 3: *mcdst++ = *mcsrc++; \
  1432.     case 2: *mcdst++ = *mcsrc++; \
  1433.     case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \
  1434.   } \
  1435. } while(0)

  1436. #endif

  1437. /* ------------------ MMAP support ------------------ */


  1438. #if HAVE_MMAP

  1439. #include <fcntl.h>
  1440. #ifndef LACKS_SYS_MMAN_H
  1441. #include <sys/mman.h>
  1442. #endif

  1443. #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
  1444. # define MAP_ANONYMOUS MAP_ANON
  1445. #endif
  1446. #if !defined(MAP_FAILED)
  1447. # define MAP_FAILED ((char*)-1)
  1448. #endif

  1449. #ifndef MAP_NORESERVE
  1450. # ifdef MAP_AUTORESRV
  1451. # define MAP_NORESERVE MAP_AUTORESRV
  1452. # else
  1453. # define MAP_NORESERVE 0
  1454. # endif
  1455. #endif

  1456. /*
  1457.    Nearly all versions of mmap support MAP_ANONYMOUS,
  1458.    so the following is unlikely to be needed, but is
  1459.    supplied just in case.
  1460. */

  1461. #ifndef MAP_ANONYMOUS

  1462. static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */

  1463. #define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \
  1464.  (dev_zero_fd = open("/dev/zero", O_RDWR), \
  1465.   mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \
  1466.    mmap((addr), (size), (prot), (flags), dev_zero_fd, 0))

  1467. #else

  1468. #define MMAP(addr, size, prot, flags) \
  1469.  (mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0))

  1470. #endif


  1471. #endif /* HAVE_MMAP */


  1472. /*
  1473.   ----------------------- Chunk representations -----------------------
  1474. */


  1475. /*
  1476.   This struct declaration is misleading (but accurate and necessary).
  1477.   It declares a "view" into memory allowing access to necessary
  1478.   fields at known offsets from a given base. See explanation below.
  1479. */

  1480. struct malloc_chunk {

  1481.   INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
  1482.   INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */

  1483.   struct malloc_chunk* fd; /* double links -- used only if free. */
  1484.   struct malloc_chunk* bk;

  1485.   /* Only used for large blocks: pointer to next larger size. */
  1486.   struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
  1487.   struct malloc_chunk* bk_nextsize;
  1488. };


  1489. /*
  1490.    malloc_chunk details:

  1491.     (The following includes lightly edited explanations by Colin Plumb.)

  1492.     Chunks of memory are maintained using a `boundary tag' method as
  1493.     described in e.g., Knuth or Standish. (See the paper by Paul
  1494.     Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
  1495.     survey of such techniques.) Sizes of free chunks are stored both
  1496.     in the front of each chunk and at the end. This makes
  1497.     consolidating fragmented chunks into bigger chunks very fast. The
  1498.     size fields also hold bits representing whether chunks are free or
  1499.     in use.

  1500.     An allocated chunk looks like this:


  1501.     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1502.      | Size of previous chunk, if allocated | |
  1503.      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1504.      | Size of chunk, in bytes |M|P|
  1505.       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1506.      | User data starts here... .
  1507.      . .
  1508.      . (malloc_usable_size() bytes) .
  1509.      . |
  1510. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1511.      | Size of chunk |
  1512.      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


  1513.     Where "chunk" is the front of the chunk for the purpose of most of
  1514.     the malloc code, but "mem" is the pointer that is returned to the
  1515.     user. "Nextchunk" is the beginning of the next contiguous chunk.

  1516.     Chunks always begin on even word boundries, so the mem portion
  1517.     (which is returned to the user) is also on an even word boundary, and
  1518.     thus at least double-word aligned.

  1519.     Free chunks are stored in circular doubly-linked lists, and look like this:

  1520.     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1521.      | Size of previous chunk |
  1522.      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1523.     `head:' | Size of chunk, in bytes |P|
  1524.       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1525.      | Forward pointer to next chunk in list |
  1526.      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1527.      | Back pointer to previous chunk in list |
  1528.      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1529.      | Unused space (may be 0 bytes long) .
  1530.      . .
  1531.      . |
  1532. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1533.     `foot:' | Size of chunk, in bytes |
  1534.      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

  1535.     The P (PREV_INUSE) bit, stored in the unused low-order bit of the
  1536.     chunk size (which is always a multiple of two words), is an in-use
  1537.     bit for the *previous* chunk. If that bit is *clear*, then the
  1538.     word before the current chunk size contains the previous chunk
  1539.     size, and can be used to find the front of the previous chunk.
  1540.     The very first chunk allocated always has this bit set,
  1541.     preventing access to non-existent (or non-owned) memory. If
  1542.     prev_inuse is set for any given chunk, then you CANNOT determine
  1543.     the size of the previous chunk, and might even get a memory
  1544.     addressing fault when trying to do so.

  1545.     Note that the `foot' of the current chunk is actually represented
  1546.     as the prev_size of the NEXT chunk. This makes it easier to
  1547.     deal with alignments etc but can be very confusing when trying
  1548.     to extend or adapt this code.

  1549.     The two exceptions to all this are

  1550.      1. The special chunk `top' doesn't bother using the
  1551.     trailing size field since there is no next contiguous chunk
  1552.     that would have to index off it. After initialization, `top'
  1553.     is forced to always exist. If it would become less than
  1554.     MINSIZE bytes long, it is replenished.

  1555.      2. Chunks allocated via mmap, which have the second-lowest-order
  1556.     bit M (IS_MMAPPED) set in their size fields. Because they are
  1557.     allocated one-by-one, each must contain its own trailing size field.

  1558. */

  1559. /*
  1560.   ---------- Size and alignment checks and conversions ----------
  1561. */

  1562. /* conversion from malloc headers to user pointers, and back */

  1563. #define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
  1564. #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))

  1565. /* The smallest possible chunk */
  1566. #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))

  1567. /* The smallest size we can malloc is an aligned minimal chunk */

  1568. #define MINSIZE \
  1569.   (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))

  1570. /* Check if m has acceptable alignment */

  1571. #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)

  1572. #define misaligned_chunk(p) \
  1573.   ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
  1574.    & MALLOC_ALIGN_MASK)


  1575. /*
  1576.    Check if a request is so large that it would wrap around zero when
  1577.    padded and aligned. To simplify some other code, the bound is made
  1578.    low enough so that adding MINSIZE will also not wrap around zero.
  1579. */

  1580. #define REQUEST_OUT_OF_RANGE(req) \
  1581.   ((unsigned long)(req) >= \
  1582.    (unsigned long)(INTERNAL_SIZE_T)(-2 * MINSIZE))

  1583. /* pad request bytes into a usable size -- internal version */

  1584. #define request2size(req) \
  1585.   (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
  1586.    MINSIZE : \
  1587.    ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)

  1588. /* Same, except also perform argument check */

  1589. #define checked_request2size(req, sz) \
  1590.   if (REQUEST_OUT_OF_RANGE(req)) { \
  1591.     MALLOC_FAILURE_ACTION; \
  1592.     return 0; \
  1593.   } \
  1594.   (sz) = request2size(req);

  1595. /*
  1596.   --------------- Physical chunk operations ---------------
  1597. */


  1598. /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
  1599. #define PREV_INUSE 0x1

  1600. /* extract inuse bit of previous chunk */
  1601. #define prev_inuse(p) ((p)->size & PREV_INUSE)


  1602. /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
  1603. #define IS_MMAPPED 0x2

  1604. /* check for mmap()'ed chunk */
  1605. #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)


  1606. /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
  1607.    from a non-main arena. This is only set immediately before handing
  1608.    the chunk to the user, if necessary. */
  1609. #define NON_MAIN_ARENA 0x4

  1610. /* check for chunk from non-main arena */
  1611. #define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)


  1612. /*
  1613.   Bits to mask off when extracting size

  1614.   Note: IS_MMAPPED is intentionally not masked off from size field in
  1615.   macros for which mmapped chunks should never be seen. This should
  1616.   cause helpful core dumps to occur if it is tried by accident by
  1617.   people extending or adapting this malloc.
  1618. */
  1619. #define SIZE_BITS (PREV_INUSE|IS_MMAPPED|NON_MAIN_ARENA)

  1620. /* Get size, ignoring use bits */
  1621. #define chunksize(p) ((p)->size & ~(SIZE_BITS))


  1622. /* Ptr to next physical malloc_chunk. */
  1623. #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~SIZE_BITS) ))

  1624. /* Ptr to previous physical malloc_chunk */
  1625. #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))

  1626. /* Treat space at ptr + offset as a chunk */
  1627. #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))

  1628. /* extract p's inuse bit */
  1629. #define inuse(p)\
  1630. ((((mchunkptr)(((char*)(p))+((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)

  1631. /* set/clear chunk as being inuse without otherwise disturbing */
  1632. #define set_inuse(p)\
  1633. ((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE

  1634. #define clear_inuse(p)\
  1635. ((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)


  1636. /* check/set/clear inuse bits in known places */
  1637. #define inuse_bit_at_offset(p, s)\
  1638.  (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)

  1639. #define set_inuse_bit_at_offset(p, s)\
  1640.  (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)

  1641. #define clear_inuse_bit_at_offset(p, s)\
  1642.  (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))


  1643. /* Set size at head, without disturbing its use bit */
  1644. #define set_head_size(p, s) ((p)->size = (((p)->size & SIZE_BITS) | (s)))

  1645. /* Set size/use field */
  1646. #define set_head(p, s) ((p)->size = (s))

  1647. /* Set size at footer (only when chunk is not in use) */
  1648. #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))


  1649. /*
  1650.   -------------------- Internal data structures --------------------

  1651.    All internal state is held in an instance of malloc_state defined
  1652.    below. There are no other static variables, except in two optional
  1653.    cases:
  1654.    * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
  1655.    * If HAVE_MMAP is true, but mmap doesn't support
  1656.      MAP_ANONYMOUS, a dummy file descriptor for mmap.

  1657.    Beware of lots of tricks that minimize the total bookkeeping space
  1658.    requirements. The result is a little over 1K bytes (for 4byte
  1659.    pointers and size_t.)
  1660. */

  1661. /*
  1662.   Bins

  1663.     An array of bin headers for free chunks. Each bin is doubly
  1664.     linked. The bins are approximately proportionally (log) spaced.
  1665.     There are a lot of these bins (128). This may look excessive, but
  1666.     works very well in practice. Most bins hold sizes that are
  1667.     unusual as malloc request sizes, but are more usual for fragments
  1668.     and consolidated sets of chunks, which is what these bins hold, so
  1669.     they can be found quickly. All procedures maintain the invariant
  1670.     that no consolidated chunk physically borders another one, so each
  1671.     chunk in a list is known to be preceeded and followed by either
  1672.     inuse chunks or the ends of memory.

  1673.     Chunks in bins are kept in size order, with ties going to the
  1674.     approximately least recently used chunk. Ordering isn't needed
  1675.     for the small bins, which all contain the same-sized chunks, but
  1676.     facilitates best-fit allocation for larger chunks. These lists
  1677.     are just sequential. Keeping them in order almost never requires
  1678.     enough traversal to warrant using fancier ordered data
  1679.     structures.

  1680.     Chunks of the same size are linked with the most
  1681.     recently freed at the front, and allocations are taken from the
  1682.     back. This results in LRU (FIFO) allocation order, which tends
  1683.     to give each chunk an equal opportunity to be consolidated with
  1684.     adjacent freed chunks, resulting in larger free chunks and less
  1685.     fragmentation.

  1686.     To simplify use in double-linked lists, each bin header acts
  1687.     as a malloc_chunk. This avoids special-casing for headers.
  1688.     But to conserve space and improve locality, we allocate
  1689.     only the fd/bk pointers of bins, and then use repositioning tricks
  1690.     to treat these as the fields of a malloc_chunk*.
  1691. */

  1692. typedef struct malloc_chunk* mbinptr;

  1693. /* addressing -- note that bin_at(0) does not exist */
  1694. #define bin_at(m, i) \
  1695.   (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2]))             \
  1696.      - offsetof (struct malloc_chunk, fd))

  1697. /* analog of ++bin */
  1698. #define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1)))

  1699. /* Reminders about list directionality within bins */
  1700. #define first(b) ((b)->fd)
  1701. #define last(b) ((b)->bk)

  1702. /* Take a chunk off a bin list */
  1703. #define unlink(P, BK, FD) { \
  1704.   FD = P->fd; \
  1705.   BK = P->bk; \
  1706.   if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
  1707.     malloc_printerr (check_action, "corrupted double-linked list", P); \
  1708.   else { \
  1709.     FD->bk = BK; \
  1710.     BK->fd = FD; \
  1711.     if (!in_smallbin_range (P->size)                 \
  1712.     && __builtin_expect (P->fd_nextsize != NULL, 0)) {     \
  1713.       assert (P->fd_nextsize->bk_nextsize == P);         \
  1714.       assert (P->bk_nextsize->fd_nextsize == P);         \
  1715.       if (FD->fd_nextsize == NULL) {                 \
  1716.     if (P->fd_nextsize == P)                 \
  1717.      FD->fd_nextsize = FD->bk_nextsize = FD;         \
  1718.     else {                             \
  1719.      FD->fd_nextsize = P->fd_nextsize;             \
  1720.      FD->bk_nextsize = P->bk_nextsize;             \
  1721.      P->fd_nextsize->bk_nextsize = FD;             \
  1722.      P->bk_nextsize->fd_nextsize = FD;             \
  1723.     }                             \
  1724.       }    else {                             \
  1725.     P->fd_nextsize->bk_nextsize = P->bk_nextsize;         \
  1726.     P->bk_nextsize->fd_nextsize = P->fd_nextsize;         \
  1727.       }                                 \
  1728.     }                                 \
  1729.   } \
  1730. }

  1731. /*
  1732.   Indexing

  1733.     Bins for sizes < 512 bytes contain chunks of all the same size, spaced
  1734.     8 bytes apart. Larger bins are approximately logarithmically spaced:

  1735.     64 bins of size 8
  1736.     32 bins of size 64
  1737.     16 bins of size 512
  1738.      8 bins of size 4096
  1739.      4 bins of size 32768
  1740.      2 bins of size 262144
  1741.      1 bin of size what's left

  1742.     There is actually a little bit of slop in the numbers in bin_index
  1743.     for the sake of speed. This makes no difference elsewhere.

  1744.     The bins top out around 1MB because we expect to service large
  1745.     requests via mmap.
  1746. */

  1747. #define NBINS 128
  1748. #define NSMALLBINS 64
  1749. #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
  1750. #define MIN_LARGE_SIZE (NSMALLBINS * SMALLBIN_WIDTH)

  1751. #define in_smallbin_range(sz) \
  1752.   ((unsigned long)(sz) < (unsigned long)MIN_LARGE_SIZE)

  1753. #define smallbin_index(sz) \
  1754.   (SMALLBIN_WIDTH == 16 ? (((unsigned)(sz)) >> 4) : (((unsigned)(sz)) >> 3))

  1755. #define largebin_index_32(sz) \
  1756. (((((unsigned long)(sz)) >> 6) <= 38)? 56 + (((unsigned long)(sz)) >> 6): \
  1757.  ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \
  1758.  ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \
  1759.  ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \
  1760.  ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \
  1761.                     126)

  1762. // XXX It remains to be seen whether it is good to keep the widths of
  1763. // XXX the buckets the same or whether it should be scaled by a factor
  1764. // XXX of two as well.
  1765. #define largebin_index_64(sz) \
  1766. (((((unsigned long)(sz)) >> 6) <= 48)? 48 + (((unsigned long)(sz)) >> 6): \
  1767.  ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \
  1768.  ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \
  1769.  ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \
  1770.  ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \
  1771.                     126)

  1772. #define largebin_index(sz) \
  1773.   (SIZE_SZ == 8 ? largebin_index_64 (sz) : largebin_index_32 (sz))

  1774. #define bin_index(sz) \
  1775.  ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz))


  1776. /*
  1777.   Unsorted chunks

  1778.     All remainders from chunk splits, as well as all returned chunks,
  1779.     are first placed in the "unsorted" bin. They are then placed
  1780.     in regular bins after malloc gives them ONE chance to be used before
  1781.     binning. So, basically, the unsorted_chunks list acts as a queue,
  1782.     with chunks being placed on it in free (and malloc_consolidate),
  1783.     and taken off (to be either used or placed in bins) in malloc.

  1784.     The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
  1785.     does not have to be taken into account in size comparisons.
  1786. */

  1787. /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
  1788. #define unsorted_chunks(M) (bin_at(M, 1))

  1789. /*
  1790.   Top

  1791.     The top-most available chunk (i.e., the one bordering the end of
  1792.     available memory) is treated specially. It is never included in
  1793.     any bin, is used only if no other chunk is available, and is
  1794.     released back to the system if it is very large (see
  1795.     M_TRIM_THRESHOLD). Because top initially
  1796.     points to its own bin with initial zero size, thus forcing
  1797.     extension on the first malloc request, we avoid having any special
  1798.     code in malloc to check whether it even exists yet. But we still
  1799.     need to do so when getting memory from system, so we make
  1800.     initial_top treat the bin as a legal but unusable chunk during the
  1801.     interval between initialization and the first call to
  1802.     sYSMALLOc. (This is somewhat delicate, since it relies on
  1803.     the 2 preceding words to be zero during this interval as well.)
  1804. */

  1805. /* Conveniently, the unsorted bin can be used as dummy top on first call */
  1806. #define initial_top(M) (unsorted_chunks(M))

  1807. /*
  1808.   Binmap

  1809.     To help compensate for the large number of bins, a one-level index
  1810.     structure is used for bin-by-bin searching. `binmap' is a
  1811.     bitvector recording whether bins are definitely empty so they can
  1812.     be skipped over during during traversals. The bits are NOT always
  1813.     cleared as soon as bins are empty, but instead only
  1814.     when they are noticed to be empty during traversal in malloc.
  1815. */

  1816. /* Conservatively use 32 bits per map word, even if on 64bit system */
  1817. #define BINMAPSHIFT 5
  1818. #define BITSPERMAP (1U << BINMAPSHIFT)
  1819. #define BINMAPSIZE (NBINS / BITSPERMAP)

  1820. #define idx2block(i) ((i) >> BINMAPSHIFT)
  1821. #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1))))

  1822. #define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i))
  1823. #define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i)))
  1824. #define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i))

  1825. /*
  1826.   Fastbins

  1827.     An array of lists holding recently freed small chunks. Fastbins
  1828.     are not doubly linked. It is faster to single-link them, and
  1829.     since chunks are never removed from the middles of these lists,
  1830.     double linking is not necessary. Also, unlike regular bins, they
  1831.     are not even processed in FIFO order (they use faster LIFO) since
  1832.     ordering doesn't much matter in the transient contexts in which
  1833.     fastbins are normally used.

  1834.     Chunks in fastbins keep their inuse bit set, so they cannot
  1835.     be consolidated with other free chunks. malloc_consolidate
  1836.     releases all chunks in fastbins and consolidates them with
  1837.     other free chunks.
  1838. */

  1839. typedef struct malloc_chunk* mfastbinptr;
  1840. #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])

  1841. /* offset 2 to use otherwise unindexable first 2 bins */
  1842. #define fastbin_index(sz) \
  1843.   ((((unsigned int)(sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)


  1844. /* The maximum fastbin request size we support */
  1845. #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)

  1846. #define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1)

  1847. /*
  1848.   FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
  1849.   that triggers automatic consolidation of possibly-surrounding
  1850.   fastbin chunks. This is a heuristic, so the exact value should not
  1851.   matter too much. It is defined at half the default trim threshold as a
  1852.   compromise heuristic to only attempt consolidation if it is likely
  1853.   to lead to trimming. However, it is not dynamically tunable, since
  1854.   consolidation reduces fragmentation surrounding large chunks even
  1855.   if trimming is not used.
  1856. */

  1857. #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)

  1858. /*
  1859.   Since the lowest 2 bits in max_fast don't matter in size comparisons,
  1860.   they are used as flags.
  1861. */

  1862. /*
  1863.   FASTCHUNKS_BIT held in max_fast indicates that there are probably
  1864.   some fastbin chunks. It is set true on entering a chunk into any
  1865.   fastbin, and cleared only in malloc_consolidate.

  1866.   The truth value is inverted so that have_fastchunks will be true
  1867.   upon startup (since statics are zero-filled), simplifying
  1868.   initialization checks.
  1869. */

  1870. #define FASTCHUNKS_BIT (1U)

  1871. #define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
  1872. #ifdef ATOMIC_FASTBINS
  1873. #define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT)
  1874. #define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT)
  1875. #else
  1876. #define clear_fastchunks(M) ((M)->flags |= FASTCHUNKS_BIT)
  1877. #define set_fastchunks(M) ((M)->flags &= ~FASTCHUNKS_BIT)
  1878. #endif

  1879. /*
  1880.   NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
  1881.   regions. Otherwise, contiguity is exploited in merging together,
  1882.   when possible, results from consecutive MORECORE calls.

  1883.   The initial value comes from MORECORE_CONTIGUOUS, but is
  1884.   changed dynamically if mmap is ever used as an sbrk substitute.
  1885. */

  1886. #define NONCONTIGUOUS_BIT (2U)

  1887. #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
  1888. #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
  1889. #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
  1890. #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)

  1891. /*
  1892.    Set value of max_fast.
  1893.    Use impossibly small value if 0.
  1894.    Precondition: there are no existing fastbin chunks.
  1895.    Setting the value clears fastchunk bit but preserves noncontiguous bit.
  1896. */

  1897. #define set_max_fast(s) \
  1898.   global_max_fast = (((s) == 0)                         \
  1899.          ? SMALLBIN_WIDTH: ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
  1900. #define get_max_fast() global_max_fast


  1901. /*
  1902.    ----------- Internal state representation and initialization -----------
  1903. */

  1904. struct malloc_state {
  1905.   /* Serialize access. */
  1906.   mutex_t mutex;

  1907.   /* Flags (formerly in max_fast). */
  1908.   int flags;

  1909. #if THREAD_STATS
  1910.   /* Statistics for locking. Only used if THREAD_STATS is defined. */
  1911.   long stat_lock_direct, stat_lock_loop, stat_lock_wait;
  1912. #endif

  1913.   /* Fastbins */
  1914.   mfastbinptr fastbinsY[NFASTBINS];

  1915.   /* Base of the topmost chunk -- not otherwise kept in a bin */
  1916.   mchunkptr top;

  1917.   /* The remainder from the most recent split of a small request */
  1918.   mchunkptr last_remainder;

  1919.   /* Normal bins packed as described above */
  1920.   mchunkptr bins[NBINS * 2 - 2];

  1921.   /* Bitmap of bins */
  1922.   unsigned int binmap[BINMAPSIZE];

  1923.   /* Linked list */
  1924.   struct malloc_state *next;

  1925. #ifdef PER_THREAD
  1926.   /* Linked list for free arenas. */
  1927.   struct malloc_state *next_free;
  1928. #endif

  1929.   /* Memory allocated from the system in this arena. */
  1930.   INTERNAL_SIZE_T system_mem;
  1931.   INTERNAL_SIZE_T max_system_mem;
  1932. };

  1933. struct malloc_par {
  1934.   /* Tunable parameters */
  1935.   unsigned long trim_threshold;
  1936.   INTERNAL_SIZE_T top_pad;
  1937.   INTERNAL_SIZE_T mmap_threshold;
  1938. #ifdef PER_THREAD
  1939.   INTERNAL_SIZE_T arena_test;
  1940.   INTERNAL_SIZE_T arena_max;
  1941. #endif

  1942.   /* Memory map support */
  1943.   int n_mmaps;
  1944.   int n_mmaps_max;
  1945.   int max_n_mmaps;
  1946.   /* the mmap_threshold is dynamic, until the user sets
  1947.      it manually, at which point we need to disable any
  1948.      dynamic behavior. */
  1949.   int no_dyn_threshold;

  1950.   /* Cache malloc_getpagesize */
  1951.   unsigned int pagesize;

  1952.   /* Statistics */
  1953.   INTERNAL_SIZE_T mmapped_mem;
  1954.   /*INTERNAL_SIZE_T sbrked_mem;*/
  1955.   /*INTERNAL_SIZE_T max_sbrked_mem;*/
  1956.   INTERNAL_SIZE_T max_mmapped_mem;
  1957.   INTERNAL_SIZE_T max_total_mem; /* only kept for NO_THREADS */

  1958.   /* First address handed out by MORECORE/sbrk. */
  1959.   char* sbrk_base;
  1960. };

  1961. /* There are several instances of this struct ("arenas") in this
  1962.    malloc. If you are adapting this malloc in a way that does NOT use
  1963.    a static or mmapped malloc_state, you MUST explicitly zero-fill it
  1964.    before using. This malloc relies on the property that malloc_state
  1965.    is initialized to all zeroes (as is true of C statics). */

  1966. static struct malloc_state main_arena;

  1967. /* There is only one instance of the malloc parameters. */

  1968. static struct malloc_par mp_;


  1969. #ifdef PER_THREAD
  1970. /* Non public mallopt parameters. */
  1971. #define M_ARENA_TEST -7
  1972. #define M_ARENA_MAX -8
  1973. #endif


  1974. /* Maximum size of memory handled in fastbins. */
  1975. static INTERNAL_SIZE_T global_max_fast;

  1976. /*
  1977.   Initialize a malloc_state struct.

  1978.   This is called only from within malloc_consolidate, which needs
  1979.   be called in the same contexts anyway. It is never called directly
  1980.   outside of malloc_consolidate because some optimizing compilers try
  1981.   to inline it at all call points, which turns out not to be an
  1982.   optimization at all. (Inlining it in malloc_consolidate is fine though.)
  1983. */

  1984. #if __STD_C
  1985. static void malloc_init_state(mstate av)
  1986. #else
  1987. static void malloc_init_state(av) mstate av;
  1988. #endif
  1989. {
  1990.   int i;
  1991.   mbinptr bin;

  1992.   /* Establish circular links for normal bins */
  1993.   for (i = 1; i < NBINS; ++i) {
  1994.     bin = bin_at(av,i);
  1995.     bin->fd = bin->bk = bin;
  1996.   }

  1997. #if MORECORE_CONTIGUOUS
  1998.   if (av != &main_arena)
  1999. #endif
  2000.     set_noncontiguous(av);
  2001.   if (av == &main_arena)
  2002.     set_max_fast(DEFAULT_MXFAST);
  2003.   av->flags |= FASTCHUNKS_BIT;

  2004.   av->top = initial_top(av);
  2005. }

  2006. /*
  2007.    Other internal utilities operating on mstates
  2008. */

  2009. #if __STD_C
  2010. static Void_t* sYSMALLOc(INTERNAL_SIZE_T, mstate);
  2011. static int sYSTRIm(size_t, mstate);
  2012. static void malloc_consolidate(mstate);
  2013. #ifndef _LIBC
  2014. static Void_t** iALLOc(mstate, size_t, size_t*, int, Void_t**);
  2015. #endif
  2016. #else
  2017. static Void_t* sYSMALLOc();
  2018. static int sYSTRIm();
  2019. static void malloc_consolidate();
  2020. static Void_t** iALLOc();
  2021. #endif


  2022. /* -------------- Early definitions for debugging hooks ---------------- */

  2023. /* Define and initialize the hook variables. These weak definitions must
  2024.    appear before any use of the variables in a function (arena.c uses one). */
  2025. #ifndef weak_variable
  2026. #ifndef _LIBC
  2027. #define weak_variable /**/
  2028. #else
  2029. /* In GNU libc we want the hook variables to be weak definitions to
  2030.    avoid a problem with Emacs. */
  2031. #define weak_variable weak_function
  2032. #endif
  2033. #endif

  2034. /* Forward declarations. */
  2035. static Void_t* malloc_hook_ini __MALLOC_P ((size_t sz,
  2036.                      const __malloc_ptr_t caller));
  2037. static Void_t* realloc_hook_ini __MALLOC_P ((Void_t* ptr, size_t sz,
  2038.                      const __malloc_ptr_t caller));
  2039. static Void_t* memalign_hook_ini __MALLOC_P ((size_t alignment, size_t sz,
  2040.                      const __malloc_ptr_t caller));

  2041. void weak_variable (*__malloc_initialize_hook) (void) = NULL;
  2042. void weak_variable (*__free_hook) (__malloc_ptr_t __ptr,
  2043.                  const __malloc_ptr_t) = NULL;
  2044. __malloc_ptr_t weak_variable (*__malloc_hook)
  2045.      (size_t __size, const __malloc_ptr_t) = malloc_hook_ini;
  2046. __malloc_ptr_t weak_variable (*__realloc_hook)
  2047.      (__malloc_ptr_t __ptr, size_t __size, const __malloc_ptr_t)
  2048.      = realloc_hook_ini;
  2049. __malloc_ptr_t weak_variable (*__memalign_hook)
  2050.      (size_t __alignment, size_t __size, const __malloc_ptr_t)
  2051.      = memalign_hook_ini;
  2052. void weak_variable (*__after_morecore_hook) (void) = NULL;


  2053. /* ---------------- Error behavior ------------------------------------ */

  2054. #ifndef DEFAULT_CHECK_ACTION
  2055. #define DEFAULT_CHECK_ACTION 3
  2056. #endif

  2057. static int check_action = DEFAULT_CHECK_ACTION;


  2058. /* ------------------ Testing support ----------------------------------*/

  2059. static int perturb_byte;

  2060. #define alloc_perturb(p, n) memset (p, (perturb_byte ^ 0xff) & 0xff, n)
  2061. #define free_perturb(p, n) memset (p, perturb_byte & 0xff, n)


  2062. /* ------------------- Support for multiple arenas -------------------- */
  2063. #include "arena.c"

  2064. /*
  2065.   Debugging support

  2066.   These routines make a number of assertions about the states
  2067.   of data structures that should be true at all times. If any
  2068.   are not true, it's very likely that a user program has somehow
  2069.   trashed memory. (It's also possible that there is a coding error
  2070.   in malloc. In which case, please report
  2071. */

  2072. #if ! MALLOC_DEBUG

  2073. #define check_chunk(A,P)
  2074. #define check_free_chunk(A,P)
  2075. #define check_inuse_chunk(A,P)
  2076. #define check_remalloced_chunk(A,P,N)
  2077. #define check_malloced_chunk(A,P,N)
  2078. #define check_malloc_state(A)

  2079. #else

  2080. #define check_chunk(A,P) do_check_chunk(A,P)
  2081. #define check_free_chunk(A,P) do_check_free_chunk(A,P)
  2082. #define check_inuse_chunk(A,P) do_check_inuse_chunk(A,P)
  2083. #define check_remalloced_chunk(A,P,N) do_check_remalloced_chunk(A,P,N)
  2084. #define check_malloced_chunk(A,P,N) do_check_malloced_chunk(A,P,N)
  2085. #define check_malloc_state(A) do_check_malloc_state(A)

  2086. /*
  2087.   Properties of all chunks
  2088. */

  2089. #if __STD_C
  2090. static void do_check_chunk(mstate av, mchunkptr p)
  2091. #else
  2092. static void do_check_chunk(av, p) mstate av; mchunkptr p;
  2093. #endif
  2094. {
  2095.   unsigned long sz = chunksize(p);
  2096.   /* min and max possible addresses assuming contiguous allocation */
  2097.   char* max_address = (char*)(av->top) + chunksize(av->top);
  2098.   char* min_address = max_address - av->system_mem;

  2099.   if (!chunk_is_mmapped(p)) {

  2100.     /* Has legal address ... */
  2101.     if (p != av->top) {
  2102.       if (contiguous(av)) {
  2103.     assert(((char*)p) >= min_address);
  2104.     assert(((char*)p + sz) <= ((char*)(av->top)));
  2105.       }
  2106.     }
  2107.     else {
  2108.       /* top size is always at least MINSIZE */
  2109.       assert((unsigned long)(sz) >= MINSIZE);
  2110.       /* top predecessor always marked inuse */
  2111.       assert(prev_inuse(p));
  2112.     }

  2113.   }
  2114.   else {
  2115. #if HAVE_MMAP
  2116.     /* address is outside main heap */
  2117.     if (contiguous(av) && av->top != initial_top(av)) {
  2118.       assert(((char*)p) < min_address || ((char*)p) >= max_address);
  2119.     }
  2120.     /* chunk is page-aligned */
  2121.     assert(((p->prev_size + sz) & (mp_.pagesize-1)) == 0);
  2122.     /* mem is aligned */
  2123.     assert(aligned_OK(chunk2mem(p)));
  2124. #else
  2125.     /* force an appropriate assert violation if debug set */
  2126.     assert(!chunk_is_mmapped(p));
  2127. #endif
  2128.   }
  2129. }

  2130. /*
  2131.   Properties of free chunks
  2132. */

  2133. #if __STD_C
  2134. static void do_check_free_chunk(mstate av, mchunkptr p)
  2135. #else
  2136. static void do_check_free_chunk(av, p) mstate av; mchunkptr p;
  2137. #endif
  2138. {
  2139.   INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
  2140.   mchunkptr next = chunk_at_offset(p, sz);

  2141.   do_check_chunk(av, p);

  2142.   /* Chunk must claim to be free ... */
  2143.   assert(!inuse(p));
  2144.   assert (!chunk_is_mmapped(p));

  2145.   /* Unless a special marker, must have OK fields */
  2146.   if ((unsigned long)(sz) >= MINSIZE)
  2147.   {
  2148.     assert((sz & MALLOC_ALIGN_MASK) == 0);
  2149.     assert(aligned_OK(chunk2mem(p)));
  2150.     /* ... matching footer field */
  2151.     assert(next->prev_size == sz);
  2152.     /* ... and is fully consolidated */
  2153.     assert(prev_inuse(p));
  2154.     assert (next == av->top || inuse(next));

  2155.     /* ... and has minimally sane links */
  2156.     assert(p->fd->bk == p);
  2157.     assert(p->bk->fd == p);
  2158.   }
  2159.   else /* markers are always of size SIZE_SZ */
  2160.     assert(sz == SIZE_SZ);
  2161. }

  2162. /*
  2163.   Properties of inuse chunks
  2164. */

  2165. #if __STD_C
  2166. static void do_check_inuse_chunk(mstate av, mchunkptr p)
  2167. #else
  2168. static void do_check_inuse_chunk(av, p) mstate av; mchunkptr p;
  2169. #endif
  2170. {
  2171.   mchunkptr next;

  2172.   do_check_chunk(av, p);

  2173.   if (chunk_is_mmapped(p))
  2174.     return; /* mmapped chunks have no next/prev */

  2175.   /* Check whether it claims to be in use ... */
  2176.   assert(inuse(p));

  2177.   next = next_chunk(p);

  2178.   /* ... and is surrounded by OK chunks.
  2179.     Since more things can be checked with free chunks than inuse ones,
  2180.     if an inuse chunk borders them and debug is on, it's worth doing them.
  2181.   */
  2182.   if (!prev_inuse(p)) {
  2183.     /* Note that we cannot even look at prev unless it is not inuse */
  2184.     mchunkptr prv = prev_chunk(p);
  2185.     assert(next_chunk(prv) == p);
  2186.     do_check_free_chunk(av, prv);
  2187.   }

  2188.   if (next == av->top) {
  2189.     assert(prev_inuse(next));
  2190.     assert(chunksize(next) >= MINSIZE);
  2191.   }
  2192.   else if (!inuse(next))
  2193.     do_check_free_chunk(av, next);
  2194. }

  2195. /*
  2196.   Properties of chunks recycled from fastbins
  2197. */

  2198. #if __STD_C
  2199. static void do_check_remalloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
  2200. #else
  2201. static void do_check_remalloced_chunk(av, p, s)
  2202. mstate av; mchunkptr p; INTERNAL_SIZE_T s;
  2203. #endif
  2204. {
  2205.   INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);

  2206.   if (!chunk_is_mmapped(p)) {
  2207.     assert(av == arena_for_chunk(p));
  2208.     if (chunk_non_main_arena(p))
  2209.       assert(av != &main_arena);
  2210.     else
  2211.       assert(av == &main_arena);
  2212.   }

  2213.   do_check_inuse_chunk(av, p);

  2214.   /* Legal size ... */
  2215.   assert((sz & MALLOC_ALIGN_MASK) == 0);
  2216.   assert((unsigned long)(sz) >= MINSIZE);
  2217.   /* ... and alignment */
  2218.   assert(aligned_OK(chunk2mem(p)));
  2219.   /* chunk is less than MINSIZE more than request */
  2220.   assert((long)(sz) - (long)(s) >= 0);
  2221.   assert((long)(sz) - (long)(s + MINSIZE) < 0);
  2222. }

  2223. /*
  2224.   Properties of nonrecycled chunks at the point they are malloced
  2225. */

  2226. #if __STD_C
  2227. static void do_check_malloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
  2228. #else
  2229. static void do_check_malloced_chunk(av, p, s)
  2230. mstate av; mchunkptr p; INTERNAL_SIZE_T s;
  2231. #endif
  2232. {
  2233.   /* same as recycled case ... */
  2234.   do_check_remalloced_chunk(av, p, s);

  2235.   /*
  2236.     ... plus, must obey implementation invariant that prev_inuse is
  2237.     always true of any allocated chunk; i.e., that each allocated
  2238.     chunk borders either a previously allocated and still in-use
  2239.     chunk, or the base of its memory arena. This is ensured
  2240.     by making all allocations from the `lowest' part of any found
  2241.     chunk. This does not necessarily hold however for chunks
  2242.     recycled via fastbins.
  2243.   */

  2244.   assert(prev_inuse(p));
  2245. }


  2246. /*
  2247.   Properties of malloc_state.

  2248.   This may be useful for debugging malloc, as well as detecting user
  2249.   programmer errors that somehow write into malloc_state.

  2250.   If you are extending or experimenting with this malloc, you can
  2251.   probably figure out how to hack this routine to print out or
  2252.   display chunk addresses, sizes, bins, and other instrumentation.
  2253. */

  2254. static void do_check_malloc_state(mstate av)
  2255. {
  2256.   int i;
  2257.   mchunkptr p;
  2258.   mchunkptr q;
  2259.   mbinptr b;
  2260.   unsigned int idx;
  2261.   INTERNAL_SIZE_T size;
  2262.   unsigned long total = 0;
  2263.   int max_fast_bin;

  2264.   /* internal size_t must be no wider than pointer type */
  2265.   assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*));

  2266.   /* alignment is a power of 2 */
  2267.   assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0);

  2268.   /* cannot run remaining checks until fully initialized */
  2269.   if (av->top == 0 || av->top == initial_top(av))
  2270.     return;

  2271.   /* pagesize is a power of 2 */
  2272.   assert((mp_.pagesize & (mp_.pagesize-1)) == 0);

  2273.   /* A contiguous main_arena is consistent with sbrk_base. */
  2274.   if (av == &main_arena && contiguous(av))
  2275.     assert((char*)mp_.sbrk_base + av->system_mem ==
  2276.      (char*)av->top + chunksize(av->top));

  2277.   /* properties of fastbins */

  2278.   /* max_fast is in allowed range */
  2279.   assert((get_max_fast () & ~1) <= request2size(MAX_FAST_SIZE));

  2280.   max_fast_bin = fastbin_index(get_max_fast ());

  2281.   for (i = 0; i < NFASTBINS; ++i) {
  2282.     p = fastbin (av, i);

  2283.     /* The following test can only be performed for the main arena.
  2284.        While mallopt calls malloc_consolidate to get rid of all fast
  2285.        bins (especially those larger than the new maximum) this does
  2286.        only happen for the main arena. Trying to do this for any
  2287.        other arena would mean those arenas have to be locked and
  2288.        malloc_consolidate be called for them. This is excessive. And
  2289.        even if this is acceptable to somebody it still cannot solve
  2290.        the problem completely since if the arena is locked a
  2291.        concurrent malloc call might create a new arena which then
  2292.        could use the newly invalid fast bins. */

  2293.     /* all bins past max_fast are empty */
  2294.     if (av == &main_arena && i > max_fast_bin)
  2295.       assert(p == 0);

  2296.     while (p != 0) {
  2297.       /* each chunk claims to be inuse */
  2298.       do_check_inuse_chunk(av, p);
  2299.       total += chunksize(p);
  2300.       /* chunk belongs in this bin */
  2301.       assert(fastbin_index(chunksize(p)) == i);
  2302.       p = p->fd;
  2303.     }
  2304.   }

  2305.   if (total != 0)
  2306.     assert(have_fastchunks(av));
  2307.   else if (!have_fastchunks(av))
  2308.     assert(total == 0);

  2309.   /* check normal bins */
  2310.   for (i = 1; i < NBINS; ++i) {
  2311.     b = bin_at(av,i);

  2312.     /* binmap is accurate (except for bin 1 == unsorted_chunks) */
  2313.     if (i >= 2) {
  2314.       unsigned int binbit = get_binmap(av,i);
  2315.       int empty = last(b) == b;
  2316.       if (!binbit)
  2317.     assert(empty);
  2318.       else if (!empty)
  2319.     assert(binbit);
  2320.     }

  2321.     for (p = last(b); p != b; p = p->bk) {
  2322.       /* each chunk claims to be free */
  2323.       do_check_free_chunk(av, p);
  2324.       size = chunksize(p);
  2325.       total += size;
  2326.       if (i >= 2) {
  2327.     /* chunk belongs in bin */
  2328.     idx = bin_index(size);
  2329.     assert(idx == i);
  2330.     /* lists are sorted */
  2331.     assert(p->bk == b ||
  2332.      (unsigned long)chunksize(p->bk) >= (unsigned long)chunksize(p));

  2333.     if (!in_smallbin_range(size))
  2334.      {
  2335.      if (p->fd_nextsize != NULL)
  2336.      {
  2337.         if (p->fd_nextsize == p)
  2338.          assert (p->bk_nextsize == p);
  2339.         else
  2340.          {
  2341.          if (p->fd_nextsize == first (b))
  2342.          assert (chunksize (p) < chunksize (p->fd_nextsize));
  2343.          else
  2344.          assert (chunksize (p) > chunksize (p->fd_nextsize));

  2345.          if (p == first (b))
  2346.          assert (chunksize (p) > chunksize (p->bk_nextsize));
  2347.          else
  2348.          assert (chunksize (p) < chunksize (p->bk_nextsize));
  2349.          }
  2350.      }
  2351.      else
  2352.      assert (p->bk_nextsize == NULL);
  2353.      }
  2354.       } else if (!in_smallbin_range(size))
  2355.     assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
  2356.       /* chunk is followed by a legal chain of inuse chunks */
  2357.       for (q = next_chunk(p);
  2358.      (q != av->top && inuse(q) &&
  2359.      (unsigned long)(chunksize(q)) >= MINSIZE);
  2360.      q = next_chunk(q))
  2361.     do_check_inuse_chunk(av, q);
  2362.     }
  2363.   }

  2364.   /* top chunk is OK */
  2365.   check_chunk(av, av->top);

  2366.   /* sanity checks for statistics */

  2367. #ifdef NO_THREADS
  2368.   assert(total <= (unsigned long)(mp_.max_total_mem));
  2369.   assert(mp_.n_mmaps >= 0);
  2370. #endif
  2371.   assert(mp_.n_mmaps <= mp_.max_n_mmaps);

  2372.   assert((unsigned long)(av->system_mem) <=
  2373.      (unsigned long)(av->max_system_mem));

  2374.   assert((unsigned long)(mp_.mmapped_mem) <=
  2375.      (unsigned long)(mp_.max_mmapped_mem));

  2376. #ifdef NO_THREADS
  2377.   assert((unsigned long)(mp_.max_total_mem) >=
  2378.      (unsigned long)(mp_.mmapped_mem) + (unsigned long)(av->system_mem));
  2379. #endif
  2380. }
  2381. #endif


  2382. /* ----------------- Support for debugging hooks -------------------- */
  2383. #include "hooks.c"


  2384. /* ----------- Routines dealing with system allocation -------------- */

  2385. /*
  2386.   sysmalloc handles malloc cases requiring more memory from the system.
  2387.   On entry, it is assumed that av->top does not have enough
  2388.   space to service request for nb bytes, thus requiring that av->top
  2389.   be extended or replaced.
  2390. */

  2391. #if __STD_C
  2392. static Void_t* sYSMALLOc(INTERNAL_SIZE_T nb, mstate av)
  2393. #else
  2394. static Void_t* sYSMALLOc(nb, av) INTERNAL_SIZE_T nb; mstate av;
  2395. #endif
  2396. {
  2397.   mchunkptr old_top; /* incoming value of av->top */
  2398.   INTERNAL_SIZE_T old_size; /* its size */
  2399.   char* old_end; /* its end address */

  2400.   long size; /* arg to first MORECORE or mmap call */
  2401.   char* brk; /* return value from MORECORE */

  2402.   long correction; /* arg to 2nd MORECORE call */
  2403.   char* snd_brk; /* 2nd return val */

  2404.   INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
  2405.   INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
  2406.   char* aligned_brk; /* aligned offset into brk */

  2407.   mchunkptr p; /* the allocated/returned chunk */
  2408.   mchunkptr remainder; /* remainder from allocation */
  2409.   unsigned long remainder_size; /* its size */

  2410.   unsigned long sum; /* for updating stats */

  2411.   size_t pagemask = mp_.pagesize - 1;
  2412.   bool tried_mmap = false;


  2413. #if HAVE_MMAP

  2414.   /*
  2415.     If have mmap, and the request size meets the mmap threshold, and
  2416.     the system supports mmap, and there are few enough currently
  2417.     allocated mmapped regions, try to directly map this request
  2418.     rather than expanding top.
  2419.   */

  2420.   if ((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) &&
  2421.       (mp_.n_mmaps < mp_.n_mmaps_max)) {

  2422.     char* mm; /* return value from mmap call*/

  2423.   try_mmap:
  2424.     /*
  2425.       Round up size to nearest page. For mmapped chunks, the overhead
  2426.       is one SIZE_SZ unit larger than for normal chunks, because there
  2427.       is no following chunk whose prev_size field could be used.
  2428.     */
  2429. #if 1
  2430.     /* See the front_misalign handling below, for glibc there is no
  2431.        need for further alignments. */
  2432.     size = (nb + SIZE_SZ + pagemask) & ~pagemask;
  2433. #else
  2434.     size = (nb + SIZE_SZ + MALLOC_ALIGN_MASK + pagemask) & ~pagemask;
  2435. #endif
  2436.     tried_mmap = true;

  2437.     /* Don't try if size wraps around 0 */
  2438.     if ((unsigned long)(size) > (unsigned long)(nb)) {

  2439.       mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE));

  2440.       if (mm != MAP_FAILED) {

  2441.     /*
  2442.      The offset to the start of the mmapped region is stored
  2443.      in the prev_size field of the chunk. This allows us to adjust
  2444.      returned start address to meet alignment requirements here
  2445.      and in memalign(), and still be able to compute proper
  2446.      address argument for later munmap in free() and realloc().
  2447.     */

  2448. #if 1
  2449.     /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and
  2450.      MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
  2451.      aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
  2452.     assert (((INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK) == 0);
  2453. #else
  2454.     front_misalign = (INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK;
  2455.     if (front_misalign > 0) {
  2456.      correction = MALLOC_ALIGNMENT - front_misalign;
  2457.      p = (mchunkptr)(mm + correction);
  2458.      p->prev_size = correction;
  2459.      set_head(p, (size - correction) |IS_MMAPPED);
  2460.     }
  2461.     else
  2462. #endif
  2463.      {
  2464.      p = (mchunkptr)mm;
  2465.      set_head(p, size|IS_MMAPPED);
  2466.      }

  2467.     /* update statistics */

  2468.     if (++mp_.n_mmaps > mp_.max_n_mmaps)
  2469.      mp_.max_n_mmaps = mp_.n_mmaps;

  2470.     sum = mp_.mmapped_mem += size;
  2471.     if (sum > (unsigned long)(mp_.max_mmapped_mem))
  2472.      mp_.max_mmapped_mem = sum;
  2473. #ifdef NO_THREADS
  2474.     sum += av->system_mem;
  2475.     if (sum > (unsigned long)(mp_.max_total_mem))
  2476.      mp_.max_total_mem = sum;
  2477. #endif

  2478.     check_chunk(av, p);

  2479.     return chunk2mem(p);
  2480.       }
  2481.     }
  2482.   }
  2483. #endif

  2484.   /* Record incoming configuration of top */

  2485.   old_top = av->top;
  2486.   old_size = chunksize(old_top);
  2487.   old_end = (char*)(chunk_at_offset(old_top, old_size));

  2488.   brk = snd_brk = (char*)(MORECORE_FAILURE);

  2489.   /*
  2490.      If not the first time through, we require old_size to be
  2491.      at least MINSIZE and to have prev_inuse set.
  2492.   */

  2493.   assert((old_top == initial_top(av) && old_size == 0) ||
  2494.      ((unsigned long) (old_size) >= MINSIZE &&
  2495.      prev_inuse(old_top) &&
  2496.      ((unsigned long)old_end & pagemask) == 0));

  2497.   /* Precondition: not enough current space to satisfy nb request */
  2498.   assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE));

  2499. #ifndef ATOMIC_FASTBINS
  2500.   /* Precondition: all fastbins are consolidated */
  2501.   assert(!have_fastchunks(av));
  2502. #endif


  2503.   if (av != &main_arena) {

  2504.     heap_info *old_heap, *heap;
  2505.     size_t old_heap_size;

  2506.     /* First try to extend the current heap. */
  2507.     old_heap = heap_for_ptr(old_top);
  2508.     old_heap_size = old_heap->size;
  2509.     if ((long) (MINSIZE + nb - old_size) > 0
  2510.     && grow_heap(old_heap, MINSIZE + nb - old_size) == 0) {
  2511.       av->system_mem += old_heap->size - old_heap_size;
  2512.       arena_mem += old_heap->size - old_heap_size;
  2513. #if 0
  2514.       if(mmapped_mem + arena_mem + sbrked_mem > max_total_mem)
  2515.     max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
  2516. #endif
  2517.       set_head(old_top, (((char *)old_heap + old_heap->size) - (char *)old_top)
  2518.      | PREV_INUSE);
  2519.     }
  2520.     else if ((heap = new_heap(nb + (MINSIZE + sizeof(*heap)), mp_.top_pad))) {
  2521.       /* Use a newly allocated heap. */
  2522.       heap->ar_ptr = av;
  2523.       heap->prev = old_heap;
  2524.       av->system_mem += heap->size;
  2525.       arena_mem += heap->size;
  2526. #if 0
  2527.       if((unsigned long)(mmapped_mem + arena_mem + sbrked_mem) > max_total_mem)
  2528.     max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
  2529. #endif
  2530.       /* Set up the new top. */
  2531.       top(av) = chunk_at_offset(heap, sizeof(*heap));
  2532.       set_head(top(av), (heap->size - sizeof(*heap)) | PREV_INUSE);

  2533.       /* Setup fencepost and free the old top chunk. */
  2534.       /* The fencepost takes at least MINSIZE bytes, because it might
  2535.      become the top chunk again later. Note that a footer is set
  2536.      up, too, although the chunk is marked in use. */
  2537.       old_size -= MINSIZE;
  2538.       set_head(chunk_at_offset(old_top, old_size + 2*SIZE_SZ), 0|PREV_INUSE);
  2539.       if (old_size >= MINSIZE) {
  2540.     set_head(chunk_at_offset(old_top, old_size), (2*SIZE_SZ)|PREV_INUSE);
  2541.     set_foot(chunk_at_offset(old_top, old_size), (2*SIZE_SZ));
  2542.     set_head(old_top, old_size|PREV_INUSE|NON_MAIN_ARENA);
  2543. #ifdef ATOMIC_FASTBINS
  2544.     _int_free(av, old_top, 1);
  2545. #else
  2546.     _int_free(av, old_top);
  2547. #endif
  2548.       } else {
  2549.     set_head(old_top, (old_size + 2*SIZE_SZ)|PREV_INUSE);
  2550.     set_foot(old_top, (old_size + 2*SIZE_SZ));
  2551.       }
  2552.     }
  2553.     else if (!tried_mmap)
  2554.       /* We can at least try to use to mmap memory. */
  2555.       goto try_mmap;

  2556.   } else { /* av == main_arena */


  2557.   /* Request enough space for nb + pad + overhead */

  2558.   size = nb + mp_.top_pad + MINSIZE;

  2559.   /*
  2560.     If contiguous, we can subtract out existing space that we hope to
  2561.     combine with new space. We add it back later only if
  2562.     we don't actually get contiguous space.
  2563.   */

  2564.   if (contiguous(av))
  2565.     size -= old_size;

  2566.   /*
  2567.     Round to a multiple of page size.
  2568.     If MORECORE is not contiguous, this ensures that we only call it
  2569.     with whole-page arguments. And if MORECORE is contiguous and
  2570.     this is not first time through, this preserves page-alignment of
  2571.     previous calls. Otherwise, we correct to page-align below.
  2572.   */

  2573.   size = (size + pagemask) & ~pagemask;

  2574.   /*
  2575.     Don't try to call MORECORE if argument is so big as to appear
  2576.     negative. Note that since mmap takes size_t arg, it may succeed
  2577.     below even if we cannot call MORECORE.
  2578.   */

  2579.   if (size > 0)
  2580.     brk = (char*)(MORECORE(size));

  2581.   if (brk != (char*)(MORECORE_FAILURE)) {
  2582.     /* Call the `morecore' hook if necessary. */
  2583.     void (*hook) (void) = force_reg (__after_morecore_hook);
  2584.     if (__builtin_expect (hook != NULL, 0))
  2585.       (*hook) ();
  2586.   } else {
  2587.   /*
  2588.     If have mmap, try using it as a backup when MORECORE fails or
  2589.     cannot be used. This is worth doing on systems that have "holes" in
  2590.     address space, so sbrk cannot extend to give contiguous space, but
  2591.     space is available elsewhere. Note that we ignore mmap max count
  2592.     and threshold limits, since the space will not be used as a
  2593.     segregated mmap region.
  2594.   */

  2595. #if HAVE_MMAP
  2596.     /* Cannot merge with old top, so add its size back in */
  2597.     if (contiguous(av))
  2598.       size = (size + old_size + pagemask) & ~pagemask;

  2599.     /* If we are relying on mmap as backup, then use larger units */
  2600.     if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE))
  2601.       size = MMAP_AS_MORECORE_SIZE;

  2602.     /* Don't try if size wraps around 0 */
  2603.     if ((unsigned long)(size) > (unsigned long)(nb)) {

  2604.       char *mbrk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE));

  2605.       if (mbrk != MAP_FAILED) {

  2606.     /* We do not need, and cannot use, another sbrk call to find end */
  2607.     brk = mbrk;
  2608.     snd_brk = brk + size;

  2609.     /*
  2610.      Record that we no longer have a contiguous sbrk region.
  2611.      After the first time mmap is used as backup, we do not
  2612.      ever rely on contiguous space since this could incorrectly
  2613.      bridge regions.
  2614.     */
  2615.     set_noncontiguous(av);
  2616.       }
  2617.     }
  2618. #endif
  2619.   }

  2620.   if (brk != (char*)(MORECORE_FAILURE)) {
  2621.     if (mp_.sbrk_base == 0)
  2622.       mp_.sbrk_base = brk;
  2623.     av->system_mem += size;

  2624.     /*
  2625.       If MORECORE extends previous space, we can likewise extend top size.
  2626.     */

  2627.     if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE))
  2628.       set_head(old_top, (size + old_size) | PREV_INUSE);

  2629.     else if (contiguous(av) && old_size && brk < old_end) {
  2630.       /* Someone else killed our space.. Can't touch anything. */
  2631.       malloc_printerr (3, "break adjusted to free malloc space", brk);
  2632.     }

  2633.     /*
  2634.       Otherwise, make adjustments:

  2635.       * If the first time through or noncontiguous, we need to call sbrk
  2636.     just to find out where the end of memory lies.

  2637.       * We need to ensure that all returned chunks from malloc will meet
  2638.     MALLOC_ALIGNMENT

  2639.       * If there was an intervening foreign sbrk, we need to adjust sbrk
  2640.     request size to account for fact that we will not be able to
  2641.     combine new space with existing space in old_top.

  2642.       * Almost all systems internally allocate whole pages at a time, in
  2643.     which case we might as well use the whole last page of request.
  2644.     So we allocate enough more memory to hit a page boundary now,
  2645.     which in turn causes future contiguous calls to page-align.
  2646.     */

  2647.     else {
  2648.       front_misalign = 0;
  2649.       end_misalign = 0;
  2650.       correction = 0;
  2651.       aligned_brk = brk;

  2652.       /* handle contiguous cases */
  2653.       if (contiguous(av)) {

  2654.     /* Count foreign sbrk as system_mem. */
  2655.     if (old_size)
  2656.      av->system_mem += brk - old_end;

  2657.     /* Guarantee alignment of first new chunk made from this space */

  2658.     front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;
  2659.     if (front_misalign > 0) {

  2660.      /*
  2661.      Skip over some bytes to arrive at an aligned position.
  2662.      We don't need to specially mark these wasted front bytes.
  2663.      They will never be accessed anyway because
  2664.      prev_inuse of av->top (and any chunk created from its start)
  2665.      is always true after initialization.
  2666.      */

  2667.      correction = MALLOC_ALIGNMENT - front_misalign;
  2668.      aligned_brk += correction;
  2669.     }

  2670.     /*
  2671.      If this isn't adjacent to existing space, then we will not
  2672.      be able to merge with old_top space, so must add to 2nd request.
  2673.     */

  2674.     correction += old_size;

  2675.     /* Extend the end address to hit a page boundary */
  2676.     end_misalign = (INTERNAL_SIZE_T)(brk + size + correction);
  2677.     correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign;

  2678.     assert(correction >= 0);
  2679.     snd_brk = (char*)(MORECORE(correction));

  2680.     /*
  2681.      If can't allocate correction, try to at least find out current
  2682.      brk. It might be enough to proceed without failing.

  2683.      Note that if second sbrk did NOT fail, we assume that space
  2684.      is contiguous with first sbrk. This is a safe assumption unless
  2685.      program is multithreaded but doesn't use locks and a foreign sbrk
  2686.      occurred between our first and second calls.
  2687.     */

  2688.     if (snd_brk == (char*)(MORECORE_FAILURE)) {
  2689.      correction = 0;
  2690.      snd_brk = (char*)(MORECORE(0));
  2691.     } else {
  2692.      /* Call the `morecore' hook if necessary. */
  2693.      void (*hook) (void) = force_reg (__after_morecore_hook);
  2694.      if (__builtin_expect (hook != NULL, 0))
  2695.      (*hook) ();
  2696.     }
  2697.       }

  2698.       /* handle non-contiguous cases */
  2699.       else {
  2700.     /* MORECORE/mmap must correctly align */
  2701.     assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0);

  2702.     /* Find out current end of memory */
  2703.     if (snd_brk == (char*)(MORECORE_FAILURE)) {
  2704.      snd_brk = (char*)(MORECORE(0));
  2705.     }
  2706.       }

  2707.       /* Adjust top based on results of second sbrk */
  2708.       if (snd_brk != (char*)(MORECORE_FAILURE)) {
  2709.     av->top = (mchunkptr)aligned_brk;
  2710.     set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
  2711.     av->system_mem += correction;

  2712.     /*
  2713.      If not the first time through, we either have a
  2714.      gap due to foreign sbrk or a non-contiguous region. Insert a
  2715.      double fencepost at old_top to prevent consolidation with space
  2716.      we don't own. These fenceposts are artificial chunks that are
  2717.      marked as inuse and are in any case too small to use. We need
  2718.      two to make sizes and alignments work out.
  2719.     */

  2720.     if (old_size != 0) {
  2721.      /*
  2722.      Shrink old_top to insert fenceposts, keeping size a
  2723.      multiple of MALLOC_ALIGNMENT. We know there is at least
  2724.      enough space in old_top to do this.
  2725.      */
  2726.      old_size = (old_size - 4*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
  2727.      set_head(old_top, old_size | PREV_INUSE);

  2728.      /*
  2729.      Note that the following assignments completely overwrite
  2730.      old_top when old_size was previously MINSIZE. This is
  2731.      intentional. We need the fencepost, even if old_top otherwise gets
  2732.      lost.
  2733.      */
  2734.      chunk_at_offset(old_top, old_size )->size =
  2735.      (2*SIZE_SZ)|PREV_INUSE;

  2736.      chunk_at_offset(old_top, old_size + 2*SIZE_SZ)->size =
  2737.      (2*SIZE_SZ)|PREV_INUSE;

  2738.      /* If possible, release the rest. */
  2739.      if (old_size >= MINSIZE) {
  2740. #ifdef ATOMIC_FASTBINS
  2741.      _int_free(av, old_top, 1);
  2742. #else
  2743.      _int_free(av, old_top);
  2744. #endif
  2745.      }

  2746.     }
  2747.       }
  2748.     }

  2749.     /* Update statistics */
  2750. #ifdef NO_THREADS
  2751.     sum = av->system_mem + mp_.mmapped_mem;
  2752.     if (sum > (unsigned long)(mp_.max_total_mem))
  2753.       mp_.max_total_mem = sum;
  2754. #endif

  2755.   }

  2756.   } /* if (av != &main_arena) */

  2757.   if ((unsigned long)av->system_mem > (unsigned long)(av->max_system_mem))
  2758.     av->max_system_mem = av->system_mem;
  2759.   check_malloc_state(av);

  2760.   /* finally, do the allocation */
  2761.   p = av->top;
  2762.   size = chunksize(p);

  2763.   /* check that one of the above allocation paths succeeded */
  2764.   if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
  2765.     remainder_size = size - nb;
  2766.     remainder = chunk_at_offset(p, nb);
  2767.     av->top = remainder;
  2768.     set_head(p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
  2769.     set_head(remainder, remainder_size | PREV_INUSE);
  2770.     check_malloced_chunk(av, p, nb);
  2771.     return chunk2mem(p);
  2772.   }

  2773.   /* catch all failure paths */
  2774.   MALLOC_FAILURE_ACTION;
  2775.   return 0;
  2776. }


  2777. /*
  2778.   sYSTRIm is an inverse of sorts to sYSMALLOc. It gives memory back
  2779.   to the system (via negative arguments to sbrk) if there is unused
  2780.   memory at the `high' end of the malloc pool. It is called
  2781.   automatically by free() when top space exceeds the trim
  2782.   threshold. It is also called by the public malloc_trim routine. It
  2783.   returns 1 if it actually released any memory, else 0.
  2784. */

  2785. #if __STD_C
  2786. static int sYSTRIm(size_t pad, mstate av)
  2787. #else
  2788. static int sYSTRIm(pad, av) size_t pad; mstate av;
  2789. #endif
  2790. {
  2791.   long top_size; /* Amount of top-most memory */
  2792.   long extra; /* Amount to release */
  2793.   long released; /* Amount actually released */
  2794.   char* current_brk; /* address returned by pre-check sbrk call */
  2795.   char* new_brk; /* address returned by post-check sbrk call */
  2796.   size_t pagesz;

  2797.   pagesz = mp_.pagesize;
  2798.   top_size = chunksize(av->top);

  2799.   /* Release in pagesize units, keeping at least one page */
  2800.   extra = (top_size - pad - MINSIZE - 1) & ~(pagesz - 1);

  2801.   if (extra > 0) {

  2802.     /*
  2803.       Only proceed if end of memory is where we last set it.
  2804.       This avoids problems if there were foreign sbrk calls.
  2805.     */
  2806.     current_brk = (char*)(MORECORE(0));
  2807.     if (current_brk == (char*)(av->top) + top_size) {

  2808.       /*
  2809.     Attempt to release memory. We ignore MORECORE return value,
  2810.     and instead call again to find out where new end of memory is.
  2811.     This avoids problems if first call releases less than we asked,
  2812.     of if failure somehow altered brk value. (We could still
  2813.     encounter problems if it altered brk in some very bad way,
  2814.     but the only thing we can do is adjust anyway, which will cause
  2815.     some downstream failure.)
  2816.       */

  2817.       MORECORE(-extra);
  2818.       /* Call the `morecore' hook if necessary. */
  2819.       void (*hook) (void) = force_reg (__after_morecore_hook);
  2820.       if (__builtin_expect (hook != NULL, 0))
  2821.     (*hook) ();
  2822.       new_brk = (char*)(MORECORE(0));

  2823.       if (new_brk != (char*)MORECORE_FAILURE) {
  2824.     released = (long)(current_brk - new_brk);

  2825.     if (released != 0) {
  2826.      /* Success. Adjust top. */
  2827.      av->system_mem -= released;
  2828.      set_head(av->top, (top_size - released) | PREV_INUSE);
  2829.      check_malloc_state(av);
  2830.      return 1;
  2831.     }
  2832.       }
  2833.     }
  2834.   }
  2835.   return 0;
  2836. }

  2837. #ifdef HAVE_MMAP

  2838. static void
  2839. internal_function
  2840. #if __STD_C
  2841. munmap_chunk(mchunkptr p)
  2842. #else
  2843. munmap_chunk(p) mchunkptr p;
  2844. #endif
  2845. {
  2846.   INTERNAL_SIZE_T size = chunksize(p);

  2847.   assert (chunk_is_mmapped(p));
  2848. #if 0
  2849.   assert(! ((char*)p >= mp_.sbrk_base && (char*)p < mp_.sbrk_base + mp_.sbrked_mem));
  2850.   assert((mp_.n_mmaps > 0));
  2851. #endif

  2852.   uintptr_t block = (uintptr_t) p - p->prev_size;
  2853.   size_t total_size = p->prev_size + size;
  2854.   /* Unfortunately we have to do the compilers job by hand here. Normally
  2855.      we would test BLOCK and TOTAL-SIZE separately for compliance with the
  2856.      page size. But gcc does not recognize the optimization possibility
  2857.      (in the moment at least) so we combine the two values into one before
  2858.      the bit test. */
  2859.   if (__builtin_expect (((block | total_size) & (mp_.pagesize - 1)) != 0, 0))
  2860.     {
  2861.       malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
  2862.          chunk2mem (p));
  2863.       return;
  2864.     }

  2865.   mp_.n_mmaps--;
  2866.   mp_.mmapped_mem -= total_size;

  2867.   int ret __attribute__ ((unused)) = munmap((char *)block, total_size);

  2868.   /* munmap returns non-zero on failure */
  2869.   assert(ret == 0);
  2870. }

  2871. #if HAVE_MREMAP

  2872. static mchunkptr
  2873. internal_function
  2874. #if __STD_C
  2875. mremap_chunk(mchunkptr p, size_t new_size)
  2876. #else
  2877. mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
  2878. #endif
  2879. {
  2880.   size_t page_mask = mp_.pagesize - 1;
  2881.   INTERNAL_SIZE_T offset = p->prev_size;
  2882.   INTERNAL_SIZE_T size = chunksize(p);
  2883.   char *cp;

  2884.   assert (chunk_is_mmapped(p));
  2885. #if 0
  2886.   assert(! ((char*)p >= mp_.sbrk_base && (char*)p < mp_.sbrk_base + mp_.sbrked_mem));
  2887.   assert((mp_.n_mmaps > 0));
  2888. #endif
  2889.   assert(((size + offset) & (mp_.pagesize-1)) == 0);

  2890.   /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
  2891.   new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;

  2892.   /* No need to remap if the number of pages does not change. */
  2893.   if (size + offset == new_size)
  2894.     return p;

  2895.   cp = (char *)mremap((char *)p - offset, size + offset, new_size,
  2896.          MREMAP_MAYMOVE);

  2897.   if (cp == MAP_FAILED) return 0;

  2898.   p = (mchunkptr)(cp + offset);

  2899.   assert(aligned_OK(chunk2mem(p)));

  2900.   assert((p->prev_size == offset));
  2901.   set_head(p, (new_size - offset)|IS_MMAPPED);

  2902.   mp_.mmapped_mem -= size + offset;
  2903.   mp_.mmapped_mem += new_size;
  2904.   if ((unsigned long)mp_.mmapped_mem > (unsigned long)mp_.max_mmapped_mem)
  2905.     mp_.max_mmapped_mem = mp_.mmapped_mem;
  2906. #ifdef NO_THREADS
  2907.   if ((unsigned long)(mp_.mmapped_mem + arena_mem + main_arena.system_mem) >
  2908.       mp_.max_total_mem)
  2909.     mp_.max_total_mem = mp_.mmapped_mem + arena_mem + main_arena.system_mem;
  2910. #endif
  2911.   return p;
  2912. }

  2913. #endif /* HAVE_MREMAP */

  2914. #endif /* HAVE_MMAP */

  2915. /*------------------------ Public wrappers. --------------------------------*/

  2916. Void_t*
  2917. public_mALLOc(size_t bytes)
  2918. {
  2919.   mstate ar_ptr;
  2920.   Void_t *victim;

  2921.   __malloc_ptr_t (*hook) (size_t, __const __malloc_ptr_t)
  2922.     = force_reg (__malloc_hook);
  2923.   if (__builtin_expect (hook != NULL, 0))
  2924.     return (*hook)(bytes, RETURN_ADDRESS (0));

  2925.   arena_lookup(ar_ptr);
  2926. #if 0
  2927.   // XXX We need double-word CAS and fastbins must be extended to also
  2928.   // XXX hold a generation counter for each entry.
  2929.   if (ar_ptr) {
  2930.     INTERNAL_SIZE_T nb; /* normalized request size */
  2931.     checked_request2size(bytes, nb);
  2932.     if (nb <= get_max_fast ()) {
  2933.       long int idx = fastbin_index(nb);
  2934.       mfastbinptr* fb = &fastbin (ar_ptr, idx);
  2935.       mchunkptr pp = *fb;
  2936.       mchunkptr v;
  2937.       do
  2938.     {
  2939.      v = pp;
  2940.      if (v == NULL)
  2941.      break;
  2942.     }
  2943.       while ((pp = catomic_compare_and_exchange_val_acq (fb, v->fd, v)) != v);
  2944.       if (v != 0) {
  2945.     if (__builtin_expect (fastbin_index (chunksize (v)) != idx, 0))
  2946.      malloc_printerr (check_action, "malloc(): memory corruption (fast)",
  2947.              chunk2mem (v));
  2948.     check_remalloced_chunk(ar_ptr, v, nb);
  2949.     void *p = chunk2mem(v);
  2950.     if (__builtin_expect (perturb_byte, 0))
  2951.      alloc_perturb (p, bytes);
  2952.     return p;
  2953.       }
  2954.     }
  2955.   }
  2956. #endif

  2957.   arena_lock(ar_ptr, bytes);
  2958.   if(!ar_ptr)
  2959.     return 0;
  2960.   victim = _int_malloc(ar_ptr, bytes);
  2961.   if(!victim) {
  2962.     /* Maybe the failure is due to running out of mmapped areas. */
  2963.     if(ar_ptr != &main_arena) {
  2964.       (void)mutex_unlock(&ar_ptr->mutex);
  2965.       ar_ptr = &main_arena;
  2966.       (void)mutex_lock(&ar_ptr->mutex);
  2967.       victim = _int_malloc(ar_ptr, bytes);
  2968.       (void)mutex_unlock(&ar_ptr->mutex);
  2969.     } else {
  2970. #if USE_ARENAS
  2971.       /* ... or sbrk() has failed and there is still a chance to mmap() */
  2972.       ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
  2973.       (void)mutex_unlock(&main_arena.mutex);
  2974.       if(ar_ptr) {
  2975.     victim = _int_malloc(ar_ptr, bytes);
  2976.     (void)mutex_unlock(&ar_ptr->mutex);
  2977.       }
  2978. #endif
  2979.     }
  2980.   } else
  2981.     (void)mutex_unlock(&ar_ptr->mutex);
  2982.   assert(!victim || chunk_is_mmapped(mem2chunk(victim)) ||
  2983.      ar_ptr == arena_for_chunk(mem2chunk(victim)));
  2984.   return victim;
  2985. }
  2986. #ifdef libc_hidden_def
  2987. libc_hidden_def(public_mALLOc)
  2988. #endif

  2989. void
  2990. public_fREe(Void_t* mem)
  2991. {
  2992.   mstate ar_ptr;
  2993.   mchunkptr p; /* chunk corresponding to mem */

  2994.   void (*hook) (__malloc_ptr_t, __const __malloc_ptr_t)
  2995.     = force_reg (__free_hook);
  2996.   if (__builtin_expect (hook != NULL, 0)) {
  2997.     (*hook)(mem, RETURN_ADDRESS (0));
  2998.     return;
  2999.   }

  3000.   if (mem == 0) /* free(0) has no effect */
  3001.     return;

  3002.   p = mem2chunk(mem);

  3003. #if HAVE_MMAP
  3004.   if (chunk_is_mmapped(p)) /* release mmapped memory. */
  3005.   {
  3006.     /* see if the dynamic brk/mmap threshold needs adjusting */
  3007.     if (!mp_.no_dyn_threshold
  3008.     && p->size > mp_.mmap_threshold
  3009.     && p->size <= DEFAULT_MMAP_THRESHOLD_MAX)
  3010.       {
  3011.     mp_.mmap_threshold = chunksize (p);
  3012.     mp_.trim_threshold = 2 * mp_.mmap_threshold;
  3013.       }
  3014.     munmap_chunk(p);
  3015.     return;
  3016.   }
  3017. #endif

  3018.   ar_ptr = arena_for_chunk(p);
  3019. #ifdef ATOMIC_FASTBINS
  3020.   _int_free(ar_ptr, p, 0);
  3021. #else
  3022. # if THREAD_STATS
  3023.   if(!mutex_trylock(&ar_ptr->mutex))
  3024.     ++(ar_ptr->stat_lock_direct);
  3025.   else {
  3026.     (void)mutex_lock(&ar_ptr->mutex);
  3027.     ++(ar_ptr->stat_lock_wait);
  3028.   }
  3029. # else
  3030.   (void)mutex_lock(&ar_ptr->mutex);
  3031. # endif
  3032.   _int_free(ar_ptr, p);
  3033.   (void)mutex_unlock(&ar_ptr->mutex);
  3034. #endif
  3035. }
  3036. #ifdef libc_hidden_def
  3037. libc_hidden_def (public_fREe)
  3038. #endif

  3039. Void_t*
  3040. public_rEALLOc(Void_t* oldmem, size_t bytes)
  3041. {
  3042.   mstate ar_ptr;
  3043.   INTERNAL_SIZE_T nb; /* padded request size */

  3044.   Void_t* newp; /* chunk to return */

  3045.   __malloc_ptr_t (*hook) (__malloc_ptr_t, size_t, __const __malloc_ptr_t) =
  3046.     force_reg (__realloc_hook);
  3047.   if (__builtin_expect (hook != NULL, 0))
  3048.     return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));

  3049. #if REALLOC_ZERO_BYTES_FREES
  3050.   if (bytes == 0 && oldmem != NULL) { public_fREe(oldmem); return 0; }
  3051. #endif

  3052.   /* realloc of null is supposed to be same as malloc */
  3053.   if (oldmem == 0) return public_mALLOc(bytes);

  3054.   /* chunk corresponding to oldmem */
  3055.   const mchunkptr oldp = mem2chunk(oldmem);
  3056.   /* its size */
  3057.   const INTERNAL_SIZE_T oldsize = chunksize(oldp);

  3058.   /* Little security check which won't hurt performance: the
  3059.      allocator never wrapps around at the end of the address space.
  3060.      Therefore we can exclude some size values which might appear
  3061.      here by accident or by "design" from some intruder. */
  3062.   if (__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
  3063.       || __builtin_expect (misaligned_chunk (oldp), 0))
  3064.     {
  3065.       malloc_printerr (check_action, "realloc(): invalid pointer", oldmem);
  3066.       return NULL;
  3067.     }

  3068.   checked_request2size(bytes, nb);

  3069. #if HAVE_MMAP
  3070.   if (chunk_is_mmapped(oldp))
  3071.   {
  3072.     Void_t* newmem;

  3073. #if HAVE_MREMAP
  3074.     newp = mremap_chunk(oldp, nb);
  3075.     if(newp) return chunk2mem(newp);
  3076. #endif
  3077.     /* Note the extra SIZE_SZ overhead. */
  3078.     if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
  3079.     /* Must alloc, copy, free. */
  3080.     newmem = public_mALLOc(bytes);
  3081.     if (newmem == 0) return 0; /* propagate failure */
  3082.     MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
  3083.     munmap_chunk(oldp);
  3084.     return newmem;
  3085.   }
  3086. #endif

  3087.   ar_ptr = arena_for_chunk(oldp);
  3088. #if THREAD_STATS
  3089.   if(!mutex_trylock(&ar_ptr->mutex))
  3090.     ++(ar_ptr->stat_lock_direct);
  3091.   else {
  3092.     (void)mutex_lock(&ar_ptr->mutex);
  3093.     ++(ar_ptr->stat_lock_wait);
  3094.   }
  3095. #else
  3096.   (void)mutex_lock(&ar_ptr->mutex);
  3097. #endif

  3098. #if !defined NO_THREADS && !defined PER_THREAD
  3099.   /* As in malloc(), remember this arena for the next allocation. */
  3100.   tsd_setspecific(arena_key, (Void_t *)ar_ptr);
  3101. #endif

  3102.   newp = _int_realloc(ar_ptr, oldp, oldsize, nb);

  3103.   (void)mutex_unlock(&ar_ptr->mutex);
  3104.   assert(!newp || chunk_is_mmapped(mem2chunk(newp)) ||
  3105.      ar_ptr == arena_for_chunk(mem2chunk(newp)));

  3106.   if (newp == NULL)
  3107.     {
  3108.       /* Try harder to allocate memory in other arenas. */
  3109.       newp = public_mALLOc(bytes);
  3110.       if (newp != NULL)
  3111.     {
  3112.      MALLOC_COPY (newp, oldmem, oldsize - SIZE_SZ);
  3113. #ifdef ATOMIC_FASTBINS
  3114.      _int_free(ar_ptr, oldp, 0);
  3115. #else
  3116. # if THREAD_STATS
  3117.      if(!mutex_trylock(&ar_ptr->mutex))
  3118.      ++(ar_ptr->stat_lock_direct);
  3119.      else {
  3120.      (void)mutex_lock(&ar_ptr->mutex);
  3121.      ++(ar_ptr->stat_lock_wait);
  3122.      }
  3123. # else
  3124.      (void)mutex_lock(&ar_ptr->mutex);
  3125. # endif
  3126.      _int_free(ar_ptr, oldp);
  3127.      (void)mutex_unlock(&ar_ptr->mutex);
  3128. #endif
  3129.     }
  3130.     }

  3131.   return newp;
  3132. }
  3133. #ifdef libc_hidden_def
  3134. libc_hidden_def (public_rEALLOc)
  3135. #endif

  3136. Void_t*
  3137. public_mEMALIGn(size_t alignment, size_t bytes)
  3138. {
  3139.   mstate ar_ptr;
  3140.   Void_t *p;

  3141.   __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
  3142.                     __const __malloc_ptr_t)) =
  3143.     force_reg (__memalign_hook);
  3144.   if (__builtin_expect (hook != NULL, 0))
  3145.     return (*hook)(alignment, bytes, RETURN_ADDRESS (0));

  3146.   /* If need less alignment than we give anyway, just relay to malloc */
  3147.   if (alignment <= MALLOC_ALIGNMENT) return public_mALLOc(bytes);

  3148.   /* Otherwise, ensure that it is at least a minimum chunk size */
  3149.   if (alignment < MINSIZE) alignment = MINSIZE;

  3150.   arena_get(ar_ptr, bytes + alignment + MINSIZE);
  3151.   if(!ar_ptr)
  3152.     return 0;
  3153.   p = _int_memalign(ar_ptr, alignment, bytes);
  3154.   if(!p) {
  3155.     /* Maybe the failure is due to running out of mmapped areas. */
  3156.     if(ar_ptr != &main_arena) {
  3157.       (void)mutex_unlock(&ar_ptr->mutex);
  3158.       ar_ptr = &main_arena;
  3159.       (void)mutex_lock(&ar_ptr->mutex);
  3160.       p = _int_memalign(ar_ptr, alignment, bytes);
  3161.       (void)mutex_unlock(&ar_ptr->mutex);
  3162.     } else {
  3163. #if USE_ARENAS
  3164.       /* ... or sbrk() has failed and there is still a chance to mmap() */
  3165.       mstate prev = ar_ptr->next ? ar_ptr : 0;
  3166.       (void)mutex_unlock(&ar_ptr->mutex);
  3167.       ar_ptr = arena_get2(prev, bytes);
  3168.       if(ar_ptr) {
  3169.     p = _int_memalign(ar_ptr, alignment, bytes);
  3170.     (void)mutex_unlock(&ar_ptr->mutex);
  3171.       }
  3172. #endif
  3173.     }
  3174.   } else
  3175.     (void)mutex_unlock(&ar_ptr->mutex);
  3176.   assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
  3177.      ar_ptr == arena_for_chunk(mem2chunk(p)));
  3178.   return p;
  3179. }
  3180. #ifdef libc_hidden_def
  3181. libc_hidden_def (public_mEMALIGn)
  3182. #endif

  3183. Void_t*
  3184. public_vALLOc(size_t bytes)
  3185. {
  3186.   mstate ar_ptr;
  3187.   Void_t *p;

  3188.   if(__malloc_initialized < 0)
  3189.     ptmalloc_init ();

  3190.   size_t pagesz = mp_.pagesize;

  3191.   __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
  3192.                     __const __malloc_ptr_t)) =
  3193.     force_reg (__memalign_hook);
  3194.   if (__builtin_expect (hook != NULL, 0))
  3195.     return (*hook)(pagesz, bytes, RETURN_ADDRESS (0));

  3196.   arena_get(ar_ptr, bytes + pagesz + MINSIZE);
  3197.   if(!ar_ptr)
  3198.     return 0;
  3199.   p = _int_valloc(ar_ptr, bytes);
  3200.   (void)mutex_unlock(&ar_ptr->mutex);
  3201.   if(!p) {
  3202.     /* Maybe the failure is due to running out of mmapped areas. */
  3203.     if(ar_ptr != &main_arena) {
  3204.       ar_ptr = &main_arena;
  3205.       (void)mutex_lock(&ar_ptr->mutex);
  3206.       p = _int_memalign(ar_ptr, pagesz, bytes);
  3207.       (void)mutex_unlock(&ar_ptr->mutex);
  3208.     } else {
  3209. #if USE_ARENAS
  3210.       /* ... or sbrk() has failed and there is still a chance to mmap() */
  3211.       ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
  3212.       if(ar_ptr) {
  3213.     p = _int_memalign(ar_ptr, pagesz, bytes);
  3214.     (void)mutex_unlock(&ar_ptr->mutex);
  3215.       }
  3216. #endif
  3217.     }
  3218.   }
  3219.   assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
  3220.      ar_ptr == arena_for_chunk(mem2chunk(p)));

  3221.   return p;
  3222. }

  3223. Void_t*
  3224. public_pVALLOc(size_t bytes)
  3225. {
  3226.   mstate ar_ptr;
  3227.   Void_t *p;

  3228.   if(__malloc_initialized < 0)
  3229.     ptmalloc_init ();

  3230.   size_t pagesz = mp_.pagesize;
  3231.   size_t page_mask = mp_.pagesize - 1;
  3232.   size_t rounded_bytes = (bytes + page_mask) & ~(page_mask);

  3233.   __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
  3234.                     __const __malloc_ptr_t)) =
  3235.     force_reg (__memalign_hook);
  3236.   if (__builtin_expect (hook != NULL, 0))
  3237.     return (*hook)(pagesz, rounded_bytes, RETURN_ADDRESS (0));

  3238.   arena_get(ar_ptr, bytes + 2*pagesz + MINSIZE);
  3239.   p = _int_pvalloc(ar_ptr, bytes);
  3240.   (void)mutex_unlock(&ar_ptr->mutex);
  3241.   if(!p) {
  3242.     /* Maybe the failure is due to running out of mmapped areas. */
  3243.     if(ar_ptr != &main_arena) {
  3244.       ar_ptr = &main_arena;
  3245.       (void)mutex_lock(&ar_ptr->mutex);
  3246.       p = _int_memalign(ar_ptr, pagesz, rounded_bytes);
  3247.       (void)mutex_unlock(&ar_ptr->mutex);
  3248.     } else {
  3249. #if USE_ARENAS
  3250.       /* ... or sbrk() has failed and there is still a chance to mmap() */
  3251.       ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0,
  3252.              bytes + 2*pagesz + MINSIZE);
  3253.       if(ar_ptr) {
  3254.     p = _int_memalign(ar_ptr, pagesz, rounded_bytes);
  3255.     (void)mutex_unlock(&ar_ptr->mutex);
  3256.       }
  3257. #endif
  3258.     }
  3259.   }
  3260.   assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
  3261.      ar_ptr == arena_for_chunk(mem2chunk(p)));

  3262.   return p;
  3263. }

  3264. Void_t*
  3265. public_cALLOc(size_t n, size_t elem_size)
  3266. {
  3267.   mstate av;
  3268.   mchunkptr oldtop, p;
  3269.   INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
  3270.   Void_t* mem;
  3271.   unsigned long clearsize;
  3272.   unsigned long nclears;
  3273.   INTERNAL_SIZE_T* d;

  3274.   /* size_t is unsigned so the behavior on overflow is defined. */
  3275.   bytes = n * elem_size;
  3276. #define HALF_INTERNAL_SIZE_T \
  3277.   (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
  3278.   if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) {
  3279.     if (elem_size != 0 && bytes / elem_size != n) {
  3280.       MALLOC_FAILURE_ACTION;
  3281.       return 0;
  3282.     }
  3283.   }

  3284.   __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, __const __malloc_ptr_t)) =
  3285.     force_reg (__malloc_hook);
  3286.   if (__builtin_expect (hook != NULL, 0)) {
  3287.     sz = bytes;
  3288.     mem = (*hook)(sz, RETURN_ADDRESS (0));
  3289.     if(mem == 0)
  3290.       return 0;
  3291. #ifdef HAVE_MEMCPY
  3292.     return memset(mem, 0, sz);
  3293. #else
  3294.     while(sz > 0) ((char*)mem)[--sz] = 0; /* rather inefficient */
  3295.     return mem;
  3296. #endif
  3297.   }

  3298.   sz = bytes;

  3299.   arena_get(av, sz);
  3300.   if(!av)
  3301.     return 0;

  3302.   /* Check if we hand out the top chunk, in which case there may be no
  3303.      need to clear. */
  3304. #if MORECORE_CLEARS
  3305.   oldtop = top(av);
  3306.   oldtopsize = chunksize(top(av));
  3307. #if MORECORE_CLEARS < 2
  3308.   /* Only newly allocated memory is guaranteed to be cleared. */
  3309.   if (av == &main_arena &&
  3310.       oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *)oldtop)
  3311.     oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *)oldtop);
  3312. #endif
  3313.   if (av != &main_arena)
  3314.     {
  3315.       heap_info *heap = heap_for_ptr (oldtop);
  3316.       if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
  3317.     oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
  3318.     }
  3319. #endif
  3320.   mem = _int_malloc(av, sz);

  3321.   /* Only clearing follows, so we can unlock early. */
  3322.   (void)mutex_unlock(&av->mutex);

  3323.   assert(!mem || chunk_is_mmapped(mem2chunk(mem)) ||
  3324.      av == arena_for_chunk(mem2chunk(mem)));

  3325.   if (mem == 0) {
  3326.     /* Maybe the failure is due to running out of mmapped areas. */
  3327.     if(av != &main_arena) {
  3328.       (void)mutex_lock(&main_arena.mutex);
  3329.       mem = _int_malloc(&main_arena, sz);
  3330.       (void)mutex_unlock(&main_arena.mutex);
  3331.     } else {
  3332. #if USE_ARENAS
  3333.       /* ... or sbrk() has failed and there is still a chance to mmap() */
  3334.       (void)mutex_lock(&main_arena.mutex);
  3335.       av = arena_get2(av->next ? av : 0, sz);
  3336.       (void)mutex_unlock(&main_arena.mutex);
  3337.       if(av) {
  3338.     mem = _int_malloc(av, sz);
  3339.     (void)mutex_unlock(&av->mutex);
  3340.       }
  3341. #endif
  3342.     }
  3343.     if (mem == 0) return 0;
  3344.   }
  3345.   p = mem2chunk(mem);

  3346.   /* Two optional cases in which clearing not necessary */
  3347. #if HAVE_MMAP
  3348.   if (chunk_is_mmapped (p))
  3349.     {
  3350.       if (__builtin_expect (perturb_byte, 0))
  3351.     MALLOC_ZERO (mem, sz);
  3352.       return mem;
  3353.     }
  3354. #endif

  3355.   csz = chunksize(p);

  3356. #if MORECORE_CLEARS
  3357.   if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize)) {
  3358.     /* clear only the bytes from non-freshly-sbrked memory */
  3359.     csz = oldtopsize;
  3360.   }
  3361. #endif

  3362.   /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
  3363.      contents have an odd number of INTERNAL_SIZE_T-sized words;
  3364.      minimally 3. */
  3365.   d = (INTERNAL_SIZE_T*)mem;
  3366.   clearsize = csz - SIZE_SZ;
  3367.   nclears = clearsize / sizeof(INTERNAL_SIZE_T);
  3368.   assert(nclears >= 3);

  3369.   if (nclears > 9)
  3370.     MALLOC_ZERO(d, clearsize);

  3371.   else {
  3372.     *(d+0) = 0;
  3373.     *(d+1) = 0;
  3374.     *(d+2) = 0;
  3375.     if (nclears > 4) {
  3376.       *(d+3) = 0;
  3377.       *(d+4) = 0;
  3378.       if (nclears > 6) {
  3379.     *(d+5) = 0;
  3380.     *(d+6) = 0;
  3381.     if (nclears > 8) {
  3382.      *(d+7) = 0;
  3383.      *(d+8) = 0;
  3384.     }
  3385.       }
  3386.     }
  3387.   }

  3388.   return mem;
  3389. }

  3390. #ifndef _LIBC

  3391. Void_t**
  3392. public_iCALLOc(size_t n, size_t elem_size, Void_t** chunks)
  3393. {
  3394.   mstate ar_ptr;
  3395.   Void_t** m;

  3396.   arena_get(ar_ptr, n*elem_size);
  3397.   if(!ar_ptr)
  3398.     return 0;

  3399.   m = _int_icalloc(ar_ptr, n, elem_size, chunks);
  3400.   (void)mutex_unlock(&ar_ptr->mutex);
  3401.   return m;
  3402. }

  3403. Void_t**
  3404. public_iCOMALLOc(size_t n, size_t sizes[], Void_t** chunks)
  3405. {
  3406.   mstate ar_ptr;
  3407.   Void_t** m;

  3408.   arena_get(ar_ptr, 0);
  3409.   if(!ar_ptr)
  3410.     return 0;

  3411.   m = _int_icomalloc(ar_ptr, n, sizes, chunks);
  3412.   (void)mutex_unlock(&ar_ptr->mutex);
  3413.   return m;
  3414. }

  3415. void
  3416. public_cFREe(Void_t* m)
  3417. {
  3418.   public_fREe(m);
  3419. }

  3420. #endif /* _LIBC */

  3421. int
  3422. public_mTRIm(size_t s)
  3423. {
  3424.   int result = 0;

  3425.   if(__malloc_initialized < 0)
  3426.     ptmalloc_init ();

  3427.   mstate ar_ptr = &main_arena;
  3428.   do
  3429.     {
  3430.       (void) mutex_lock (&ar_ptr->mutex);
  3431.       result |= mTRIm (ar_ptr, s);
  3432.       (void) mutex_unlock (&ar_ptr->mutex);

  3433.       ar_ptr = ar_ptr->next;
  3434.     }
  3435.   while (ar_ptr != &main_arena);

  3436.   return result;
  3437. }

  3438. size_t
  3439. public_mUSABLe(Void_t* m)
  3440. {
  3441.   size_t result;

  3442.   result = mUSABLe(m);
  3443.   return result;
  3444. }

  3445. void
  3446. public_mSTATs()
  3447. {
  3448.   mSTATs();
  3449. }

  3450. struct mallinfo public_mALLINFo()
  3451. {
  3452.   struct mallinfo m;

  3453.   if(__malloc_initialized < 0)
  3454.     ptmalloc_init ();
  3455.   (void)mutex_lock(&main_arena.mutex);
  3456.   m = mALLINFo(&main_arena);
  3457.   (void)mutex_unlock(&main_arena.mutex);
  3458.   return m;
  3459. }

  3460. int
  3461. public_mALLOPt(int p, int v)
  3462. {
  3463.   int result;
  3464.   result = mALLOPt(p, v);
  3465.   return result;
  3466. }

  3467. /*
  3468.   ------------------------------ malloc ------------------------------
  3469. */

  3470. static Void_t*
  3471. _int_malloc(mstate av, size_t bytes)
  3472. {
  3473.   INTERNAL_SIZE_T nb; /* normalized request size */
  3474.   unsigned int idx; /* associated bin index */
  3475.   mbinptr bin; /* associated bin */

  3476.   mchunkptr victim; /* inspected/selected chunk */
  3477.   INTERNAL_SIZE_T size; /* its size */
  3478.   int victim_index; /* its bin index */

  3479.   mchunkptr remainder; /* remainder from a split */
  3480.   unsigned long remainder_size; /* its size */

  3481.   unsigned int block; /* bit map traverser */
  3482.   unsigned int bit; /* bit map traverser */
  3483.   unsigned int map; /* current word of binmap */

  3484.   mchunkptr fwd; /* misc temp for linking */
  3485.   mchunkptr bck; /* misc temp for linking */

  3486.   const char *errstr = NULL;

  3487.   /*
  3488.     Convert request size to internal form by adding SIZE_SZ bytes
  3489.     overhead plus possibly more to obtain necessary alignment and/or
  3490.     to obtain a size of at least MINSIZE, the smallest allocatable
  3491.     size. Also, checked_request2size traps (returning 0) request sizes
  3492.     that are so large that they wrap around zero when padded and
  3493.     aligned.
  3494.   */

  3495.   checked_request2size(bytes, nb);

  3496.   /*
  3497.     If the size qualifies as a fastbin, first check corresponding bin.
  3498.     This code is safe to execute even if av is not yet initialized, so we
  3499.     can try it without checking, which saves some time on this fast path.
  3500.   */

  3501.   if ((unsigned long)(nb) <= (unsigned long)(get_max_fast ())) {
  3502.     idx = fastbin_index(nb);
  3503.     mfastbinptr* fb = &fastbin (av, idx);
  3504. #ifdef ATOMIC_FASTBINS
  3505.     mchunkptr pp = *fb;
  3506.     do
  3507.       {
  3508.     victim = pp;
  3509.     if (victim == NULL)
  3510.      break;
  3511.       }
  3512.     while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim))
  3513.      != victim);
  3514. #else
  3515.     victim = *fb;
  3516. #endif
  3517.     if (victim != 0) {
  3518.       if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
  3519.     {
  3520.      errstr = "malloc(): memory corruption (fast)";
  3521.     errout:
  3522.      malloc_printerr (check_action, errstr, chunk2mem (victim));
  3523.      return NULL;
  3524.     }
  3525. #ifndef ATOMIC_FASTBINS
  3526.       *fb = victim->fd;
  3527. #endif
  3528.       check_remalloced_chunk(av, victim, nb);
  3529.       void *p = chunk2mem(victim);
  3530.       if (__builtin_expect (perturb_byte, 0))
  3531.     alloc_perturb (p, bytes);
  3532.       return p;
  3533.     }
  3534.   }

  3535.   /*
  3536.     If a small request, check regular bin. Since these "smallbins"
  3537.     hold one size each, no searching within bins is necessary.
  3538.     (For a large request, we need to wait until unsorted chunks are
  3539.     processed to find best fit. But for small ones, fits are exact
  3540.     anyway, so we can check now, which is faster.)
  3541.   */

  3542.   if (in_smallbin_range(nb)) {
  3543.     idx = smallbin_index(nb);
  3544.     bin = bin_at(av,idx);

  3545.     if ( (victim = last(bin)) != bin) {
  3546.       if (victim == 0) /* initialization check */
  3547.     malloc_consolidate(av);
  3548.       else {
  3549.     bck = victim->bk;
  3550.     if (__builtin_expect (bck->fd != victim, 0))
  3551.      {
  3552.      errstr = "malloc(): smallbin double linked list corrupted";
  3553.      goto errout;
  3554.      }
  3555.     set_inuse_bit_at_offset(victim, nb);
  3556.     bin->bk = bck;
  3557.     bck->fd = bin;

  3558.     if (av != &main_arena)
  3559.      victim->size |= NON_MAIN_ARENA;
  3560.     check_malloced_chunk(av, victim, nb);
  3561.     void *p = chunk2mem(victim);
  3562.     if (__builtin_expect (perturb_byte, 0))
  3563.      alloc_perturb (p, bytes);
  3564.     return p;
  3565.       }
  3566.     }
  3567.   }

  3568.   /*
  3569.      If this is a large request, consolidate fastbins before continuing.
  3570.      While it might look excessive to kill all fastbins before
  3571.      even seeing if there is space available, this avoids
  3572.      fragmentation problems normally associated with fastbins.
  3573.      Also, in practice, programs tend to have runs of either small or
  3574.      large requests, but less often mixtures, so consolidation is not
  3575.      invoked all that often in most programs. And the programs that
  3576.      it is called frequently in otherwise tend to fragment.
  3577.   */

  3578.   else {
  3579.     idx = largebin_index(nb);
  3580.     if (have_fastchunks(av))
  3581.       malloc_consolidate(av);
  3582.   }

  3583.   /*
  3584.     Process recently freed or remaindered chunks, taking one only if
  3585.     it is exact fit, or, if this a small request, the chunk is remainder from
  3586.     the most recent non-exact fit. Place other traversed chunks in
  3587.     bins. Note that this step is the only place in any routine where
  3588.     chunks are placed in bins.

  3589.     The outer loop here is needed because we might not realize until
  3590.     near the end of malloc that we should have consolidated, so must
  3591.     do so and retry. This happens at most once, and only when we would
  3592.     otherwise need to expand memory to service a "small" request.
  3593.   */

  3594.   for(;;) {

  3595.     int iters = 0;
  3596.     while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
  3597.       bck = victim->bk;
  3598.       if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0)
  3599.      || __builtin_expect (victim->size > av->system_mem, 0))
  3600.     malloc_printerr (check_action, "malloc(): memory corruption",
  3601.              chunk2mem (victim));
  3602.       size = chunksize(victim);

  3603.       /*
  3604.      If a small request, try to use last remainder if it is the
  3605.      only chunk in unsorted bin. This helps promote locality for
  3606.      runs of consecutive small requests. This is the only
  3607.      exception to best-fit, and applies only when there is
  3608.      no exact fit for a small chunk.
  3609.       */

  3610.       if (in_smallbin_range(nb) &&
  3611.      bck == unsorted_chunks(av) &&
  3612.      victim == av->last_remainder &&
  3613.      (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {

  3614.     /* split and reattach remainder */
  3615.     remainder_size = size - nb;
  3616.     remainder = chunk_at_offset(victim, nb);
  3617.     unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  3618.     av->last_remainder = remainder;
  3619.     remainder->bk = remainder->fd = unsorted_chunks(av);
  3620.     if (!in_smallbin_range(remainder_size))
  3621.      {
  3622.      remainder->fd_nextsize = NULL;
  3623.      remainder->bk_nextsize = NULL;
  3624.      }

  3625.     set_head(victim, nb | PREV_INUSE |
  3626.          (av != &main_arena ? NON_MAIN_ARENA : 0));
  3627.     set_head(remainder, remainder_size | PREV_INUSE);
  3628.     set_foot(remainder, remainder_size);

  3629.     check_malloced_chunk(av, victim, nb);
  3630.     void *p = chunk2mem(victim);
  3631.     if (__builtin_expect (perturb_byte, 0))
  3632.      alloc_perturb (p, bytes);
  3633.     return p;
  3634.       }

  3635.       /* remove from unsorted list */
  3636.       unsorted_chunks(av)->bk = bck;
  3637.       bck->fd = unsorted_chunks(av);

  3638.       /* Take now instead of binning if exact fit */

  3639.       if (size == nb) {
  3640.     set_inuse_bit_at_offset(victim, size);
  3641.     if (av != &main_arena)
  3642.      victim->size |= NON_MAIN_ARENA;
  3643.     check_malloced_chunk(av, victim, nb);
  3644.     void *p = chunk2mem(victim);
  3645.     if (__builtin_expect (perturb_byte, 0))
  3646.      alloc_perturb (p, bytes);
  3647.     return p;
  3648.       }

  3649.       /* place chunk in bin */

  3650.       if (in_smallbin_range(size)) {
  3651.     victim_index = smallbin_index(size);
  3652.     bck = bin_at(av, victim_index);
  3653.     fwd = bck->fd;
  3654.       }
  3655.       else {
  3656.     victim_index = largebin_index(size);
  3657.     bck = bin_at(av, victim_index);
  3658.     fwd = bck->fd;

  3659.     /* maintain large bins in sorted order */
  3660.     if (fwd != bck) {
  3661.      /* Or with inuse bit to speed comparisons */
  3662.      size |= PREV_INUSE;
  3663.      /* if smaller than smallest, bypass loop below */
  3664.      assert((bck->bk->size & NON_MAIN_ARENA) == 0);
  3665.      if ((unsigned long)(size) < (unsigned long)(bck->bk->size)) {
  3666.      fwd = bck;
  3667.      bck = bck->bk;

  3668.      victim->fd_nextsize = fwd->fd;
  3669.      victim->bk_nextsize = fwd->fd->bk_nextsize;
  3670.      fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
  3671.      }
  3672.      else {
  3673.      assert((fwd->size & NON_MAIN_ARENA) == 0);
  3674.      while ((unsigned long) size < fwd->size)
  3675.      {
  3676.         fwd = fwd->fd_nextsize;
  3677.         assert((fwd->size & NON_MAIN_ARENA) == 0);
  3678.      }

  3679.      if ((unsigned long) size == (unsigned long) fwd->size)
  3680.      /* Always insert in the second position. */
  3681.      fwd = fwd->fd;
  3682.      else
  3683.      {
  3684.         victim->fd_nextsize = fwd;
  3685.         victim->bk_nextsize = fwd->bk_nextsize;
  3686.         fwd->bk_nextsize = victim;
  3687.         victim->bk_nextsize->fd_nextsize = victim;
  3688.      }
  3689.      bck = fwd->bk;
  3690.      }
  3691.     } else
  3692.      victim->fd_nextsize = victim->bk_nextsize = victim;
  3693.       }

  3694.       mark_bin(av, victim_index);
  3695.       victim->bk = bck;
  3696.       victim->fd = fwd;
  3697.       fwd->bk = victim;
  3698.       bck->fd = victim;

  3699. #define MAX_ITERS    10000
  3700.       if (++iters >= MAX_ITERS)
  3701.     break;
  3702.     }

  3703.     /*
  3704.       If a large request, scan through the chunks of current bin in
  3705.       sorted order to find smallest that fits. Use the skip list for this.
  3706.     */

  3707.     if (!in_smallbin_range(nb)) {
  3708.       bin = bin_at(av, idx);

  3709.       /* skip scan if empty or largest chunk is too small */
  3710.       if ((victim = first(bin)) != bin &&
  3711.      (unsigned long)(victim->size) >= (unsigned long)(nb)) {

  3712.     victim = victim->bk_nextsize;
  3713.     while (((unsigned long)(size = chunksize(victim)) <
  3714.         (unsigned long)(nb)))
  3715.      victim = victim->bk_nextsize;

  3716.     /* Avoid removing the first entry for a size so that the skip
  3717.      list does not have to be rerouted. */
  3718.     if (victim != last(bin) && victim->size == victim->fd->size)
  3719.      victim = victim->fd;

  3720.     remainder_size = size - nb;
  3721.     unlink(victim, bck, fwd);

  3722.     /* Exhaust */
  3723.     if (remainder_size < MINSIZE) {
  3724.      set_inuse_bit_at_offset(victim, size);
  3725.      if (av != &main_arena)
  3726.      victim->size |= NON_MAIN_ARENA;
  3727.     }
  3728.     /* Split */
  3729.     else {
  3730.      remainder = chunk_at_offset(victim, nb);
  3731.      /* We cannot assume the unsorted list is empty and therefore
  3732.      have to perform a complete insert here. */
  3733.      bck = unsorted_chunks(av);
  3734.      fwd = bck->fd;
  3735.      if (__builtin_expect (fwd->bk != bck, 0))
  3736.      {
  3737.      errstr = "malloc(): corrupted unsorted chunks";
  3738.      goto errout;
  3739.      }
  3740.      remainder->bk = bck;
  3741.      remainder->fd = fwd;
  3742.      bck->fd = remainder;
  3743.      fwd->bk = remainder;
  3744.      if (!in_smallbin_range(remainder_size))
  3745.      {
  3746.      remainder->fd_nextsize = NULL;
  3747.      remainder->bk_nextsize = NULL;
  3748.      }
  3749.      set_head(victim, nb | PREV_INUSE |
  3750.          (av != &main_arena ? NON_MAIN_ARENA : 0));
  3751.      set_head(remainder, remainder_size | PREV_INUSE);
  3752.      set_foot(remainder, remainder_size);
  3753.     }
  3754.     check_malloced_chunk(av, victim, nb);
  3755.     void *p = chunk2mem(victim);
  3756.     if (__builtin_expect (perturb_byte, 0))
  3757.      alloc_perturb (p, bytes);
  3758.     return p;
  3759.       }
  3760.     }

  3761.     /*
  3762.       Search for a chunk by scanning bins, starting with next largest
  3763.       bin. This search is strictly by best-fit; i.e., the smallest
  3764.       (with ties going to approximately the least recently used) chunk
  3765.       that fits is selected.

  3766.       The bitmap avoids needing to check that most blocks are nonempty.
  3767.       The particular case of skipping all bins during warm-up phases
  3768.       when no chunks have been returned yet is faster than it might look.
  3769.     */

  3770.     ++idx;
  3771.     bin = bin_at(av,idx);
  3772.     block = idx2block(idx);
  3773.     map = av->binmap[block];
  3774.     bit = idx2bit(idx);

  3775.     for (;;) {

  3776.       /* Skip rest of block if there are no more set bits in this block. */
  3777.       if (bit > map || bit == 0) {
  3778.     do {
  3779.      if (++block >= BINMAPSIZE) /* out of bins */
  3780.      goto use_top;
  3781.     } while ( (map = av->binmap[block]) == 0);

  3782.     bin = bin_at(av, (block << BINMAPSHIFT));
  3783.     bit = 1;
  3784.       }

  3785.       /* Advance to bin with set bit. There must be one. */
  3786.       while ((bit & map) == 0) {
  3787.     bin = next_bin(bin);
  3788.     bit <<= 1;
  3789.     assert(bit != 0);
  3790.       }

  3791.       /* Inspect the bin. It is likely to be non-empty */
  3792.       victim = last(bin);

  3793.       /* If a false alarm (empty bin), clear the bit. */
  3794.       if (victim == bin) {
  3795.     av->binmap[block] = map &= ~bit; /* Write through */
  3796.     bin = next_bin(bin);
  3797.     bit <<= 1;
  3798.       }

  3799.       else {
  3800.     size = chunksize(victim);

  3801.     /* We know the first chunk in this bin is big enough to use. */
  3802.     assert((unsigned long)(size) >= (unsigned long)(nb));

  3803.     remainder_size = size - nb;

  3804.     /* unlink */
  3805.     unlink(victim, bck, fwd);

  3806.     /* Exhaust */
  3807.     if (remainder_size < MINSIZE) {
  3808.      set_inuse_bit_at_offset(victim, size);
  3809.      if (av != &main_arena)
  3810.      victim->size |= NON_MAIN_ARENA;
  3811.     }

  3812.     /* Split */
  3813.     else {
  3814.      remainder = chunk_at_offset(victim, nb);

  3815.      /* We cannot assume the unsorted list is empty and therefore
  3816.      have to perform a complete insert here. */
  3817.      bck = unsorted_chunks(av);
  3818.      fwd = bck->fd;
  3819.      if (__builtin_expect (fwd->bk != bck, 0))
  3820.      {
  3821.      errstr = "malloc(): corrupted unsorted chunks 2";
  3822.      goto errout;
  3823.      }
  3824.      remainder->bk = bck;
  3825.      remainder->fd = fwd;
  3826.      bck->fd = remainder;
  3827.      fwd->bk = remainder;

  3828.      /* advertise as last remainder */
  3829.      if (in_smallbin_range(nb))
  3830.      av->last_remainder = remainder;
  3831.      if (!in_smallbin_range(remainder_size))
  3832.      {
  3833.      remainder->fd_nextsize = NULL;
  3834.      remainder->bk_nextsize = NULL;
  3835.      }
  3836.      set_head(victim, nb | PREV_INUSE |
  3837.          (av != &main_arena ? NON_MAIN_ARENA : 0));
  3838.      set_head(remainder, remainder_size | PREV_INUSE);
  3839.      set_foot(remainder, remainder_size);
  3840.     }
  3841.     check_malloced_chunk(av, victim, nb);
  3842.     void *p = chunk2mem(victim);
  3843.     if (__builtin_expect (perturb_byte, 0))
  3844.      alloc_perturb (p, bytes);
  3845.     return p;
  3846.       }
  3847.     }

  3848.   use_top:
  3849.     /*
  3850.       If large enough, split off the chunk bordering the end of memory
  3851.       (held in av->top). Note that this is in accord with the best-fit
  3852.       search rule. In effect, av->top is treated as larger (and thus
  3853.       less well fitting) than any other available chunk since it can
  3854.       be extended to be as large as necessary (up to system
  3855.       limitations).

  3856.       We require that av->top always exists (i.e., has size >=
  3857.       MINSIZE) after initialization, so if it would otherwise be
  3858.       exhausted by current request, it is replenished. (The main
  3859.       reason for ensuring it exists is that we may need MINSIZE space
  3860.       to put in fenceposts in sysmalloc.)
  3861.     */

  3862.     victim = av->top;
  3863.     size = chunksize(victim);

  3864.     if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
  3865.       remainder_size = size - nb;
  3866.       remainder = chunk_at_offset(victim, nb);
  3867.       av->top = remainder;
  3868.       set_head(victim, nb | PREV_INUSE |
  3869.      (av != &main_arena ? NON_MAIN_ARENA : 0));
  3870.       set_head(remainder, remainder_size | PREV_INUSE);

  3871.       check_malloced_chunk(av, victim, nb);
  3872.       void *p = chunk2mem(victim);
  3873.       if (__builtin_expect (perturb_byte, 0))
  3874.     alloc_perturb (p, bytes);
  3875.       return p;
  3876.     }

  3877. #ifdef ATOMIC_FASTBINS
  3878.     /* When we are using atomic ops to free fast chunks we can get
  3879.        here for all block sizes. */
  3880.     else if (have_fastchunks(av)) {
  3881.       malloc_consolidate(av);
  3882.       /* restore original bin index */
  3883.       if (in_smallbin_range(nb))
  3884.     idx = smallbin_index(nb);
  3885.       else
  3886.     idx = largebin_index(nb);
  3887.     }
  3888. #else
  3889.     /*
  3890.       If there is space available in fastbins, consolidate and retry,
  3891.       to possibly avoid expanding memory. This can occur only if nb is
  3892.       in smallbin range so we didn't consolidate upon entry.
  3893.     */

  3894.     else if (have_fastchunks(av)) {
  3895.       assert(in_smallbin_range(nb));
  3896.       malloc_consolidate(av);
  3897.       idx = smallbin_index(nb); /* restore original bin index */
  3898.     }
  3899. #endif

  3900.     /*
  3901.        Otherwise, relay to handle system-dependent cases
  3902.     */
  3903.     else {
  3904.       void *p = sYSMALLOc(nb, av);
  3905.       if (p != NULL && __builtin_expect (perturb_byte, 0))
  3906.     alloc_perturb (p, bytes);
  3907.       return p;
  3908.     }
  3909.   }
  3910. }

  3911. /*
  3912.   ------------------------------ free ------------------------------
  3913. */

  3914. static void
  3915. #ifdef ATOMIC_FASTBINS
  3916. _int_free(mstate av, mchunkptr p, int have_lock)
  3917. #else
  3918. _int_free(mstate av, mchunkptr p)
  3919. #endif
  3920. {
  3921.   INTERNAL_SIZE_T size; /* its size */
  3922.   mfastbinptr* fb; /* associated fastbin */
  3923.   mchunkptr nextchunk; /* next contiguous chunk */
  3924.   INTERNAL_SIZE_T nextsize; /* its size */
  3925.   int nextinuse; /* true if nextchunk is used */
  3926.   INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
  3927.   mchunkptr bck; /* misc temp for linking */
  3928.   mchunkptr fwd; /* misc temp for linking */

  3929.   const char *errstr = NULL;
  3930. #ifdef ATOMIC_FASTBINS
  3931.   int locked = 0;
  3932. #endif

  3933.   size = chunksize(p);

  3934.   /* Little security check which won't hurt performance: the
  3935.      allocator never wrapps around at the end of the address space.
  3936.      Therefore we can exclude some size values which might appear
  3937.      here by accident or by "design" from some intruder. */
  3938.   if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
  3939.       || __builtin_expect (misaligned_chunk (p), 0))
  3940.     {
  3941.       errstr = "free(): invalid pointer";
  3942.     errout:
  3943. #ifdef ATOMIC_FASTBINS
  3944.       if (! have_lock && locked)
  3945.     (void)mutex_unlock(&av->mutex);
  3946. #endif
  3947.       malloc_printerr (check_action, errstr, chunk2mem(p));
  3948.       return;
  3949.     }
  3950.   /* We know that each chunk is at least MINSIZE bytes in size. */
  3951.   if (__builtin_expect (size < MINSIZE, 0))
  3952.     {
  3953.       errstr = "free(): invalid size";
  3954.       goto errout;
  3955.     }

  3956.   check_inuse_chunk(av, p);

  3957.   /*
  3958.     If eligible, place chunk on a fastbin so it can be found
  3959.     and used quickly in malloc.
  3960.   */

  3961.   if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())

  3962. #if TRIM_FASTBINS
  3963.       /*
  3964.     If TRIM_FASTBINS set, don't place chunks
  3965.     bordering top into fastbins
  3966.       */
  3967.       && (chunk_at_offset(p, size) != av->top)
  3968. #endif
  3969.       ) {

  3970.     if (__builtin_expect (chunk_at_offset (p, size)->size <= 2 * SIZE_SZ, 0)
  3971.     || __builtin_expect (chunksize (chunk_at_offset (p, size))
  3972.              >= av->system_mem, 0))
  3973.       {
  3974. #ifdef ATOMIC_FASTBINS
  3975.     /* We might not have a lock at this point and concurrent modifications
  3976.      of system_mem might have let to a false positive. Redo the test
  3977.      after getting the lock. */
  3978.     if (have_lock
  3979.      || ({ assert (locked == 0);
  3980.          mutex_lock(&av->mutex);
  3981.          locked = 1;
  3982.          chunk_at_offset (p, size)->size <= 2 * SIZE_SZ
  3983.          || chunksize (chunk_at_offset (p, size)) >= av->system_mem;
  3984.      }))
  3985. #endif
  3986.      {
  3987.      errstr = "free(): invalid next size (fast)";
  3988.      goto errout;
  3989.      }
  3990. #ifdef ATOMIC_FASTBINS
  3991.     if (! have_lock)
  3992.      {
  3993.      (void)mutex_unlock(&av->mutex);
  3994.      locked = 0;
  3995.      }
  3996. #endif
  3997.       }

  3998.     if (__builtin_expect (perturb_byte, 0))
  3999.       free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);

  4000.     set_fastchunks(av);
  4001.     unsigned int idx = fastbin_index(size);
  4002.     fb = &fastbin (av, idx);

  4003. #ifdef ATOMIC_FASTBINS
  4004.     mchunkptr fd;
  4005.     mchunkptr old = *fb;
  4006.     unsigned int old_idx = ~0u;
  4007.     do
  4008.       {
  4009.     /* Another simple check: make sure the top of the bin is not the
  4010.      record we are going to add (i.e., double free). */
  4011.     if (__builtin_expect (old == p, 0))
  4012.      {
  4013.      errstr = "double free or corruption (fasttop)";
  4014.      goto errout;
  4015.      }
  4016.     if (old != NULL)
  4017.      old_idx = fastbin_index(chunksize(old));
  4018.     p->fd = fd = old;
  4019.       }
  4020.     while ((old = catomic_compare_and_exchange_val_rel (fb, p, fd)) != fd);

  4021.     if (fd != NULL && __builtin_expect (old_idx != idx, 0))
  4022.       {
  4023.     errstr = "invalid fastbin entry (free)";
  4024.     goto errout;
  4025.       }
  4026. #else
  4027.     /* Another simple check: make sure the top of the bin is not the
  4028.        record we are going to add (i.e., double free). */
  4029.     if (__builtin_expect (*fb == p, 0))
  4030.       {
  4031.     errstr = "double free or corruption (fasttop)";
  4032.     goto errout;
  4033.       }
  4034.     if (*fb != NULL
  4035.     && __builtin_expect (fastbin_index(chunksize(*fb)) != idx, 0))
  4036.       {
  4037.     errstr = "invalid fastbin entry (free)";
  4038.     goto errout;
  4039.       }

  4040.     p->fd = *fb;
  4041.     *fb = p;
  4042. #endif
  4043.   }

  4044.   /*
  4045.     Consolidate other non-mmapped chunks as they arrive.
  4046.   */

  4047.   else if (!chunk_is_mmapped(p)) {
  4048. #ifdef ATOMIC_FASTBINS
  4049.     if (! have_lock) {
  4050. # if THREAD_STATS
  4051.       if(!mutex_trylock(&av->mutex))
  4052.     ++(av->stat_lock_direct);
  4053.       else {
  4054.     (void)mutex_lock(&av->mutex);
  4055.     ++(av->stat_lock_wait);
  4056.       }
  4057. # else
  4058.       (void)mutex_lock(&av->mutex);
  4059. # endif
  4060.       locked = 1;
  4061.     }
  4062. #endif

  4063.     nextchunk = chunk_at_offset(p, size);

  4064.     /* Lightweight tests: check whether the block is already the
  4065.        top block. */
  4066.     if (__builtin_expect (p == av->top, 0))
  4067.       {
  4068.     errstr = "double free or corruption (top)";
  4069.     goto errout;
  4070.       }
  4071.     /* Or whether the next chunk is beyond the boundaries of the arena. */
  4072.     if (__builtin_expect (contiguous (av)
  4073.              && (char *) nextchunk
  4074.              >= ((char *) av->top + chunksize(av->top)), 0))
  4075.       {
  4076.     errstr = "double free or corruption (out)";
  4077.     goto errout;
  4078.       }
  4079.     /* Or whether the block is actually not marked used. */
  4080.     if (__builtin_expect (!prev_inuse(nextchunk), 0))
  4081.       {
  4082.     errstr = "double free or corruption (!prev)";
  4083.     goto errout;
  4084.       }

  4085.     nextsize = chunksize(nextchunk);
  4086.     if (__builtin_expect (nextchunk->size <= 2 * SIZE_SZ, 0)
  4087.     || __builtin_expect (nextsize >= av->system_mem, 0))
  4088.       {
  4089.     errstr = "free(): invalid next size (normal)";
  4090.     goto errout;
  4091.       }

  4092.     if (__builtin_expect (perturb_byte, 0))
  4093.       free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);

  4094.     /* consolidate backward */
  4095.     if (!prev_inuse(p)) {
  4096.       prevsize = p->prev_size;
  4097.       size += prevsize;
  4098.       p = chunk_at_offset(p, -((long) prevsize));
  4099.       unlink(p, bck, fwd);
  4100.     }

  4101.     if (nextchunk != av->top) {
  4102.       /* get and clear inuse bit */
  4103.       nextinuse = inuse_bit_at_offset(nextchunk, nextsize);

  4104.       /* consolidate forward */
  4105.       if (!nextinuse) {
  4106.     unlink(nextchunk, bck, fwd);
  4107.     size += nextsize;
  4108.       } else
  4109.     clear_inuse_bit_at_offset(nextchunk, 0);

  4110.       /*
  4111.     Place the chunk in unsorted chunk list. Chunks are
  4112.     not placed into regular bins until after they have
  4113.     been given one chance to be used in malloc.
  4114.       */

  4115.       bck = unsorted_chunks(av);
  4116.       fwd = bck->fd;
  4117.       if (__builtin_expect (fwd->bk != bck, 0))
  4118.     {
  4119.      errstr = "free(): corrupted unsorted chunks";
  4120.      goto errout;
  4121.     }
  4122.       p->fd = fwd;
  4123.       p->bk = bck;
  4124.       if (!in_smallbin_range(size))
  4125.     {
  4126.      p->fd_nextsize = NULL;
  4127.      p->bk_nextsize = NULL;
  4128.     }
  4129.       bck->fd = p;
  4130.       fwd->bk = p;

  4131.       set_head(p, size | PREV_INUSE);
  4132.       set_foot(p, size);

  4133.       check_free_chunk(av, p);
  4134.     }

  4135.     /*
  4136.       If the chunk borders the current high end of memory,
  4137.       consolidate into top
  4138.     */

  4139.     else {
  4140.       size += nextsize;
  4141.       set_head(p, size | PREV_INUSE);
  4142.       av->top = p;
  4143.       check_chunk(av, p);
  4144.     }

  4145.     /*
  4146.       If freeing a large space, consolidate possibly-surrounding
  4147.       chunks. Then, if the total unused topmost memory exceeds trim
  4148.       threshold, ask malloc_trim to reduce top.

  4149.       Unless max_fast is 0, we don't know if there are fastbins
  4150.       bordering top, so we cannot tell for sure whether threshold
  4151.       has been reached unless fastbins are consolidated. But we
  4152.       don't want to consolidate on each free. As a compromise,
  4153.       consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
  4154.       is reached.
  4155.     */

  4156.     if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
  4157.       if (have_fastchunks(av))
  4158.     malloc_consolidate(av);

  4159.       if (av == &main_arena) {
  4160. #ifndef MORECORE_CANNOT_TRIM
  4161.     if ((unsigned long)(chunksize(av->top)) >=
  4162.      (unsigned long)(mp_.trim_threshold))
  4163.      sYSTRIm(mp_.top_pad, av);
  4164. #endif
  4165.       } else {
  4166.     /* Always try heap_trim(), even if the top chunk is not
  4167.      large, because the corresponding heap might go away. */
  4168.     heap_info *heap = heap_for_ptr(top(av));

  4169.     assert(heap->ar_ptr == av);
  4170.     heap_trim(heap, mp_.top_pad);
  4171.       }
  4172.     }

  4173. #ifdef ATOMIC_FASTBINS
  4174.     if (! have_lock) {
  4175.       assert (locked);
  4176.       (void)mutex_unlock(&av->mutex);
  4177.     }
  4178. #endif
  4179.   }
  4180.   /*
  4181.     If the chunk was allocated via mmap, release via munmap(). Note
  4182.     that if HAVE_MMAP is false but chunk_is_mmapped is true, then
  4183.     user must have overwritten memory. There's nothing we can do to
  4184.     catch this error unless MALLOC_DEBUG is set, in which case
  4185.     check_inuse_chunk (above) will have triggered error.
  4186.   */

  4187.   else {
  4188. #if HAVE_MMAP
  4189.     munmap_chunk (p);
  4190. #endif
  4191.   }
  4192. }

  4193. /*
  4194.   ------------------------- malloc_consolidate -------------------------

  4195.   malloc_consolidate is a specialized version of free() that tears
  4196.   down chunks held in fastbins. Free itself cannot be used for this
  4197.   purpose since, among other things, it might place chunks back onto
  4198.   fastbins. So, instead, we need to use a minor variant of the same
  4199.   code.

  4200.   Also, because this routine needs to be called the first time through
  4201.   malloc anyway, it turns out to be the perfect place to trigger
  4202.   initialization code.
  4203. */

  4204. #if __STD_C
  4205. static void malloc_consolidate(mstate av)
  4206. #else
  4207. static void malloc_consolidate(av) mstate av;
  4208. #endif
  4209. {
  4210.   mfastbinptr* fb; /* current fastbin being consolidated */
  4211.   mfastbinptr* maxfb; /* last fastbin (for loop control) */
  4212.   mchunkptr p; /* current chunk being consolidated */
  4213.   mchunkptr nextp; /* next chunk to consolidate */
  4214.   mchunkptr unsorted_bin; /* bin header */
  4215.   mchunkptr first_unsorted; /* chunk to link to */

  4216.   /* These have same use as in free() */
  4217.   mchunkptr nextchunk;
  4218.   INTERNAL_SIZE_T size;
  4219.   INTERNAL_SIZE_T nextsize;
  4220.   INTERNAL_SIZE_T prevsize;
  4221.   int nextinuse;
  4222.   mchunkptr bck;
  4223.   mchunkptr fwd;

  4224.   /*
  4225.     If max_fast is 0, we know that av hasn't
  4226.     yet been initialized, in which case do so below
  4227.   */

  4228.   if (get_max_fast () != 0) {
  4229.     clear_fastchunks(av);

  4230.     unsorted_bin = unsorted_chunks(av);

  4231.     /*
  4232.       Remove each chunk from fast bin and consolidate it, placing it
  4233.       then in unsorted bin. Among other reasons for doing this,
  4234.       placing in unsorted bin avoids needing to calculate actual bins
  4235.       until malloc is sure that chunks aren't immediately going to be
  4236.       reused anyway.
  4237.     */

  4238. #if 0
  4239.     /* It is wrong to limit the fast bins to search using get_max_fast
  4240.        because, except for the main arena, all the others might have
  4241.        blocks in the high fast bins. It's not worth it anyway, just
  4242.        search all bins all the time. */
  4243.     maxfb = &fastbin (av, fastbin_index(get_max_fast ()));
  4244. #else
  4245.     maxfb = &fastbin (av, NFASTBINS - 1);
  4246. #endif
  4247.     fb = &fastbin (av, 0);
  4248.     do {
  4249. #ifdef ATOMIC_FASTBINS
  4250.       p = atomic_exchange_acq (fb, 0);
  4251. #else
  4252.       p = *fb;
  4253. #endif
  4254.       if (p != 0) {
  4255. #ifndef ATOMIC_FASTBINS
  4256.     *fb = 0;
  4257. #endif
  4258.     do {
  4259.      check_inuse_chunk(av, p);
  4260.      nextp = p->fd;

  4261.      /* Slightly streamlined version of consolidation code in free() */
  4262.      size = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
  4263.      nextchunk = chunk_at_offset(p, size);
  4264.      nextsize = chunksize(nextchunk);

  4265.      if (!prev_inuse(p)) {
  4266.      prevsize = p->prev_size;
  4267.      size += prevsize;
  4268.      p = chunk_at_offset(p, -((long) prevsize));
  4269.      unlink(p, bck, fwd);
  4270.      }

  4271.      if (nextchunk != av->top) {
  4272.      nextinuse = inuse_bit_at_offset(nextchunk, nextsize);

  4273.      if (!nextinuse) {
  4274.      size += nextsize;
  4275.      unlink(nextchunk, bck, fwd);
  4276.      } else
  4277.      clear_inuse_bit_at_offset(nextchunk, 0);

  4278.      first_unsorted = unsorted_bin->fd;
  4279.      unsorted_bin->fd = p;
  4280.      first_unsorted->bk = p;

  4281.      if (!in_smallbin_range (size)) {
  4282.      p->fd_nextsize = NULL;
  4283.      p->bk_nextsize = NULL;
  4284.      }

  4285.      set_head(p, size | PREV_INUSE);
  4286.      p->bk = unsorted_bin;
  4287.      p->fd = first_unsorted;
  4288.      set_foot(p, size);
  4289.      }

  4290.      else {
  4291.      size += nextsize;
  4292.      set_head(p, size | PREV_INUSE);
  4293.      av->top = p;
  4294.      }

  4295.     } while ( (p = nextp) != 0);

  4296.       }
  4297.     } while (fb++ != maxfb);
  4298.   }
  4299.   else {
  4300.     malloc_init_state(av);
  4301.     check_malloc_state(av);
  4302.   }
  4303. }

  4304. /*
  4305.   ------------------------------ realloc ------------------------------
  4306. */

  4307. Void_t*
  4308. _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
  4309.      INTERNAL_SIZE_T nb)
  4310. {
  4311.   mchunkptr newp; /* chunk to return */
  4312.   INTERNAL_SIZE_T newsize; /* its size */
  4313.   Void_t* newmem; /* corresponding user mem */

  4314.   mchunkptr next; /* next contiguous chunk after oldp */

  4315.   mchunkptr remainder; /* extra space at end of newp */
  4316.   unsigned long remainder_size; /* its size */

  4317.   mchunkptr bck; /* misc temp for linking */
  4318.   mchunkptr fwd; /* misc temp for linking */

  4319.   unsigned long copysize; /* bytes to copy */
  4320.   unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
  4321.   INTERNAL_SIZE_T* s; /* copy source */
  4322.   INTERNAL_SIZE_T* d; /* copy destination */

  4323.   const char *errstr = NULL;

  4324.   /* oldmem size */
  4325.   if (__builtin_expect (oldp->size <= 2 * SIZE_SZ, 0)
  4326.       || __builtin_expect (oldsize >= av->system_mem, 0))
  4327.     {
  4328.       errstr = "realloc(): invalid old size";
  4329.     errout:
  4330.       malloc_printerr (check_action, errstr, chunk2mem(oldp));
  4331.       return NULL;
  4332.     }

  4333.   check_inuse_chunk(av, oldp);

  4334.   /* All callers already filter out mmap'ed chunks. */
  4335. #if 0
  4336.   if (!chunk_is_mmapped(oldp))
  4337. #else
  4338.   assert (!chunk_is_mmapped(oldp));
  4339. #endif
  4340.   {

  4341.     next = chunk_at_offset(oldp, oldsize);
  4342.     INTERNAL_SIZE_T nextsize = chunksize(next);
  4343.     if (__builtin_expect (next->size <= 2 * SIZE_SZ, 0)
  4344.     || __builtin_expect (nextsize >= av->system_mem, 0))
  4345.       {
  4346.     errstr = "realloc(): invalid next size";
  4347.     goto errout;
  4348.       }

  4349.     if ((unsigned long)(oldsize) >= (unsigned long)(nb)) {
  4350.       /* already big enough; split below */
  4351.       newp = oldp;
  4352.       newsize = oldsize;
  4353.     }

  4354.     else {
  4355.       /* Try to expand forward into top */
  4356.       if (next == av->top &&
  4357.      (unsigned long)(newsize = oldsize + nextsize) >=
  4358.      (unsigned long)(nb + MINSIZE)) {
  4359.     set_head_size(oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
  4360.     av->top = chunk_at_offset(oldp, nb);
  4361.     set_head(av->top, (newsize - nb) | PREV_INUSE);
  4362.     check_inuse_chunk(av, oldp);
  4363.     return chunk2mem(oldp);
  4364.       }

  4365.       /* Try to expand forward into next chunk; split off remainder below */
  4366.       else if (next != av->top &&
  4367.      !inuse(next) &&
  4368.      (unsigned long)(newsize = oldsize + nextsize) >=
  4369.      (unsigned long)(nb)) {
  4370.     newp = oldp;
  4371.     unlink(next, bck, fwd);
  4372.       }

  4373.       /* allocate, copy, free */
  4374.       else {
  4375.     newmem = _int_malloc(av, nb - MALLOC_ALIGN_MASK);
  4376.     if (newmem == 0)
  4377.      return 0; /* propagate failure */

  4378.     newp = mem2chunk(newmem);
  4379.     newsize = chunksize(newp);

  4380.     /*
  4381.      Avoid copy if newp is next chunk after oldp.
  4382.     */
  4383.     if (newp == next) {
  4384.      newsize += oldsize;
  4385.      newp = oldp;
  4386.     }
  4387.     else {
  4388.      /*
  4389.      Unroll copy of <= 36 bytes (72 if 8byte sizes)
  4390.      We know that contents have an odd number of
  4391.      INTERNAL_SIZE_T-sized words; minimally 3.
  4392.      */

  4393.      copysize = oldsize - SIZE_SZ;
  4394.      s = (INTERNAL_SIZE_T*)(chunk2mem(oldp));
  4395.      d = (INTERNAL_SIZE_T*)(newmem);
  4396.      ncopies = copysize / sizeof(INTERNAL_SIZE_T);
  4397.      assert(ncopies >= 3);

  4398.      if (ncopies > 9)
  4399.      MALLOC_COPY(d, s, copysize);

  4400.      else {
  4401.      *(d+0) = *(s+0);
  4402.      *(d+1) = *(s+1);
  4403.      *(d+2) = *(s+2);
  4404.      if (ncopies > 4) {
  4405.      *(d+3) = *(s+3);
  4406.      *(d+4) = *(s+4);
  4407.      if (ncopies > 6) {
  4408.         *(d+5) = *(s+5);
  4409.         *(d+6) = *(s+6);
  4410.         if (ncopies > 8) {
  4411.          *(d+7) = *(s+7);
  4412.          *(d+8) = *(s+8);
  4413.         }
  4414.      }
  4415.      }
  4416.      }

  4417. #ifdef ATOMIC_FASTBINS
  4418.      _int_free(av, oldp, 1);
  4419. #else
  4420.      _int_free(av, oldp);
  4421. #endif
  4422.      check_inuse_chunk(av, newp);
  4423.      return chunk2mem(newp);
  4424.     }
  4425.       }
  4426.     }

  4427.     /* If possible, free extra space in old or extended chunk */

  4428.     assert((unsigned long)(newsize) >= (unsigned long)(nb));

  4429.     remainder_size = newsize - nb;

  4430.     if (remainder_size < MINSIZE) { /* not enough extra to split off */
  4431.       set_head_size(newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
  4432.       set_inuse_bit_at_offset(newp, newsize);
  4433.     }
  4434.     else { /* split remainder */
  4435.       remainder = chunk_at_offset(newp, nb);
  4436.       set_head_size(newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
  4437.       set_head(remainder, remainder_size | PREV_INUSE |
  4438.      (av != &main_arena ? NON_MAIN_ARENA : 0));
  4439.       /* Mark remainder as inuse so free() won't complain */
  4440.       set_inuse_bit_at_offset(remainder, remainder_size);
  4441. #ifdef ATOMIC_FASTBINS
  4442.       _int_free(av, remainder, 1);
  4443. #else
  4444.       _int_free(av, remainder);
  4445. #endif
  4446.     }

  4447.     check_inuse_chunk(av, newp);
  4448.     return chunk2mem(newp);
  4449.   }

  4450. #if 0
  4451.   /*
  4452.     Handle mmap cases
  4453.   */

  4454.   else {
  4455. #if HAVE_MMAP

  4456. #if HAVE_MREMAP
  4457.     INTERNAL_SIZE_T offset = oldp->prev_size;
  4458.     size_t pagemask = mp_.pagesize - 1;
  4459.     char *cp;
  4460.     unsigned long sum;

  4461.     /* Note the extra SIZE_SZ overhead */
  4462.     newsize = (nb + offset + SIZE_SZ + pagemask) & ~pagemask;

  4463.     /* don't need to remap if still within same page */
  4464.     if (oldsize == newsize - offset)
  4465.       return chunk2mem(oldp);

  4466.     cp = (char*)mremap((char*)oldp - offset, oldsize + offset, newsize, 1);

  4467.     if (cp != MAP_FAILED) {

  4468.       newp = (mchunkptr)(cp + offset);
  4469.       set_head(newp, (newsize - offset)|IS_MMAPPED);

  4470.       assert(aligned_OK(chunk2mem(newp)));
  4471.       assert((newp->prev_size == offset));

  4472.       /* update statistics */
  4473.       sum = mp_.mmapped_mem += newsize - oldsize;
  4474.       if (sum > (unsigned long)(mp_.max_mmapped_mem))
  4475.     mp_.max_mmapped_mem = sum;
  4476. #ifdef NO_THREADS
  4477.       sum += main_arena.system_mem;
  4478.       if (sum > (unsigned long)(mp_.max_total_mem))
  4479.     mp_.max_total_mem = sum;
  4480. #endif

  4481.       return chunk2mem(newp);
  4482.     }
  4483. #endif

  4484.     /* Note the extra SIZE_SZ overhead. */
  4485.     if ((unsigned long)(oldsize) >= (unsigned long)(nb + SIZE_SZ))
  4486.       newmem = chunk2mem(oldp); /* do nothing */
  4487.     else {
  4488.       /* Must alloc, copy, free. */
  4489.       newmem = _int_malloc(av, nb - MALLOC_ALIGN_MASK);
  4490.       if (newmem != 0) {
  4491.     MALLOC_COPY(newmem, chunk2mem(oldp), oldsize - 2*SIZE_SZ);
  4492. #ifdef ATOMIC_FASTBINS
  4493.     _int_free(av, oldp, 1);
  4494. #else
  4495.     _int_free(av, oldp);
  4496. #endif
  4497.       }
  4498.     }
  4499.     return newmem;

  4500. #else
  4501.     /* If !HAVE_MMAP, but chunk_is_mmapped, user must have overwritten mem */
  4502.     check_malloc_state(av);
  4503.     MALLOC_FAILURE_ACTION;
  4504.     return 0;
  4505. #endif
  4506.   }
  4507. #endif
  4508. }

  4509. /*
  4510.   ------------------------------ memalign ------------------------------
  4511. */

  4512. static Void_t*
  4513. _int_memalign(mstate av, size_t alignment, size_t bytes)
  4514. {
  4515.   INTERNAL_SIZE_T nb; /* padded request size */
  4516.   char* m; /* memory returned by malloc call */
  4517.   mchunkptr p; /* corresponding chunk */
  4518.   char* brk; /* alignment point within p */
  4519.   mchunkptr newp; /* chunk to return */
  4520.   INTERNAL_SIZE_T newsize; /* its size */
  4521.   INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
  4522.   mchunkptr remainder; /* spare room at end to split off */
  4523.   unsigned long remainder_size; /* its size */
  4524.   INTERNAL_SIZE_T size;

  4525.   /* If need less alignment than we give anyway, just relay to malloc */

  4526.   if (alignment <= MALLOC_ALIGNMENT) return _int_malloc(av, bytes);

  4527.   /* Otherwise, ensure that it is at least a minimum chunk size */

  4528.   if (alignment < MINSIZE) alignment = MINSIZE;

  4529.   /* Make sure alignment is power of 2 (in case MINSIZE is not). */
  4530.   if ((alignment & (alignment - 1)) != 0) {
  4531.     size_t a = MALLOC_ALIGNMENT * 2;
  4532.     while ((unsigned long)a < (unsigned long)alignment) a <<= 1;
  4533.     alignment = a;
  4534.   }

  4535.   checked_request2size(bytes, nb);

  4536.   /*
  4537.     Strategy: find a spot within that chunk that meets the alignment
  4538.     request, and then possibly free the leading and trailing space.
  4539.   */


  4540.   /* Call malloc with worst case padding to hit alignment. */

  4541.   m = (char*)(_int_malloc(av, nb + alignment + MINSIZE));

  4542.   if (m == 0) return 0; /* propagate failure */

  4543.   p = mem2chunk(m);

  4544.   if ((((unsigned long)(m)) % alignment) != 0) { /* misaligned */

  4545.     /*
  4546.       Find an aligned spot inside chunk. Since we need to give back
  4547.       leading space in a chunk of at least MINSIZE, if the first
  4548.       calculation places us at a spot with less than MINSIZE leader,
  4549.       we can move to the next aligned spot -- we've allocated enough
  4550.       total room so that this is always possible.
  4551.     */

  4552.     brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) &
  4553.              -((signed long) alignment));
  4554.     if ((unsigned long)(brk - (char*)(p)) < MINSIZE)
  4555.       brk += alignment;

  4556.     newp = (mchunkptr)brk;
  4557.     leadsize = brk - (char*)(p);
  4558.     newsize = chunksize(p) - leadsize;

  4559.     /* For mmapped chunks, just adjust offset */
  4560.     if (chunk_is_mmapped(p)) {
  4561.       newp->prev_size = p->prev_size + leadsize;
  4562.       set_head(newp, newsize|IS_MMAPPED);
  4563.       return chunk2mem(newp);
  4564.     }

  4565.     /* Otherwise, give back leader, use the rest */
  4566.     set_head(newp, newsize | PREV_INUSE |
  4567.      (av != &main_arena ? NON_MAIN_ARENA : 0));
  4568.     set_inuse_bit_at_offset(newp, newsize);
  4569.     set_head_size(p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
  4570. #ifdef ATOMIC_FASTBINS
  4571.     _int_free(av, p, 1);
  4572. #else
  4573.     _int_free(av, p);
  4574. #endif
  4575.     p = newp;

  4576.     assert (newsize >= nb &&
  4577.      (((unsigned long)(chunk2mem(p))) % alignment) == 0);
  4578.   }

  4579.   /* Also give back spare room at the end */
  4580.   if (!chunk_is_mmapped(p)) {
  4581.     size = chunksize(p);
  4582.     if ((unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
  4583.       remainder_size = size - nb;
  4584.       remainder = chunk_at_offset(p, nb);
  4585.       set_head(remainder, remainder_size | PREV_INUSE |
  4586.      (av != &main_arena ? NON_MAIN_ARENA : 0));
  4587.       set_head_size(p, nb);
  4588. #ifdef ATOMIC_FASTBINS
  4589.       _int_free(av, remainder, 1);
  4590. #else
  4591.       _int_free(av, remainder);
  4592. #endif
  4593.     }
  4594.   }

  4595.   check_inuse_chunk(av, p);
  4596.   return chunk2mem(p);
  4597. }

  4598. #if 0
  4599. /*
  4600.   ------------------------------ calloc ------------------------------
  4601. */

  4602. #if __STD_C
  4603. Void_t* cALLOc(size_t n_elements, size_t elem_size)
  4604. #else
  4605. Void_t* cALLOc(n_elements, elem_size) size_t n_elements; size_t elem_size;
  4606. #endif
  4607. {
  4608.   mchunkptr p;
  4609.   unsigned long clearsize;
  4610.   unsigned long nclears;
  4611.   INTERNAL_SIZE_T* d;

  4612.   Void_t* mem = mALLOc(n_elements * elem_size);

  4613.   if (mem != 0) {
  4614.     p = mem2chunk(mem);

  4615. #if MMAP_CLEARS
  4616.     if (!chunk_is_mmapped(p)) /* don't need to clear mmapped space */
  4617. #endif
  4618.     {
  4619.       /*
  4620.     Unroll clear of <= 36 bytes (72 if 8byte sizes)
  4621.     We know that contents have an odd number of
  4622.     INTERNAL_SIZE_T-sized words; minimally 3.
  4623.       */

  4624.       d = (INTERNAL_SIZE_T*)mem;
  4625.       clearsize = chunksize(p) - SIZE_SZ;
  4626.       nclears = clearsize / sizeof(INTERNAL_SIZE_T);
  4627.       assert(nclears >= 3);

  4628.       if (nclears > 9)
  4629.     MALLOC_ZERO(d, clearsize);

  4630.       else {
  4631.     *(d+0) = 0;
  4632.     *(d+1) = 0;
  4633.     *(d+2) = 0;
  4634.     if (nclears > 4) {
  4635.      *(d+3) = 0;
  4636.      *(d+4) = 0;
  4637.      if (nclears > 6) {
  4638.      *(d+5) = 0;
  4639.      *(d+6) = 0;
  4640.      if (nclears > 8) {
  4641.      *(d+7) = 0;
  4642.      *(d+8) = 0;
  4643.      }
  4644.      }
  4645.     }
  4646.       }
  4647.     }
  4648.   }
  4649.   return mem;
  4650. }
  4651. #endif /* 0 */

  4652. #ifndef _LIBC
  4653. /*
  4654.   ------------------------- independent_calloc -------------------------
  4655. */

  4656. Void_t**
  4657. #if __STD_C
  4658. _int_icalloc(mstate av, size_t n_elements, size_t elem_size, Void_t* chunks[])
  4659. #else
  4660. _int_icalloc(av, n_elements, elem_size, chunks)
  4661. mstate av; size_t n_elements; size_t elem_size; Void_t* chunks[];
  4662. #endif
  4663. {
  4664.   size_t sz = elem_size; /* serves as 1-element array */
  4665.   /* opts arg of 3 means all elements are same size, and should be cleared */
  4666.   return iALLOc(av, n_elements, &sz, 3, chunks);
  4667. }

  4668. /*
  4669.   ------------------------- independent_comalloc -------------------------
  4670. */

  4671. Void_t**
  4672. #if __STD_C
  4673. _int_icomalloc(mstate av, size_t n_elements, size_t sizes[], Void_t* chunks[])
  4674. #else
  4675. _int_icomalloc(av, n_elements, sizes, chunks)
  4676. mstate av; size_t n_elements; size_t sizes[]; Void_t* chunks[];
  4677. #endif
  4678. {
  4679.   return iALLOc(av, n_elements, sizes, 0, chunks);
  4680. }


  4681. /*
  4682.   ------------------------------ ialloc ------------------------------
  4683.   ialloc provides common support for independent_X routines, handling all of
  4684.   the combinations that can result.

  4685.   The opts arg has:
  4686.     bit 0 set if all elements are same size (using sizes[0])
  4687.     bit 1 set if elements should be zeroed
  4688. */


  4689. static Void_t**
  4690. #if __STD_C
  4691. iALLOc(mstate av, size_t n_elements, size_t* sizes, int opts, Void_t* chunks[])
  4692. #else
  4693. iALLOc(av, n_elements, sizes, opts, chunks)
  4694. mstate av; size_t n_elements; size_t* sizes; int opts; Void_t* chunks[];
  4695. #endif
  4696. {
  4697.   INTERNAL_SIZE_T element_size; /* chunksize of each element, if all same */
  4698.   INTERNAL_SIZE_T contents_size; /* total size of elements */
  4699.   INTERNAL_SIZE_T array_size; /* request size of pointer array */
  4700.   Void_t* mem; /* malloced aggregate space */
  4701.   mchunkptr p; /* corresponding chunk */
  4702.   INTERNAL_SIZE_T remainder_size; /* remaining bytes while splitting */
  4703.   Void_t** marray; /* either "chunks" or malloced ptr array */
  4704.   mchunkptr array_chunk; /* chunk for malloced ptr array */
  4705.   int mmx; /* to disable mmap */
  4706.   INTERNAL_SIZE_T size;
  4707.   INTERNAL_SIZE_T size_flags;
  4708.   size_t i;

  4709.   /* Ensure initialization/consolidation */
  4710.   if (have_fastchunks(av)) malloc_consolidate(av);

  4711.   /* compute array length, if needed */
  4712.   if (chunks != 0) {
  4713.     if (n_elements == 0)
  4714.       return chunks; /* nothing to do */
  4715.     marray = chunks;
  4716.     array_size = 0;
  4717.   }
  4718.   else {
  4719.     /* if empty req, must still return chunk representing empty array */
  4720.     if (n_elements == 0)
  4721.       return (Void_t**) _int_malloc(av, 0);
  4722.     marray = 0;
  4723.     array_size = request2size(n_elements * (sizeof(Void_t*)));
  4724.   }

  4725.