src/stdlib/SDL_malloc.c
author Sam Lantinga <slouken@libsdl.org>
Mon, 16 Jul 2007 00:08:35 +0000
changeset 2203 fca1cdc673b2
parent 2196 2aee80dab68a
child 2210 1de324fce4e8
permissions -rw-r--r--
Fixed bug #428

This fix is overkill, but approved by Doug Lea, and he'll be releasing a
new version of his malloc.c sometime next month.
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997-2006 Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Lesser General Public
     7     License as published by the Free Software Foundation; either
     8     version 2.1 of the License, or (at your option) any later version.
     9 
    10     This 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 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 */
    22 #include "SDL_config.h"
    23 
    24 /* This file contains portable memory management functions for SDL */
    25 
    26 #include "SDL_stdinc.h"
    27 
    28 #ifndef HAVE_MALLOC
    29 
    30 #define LACKS_SYS_TYPES_H
    31 #define LACKS_STDIO_H
    32 #define LACKS_STRINGS_H
    33 #define LACKS_STRING_H
    34 #define LACKS_STDLIB_H
    35 #define ABORT
    36 
    37 /*
    38   This is a version (aka dlmalloc) of malloc/free/realloc written by
    39   Doug Lea and released to the public domain, as explained at
    40   http://creativecommons.org/licenses/publicdomain.  Send questions,
    41   comments, complaints, performance data, etc to dl@cs.oswego.edu
    42 
    43 * Version 2.8.3 Thu Sep 22 11:16:15 2005  Doug Lea  (dl at gee)
    44 
    45    Note: There may be an updated version of this malloc obtainable at
    46            ftp://gee.cs.oswego.edu/pub/misc/malloc.c
    47          Check before installing!
    48 
    49 * Quickstart
    50 
    51   This library is all in one file to simplify the most common usage:
    52   ftp it, compile it (-O3), and link it into another program. All of
    53   the compile-time options default to reasonable values for use on
    54   most platforms.  You might later want to step through various
    55   compile-time and dynamic tuning options.
    56 
    57   For convenience, an include file for code using this malloc is at:
    58      ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
    59   You don't really need this .h file unless you call functions not
    60   defined in your system include files.  The .h file contains only the
    61   excerpts from this file needed for using this malloc on ANSI C/C++
    62   systems, so long as you haven't changed compile-time options about
    63   naming and tuning parameters.  If you do, then you can create your
    64   own malloc.h that does include all settings by cutting at the point
    65   indicated below. Note that you may already by default be using a C
    66   library containing a malloc that is based on some version of this
    67   malloc (for example in linux). You might still want to use the one
    68   in this file to customize settings or to avoid overheads associated
    69   with library versions.
    70 
    71 * Vital statistics:
    72 
    73   Supported pointer/size_t representation:       4 or 8 bytes
    74        size_t MUST be an unsigned type of the same width as
    75        pointers. (If you are using an ancient system that declares
    76        size_t as a signed type, or need it to be a different width
    77        than pointers, you can use a previous release of this malloc
    78        (e.g. 2.7.2) supporting these.)
    79 
    80   Alignment:                                     8 bytes (default)
    81        This suffices for nearly all current machines and C compilers.
    82        However, you can define MALLOC_ALIGNMENT to be wider than this
    83        if necessary (up to 128bytes), at the expense of using more space.
    84 
    85   Minimum overhead per allocated chunk:   4 or  8 bytes (if 4byte sizes)
    86                                           8 or 16 bytes (if 8byte sizes)
    87        Each malloced chunk has a hidden word of overhead holding size
    88        and status information, and additional cross-check word
    89        if FOOTERS is defined.
    90 
    91   Minimum allocated size: 4-byte ptrs:  16 bytes    (including overhead)
    92                           8-byte ptrs:  32 bytes    (including overhead)
    93 
    94        Even a request for zero bytes (i.e., malloc(0)) returns a
    95        pointer to something of the minimum allocatable size.
    96        The maximum overhead wastage (i.e., number of extra bytes
    97        allocated than were requested in malloc) is less than or equal
    98        to the minimum size, except for requests >= mmap_threshold that
    99        are serviced via mmap(), where the worst case wastage is about
   100        32 bytes plus the remainder from a system page (the minimal
   101        mmap unit); typically 4096 or 8192 bytes.
   102 
   103   Security: static-safe; optionally more or less
   104        The "security" of malloc refers to the ability of malicious
   105        code to accentuate the effects of errors (for example, freeing
   106        space that is not currently malloc'ed or overwriting past the
   107        ends of chunks) in code that calls malloc.  This malloc
   108        guarantees not to modify any memory locations below the base of
   109        heap, i.e., static variables, even in the presence of usage
   110        errors.  The routines additionally detect most improper frees
   111        and reallocs.  All this holds as long as the static bookkeeping
   112        for malloc itself is not corrupted by some other means.  This
   113        is only one aspect of security -- these checks do not, and
   114        cannot, detect all possible programming errors.
   115 
   116        If FOOTERS is defined nonzero, then each allocated chunk
   117        carries an additional check word to verify that it was malloced
   118        from its space.  These check words are the same within each
   119        execution of a program using malloc, but differ across
   120        executions, so externally crafted fake chunks cannot be
   121        freed. This improves security by rejecting frees/reallocs that
   122        could corrupt heap memory, in addition to the checks preventing
   123        writes to statics that are always on.  This may further improve
   124        security at the expense of time and space overhead.  (Note that
   125        FOOTERS may also be worth using with MSPACES.)
   126 
   127        By default detected errors cause the program to abort (calling
   128        "abort()"). You can override this to instead proceed past
   129        errors by defining PROCEED_ON_ERROR.  In this case, a bad free
   130        has no effect, and a malloc that encounters a bad address
   131        caused by user overwrites will ignore the bad address by
   132        dropping pointers and indices to all known memory. This may
   133        be appropriate for programs that should continue if at all
   134        possible in the face of programming errors, although they may
   135        run out of memory because dropped memory is never reclaimed.
   136 
   137        If you don't like either of these options, you can define
   138        CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
   139        else. And if if you are sure that your program using malloc has
   140        no errors or vulnerabilities, you can define INSECURE to 1,
   141        which might (or might not) provide a small performance improvement.
   142 
   143   Thread-safety: NOT thread-safe unless USE_LOCKS defined
   144        When USE_LOCKS is defined, each public call to malloc, free,
   145        etc is surrounded with either a pthread mutex or a win32
   146        spinlock (depending on WIN32). This is not especially fast, and
   147        can be a major bottleneck.  It is designed only to provide
   148        minimal protection in concurrent environments, and to provide a
   149        basis for extensions.  If you are using malloc in a concurrent
   150        program, consider instead using ptmalloc, which is derived from
   151        a version of this malloc. (See http://www.malloc.de).
   152 
   153   System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
   154        This malloc can use unix sbrk or any emulation (invoked using
   155        the CALL_MORECORE macro) and/or mmap/munmap or any emulation
   156        (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
   157        memory.  On most unix systems, it tends to work best if both
   158        MORECORE and MMAP are enabled.  On Win32, it uses emulations
   159        based on VirtualAlloc. It also uses common C library functions
   160        like memset.
   161 
   162   Compliance: I believe it is compliant with the Single Unix Specification
   163        (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
   164        others as well.
   165 
   166 * Overview of algorithms
   167 
   168   This is not the fastest, most space-conserving, most portable, or
   169   most tunable malloc ever written. However it is among the fastest
   170   while also being among the most space-conserving, portable and
   171   tunable.  Consistent balance across these factors results in a good
   172   general-purpose allocator for malloc-intensive programs.
   173 
   174   In most ways, this malloc is a best-fit allocator. Generally, it
   175   chooses the best-fitting existing chunk for a request, with ties
   176   broken in approximately least-recently-used order. (This strategy
   177   normally maintains low fragmentation.) However, for requests less
   178   than 256bytes, it deviates from best-fit when there is not an
   179   exactly fitting available chunk by preferring to use space adjacent
   180   to that used for the previous small request, as well as by breaking
   181   ties in approximately most-recently-used order. (These enhance
   182   locality of series of small allocations.)  And for very large requests
   183   (>= 256Kb by default), it relies on system memory mapping
   184   facilities, if supported.  (This helps avoid carrying around and
   185   possibly fragmenting memory used only for large chunks.)
   186 
   187   All operations (except malloc_stats and mallinfo) have execution
   188   times that are bounded by a constant factor of the number of bits in
   189   a size_t, not counting any clearing in calloc or copying in realloc,
   190   or actions surrounding MORECORE and MMAP that have times
   191   proportional to the number of non-contiguous regions returned by
   192   system allocation routines, which is often just 1.
   193 
   194   The implementation is not very modular and seriously overuses
   195   macros. Perhaps someday all C compilers will do as good a job
   196   inlining modular code as can now be done by brute-force expansion,
   197   but now, enough of them seem not to.
   198 
   199   Some compilers issue a lot of warnings about code that is
   200   dead/unreachable only on some platforms, and also about intentional
   201   uses of negation on unsigned types. All known cases of each can be
   202   ignored.
   203 
   204   For a longer but out of date high-level description, see
   205      http://gee.cs.oswego.edu/dl/html/malloc.html
   206 
   207 * MSPACES
   208   If MSPACES is defined, then in addition to malloc, free, etc.,
   209   this file also defines mspace_malloc, mspace_free, etc. These
   210   are versions of malloc routines that take an "mspace" argument
   211   obtained using create_mspace, to control all internal bookkeeping.
   212   If ONLY_MSPACES is defined, only these versions are compiled.
   213   So if you would like to use this allocator for only some allocations,
   214   and your system malloc for others, you can compile with
   215   ONLY_MSPACES and then do something like...
   216     static mspace mymspace = create_mspace(0,0); // for example
   217     #define mymalloc(bytes)  mspace_malloc(mymspace, bytes)
   218 
   219   (Note: If you only need one instance of an mspace, you can instead
   220   use "USE_DL_PREFIX" to relabel the global malloc.)
   221 
   222   You can similarly create thread-local allocators by storing
   223   mspaces as thread-locals. For example:
   224     static __thread mspace tlms = 0;
   225     void*  tlmalloc(size_t bytes) {
   226       if (tlms == 0) tlms = create_mspace(0, 0);
   227       return mspace_malloc(tlms, bytes);
   228     }
   229     void  tlfree(void* mem) { mspace_free(tlms, mem); }
   230 
   231   Unless FOOTERS is defined, each mspace is completely independent.
   232   You cannot allocate from one and free to another (although
   233   conformance is only weakly checked, so usage errors are not always
   234   caught). If FOOTERS is defined, then each chunk carries around a tag
   235   indicating its originating mspace, and frees are directed to their
   236   originating spaces.
   237 
   238  -------------------------  Compile-time options ---------------------------
   239 
   240 Be careful in setting #define values for numerical constants of type
   241 size_t. On some systems, literal values are not automatically extended
   242 to size_t precision unless they are explicitly casted.
   243 
   244 WIN32                    default: defined if _WIN32 defined
   245   Defining WIN32 sets up defaults for MS environment and compilers.
   246   Otherwise defaults are for unix.
   247 
   248 MALLOC_ALIGNMENT         default: (size_t)8
   249   Controls the minimum alignment for malloc'ed chunks.  It must be a
   250   power of two and at least 8, even on machines for which smaller
   251   alignments would suffice. It may be defined as larger than this
   252   though. Note however that code and data structures are optimized for
   253   the case of 8-byte alignment.
   254 
   255 MSPACES                  default: 0 (false)
   256   If true, compile in support for independent allocation spaces.
   257   This is only supported if HAVE_MMAP is true.
   258 
   259 ONLY_MSPACES             default: 0 (false)
   260   If true, only compile in mspace versions, not regular versions.
   261 
   262 USE_LOCKS                default: 0 (false)
   263   Causes each call to each public routine to be surrounded with
   264   pthread or WIN32 mutex lock/unlock. (If set true, this can be
   265   overridden on a per-mspace basis for mspace versions.)
   266 
   267 FOOTERS                  default: 0
   268   If true, provide extra checking and dispatching by placing
   269   information in the footers of allocated chunks. This adds
   270   space and time overhead.
   271 
   272 INSECURE                 default: 0
   273   If true, omit checks for usage errors and heap space overwrites.
   274 
   275 USE_DL_PREFIX            default: NOT defined
   276   Causes compiler to prefix all public routines with the string 'dl'.
   277   This can be useful when you only want to use this malloc in one part
   278   of a program, using your regular system malloc elsewhere.
   279 
   280 ABORT                    default: defined as abort()
   281   Defines how to abort on failed checks.  On most systems, a failed
   282   check cannot die with an "assert" or even print an informative
   283   message, because the underlying print routines in turn call malloc,
   284   which will fail again.  Generally, the best policy is to simply call
   285   abort(). It's not very useful to do more than this because many
   286   errors due to overwriting will show up as address faults (null, odd
   287   addresses etc) rather than malloc-triggered checks, so will also
   288   abort.  Also, most compilers know that abort() does not return, so
   289   can better optimize code conditionally calling it.
   290 
   291 PROCEED_ON_ERROR           default: defined as 0 (false)
   292   Controls whether detected bad addresses cause them to bypassed
   293   rather than aborting. If set, detected bad arguments to free and
   294   realloc are ignored. And all bookkeeping information is zeroed out
   295   upon a detected overwrite of freed heap space, thus losing the
   296   ability to ever return it from malloc again, but enabling the
   297   application to proceed. If PROCEED_ON_ERROR is defined, the
   298   static variable malloc_corruption_error_count is compiled in
   299   and can be examined to see if errors have occurred. This option
   300   generates slower code than the default abort policy.
   301 
   302 DEBUG                    default: NOT defined
   303   The DEBUG setting is mainly intended for people trying to modify
   304   this code or diagnose problems when porting to new platforms.
   305   However, it may also be able to better isolate user errors than just
   306   using runtime checks.  The assertions in the check routines spell
   307   out in more detail the assumptions and invariants underlying the
   308   algorithms.  The checking is fairly extensive, and will slow down
   309   execution noticeably. Calling malloc_stats or mallinfo with DEBUG
   310   set will attempt to check every non-mmapped allocated and free chunk
   311   in the course of computing the summaries.
   312 
   313 ABORT_ON_ASSERT_FAILURE   default: defined as 1 (true)
   314   Debugging assertion failures can be nearly impossible if your
   315   version of the assert macro causes malloc to be called, which will
   316   lead to a cascade of further failures, blowing the runtime stack.
   317   ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
   318   which will usually make debugging easier.
   319 
   320 MALLOC_FAILURE_ACTION     default: sets errno to ENOMEM, or no-op on win32
   321   The action to take before "return 0" when malloc fails to be able to
   322   return memory because there is none available.
   323 
   324 HAVE_MORECORE             default: 1 (true) unless win32 or ONLY_MSPACES
   325   True if this system supports sbrk or an emulation of it.
   326 
   327 MORECORE                  default: sbrk
   328   The name of the sbrk-style system routine to call to obtain more
   329   memory.  See below for guidance on writing custom MORECORE
   330   functions. The type of the argument to sbrk/MORECORE varies across
   331   systems.  It cannot be size_t, because it supports negative
   332   arguments, so it is normally the signed type of the same width as
   333   size_t (sometimes declared as "intptr_t").  It doesn't much matter
   334   though. Internally, we only call it with arguments less than half
   335   the max value of a size_t, which should work across all reasonable
   336   possibilities, although sometimes generating compiler warnings.  See
   337   near the end of this file for guidelines for creating a custom
   338   version of MORECORE.
   339 
   340 MORECORE_CONTIGUOUS       default: 1 (true)
   341   If true, take advantage of fact that consecutive calls to MORECORE
   342   with positive arguments always return contiguous increasing
   343   addresses.  This is true of unix sbrk. It does not hurt too much to
   344   set it true anyway, since malloc copes with non-contiguities.
   345   Setting it false when definitely non-contiguous saves time
   346   and possibly wasted space it would take to discover this though.
   347 
   348 MORECORE_CANNOT_TRIM      default: NOT defined
   349   True if MORECORE cannot release space back to the system when given
   350   negative arguments. This is generally necessary only if you are
   351   using a hand-crafted MORECORE function that cannot handle negative
   352   arguments.
   353 
   354 HAVE_MMAP                 default: 1 (true)
   355   True if this system supports mmap or an emulation of it.  If so, and
   356   HAVE_MORECORE is not true, MMAP is used for all system
   357   allocation. If set and HAVE_MORECORE is true as well, MMAP is
   358   primarily used to directly allocate very large blocks. It is also
   359   used as a backup strategy in cases where MORECORE fails to provide
   360   space from system. Note: A single call to MUNMAP is assumed to be
   361   able to unmap memory that may have be allocated using multiple calls
   362   to MMAP, so long as they are adjacent.
   363 
   364 HAVE_MREMAP               default: 1 on linux, else 0
   365   If true realloc() uses mremap() to re-allocate large blocks and
   366   extend or shrink allocation spaces.
   367 
   368 MMAP_CLEARS               default: 1 on unix
   369   True if mmap clears memory so calloc doesn't need to. This is true
   370   for standard unix mmap using /dev/zero.
   371 
   372 USE_BUILTIN_FFS            default: 0 (i.e., not used)
   373   Causes malloc to use the builtin ffs() function to compute indices.
   374   Some compilers may recognize and intrinsify ffs to be faster than the
   375   supplied C version. Also, the case of x86 using gcc is special-cased
   376   to an asm instruction, so is already as fast as it can be, and so
   377   this setting has no effect. (On most x86s, the asm version is only
   378   slightly faster than the C version.)
   379 
   380 malloc_getpagesize         default: derive from system includes, or 4096.
   381   The system page size. To the extent possible, this malloc manages
   382   memory from the system in page-size units.  This may be (and
   383   usually is) a function rather than a constant. This is ignored
   384   if WIN32, where page size is determined using getSystemInfo during
   385   initialization.
   386 
   387 USE_DEV_RANDOM             default: 0 (i.e., not used)
   388   Causes malloc to use /dev/random to initialize secure magic seed for
   389   stamping footers. Otherwise, the current time is used.
   390 
   391 NO_MALLINFO                default: 0
   392   If defined, don't compile "mallinfo". This can be a simple way
   393   of dealing with mismatches between system declarations and
   394   those in this file.
   395 
   396 MALLINFO_FIELD_TYPE        default: size_t
   397   The type of the fields in the mallinfo struct. This was originally
   398   defined as "int" in SVID etc, but is more usefully defined as
   399   size_t. The value is used only if  HAVE_USR_INCLUDE_MALLOC_H is not set
   400 
   401 REALLOC_ZERO_BYTES_FREES    default: not defined
   402   This should be set if a call to realloc with zero bytes should 
   403   be the same as a call to free. Some people think it should. Otherwise, 
   404   since this malloc returns a unique pointer for malloc(0), so does 
   405   realloc(p, 0).
   406 
   407 LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
   408 LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H,  LACKS_ERRNO_H
   409 LACKS_STDLIB_H                default: NOT defined unless on WIN32
   410   Define these if your system does not have these header files.
   411   You might need to manually insert some of the declarations they provide.
   412 
   413 DEFAULT_GRANULARITY        default: page size if MORECORE_CONTIGUOUS,
   414                                 system_info.dwAllocationGranularity in WIN32,
   415                                 otherwise 64K.
   416       Also settable using mallopt(M_GRANULARITY, x)
   417   The unit for allocating and deallocating memory from the system.  On
   418   most systems with contiguous MORECORE, there is no reason to
   419   make this more than a page. However, systems with MMAP tend to
   420   either require or encourage larger granularities.  You can increase
   421   this value to prevent system allocation functions to be called so
   422   often, especially if they are slow.  The value must be at least one
   423   page and must be a power of two.  Setting to 0 causes initialization
   424   to either page size or win32 region size.  (Note: In previous
   425   versions of malloc, the equivalent of this option was called
   426   "TOP_PAD")
   427 
   428 DEFAULT_TRIM_THRESHOLD    default: 2MB
   429       Also settable using mallopt(M_TRIM_THRESHOLD, x)
   430   The maximum amount of unused top-most memory to keep before
   431   releasing via malloc_trim in free().  Automatic trimming is mainly
   432   useful in long-lived programs using contiguous MORECORE.  Because
   433   trimming via sbrk can be slow on some systems, and can sometimes be
   434   wasteful (in cases where programs immediately afterward allocate
   435   more large chunks) the value should be high enough so that your
   436   overall system performance would improve by releasing this much
   437   memory.  As a rough guide, you might set to a value close to the
   438   average size of a process (program) running on your system.
   439   Releasing this much memory would allow such a process to run in
   440   memory.  Generally, it is worth tuning trim thresholds when a
   441   program undergoes phases where several large chunks are allocated
   442   and released in ways that can reuse each other's storage, perhaps
   443   mixed with phases where there are no such chunks at all. The trim
   444   value must be greater than page size to have any useful effect.  To
   445   disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
   446   some people use of mallocing a huge space and then freeing it at
   447   program startup, in an attempt to reserve system memory, doesn't
   448   have the intended effect under automatic trimming, since that memory
   449   will immediately be returned to the system.
   450 
   451 DEFAULT_MMAP_THRESHOLD       default: 256K
   452       Also settable using mallopt(M_MMAP_THRESHOLD, x)
   453   The request size threshold for using MMAP to directly service a
   454   request. Requests of at least this size that cannot be allocated
   455   using already-existing space will be serviced via mmap.  (If enough
   456   normal freed space already exists it is used instead.)  Using mmap
   457   segregates relatively large chunks of memory so that they can be
   458   individually obtained and released from the host system. A request
   459   serviced through mmap is never reused by any other request (at least
   460   not directly; the system may just so happen to remap successive
   461   requests to the same locations).  Segregating space in this way has
   462   the benefits that: Mmapped space can always be individually released
   463   back to the system, which helps keep the system level memory demands
   464   of a long-lived program low.  Also, mapped memory doesn't become
   465   `locked' between other chunks, as can happen with normally allocated
   466   chunks, which means that even trimming via malloc_trim would not
   467   release them.  However, it has the disadvantage that the space
   468   cannot be reclaimed, consolidated, and then used to service later
   469   requests, as happens with normal chunks.  The advantages of mmap
   470   nearly always outweigh disadvantages for "large" chunks, but the
   471   value of "large" may vary across systems.  The default is an
   472   empirically derived value that works well in most systems. You can
   473   disable mmap by setting to MAX_SIZE_T.
   474 
   475 */
   476 
   477 #ifndef WIN32
   478 #ifdef _WIN32
   479 #define WIN32 1
   480 #endif /* _WIN32 */
   481 #endif /* WIN32 */
   482 #ifdef WIN32
   483 #define WIN32_LEAN_AND_MEAN
   484 #include <windows.h>
   485 #define HAVE_MMAP 1
   486 #define HAVE_MORECORE 0
   487 #define LACKS_UNISTD_H
   488 #define LACKS_SYS_PARAM_H
   489 #define LACKS_SYS_MMAN_H
   490 #define LACKS_STRING_H
   491 #define LACKS_STRINGS_H
   492 #define LACKS_SYS_TYPES_H
   493 #define LACKS_ERRNO_H
   494 #define LACKS_FCNTL_H
   495 #define MALLOC_FAILURE_ACTION
   496 #define MMAP_CLEARS 0           /* WINCE and some others apparently don't clear */
   497 #endif /* WIN32 */
   498 
   499 #if defined(DARWIN) || defined(_DARWIN)
   500 /* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
   501 #ifndef HAVE_MORECORE
   502 #define HAVE_MORECORE 0
   503 #define HAVE_MMAP 1
   504 #endif /* HAVE_MORECORE */
   505 #endif /* DARWIN */
   506 
   507 #ifndef LACKS_SYS_TYPES_H
   508 #include <sys/types.h>          /* For size_t */
   509 #endif /* LACKS_SYS_TYPES_H */
   510 
   511 /* The maximum possible size_t value has all bits set */
   512 #define MAX_SIZE_T           (~(size_t)0)
   513 
   514 #ifndef ONLY_MSPACES
   515 #define ONLY_MSPACES 0
   516 #endif /* ONLY_MSPACES */
   517 #ifndef MSPACES
   518 #if ONLY_MSPACES
   519 #define MSPACES 1
   520 #else /* ONLY_MSPACES */
   521 #define MSPACES 0
   522 #endif /* ONLY_MSPACES */
   523 #endif /* MSPACES */
   524 #ifndef MALLOC_ALIGNMENT
   525 #define MALLOC_ALIGNMENT ((size_t)8U)
   526 #endif /* MALLOC_ALIGNMENT */
   527 #ifndef FOOTERS
   528 #define FOOTERS 0
   529 #endif /* FOOTERS */
   530 #ifndef ABORT
   531 #define ABORT  abort()
   532 #endif /* ABORT */
   533 #ifndef ABORT_ON_ASSERT_FAILURE
   534 #define ABORT_ON_ASSERT_FAILURE 1
   535 #endif /* ABORT_ON_ASSERT_FAILURE */
   536 #ifndef PROCEED_ON_ERROR
   537 #define PROCEED_ON_ERROR 0
   538 #endif /* PROCEED_ON_ERROR */
   539 #ifndef USE_LOCKS
   540 #define USE_LOCKS 0
   541 #endif /* USE_LOCKS */
   542 #ifndef INSECURE
   543 #define INSECURE 0
   544 #endif /* INSECURE */
   545 #ifndef HAVE_MMAP
   546 #define HAVE_MMAP 1
   547 #endif /* HAVE_MMAP */
   548 #ifndef MMAP_CLEARS
   549 #define MMAP_CLEARS 1
   550 #endif /* MMAP_CLEARS */
   551 #ifndef HAVE_MREMAP
   552 #ifdef linux
   553 #define HAVE_MREMAP 1
   554 #else /* linux */
   555 #define HAVE_MREMAP 0
   556 #endif /* linux */
   557 #endif /* HAVE_MREMAP */
   558 #ifndef MALLOC_FAILURE_ACTION
   559 #define MALLOC_FAILURE_ACTION  errno = ENOMEM;
   560 #endif /* MALLOC_FAILURE_ACTION */
   561 #ifndef HAVE_MORECORE
   562 #if ONLY_MSPACES
   563 #define HAVE_MORECORE 0
   564 #else /* ONLY_MSPACES */
   565 #define HAVE_MORECORE 1
   566 #endif /* ONLY_MSPACES */
   567 #endif /* HAVE_MORECORE */
   568 #if !HAVE_MORECORE
   569 #define MORECORE_CONTIGUOUS 0
   570 #else /* !HAVE_MORECORE */
   571 #ifndef MORECORE
   572 #define MORECORE sbrk
   573 #endif /* MORECORE */
   574 #ifndef MORECORE_CONTIGUOUS
   575 #define MORECORE_CONTIGUOUS 1
   576 #endif /* MORECORE_CONTIGUOUS */
   577 #endif /* HAVE_MORECORE */
   578 #ifndef DEFAULT_GRANULARITY
   579 #if MORECORE_CONTIGUOUS
   580 #define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
   581 #else /* MORECORE_CONTIGUOUS */
   582 #define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
   583 #endif /* MORECORE_CONTIGUOUS */
   584 #endif /* DEFAULT_GRANULARITY */
   585 #ifndef DEFAULT_TRIM_THRESHOLD
   586 #ifndef MORECORE_CANNOT_TRIM
   587 #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
   588 #else /* MORECORE_CANNOT_TRIM */
   589 #define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
   590 #endif /* MORECORE_CANNOT_TRIM */
   591 #endif /* DEFAULT_TRIM_THRESHOLD */
   592 #ifndef DEFAULT_MMAP_THRESHOLD
   593 #if HAVE_MMAP
   594 #define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
   595 #else /* HAVE_MMAP */
   596 #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
   597 #endif /* HAVE_MMAP */
   598 #endif /* DEFAULT_MMAP_THRESHOLD */
   599 #ifndef USE_BUILTIN_FFS
   600 #define USE_BUILTIN_FFS 0
   601 #endif /* USE_BUILTIN_FFS */
   602 #ifndef USE_DEV_RANDOM
   603 #define USE_DEV_RANDOM 0
   604 #endif /* USE_DEV_RANDOM */
   605 #ifndef NO_MALLINFO
   606 #define NO_MALLINFO 0
   607 #endif /* NO_MALLINFO */
   608 #ifndef MALLINFO_FIELD_TYPE
   609 #define MALLINFO_FIELD_TYPE size_t
   610 #endif /* MALLINFO_FIELD_TYPE */
   611 
   612 #define memset	SDL_memset
   613 #define memcpy	SDL_memcpy
   614 #define malloc	SDL_malloc
   615 #define calloc	SDL_calloc
   616 #define realloc	SDL_realloc
   617 #define free	SDL_free
   618 
   619 /*
   620   mallopt tuning options.  SVID/XPG defines four standard parameter
   621   numbers for mallopt, normally defined in malloc.h.  None of these
   622   are used in this malloc, so setting them has no effect. But this
   623   malloc does support the following options.
   624 */
   625 
   626 #define M_TRIM_THRESHOLD     (-1)
   627 #define M_GRANULARITY        (-2)
   628 #define M_MMAP_THRESHOLD     (-3)
   629 
   630 /* ------------------------ Mallinfo declarations ------------------------ */
   631 
   632 #if !NO_MALLINFO
   633 /*
   634   This version of malloc supports the standard SVID/XPG mallinfo
   635   routine that returns a struct containing usage properties and
   636   statistics. It should work on any system that has a
   637   /usr/include/malloc.h defining struct mallinfo.  The main
   638   declaration needed is the mallinfo struct that is returned (by-copy)
   639   by mallinfo().  The malloinfo struct contains a bunch of fields that
   640   are not even meaningful in this version of malloc.  These fields are
   641   are instead filled by mallinfo() with other numbers that might be of
   642   interest.
   643 
   644   HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
   645   /usr/include/malloc.h file that includes a declaration of struct
   646   mallinfo.  If so, it is included; else a compliant version is
   647   declared below.  These must be precisely the same for mallinfo() to
   648   work.  The original SVID version of this struct, defined on most
   649   systems with mallinfo, declares all fields as ints. But some others
   650   define as unsigned long. If your system defines the fields using a
   651   type of different width than listed here, you MUST #include your
   652   system version and #define HAVE_USR_INCLUDE_MALLOC_H.
   653 */
   654 
   655 /* #define HAVE_USR_INCLUDE_MALLOC_H */
   656 
   657 #ifdef HAVE_USR_INCLUDE_MALLOC_H
   658 #include "/usr/include/malloc.h"
   659 #else /* HAVE_USR_INCLUDE_MALLOC_H */
   660 
   661 struct mallinfo
   662 {
   663     MALLINFO_FIELD_TYPE arena;  /* non-mmapped space allocated from system */
   664     MALLINFO_FIELD_TYPE ordblks;        /* number of free chunks */
   665     MALLINFO_FIELD_TYPE smblks; /* always 0 */
   666     MALLINFO_FIELD_TYPE hblks;  /* always 0 */
   667     MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
   668     MALLINFO_FIELD_TYPE usmblks;        /* maximum total allocated space */
   669     MALLINFO_FIELD_TYPE fsmblks;        /* always 0 */
   670     MALLINFO_FIELD_TYPE uordblks;       /* total allocated space */
   671     MALLINFO_FIELD_TYPE fordblks;       /* total free space */
   672     MALLINFO_FIELD_TYPE keepcost;       /* releasable (via malloc_trim) space */
   673 };
   674 
   675 #endif /* HAVE_USR_INCLUDE_MALLOC_H */
   676 #endif /* NO_MALLINFO */
   677 
   678 #ifdef __cplusplus
   679 extern "C"
   680 {
   681 #endif                          /* __cplusplus */
   682 
   683 #if !ONLY_MSPACES
   684 
   685 /* ------------------- Declarations of public routines ------------------- */
   686 
   687 #ifndef USE_DL_PREFIX
   688 #define dlcalloc               calloc
   689 #define dlfree                 free
   690 #define dlmalloc               malloc
   691 #define dlmemalign             memalign
   692 #define dlrealloc              realloc
   693 #define dlvalloc               valloc
   694 #define dlpvalloc              pvalloc
   695 #define dlmallinfo             mallinfo
   696 #define dlmallopt              mallopt
   697 #define dlmalloc_trim          malloc_trim
   698 #define dlmalloc_stats         malloc_stats
   699 #define dlmalloc_usable_size   malloc_usable_size
   700 #define dlmalloc_footprint     malloc_footprint
   701 #define dlmalloc_max_footprint malloc_max_footprint
   702 #define dlindependent_calloc   independent_calloc
   703 #define dlindependent_comalloc independent_comalloc
   704 #endif                          /* USE_DL_PREFIX */
   705 
   706 
   707 /*
   708   malloc(size_t n)
   709   Returns a pointer to a newly allocated chunk of at least n bytes, or
   710   null if no space is available, in which case errno is set to ENOMEM
   711   on ANSI C systems.
   712 
   713   If n is zero, malloc returns a minimum-sized chunk. (The minimum
   714   size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
   715   systems.)  Note that size_t is an unsigned type, so calls with
   716   arguments that would be negative if signed are interpreted as
   717   requests for huge amounts of space, which will often fail. The
   718   maximum supported value of n differs across systems, but is in all
   719   cases less than the maximum representable value of a size_t.
   720 */
   721     void *dlmalloc(size_t);
   722 
   723 /*
   724   free(void* p)
   725   Releases the chunk of memory pointed to by p, that had been previously
   726   allocated using malloc or a related routine such as realloc.
   727   It has no effect if p is null. If p was not malloced or already
   728   freed, free(p) will by default cause the current program to abort.
   729 */
   730     void dlfree(void *);
   731 
   732 /*
   733   calloc(size_t n_elements, size_t element_size);
   734   Returns a pointer to n_elements * element_size bytes, with all locations
   735   set to zero.
   736 */
   737     void *dlcalloc(size_t, size_t);
   738 
   739 /*
   740   realloc(void* p, size_t n)
   741   Returns a pointer to a chunk of size n that contains the same data
   742   as does chunk p up to the minimum of (n, p's size) bytes, or null
   743   if no space is available.
   744 
   745   The returned pointer may or may not be the same as p. The algorithm
   746   prefers extending p in most cases when possible, otherwise it
   747   employs the equivalent of a malloc-copy-free sequence.
   748 
   749   If p is null, realloc is equivalent to malloc.
   750 
   751   If space is not available, realloc returns null, errno is set (if on
   752   ANSI) and p is NOT freed.
   753 
   754   if n is for fewer bytes than already held by p, the newly unused
   755   space is lopped off and freed if possible.  realloc with a size
   756   argument of zero (re)allocates a minimum-sized chunk.
   757 
   758   The old unix realloc convention of allowing the last-free'd chunk
   759   to be used as an argument to realloc is not supported.
   760 */
   761 
   762     void *dlrealloc(void *, size_t);
   763 
   764 /*
   765   memalign(size_t alignment, size_t n);
   766   Returns a pointer to a newly allocated chunk of n bytes, aligned
   767   in accord with the alignment argument.
   768 
   769   The alignment argument should be a power of two. If the argument is
   770   not a power of two, the nearest greater power is used.
   771   8-byte alignment is guaranteed by normal malloc calls, so don't
   772   bother calling memalign with an argument of 8 or less.
   773 
   774   Overreliance on memalign is a sure way to fragment space.
   775 */
   776     void *dlmemalign(size_t, size_t);
   777 
   778 /*
   779   valloc(size_t n);
   780   Equivalent to memalign(pagesize, n), where pagesize is the page
   781   size of the system. If the pagesize is unknown, 4096 is used.
   782 */
   783     void *dlvalloc(size_t);
   784 
   785 /*
   786   mallopt(int parameter_number, int parameter_value)
   787   Sets tunable parameters The format is to provide a
   788   (parameter-number, parameter-value) pair.  mallopt then sets the
   789   corresponding parameter to the argument value if it can (i.e., so
   790   long as the value is meaningful), and returns 1 if successful else
   791   0.  SVID/XPG/ANSI defines four standard param numbers for mallopt,
   792   normally defined in malloc.h.  None of these are use in this malloc,
   793   so setting them has no effect. But this malloc also supports other
   794   options in mallopt. See below for details.  Briefly, supported
   795   parameters are as follows (listed defaults are for "typical"
   796   configurations).
   797 
   798   Symbol            param #  default    allowed param values
   799   M_TRIM_THRESHOLD     -1   2*1024*1024   any   (MAX_SIZE_T disables)
   800   M_GRANULARITY        -2     page size   any power of 2 >= page size
   801   M_MMAP_THRESHOLD     -3      256*1024   any   (or 0 if no MMAP support)
   802 */
   803     int dlmallopt(int, int);
   804 
   805 /*
   806   malloc_footprint();
   807   Returns the number of bytes obtained from the system.  The total
   808   number of bytes allocated by malloc, realloc etc., is less than this
   809   value. Unlike mallinfo, this function returns only a precomputed
   810   result, so can be called frequently to monitor memory consumption.
   811   Even if locks are otherwise defined, this function does not use them,
   812   so results might not be up to date.
   813 */
   814     size_t dlmalloc_footprint(void);
   815 
   816 /*
   817   malloc_max_footprint();
   818   Returns the maximum number of bytes obtained from the system. This
   819   value will be greater than current footprint if deallocated space
   820   has been reclaimed by the system. The peak number of bytes allocated
   821   by malloc, realloc etc., is less than this value. Unlike mallinfo,
   822   this function returns only a precomputed result, so can be called
   823   frequently to monitor memory consumption.  Even if locks are
   824   otherwise defined, this function does not use them, so results might
   825   not be up to date.
   826 */
   827     size_t dlmalloc_max_footprint(void);
   828 
   829 #if !NO_MALLINFO
   830 /*
   831   mallinfo()
   832   Returns (by copy) a struct containing various summary statistics:
   833 
   834   arena:     current total non-mmapped bytes allocated from system
   835   ordblks:   the number of free chunks
   836   smblks:    always zero.
   837   hblks:     current number of mmapped regions
   838   hblkhd:    total bytes held in mmapped regions
   839   usmblks:   the maximum total allocated space. This will be greater
   840                 than current total if trimming has occurred.
   841   fsmblks:   always zero
   842   uordblks:  current total allocated space (normal or mmapped)
   843   fordblks:  total free space
   844   keepcost:  the maximum number of bytes that could ideally be released
   845                back to system via malloc_trim. ("ideally" means that
   846                it ignores page restrictions etc.)
   847 
   848   Because these fields are ints, but internal bookkeeping may
   849   be kept as longs, the reported values may wrap around zero and
   850   thus be inaccurate.
   851 */
   852     struct mallinfo dlmallinfo(void);
   853 #endif                          /* NO_MALLINFO */
   854 
   855 /*
   856   independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
   857 
   858   independent_calloc is similar to calloc, but instead of returning a
   859   single cleared space, it returns an array of pointers to n_elements
   860   independent elements that can hold contents of size elem_size, each
   861   of which starts out cleared, and can be independently freed,
   862   realloc'ed etc. The elements are guaranteed to be adjacently
   863   allocated (this is not guaranteed to occur with multiple callocs or
   864   mallocs), which may also improve cache locality in some
   865   applications.
   866 
   867   The "chunks" argument is optional (i.e., may be null, which is
   868   probably the most typical usage). If it is null, the returned array
   869   is itself dynamically allocated and should also be freed when it is
   870   no longer needed. Otherwise, the chunks array must be of at least
   871   n_elements in length. It is filled in with the pointers to the
   872   chunks.
   873 
   874   In either case, independent_calloc returns this pointer array, or
   875   null if the allocation failed.  If n_elements is zero and "chunks"
   876   is null, it returns a chunk representing an array with zero elements
   877   (which should be freed if not wanted).
   878 
   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 
   885   independent_calloc simplifies and speeds up implementations of many
   886   kinds of pools.  It may also be useful when constructing large data
   887   structures that initially have a fixed number of fixed-sized nodes,
   888   but the number is not known at compile time, and some of the nodes
   889   may later need to be freed. For example:
   890 
   891   struct Node { int item; struct Node* next; };
   892 
   893   struct Node* build_list() {
   894     struct Node** pool;
   895     int n = read_number_of_nodes_needed();
   896     if (n <= 0) return 0;
   897     pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
   898     if (pool == 0) die();
   899     // organize into a linked list...
   900     struct Node* first = pool[0];
   901     for (i = 0; i < n-1; ++i)
   902       pool[i]->next = pool[i+1];
   903     free(pool);     // Can now free the array (or not, if it is needed later)
   904     return first;
   905   }
   906 */
   907     void **dlindependent_calloc(size_t, size_t, void **);
   908 
   909 /*
   910   independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
   911 
   912   independent_comalloc allocates, all at once, a set of n_elements
   913   chunks with sizes indicated in the "sizes" array.    It returns
   914   an array of pointers to these elements, each of which can be
   915   independently freed, realloc'ed etc. The elements are guaranteed to
   916   be adjacently allocated (this is not guaranteed to occur with
   917   multiple callocs or mallocs), which may also improve cache locality
   918   in some applications.
   919 
   920   The "chunks" argument is optional (i.e., may be null). If it is null
   921   the returned array is itself dynamically allocated and should also
   922   be freed when it is no longer needed. Otherwise, the chunks array
   923   must be of at least n_elements in length. It is filled in with the
   924   pointers to the chunks.
   925 
   926   In either case, independent_comalloc returns this pointer array, or
   927   null if the allocation failed.  If n_elements is zero and chunks is
   928   null, it returns a chunk representing an array with zero elements
   929   (which should be freed if not wanted).
   930 
   931   Each element must be individually freed when it is no longer
   932   needed. If you'd like to instead be able to free all at once, you
   933   should instead use a single regular malloc, and assign pointers at
   934   particular offsets in the aggregate space. (In this case though, you
   935   cannot independently free elements.)
   936 
   937   independent_comallac differs from independent_calloc in that each
   938   element may have a different size, and also that it does not
   939   automatically clear elements.
   940 
   941   independent_comalloc can be used to speed up allocation in cases
   942   where several structs or objects must always be allocated at the
   943   same time.  For example:
   944 
   945   struct Head { ... }
   946   struct Foot { ... }
   947 
   948   void send_message(char* msg) {
   949     int msglen = strlen(msg);
   950     size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
   951     void* chunks[3];
   952     if (independent_comalloc(3, sizes, chunks) == 0)
   953       die();
   954     struct Head* head = (struct Head*)(chunks[0]);
   955     char*        body = (char*)(chunks[1]);
   956     struct Foot* foot = (struct Foot*)(chunks[2]);
   957     // ...
   958   }
   959 
   960   In general though, independent_comalloc is worth using only for
   961   larger values of n_elements. For small values, you probably won't
   962   detect enough difference from series of malloc calls to bother.
   963 
   964   Overuse of independent_comalloc can increase overall memory usage,
   965   since it cannot reuse existing noncontiguous small chunks that
   966   might be available for some of the elements.
   967 */
   968     void **dlindependent_comalloc(size_t, size_t *, void **);
   969 
   970 
   971 /*
   972   pvalloc(size_t n);
   973   Equivalent to valloc(minimum-page-that-holds(n)), that is,
   974   round up n to nearest pagesize.
   975  */
   976     void *dlpvalloc(size_t);
   977 
   978 /*
   979   malloc_trim(size_t pad);
   980 
   981   If possible, gives memory back to the system (via negative arguments
   982   to sbrk) if there is unused memory at the `high' end of the malloc
   983   pool or in unused MMAP segments. You can call this after freeing
   984   large blocks of memory to potentially reduce the system-level memory
   985   requirements of a program. However, it cannot guarantee to reduce
   986   memory. Under some allocation patterns, some large free blocks of
   987   memory will be locked between two used chunks, so they cannot be
   988   given back to the system.
   989 
   990   The `pad' argument to malloc_trim represents the amount of free
   991   trailing space to leave untrimmed. If this argument is zero, only
   992   the minimum amount of memory to maintain internal data structures
   993   will be left. Non-zero arguments can be supplied to maintain enough
   994   trailing space to service future expected allocations without having
   995   to re-obtain memory from the system.
   996 
   997   Malloc_trim returns 1 if it actually released any memory, else 0.
   998 */
   999     int dlmalloc_trim(size_t);
  1000 
  1001 /*
  1002   malloc_usable_size(void* p);
  1003 
  1004   Returns the number of bytes you can actually use in
  1005   an allocated chunk, which may be more than you requested (although
  1006   often not) due to alignment and minimum size constraints.
  1007   You can use this many bytes without worrying about
  1008   overwriting other allocated objects. This is not a particularly great
  1009   programming practice. malloc_usable_size can be more useful in
  1010   debugging and assertions, for example:
  1011 
  1012   p = malloc(n);
  1013   assert(malloc_usable_size(p) >= 256);
  1014 */
  1015     size_t dlmalloc_usable_size(void *);
  1016 
  1017 /*
  1018   malloc_stats();
  1019   Prints on stderr the amount of space obtained from the system (both
  1020   via sbrk and mmap), the maximum amount (which may be more than
  1021   current if malloc_trim and/or munmap got called), and the current
  1022   number of bytes allocated via malloc (or realloc, etc) but not yet
  1023   freed. Note that this is the number of bytes allocated, not the
  1024   number requested. It will be larger than the number requested
  1025   because of alignment and bookkeeping overhead. Because it includes
  1026   alignment wastage as being in use, this figure may be greater than
  1027   zero even when no user-level chunks are allocated.
  1028 
  1029   The reported current and maximum system memory can be inaccurate if
  1030   a program makes other calls to system memory allocation functions
  1031   (normally sbrk) outside of malloc.
  1032 
  1033   malloc_stats prints only the most commonly interesting statistics.
  1034   More information can be obtained by calling mallinfo.
  1035 */
  1036     void dlmalloc_stats(void);
  1037 
  1038 #endif                          /* ONLY_MSPACES */
  1039 
  1040 #if MSPACES
  1041 
  1042 /*
  1043   mspace is an opaque type representing an independent
  1044   region of space that supports mspace_malloc, etc.
  1045 */
  1046     typedef void *mspace;
  1047 
  1048 /*
  1049   create_mspace creates and returns a new independent space with the
  1050   given initial capacity, or, if 0, the default granularity size.  It
  1051   returns null if there is no system memory available to create the
  1052   space.  If argument locked is non-zero, the space uses a separate
  1053   lock to control access. The capacity of the space will grow
  1054   dynamically as needed to service mspace_malloc requests.  You can
  1055   control the sizes of incremental increases of this space by
  1056   compiling with a different DEFAULT_GRANULARITY or dynamically
  1057   setting with mallopt(M_GRANULARITY, value).
  1058 */
  1059     mspace create_mspace(size_t capacity, int locked);
  1060 
  1061 /*
  1062   destroy_mspace destroys the given space, and attempts to return all
  1063   of its memory back to the system, returning the total number of
  1064   bytes freed. After destruction, the results of access to all memory
  1065   used by the space become undefined.
  1066 */
  1067     size_t destroy_mspace(mspace msp);
  1068 
  1069 /*
  1070   create_mspace_with_base uses the memory supplied as the initial base
  1071   of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
  1072   space is used for bookkeeping, so the capacity must be at least this
  1073   large. (Otherwise 0 is returned.) When this initial space is
  1074   exhausted, additional memory will be obtained from the system.
  1075   Destroying this space will deallocate all additionally allocated
  1076   space (if possible) but not the initial base.
  1077 */
  1078     mspace create_mspace_with_base(void *base, size_t capacity, int locked);
  1079 
  1080 /*
  1081   mspace_malloc behaves as malloc, but operates within
  1082   the given space.
  1083 */
  1084     void *mspace_malloc(mspace msp, size_t bytes);
  1085 
  1086 /*
  1087   mspace_free behaves as free, but operates within
  1088   the given space.
  1089 
  1090   If compiled with FOOTERS==1, mspace_free is not actually needed.
  1091   free may be called instead of mspace_free because freed chunks from
  1092   any space are handled by their originating spaces.
  1093 */
  1094     void mspace_free(mspace msp, void *mem);
  1095 
  1096 /*
  1097   mspace_realloc behaves as realloc, but operates within
  1098   the given space.
  1099 
  1100   If compiled with FOOTERS==1, mspace_realloc is not actually
  1101   needed.  realloc may be called instead of mspace_realloc because
  1102   realloced chunks from any space are handled by their originating
  1103   spaces.
  1104 */
  1105     void *mspace_realloc(mspace msp, void *mem, size_t newsize);
  1106 
  1107 /*
  1108   mspace_calloc behaves as calloc, but operates within
  1109   the given space.
  1110 */
  1111     void *mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
  1112 
  1113 /*
  1114   mspace_memalign behaves as memalign, but operates within
  1115   the given space.
  1116 */
  1117     void *mspace_memalign(mspace msp, size_t alignment, size_t bytes);
  1118 
  1119 /*
  1120   mspace_independent_calloc behaves as independent_calloc, but
  1121   operates within the given space.
  1122 */
  1123     void **mspace_independent_calloc(mspace msp, size_t n_elements,
  1124                                      size_t elem_size, void *chunks[]);
  1125 
  1126 /*
  1127   mspace_independent_comalloc behaves as independent_comalloc, but
  1128   operates within the given space.
  1129 */
  1130     void **mspace_independent_comalloc(mspace msp, size_t n_elements,
  1131                                        size_t sizes[], void *chunks[]);
  1132 
  1133 /*
  1134   mspace_footprint() returns the number of bytes obtained from the
  1135   system for this space.
  1136 */
  1137     size_t mspace_footprint(mspace msp);
  1138 
  1139 /*
  1140   mspace_max_footprint() returns the peak number of bytes obtained from the
  1141   system for this space.
  1142 */
  1143     size_t mspace_max_footprint(mspace msp);
  1144 
  1145 
  1146 #if !NO_MALLINFO
  1147 /*
  1148   mspace_mallinfo behaves as mallinfo, but reports properties of
  1149   the given space.
  1150 */
  1151     struct mallinfo mspace_mallinfo(mspace msp);
  1152 #endif                          /* NO_MALLINFO */
  1153 
  1154 /*
  1155   mspace_malloc_stats behaves as malloc_stats, but reports
  1156   properties of the given space.
  1157 */
  1158     void mspace_malloc_stats(mspace msp);
  1159 
  1160 /*
  1161   mspace_trim behaves as malloc_trim, but
  1162   operates within the given space.
  1163 */
  1164     int mspace_trim(mspace msp, size_t pad);
  1165 
  1166 /*
  1167   An alias for mallopt.
  1168 */
  1169     int mspace_mallopt(int, int);
  1170 
  1171 #endif                          /* MSPACES */
  1172 
  1173 #ifdef __cplusplus
  1174 };                              /* end of extern "C" */
  1175 #endif /* __cplusplus */
  1176 
  1177 /*
  1178   ========================================================================
  1179   To make a fully customizable malloc.h header file, cut everything
  1180   above this line, put into file malloc.h, edit to suit, and #include it
  1181   on the next line, as well as in programs that use this malloc.
  1182   ========================================================================
  1183 */
  1184 
  1185 /* #include "malloc.h" */
  1186 
  1187 /*------------------------------ internal #includes ---------------------- */
  1188 
  1189 #ifdef _MSC_VER
  1190 #pragma warning( disable : 4146 )       /* no "unsigned" warnings */
  1191 #endif /* _MSC_VER */
  1192 
  1193 #ifndef LACKS_STDIO_H
  1194 #include <stdio.h>              /* for printing in malloc_stats */
  1195 #endif
  1196 
  1197 #ifndef LACKS_ERRNO_H
  1198 #include <errno.h>              /* for MALLOC_FAILURE_ACTION */
  1199 #endif /* LACKS_ERRNO_H */
  1200 #if FOOTERS
  1201 #include <time.h>               /* for magic initialization */
  1202 #endif /* FOOTERS */
  1203 #ifndef LACKS_STDLIB_H
  1204 #include <stdlib.h>             /* for abort() */
  1205 #endif /* LACKS_STDLIB_H */
  1206 #ifdef DEBUG
  1207 #if ABORT_ON_ASSERT_FAILURE
  1208 #define assert(x) if(!(x)) ABORT
  1209 #else /* ABORT_ON_ASSERT_FAILURE */
  1210 #include <assert.h>
  1211 #endif /* ABORT_ON_ASSERT_FAILURE */
  1212 #else /* DEBUG */
  1213 #define assert(x)
  1214 #endif /* DEBUG */
  1215 #ifndef LACKS_STRING_H
  1216 #include <string.h>             /* for memset etc */
  1217 #endif /* LACKS_STRING_H */
  1218 #if USE_BUILTIN_FFS
  1219 #ifndef LACKS_STRINGS_H
  1220 #include <strings.h>            /* for ffs */
  1221 #endif /* LACKS_STRINGS_H */
  1222 #endif /* USE_BUILTIN_FFS */
  1223 #if HAVE_MMAP
  1224 #ifndef LACKS_SYS_MMAN_H
  1225 #include <sys/mman.h>           /* for mmap */
  1226 #endif /* LACKS_SYS_MMAN_H */
  1227 #ifndef LACKS_FCNTL_H
  1228 #include <fcntl.h>
  1229 #endif /* LACKS_FCNTL_H */
  1230 #endif /* HAVE_MMAP */
  1231 #if HAVE_MORECORE
  1232 #ifndef LACKS_UNISTD_H
  1233 #include <unistd.h>             /* for sbrk */
  1234 #else /* LACKS_UNISTD_H */
  1235 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
  1236 extern void *sbrk(ptrdiff_t);
  1237 #endif /* FreeBSD etc */
  1238 #endif /* LACKS_UNISTD_H */
  1239 #endif /* HAVE_MMAP */
  1240 
  1241 #ifndef WIN32
  1242 #ifndef malloc_getpagesize
  1243 #  ifdef _SC_PAGESIZE           /* some SVR4 systems omit an underscore */
  1244 #    ifndef _SC_PAGE_SIZE
  1245 #      define _SC_PAGE_SIZE _SC_PAGESIZE
  1246 #    endif
  1247 #  endif
  1248 #  ifdef _SC_PAGE_SIZE
  1249 #    define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
  1250 #  else
  1251 #    if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
  1252 extern size_t getpagesize();
  1253 #      define malloc_getpagesize getpagesize()
  1254 #    else
  1255 #      ifdef WIN32              /* use supplied emulation of getpagesize */
  1256 #        define malloc_getpagesize getpagesize()
  1257 #      else
  1258 #        ifndef LACKS_SYS_PARAM_H
  1259 #          include <sys/param.h>
  1260 #        endif
  1261 #        ifdef EXEC_PAGESIZE
  1262 #          define malloc_getpagesize EXEC_PAGESIZE
  1263 #        else
  1264 #          ifdef NBPG
  1265 #            ifndef CLSIZE
  1266 #              define malloc_getpagesize NBPG
  1267 #            else
  1268 #              define malloc_getpagesize (NBPG * CLSIZE)
  1269 #            endif
  1270 #          else
  1271 #            ifdef NBPC
  1272 #              define malloc_getpagesize NBPC
  1273 #            else
  1274 #              ifdef PAGESIZE
  1275 #                define malloc_getpagesize PAGESIZE
  1276 #              else /* just guess */
  1277 #                define malloc_getpagesize ((size_t)4096U)
  1278 #              endif
  1279 #            endif
  1280 #          endif
  1281 #        endif
  1282 #      endif
  1283 #    endif
  1284 #  endif
  1285 #endif
  1286 #endif
  1287 
  1288 /* ------------------- size_t and alignment properties -------------------- */
  1289 
  1290 /* The byte and bit size of a size_t */
  1291 #define SIZE_T_SIZE         (sizeof(size_t))
  1292 #define SIZE_T_BITSIZE      (sizeof(size_t) << 3)
  1293 
  1294 /* Some constants coerced to size_t */
  1295 /* Annoying but necessary to avoid errors on some plaftorms */
  1296 #define SIZE_T_ZERO         ((size_t)0)
  1297 #define SIZE_T_ONE          ((size_t)1)
  1298 #define SIZE_T_TWO          ((size_t)2)
  1299 #define TWO_SIZE_T_SIZES    (SIZE_T_SIZE<<1)
  1300 #define FOUR_SIZE_T_SIZES   (SIZE_T_SIZE<<2)
  1301 #define SIX_SIZE_T_SIZES    (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
  1302 #define HALF_MAX_SIZE_T     (MAX_SIZE_T / 2U)
  1303 
  1304 /* The bit mask value corresponding to MALLOC_ALIGNMENT */
  1305 #define CHUNK_ALIGN_MASK    (MALLOC_ALIGNMENT - SIZE_T_ONE)
  1306 
  1307 /* True if address a has acceptable alignment */
  1308 #define is_aligned(A)       (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
  1309 
  1310 /* the number of bytes to offset an address to align it */
  1311 #define align_offset(A)\
  1312  ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
  1313   ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
  1314 
  1315 /* -------------------------- MMAP preliminaries ------------------------- */
  1316 
  1317 /*
  1318    If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
  1319    checks to fail so compiler optimizer can delete code rather than
  1320    using so many "#if"s.
  1321 */
  1322 
  1323 
  1324 /* MORECORE and MMAP must return MFAIL on failure */
  1325 #define MFAIL                ((void*)(MAX_SIZE_T))
  1326 #define CMFAIL               ((char*)(MFAIL))   /* defined for convenience */
  1327 
  1328 #if !HAVE_MMAP
  1329 #define IS_MMAPPED_BIT       (SIZE_T_ZERO)
  1330 #define USE_MMAP_BIT         (SIZE_T_ZERO)
  1331 #define CALL_MMAP(s)         MFAIL
  1332 #define CALL_MUNMAP(a, s)    (-1)
  1333 #define DIRECT_MMAP(s)       MFAIL
  1334 
  1335 #else /* HAVE_MMAP */
  1336 #define IS_MMAPPED_BIT       (SIZE_T_ONE)
  1337 #define USE_MMAP_BIT         (SIZE_T_ONE)
  1338 
  1339 #ifndef WIN32
  1340 #define CALL_MUNMAP(a, s)    munmap((a), (s))
  1341 #define MMAP_PROT            (PROT_READ|PROT_WRITE)
  1342 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
  1343 #define MAP_ANONYMOUS        MAP_ANON
  1344 #endif /* MAP_ANON */
  1345 #ifdef MAP_ANONYMOUS
  1346 #define MMAP_FLAGS           (MAP_PRIVATE|MAP_ANONYMOUS)
  1347 #define CALL_MMAP(s)         mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
  1348 #else /* MAP_ANONYMOUS */
  1349 /*
  1350    Nearly all versions of mmap support MAP_ANONYMOUS, so the following
  1351    is unlikely to be needed, but is supplied just in case.
  1352 */
  1353 #define MMAP_FLAGS           (MAP_PRIVATE)
  1354 static int dev_zero_fd = -1;    /* Cached file descriptor for /dev/zero. */
  1355 #define CALL_MMAP(s) ((dev_zero_fd < 0) ? \
  1356            (dev_zero_fd = open("/dev/zero", O_RDWR), \
  1357             mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
  1358             mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
  1359 #endif /* MAP_ANONYMOUS */
  1360 
  1361 #define DIRECT_MMAP(s)       CALL_MMAP(s)
  1362 #else /* WIN32 */
  1363 
  1364 /* Win32 MMAP via VirtualAlloc */
  1365 static void *
  1366 win32mmap(size_t size)
  1367 {
  1368     void *ptr =
  1369         VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  1370     return (ptr != 0) ? ptr : MFAIL;
  1371 }
  1372 
  1373 /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
  1374 static void *
  1375 win32direct_mmap(size_t size)
  1376 {
  1377     void *ptr = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN,
  1378                              PAGE_READWRITE);
  1379     return (ptr != 0) ? ptr : MFAIL;
  1380 }
  1381 
  1382 /* This function supports releasing coalesed segments */
  1383 static int
  1384 win32munmap(void *ptr, size_t size)
  1385 {
  1386     MEMORY_BASIC_INFORMATION minfo;
  1387     char *cptr = ptr;
  1388     while (size) {
  1389         if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
  1390             return -1;
  1391         if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
  1392             minfo.State != MEM_COMMIT || minfo.RegionSize > size)
  1393             return -1;
  1394         if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
  1395             return -1;
  1396         cptr += minfo.RegionSize;
  1397         size -= minfo.RegionSize;
  1398     }
  1399     return 0;
  1400 }
  1401 
  1402 #define CALL_MMAP(s)         win32mmap(s)
  1403 #define CALL_MUNMAP(a, s)    win32munmap((a), (s))
  1404 #define DIRECT_MMAP(s)       win32direct_mmap(s)
  1405 #endif /* WIN32 */
  1406 #endif /* HAVE_MMAP */
  1407 
  1408 #if HAVE_MMAP && HAVE_MREMAP
  1409 #define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
  1410 #else /* HAVE_MMAP && HAVE_MREMAP */
  1411 #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
  1412 #endif /* HAVE_MMAP && HAVE_MREMAP */
  1413 
  1414 #if HAVE_MORECORE
  1415 #define CALL_MORECORE(S)     MORECORE(S)
  1416 #else /* HAVE_MORECORE */
  1417 #define CALL_MORECORE(S)     MFAIL
  1418 #endif /* HAVE_MORECORE */
  1419 
  1420 /* mstate bit set if continguous morecore disabled or failed */
  1421 #define USE_NONCONTIGUOUS_BIT (4U)
  1422 
  1423 /* segment bit set in create_mspace_with_base */
  1424 #define EXTERN_BIT            (8U)
  1425 
  1426 
  1427 /* --------------------------- Lock preliminaries ------------------------ */
  1428 
  1429 #if USE_LOCKS
  1430 
  1431 /*
  1432   When locks are defined, there are up to two global locks:
  1433 
  1434   * If HAVE_MORECORE, morecore_mutex protects sequences of calls to
  1435     MORECORE.  In many cases sys_alloc requires two calls, that should
  1436     not be interleaved with calls by other threads.  This does not
  1437     protect against direct calls to MORECORE by other threads not
  1438     using this lock, so there is still code to cope the best we can on
  1439     interference.
  1440 
  1441   * magic_init_mutex ensures that mparams.magic and other
  1442     unique mparams values are initialized only once.
  1443 */
  1444 
  1445 #ifndef WIN32
  1446 /* By default use posix locks */
  1447 #include <pthread.h>
  1448 #define MLOCK_T pthread_mutex_t
  1449 #define INITIAL_LOCK(l)      pthread_mutex_init(l, NULL)
  1450 #define ACQUIRE_LOCK(l)      pthread_mutex_lock(l)
  1451 #define RELEASE_LOCK(l)      pthread_mutex_unlock(l)
  1452 
  1453 #if HAVE_MORECORE
  1454 static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER;
  1455 #endif /* HAVE_MORECORE */
  1456 
  1457 static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER;
  1458 
  1459 #else /* WIN32 */
  1460 /*
  1461    Because lock-protected regions have bounded times, and there
  1462    are no recursive lock calls, we can use simple spinlocks.
  1463 */
  1464 
  1465 #define MLOCK_T long
  1466 static int
  1467 win32_acquire_lock(MLOCK_T * sl)
  1468 {
  1469     for (;;) {
  1470 #ifdef InterlockedCompareExchangePointer
  1471         if (!InterlockedCompareExchange(sl, 1, 0))
  1472             return 0;
  1473 #else /* Use older void* version */
  1474         if (!InterlockedCompareExchange((void **) sl, (void *) 1, (void *) 0))
  1475             return 0;
  1476 #endif /* InterlockedCompareExchangePointer */
  1477         Sleep(0);
  1478     }
  1479 }
  1480 
  1481 static void
  1482 win32_release_lock(MLOCK_T * sl)
  1483 {
  1484     InterlockedExchange(sl, 0);
  1485 }
  1486 
  1487 #define INITIAL_LOCK(l)      *(l)=0
  1488 #define ACQUIRE_LOCK(l)      win32_acquire_lock(l)
  1489 #define RELEASE_LOCK(l)      win32_release_lock(l)
  1490 #if HAVE_MORECORE
  1491 static MLOCK_T morecore_mutex;
  1492 #endif /* HAVE_MORECORE */
  1493 static MLOCK_T magic_init_mutex;
  1494 #endif /* WIN32 */
  1495 
  1496 #define USE_LOCK_BIT               (2U)
  1497 #else /* USE_LOCKS */
  1498 #define USE_LOCK_BIT               (0U)
  1499 #define INITIAL_LOCK(l)
  1500 #endif /* USE_LOCKS */
  1501 
  1502 #if USE_LOCKS && HAVE_MORECORE
  1503 #define ACQUIRE_MORECORE_LOCK()    ACQUIRE_LOCK(&morecore_mutex);
  1504 #define RELEASE_MORECORE_LOCK()    RELEASE_LOCK(&morecore_mutex);
  1505 #else /* USE_LOCKS && HAVE_MORECORE */
  1506 #define ACQUIRE_MORECORE_LOCK()
  1507 #define RELEASE_MORECORE_LOCK()
  1508 #endif /* USE_LOCKS && HAVE_MORECORE */
  1509 
  1510 #if USE_LOCKS
  1511 #define ACQUIRE_MAGIC_INIT_LOCK()  ACQUIRE_LOCK(&magic_init_mutex);
  1512 #define RELEASE_MAGIC_INIT_LOCK()  RELEASE_LOCK(&magic_init_mutex);
  1513 #else /* USE_LOCKS */
  1514 #define ACQUIRE_MAGIC_INIT_LOCK()
  1515 #define RELEASE_MAGIC_INIT_LOCK()
  1516 #endif /* USE_LOCKS */
  1517 
  1518 
  1519 /* -----------------------  Chunk representations ------------------------ */
  1520 
  1521 /*
  1522   (The following includes lightly edited explanations by Colin Plumb.)
  1523 
  1524   The malloc_chunk declaration below is misleading (but accurate and
  1525   necessary).  It declares a "view" into memory allowing access to
  1526   necessary fields at known offsets from a given base.
  1527 
  1528   Chunks of memory are maintained using a `boundary tag' method as
  1529   originally described by Knuth.  (See the paper by Paul Wilson
  1530   ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
  1531   techniques.)  Sizes of free chunks are stored both in the front of
  1532   each chunk and at the end.  This makes consolidating fragmented
  1533   chunks into bigger chunks fast.  The head fields also hold bits
  1534   representing whether chunks are free or in use.
  1535 
  1536   Here are some pictures to make it clearer.  They are "exploded" to
  1537   show that the state of a chunk can be thought of as extending from
  1538   the high 31 bits of the head field of its header through the
  1539   prev_foot and PINUSE_BIT bit of the following chunk header.
  1540 
  1541   A chunk that's in use looks like:
  1542 
  1543    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1544            | Size of previous chunk (if P = 1)                             |
  1545            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1546          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
  1547          | Size of this chunk                                         1| +-+
  1548    mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1549          |                                                               |
  1550          +-                                                             -+
  1551          |                                                               |
  1552          +-                                                             -+
  1553          |                                                               :
  1554          +-      size - sizeof(size_t) available payload bytes          -+
  1555          :                                                               |
  1556  chunk-> +-                                                             -+
  1557          |                                                               |
  1558          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1559        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
  1560        | Size of next chunk (may or may not be in use)               | +-+
  1561  mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1562 
  1563     And if it's free, it looks like this:
  1564 
  1565    chunk-> +-                                                             -+
  1566            | User payload (must be in use, or we would have merged!)       |
  1567            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1568          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
  1569          | Size of this chunk                                         0| +-+
  1570    mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1571          | Next pointer                                                  |
  1572          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1573          | Prev pointer                                                  |
  1574          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1575          |                                                               :
  1576          +-      size - sizeof(struct chunk) unused bytes               -+
  1577          :                                                               |
  1578  chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1579          | Size of this chunk                                            |
  1580          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1581        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
  1582        | Size of next chunk (must be in use, or we would have merged)| +-+
  1583  mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1584        |                                                               :
  1585        +- User payload                                                -+
  1586        :                                                               |
  1587        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1588                                                                      |0|
  1589                                                                      +-+
  1590   Note that since we always merge adjacent free chunks, the chunks
  1591   adjacent to a free chunk must be in use.
  1592 
  1593   Given a pointer to a chunk (which can be derived trivially from the
  1594   payload pointer) we can, in O(1) time, find out whether the adjacent
  1595   chunks are free, and if so, unlink them from the lists that they
  1596   are on and merge them with the current chunk.
  1597 
  1598   Chunks always begin on even word boundaries, so the mem portion
  1599   (which is returned to the user) is also on an even word boundary, and
  1600   thus at least double-word aligned.
  1601 
  1602   The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
  1603   chunk size (which is always a multiple of two words), is an in-use
  1604   bit for the *previous* chunk.  If that bit is *clear*, then the
  1605   word before the current chunk size contains the previous chunk
  1606   size, and can be used to find the front of the previous chunk.
  1607   The very first chunk allocated always has this bit set, preventing
  1608   access to non-existent (or non-owned) memory. If pinuse is set for
  1609   any given chunk, then you CANNOT determine the size of the
  1610   previous chunk, and might even get a memory addressing fault when
  1611   trying to do so.
  1612 
  1613   The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
  1614   the chunk size redundantly records whether the current chunk is
  1615   inuse. This redundancy enables usage checks within free and realloc,
  1616   and reduces indirection when freeing and consolidating chunks.
  1617 
  1618   Each freshly allocated chunk must have both cinuse and pinuse set.
  1619   That is, each allocated chunk borders either a previously allocated
  1620   and still in-use chunk, or the base of its memory arena. This is
  1621   ensured by making all allocations from the the `lowest' part of any
  1622   found chunk.  Further, no free chunk physically borders another one,
  1623   so each free chunk is known to be preceded and followed by either
  1624   inuse chunks or the ends of memory.
  1625 
  1626   Note that the `foot' of the current chunk is actually represented
  1627   as the prev_foot of the NEXT chunk. This makes it easier to
  1628   deal with alignments etc but can be very confusing when trying
  1629   to extend or adapt this code.
  1630 
  1631   The exceptions to all this are
  1632 
  1633      1. The special chunk `top' is the top-most available chunk (i.e.,
  1634         the one bordering the end of available memory). It is treated
  1635         specially.  Top is never included in any bin, is used only if
  1636         no other chunk is available, and is released back to the
  1637         system if it is very large (see M_TRIM_THRESHOLD).  In effect,
  1638         the top chunk is treated as larger (and thus less well
  1639         fitting) than any other available chunk.  The top chunk
  1640         doesn't update its trailing size field since there is no next
  1641         contiguous chunk that would have to index off it. However,
  1642         space is still allocated for it (TOP_FOOT_SIZE) to enable
  1643         separation or merging when space is extended.
  1644 
  1645      3. Chunks allocated via mmap, which have the lowest-order bit
  1646         (IS_MMAPPED_BIT) set in their prev_foot fields, and do not set
  1647         PINUSE_BIT in their head fields.  Because they are allocated
  1648         one-by-one, each must carry its own prev_foot field, which is
  1649         also used to hold the offset this chunk has within its mmapped
  1650         region, which is needed to preserve alignment. Each mmapped
  1651         chunk is trailed by the first two fields of a fake next-chunk
  1652         for sake of usage checks.
  1653 
  1654 */
  1655 
  1656 struct malloc_chunk
  1657 {
  1658     size_t prev_foot;           /* Size of previous chunk (if free).  */
  1659     size_t head;                /* Size and inuse bits. */
  1660     struct malloc_chunk *fd;    /* double links -- used only if free. */
  1661     struct malloc_chunk *bk;
  1662 };
  1663 
  1664 typedef struct malloc_chunk mchunk;
  1665 typedef struct malloc_chunk *mchunkptr;
  1666 typedef struct malloc_chunk *sbinptr;   /* The type of bins of chunks */
  1667 typedef size_t bindex_t;        /* Described below */
  1668 typedef unsigned int binmap_t;  /* Described below */
  1669 typedef unsigned int flag_t;    /* The type of various bit flag sets */
  1670 
  1671 /* ------------------- Chunks sizes and alignments ----------------------- */
  1672 
  1673 #define MCHUNK_SIZE         (sizeof(mchunk))
  1674 
  1675 #if FOOTERS
  1676 #define CHUNK_OVERHEAD      (TWO_SIZE_T_SIZES)
  1677 #else /* FOOTERS */
  1678 #define CHUNK_OVERHEAD      (SIZE_T_SIZE)
  1679 #endif /* FOOTERS */
  1680 
  1681 /* MMapped chunks need a second word of overhead ... */
  1682 #define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
  1683 /* ... and additional padding for fake next-chunk at foot */
  1684 #define MMAP_FOOT_PAD       (FOUR_SIZE_T_SIZES)
  1685 
  1686 /* The smallest size we can malloc is an aligned minimal chunk */
  1687 #define MIN_CHUNK_SIZE\
  1688   ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
  1689 
  1690 /* conversion from malloc headers to user pointers, and back */
  1691 #define chunk2mem(p)        ((void*)((char*)(p)       + TWO_SIZE_T_SIZES))
  1692 #define mem2chunk(mem)      ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
  1693 /* chunk associated with aligned address A */
  1694 #define align_as_chunk(A)   (mchunkptr)((A) + align_offset(chunk2mem(A)))
  1695 
  1696 /* Bounds on request (not chunk) sizes. */
  1697 #define MAX_REQUEST         ((-MIN_CHUNK_SIZE) << 2)
  1698 #define MIN_REQUEST         (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
  1699 
  1700 /* pad request bytes into a usable size */
  1701 #define pad_request(req) \
  1702    (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
  1703 
  1704 /* pad request, checking for minimum (but not maximum) */
  1705 #define request2size(req) \
  1706   (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
  1707 
  1708 
  1709 /* ------------------ Operations on head and foot fields ----------------- */
  1710 
  1711 /*
  1712   The head field of a chunk is or'ed with PINUSE_BIT when previous
  1713   adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
  1714   use. If the chunk was obtained with mmap, the prev_foot field has
  1715   IS_MMAPPED_BIT set, otherwise holding the offset of the base of the
  1716   mmapped region to the base of the chunk.
  1717 */
  1718 
  1719 #define PINUSE_BIT          (SIZE_T_ONE)
  1720 #define CINUSE_BIT          (SIZE_T_TWO)
  1721 #define INUSE_BITS          (PINUSE_BIT|CINUSE_BIT)
  1722 
  1723 /* Head value for fenceposts */
  1724 #define FENCEPOST_HEAD      (INUSE_BITS|SIZE_T_SIZE)
  1725 
  1726 /* extraction of fields from head words */
  1727 #define cinuse(p)           ((p)->head & CINUSE_BIT)
  1728 #define pinuse(p)           ((p)->head & PINUSE_BIT)
  1729 #define chunksize(p)        ((p)->head & ~(INUSE_BITS))
  1730 
  1731 #define clear_pinuse(p)     ((p)->head &= ~PINUSE_BIT)
  1732 #define clear_cinuse(p)     ((p)->head &= ~CINUSE_BIT)
  1733 
  1734 /* Treat space at ptr +/- offset as a chunk */
  1735 #define chunk_plus_offset(p, s)  ((mchunkptr)(((char*)(p)) + (s)))
  1736 #define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
  1737 
  1738 /* Ptr to next or previous physical malloc_chunk. */
  1739 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS)))
  1740 #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
  1741 
  1742 /* extract next chunk's pinuse bit */
  1743 #define next_pinuse(p)  ((next_chunk(p)->head) & PINUSE_BIT)
  1744 
  1745 /* Get/set size at footer */
  1746 #define get_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot)
  1747 #define set_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
  1748 
  1749 /* Set size, pinuse bit, and foot */
  1750 #define set_size_and_pinuse_of_free_chunk(p, s)\
  1751   ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
  1752 
  1753 /* Set size, pinuse bit, foot, and clear next pinuse */
  1754 #define set_free_with_pinuse(p, s, n)\
  1755   (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
  1756 
  1757 #define is_mmapped(p)\
  1758   (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT))
  1759 
  1760 /* Get the internal overhead associated with chunk p */
  1761 #define overhead_for(p)\
  1762  (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
  1763 
  1764 /* Return true if malloced space is not necessarily cleared */
  1765 #if MMAP_CLEARS
  1766 #define calloc_must_clear(p) (!is_mmapped(p))
  1767 #else /* MMAP_CLEARS */
  1768 #define calloc_must_clear(p) (1)
  1769 #endif /* MMAP_CLEARS */
  1770 
  1771 /* ---------------------- Overlaid data structures ----------------------- */
  1772 
  1773 /*
  1774   When chunks are not in use, they are treated as nodes of either
  1775   lists or trees.
  1776 
  1777   "Small"  chunks are stored in circular doubly-linked lists, and look
  1778   like this:
  1779 
  1780     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1781             |             Size of previous chunk                            |
  1782             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1783     `head:' |             Size of chunk, in bytes                         |P|
  1784       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1785             |             Forward pointer to next chunk in list             |
  1786             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1787             |             Back pointer to previous chunk in list            |
  1788             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1789             |             Unused space (may be 0 bytes long)                .
  1790             .                                                               .
  1791             .                                                               |
  1792 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1793     `foot:' |             Size of chunk, in bytes                           |
  1794             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1795 
  1796   Larger chunks are kept in a form of bitwise digital trees (aka
  1797   tries) keyed on chunksizes.  Because malloc_tree_chunks are only for
  1798   free chunks greater than 256 bytes, their size doesn't impose any
  1799   constraints on user chunk sizes.  Each node looks like:
  1800 
  1801     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1802             |             Size of previous chunk                            |
  1803             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1804     `head:' |             Size of chunk, in bytes                         |P|
  1805       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1806             |             Forward pointer to next chunk of same size        |
  1807             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1808             |             Back pointer to previous chunk of same size       |
  1809             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1810             |             Pointer to left child (child[0])                  |
  1811             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1812             |             Pointer to right child (child[1])                 |
  1813             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1814             |             Pointer to parent                                 |
  1815             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1816             |             bin index of this chunk                           |
  1817             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1818             |             Unused space                                      .
  1819             .                                                               |
  1820 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1821     `foot:' |             Size of chunk, in bytes                           |
  1822             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1823 
  1824   Each tree holding treenodes is a tree of unique chunk sizes.  Chunks
  1825   of the same size are arranged in a circularly-linked list, with only
  1826   the oldest chunk (the next to be used, in our FIFO ordering)
  1827   actually in the tree.  (Tree members are distinguished by a non-null
  1828   parent pointer.)  If a chunk with the same size an an existing node
  1829   is inserted, it is linked off the existing node using pointers that
  1830   work in the same way as fd/bk pointers of small chunks.
  1831 
  1832   Each tree contains a power of 2 sized range of chunk sizes (the
  1833   smallest is 0x100 <= x < 0x180), which is is divided in half at each
  1834   tree level, with the chunks in the smaller half of the range (0x100
  1835   <= x < 0x140 for the top nose) in the left subtree and the larger
  1836   half (0x140 <= x < 0x180) in the right subtree.  This is, of course,
  1837   done by inspecting individual bits.
  1838 
  1839   Using these rules, each node's left subtree contains all smaller
  1840   sizes than its right subtree.  However, the node at the root of each
  1841   subtree has no particular ordering relationship to either.  (The
  1842   dividing line between the subtree sizes is based on trie relation.)
  1843   If we remove the last chunk of a given size from the interior of the
  1844   tree, we need to replace it with a leaf node.  The tree ordering
  1845   rules permit a node to be replaced by any leaf below it.
  1846 
  1847   The smallest chunk in a tree (a common operation in a best-fit
  1848   allocator) can be found by walking a path to the leftmost leaf in
  1849   the tree.  Unlike a usual binary tree, where we follow left child
  1850   pointers until we reach a null, here we follow the right child
  1851   pointer any time the left one is null, until we reach a leaf with
  1852   both child pointers null. The smallest chunk in the tree will be
  1853   somewhere along that path.
  1854 
  1855   The worst case number of steps to add, find, or remove a node is
  1856   bounded by the number of bits differentiating chunks within
  1857   bins. Under current bin calculations, this ranges from 6 up to 21
  1858   (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
  1859   is of course much better.
  1860 */
  1861 
  1862 struct malloc_tree_chunk
  1863 {
  1864     /* The first four fields must be compatible with malloc_chunk */
  1865     size_t prev_foot;
  1866     size_t head;
  1867     struct malloc_tree_chunk *fd;
  1868     struct malloc_tree_chunk *bk;
  1869 
  1870     struct malloc_tree_chunk *child[2];
  1871     struct malloc_tree_chunk *parent;
  1872     bindex_t index;
  1873 };
  1874 
  1875 typedef struct malloc_tree_chunk tchunk;
  1876 typedef struct malloc_tree_chunk *tchunkptr;
  1877 typedef struct malloc_tree_chunk *tbinptr;      /* The type of bins of trees */
  1878 
  1879 /* A little helper macro for trees */
  1880 #define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
  1881 
  1882 /* ----------------------------- Segments -------------------------------- */
  1883 
  1884 /*
  1885   Each malloc space may include non-contiguous segments, held in a
  1886   list headed by an embedded malloc_segment record representing the
  1887   top-most space. Segments also include flags holding properties of
  1888   the space. Large chunks that are directly allocated by mmap are not
  1889   included in this list. They are instead independently created and
  1890   destroyed without otherwise keeping track of them.
  1891 
  1892   Segment management mainly comes into play for spaces allocated by
  1893   MMAP.  Any call to MMAP might or might not return memory that is
  1894   adjacent to an existing segment.  MORECORE normally contiguously
  1895   extends the current space, so this space is almost always adjacent,
  1896   which is simpler and faster to deal with. (This is why MORECORE is
  1897   used preferentially to MMAP when both are available -- see
  1898   sys_alloc.)  When allocating using MMAP, we don't use any of the
  1899   hinting mechanisms (inconsistently) supported in various
  1900   implementations of unix mmap, or distinguish reserving from
  1901   committing memory. Instead, we just ask for space, and exploit
  1902   contiguity when we get it.  It is probably possible to do
  1903   better than this on some systems, but no general scheme seems
  1904   to be significantly better.
  1905 
  1906   Management entails a simpler variant of the consolidation scheme
  1907   used for chunks to reduce fragmentation -- new adjacent memory is
  1908   normally prepended or appended to an existing segment. However,
  1909   there are limitations compared to chunk consolidation that mostly
  1910   reflect the fact that segment processing is relatively infrequent
  1911   (occurring only when getting memory from system) and that we
  1912   don't expect to have huge numbers of segments:
  1913 
  1914   * Segments are not indexed, so traversal requires linear scans.  (It
  1915     would be possible to index these, but is not worth the extra
  1916     overhead and complexity for most programs on most platforms.)
  1917   * New segments are only appended to old ones when holding top-most
  1918     memory; if they cannot be prepended to others, they are held in
  1919     different segments.
  1920 
  1921   Except for the top-most segment of an mstate, each segment record
  1922   is kept at the tail of its segment. Segments are added by pushing
  1923   segment records onto the list headed by &mstate.seg for the
  1924   containing mstate.
  1925 
  1926   Segment flags control allocation/merge/deallocation policies:
  1927   * If EXTERN_BIT set, then we did not allocate this segment,
  1928     and so should not try to deallocate or merge with others.
  1929     (This currently holds only for the initial segment passed
  1930     into create_mspace_with_base.)
  1931   * If IS_MMAPPED_BIT set, the segment may be merged with
  1932     other surrounding mmapped segments and trimmed/de-allocated
  1933     using munmap.
  1934   * If neither bit is set, then the segment was obtained using
  1935     MORECORE so can be merged with surrounding MORECORE'd segments
  1936     and deallocated/trimmed using MORECORE with negative arguments.
  1937 */
  1938 
  1939 struct malloc_segment
  1940 {
  1941     char *base;                 /* base address */
  1942     size_t size;                /* allocated size */
  1943     struct malloc_segment *next;        /* ptr to next segment */
  1944     flag_t sflags;              /* mmap and extern flag */
  1945 };
  1946 
  1947 #define is_mmapped_segment(S)  ((S)->sflags & IS_MMAPPED_BIT)
  1948 #define is_extern_segment(S)   ((S)->sflags & EXTERN_BIT)
  1949 
  1950 typedef struct malloc_segment msegment;
  1951 typedef struct malloc_segment *msegmentptr;
  1952 
  1953 /* ---------------------------- malloc_state ----------------------------- */
  1954 
  1955 /*
  1956    A malloc_state holds all of the bookkeeping for a space.
  1957    The main fields are:
  1958 
  1959   Top
  1960     The topmost chunk of the currently active segment. Its size is
  1961     cached in topsize.  The actual size of topmost space is
  1962     topsize+TOP_FOOT_SIZE, which includes space reserved for adding
  1963     fenceposts and segment records if necessary when getting more
  1964     space from the system.  The size at which to autotrim top is
  1965     cached from mparams in trim_check, except that it is disabled if
  1966     an autotrim fails.
  1967 
  1968   Designated victim (dv)
  1969     This is the preferred chunk for servicing small requests that
  1970     don't have exact fits.  It is normally the chunk split off most
  1971     recently to service another small request.  Its size is cached in
  1972     dvsize. The link fields of this chunk are not maintained since it
  1973     is not kept in a bin.
  1974 
  1975   SmallBins
  1976     An array of bin headers for free chunks.  These bins hold chunks
  1977     with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
  1978     chunks of all the same size, spaced 8 bytes apart.  To simplify
  1979     use in double-linked lists, each bin header acts as a malloc_chunk
  1980     pointing to the real first node, if it exists (else pointing to
  1981     itself).  This avoids special-casing for headers.  But to avoid
  1982     waste, we allocate only the fd/bk pointers of bins, and then use
  1983     repositioning tricks to treat these as the fields of a chunk.
  1984 
  1985   TreeBins
  1986     Treebins are pointers to the roots of trees holding a range of
  1987     sizes. There are 2 equally spaced treebins for each power of two
  1988     from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
  1989     larger.
  1990 
  1991   Bin maps
  1992     There is one bit map for small bins ("smallmap") and one for
  1993     treebins ("treemap).  Each bin sets its bit when non-empty, and
  1994     clears the bit when empty.  Bit operations are then used to avoid
  1995     bin-by-bin searching -- nearly all "search" is done without ever
  1996     looking at bins that won't be selected.  The bit maps
  1997     conservatively use 32 bits per map word, even if on 64bit system.
  1998     For a good description of some of the bit-based techniques used
  1999     here, see Henry S. Warren Jr's book "Hacker's Delight" (and
  2000     supplement at http://hackersdelight.org/). Many of these are
  2001     intended to reduce the branchiness of paths through malloc etc, as
  2002     well as to reduce the number of memory locations read or written.
  2003 
  2004   Segments
  2005     A list of segments headed by an embedded malloc_segment record
  2006     representing the initial space.
  2007 
  2008   Address check support
  2009     The least_addr field is the least address ever obtained from
  2010     MORECORE or MMAP. Attempted frees and reallocs of any address less
  2011     than this are trapped (unless INSECURE is defined).
  2012 
  2013   Magic tag
  2014     A cross-check field that should always hold same value as mparams.magic.
  2015 
  2016   Flags
  2017     Bits recording whether to use MMAP, locks, or contiguous MORECORE
  2018 
  2019   Statistics
  2020     Each space keeps track of current and maximum system memory
  2021     obtained via MORECORE or MMAP.
  2022 
  2023   Locking
  2024     If USE_LOCKS is defined, the "mutex" lock is acquired and released
  2025     around every public call using this mspace.
  2026 */
  2027 
  2028 /* Bin types, widths and sizes */
  2029 #define NSMALLBINS        (32U)
  2030 #define NTREEBINS         (32U)
  2031 #define SMALLBIN_SHIFT    (3U)
  2032 #define SMALLBIN_WIDTH    (SIZE_T_ONE << SMALLBIN_SHIFT)
  2033 #define TREEBIN_SHIFT     (8U)
  2034 #define MIN_LARGE_SIZE    (SIZE_T_ONE << TREEBIN_SHIFT)
  2035 #define MAX_SMALL_SIZE    (MIN_LARGE_SIZE - SIZE_T_ONE)
  2036 #define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
  2037 
  2038 struct malloc_state
  2039 {
  2040     binmap_t smallmap;
  2041     binmap_t treemap;
  2042     size_t dvsize;
  2043     size_t topsize;
  2044     char *least_addr;
  2045     mchunkptr dv;
  2046     mchunkptr top;
  2047     size_t trim_check;
  2048     size_t magic;
  2049     mchunkptr smallbins[(NSMALLBINS + 1) * 2];
  2050     tbinptr treebins[NTREEBINS];
  2051     size_t footprint;
  2052     size_t max_footprint;
  2053     flag_t mflags;
  2054 #if USE_LOCKS
  2055     MLOCK_T mutex;              /* locate lock among fields that rarely change */
  2056 #endif                          /* USE_LOCKS */
  2057     msegment seg;
  2058 };
  2059 
  2060 typedef struct malloc_state *mstate;
  2061 
  2062 /* ------------- Global malloc_state and malloc_params ------------------- */
  2063 
  2064 /*
  2065   malloc_params holds global properties, including those that can be
  2066   dynamically set using mallopt. There is a single instance, mparams,
  2067   initialized in init_mparams.
  2068 */
  2069 
  2070 struct malloc_params
  2071 {
  2072     size_t magic;
  2073     size_t page_size;
  2074     size_t granularity;
  2075     size_t mmap_threshold;
  2076     size_t trim_threshold;
  2077     flag_t default_mflags;
  2078 };
  2079 
  2080 static struct malloc_params mparams;
  2081 
  2082 /* The global malloc_state used for all non-"mspace" calls */
  2083 static struct malloc_state _gm_;
  2084 #define gm                 (&_gm_)
  2085 #define is_global(M)       ((M) == &_gm_)
  2086 #define is_initialized(M)  ((M)->top != 0)
  2087 
  2088 /* -------------------------- system alloc setup ------------------------- */
  2089 
  2090 /* Operations on mflags */
  2091 
  2092 #define use_lock(M)           ((M)->mflags &   USE_LOCK_BIT)
  2093 #define enable_lock(M)        ((M)->mflags |=  USE_LOCK_BIT)
  2094 #define disable_lock(M)       ((M)->mflags &= ~USE_LOCK_BIT)
  2095 
  2096 #define use_mmap(M)           ((M)->mflags &   USE_MMAP_BIT)
  2097 #define enable_mmap(M)        ((M)->mflags |=  USE_MMAP_BIT)
  2098 #define disable_mmap(M)       ((M)->mflags &= ~USE_MMAP_BIT)
  2099 
  2100 #define use_noncontiguous(M)  ((M)->mflags &   USE_NONCONTIGUOUS_BIT)
  2101 #define disable_contiguous(M) ((M)->mflags |=  USE_NONCONTIGUOUS_BIT)
  2102 
  2103 #define set_lock(M,L)\
  2104  ((M)->mflags = (L)?\
  2105   ((M)->mflags | USE_LOCK_BIT) :\
  2106   ((M)->mflags & ~USE_LOCK_BIT))
  2107 
  2108 /* page-align a size */
  2109 #define page_align(S)\
  2110  (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE))
  2111 
  2112 /* granularity-align a size */
  2113 #define granularity_align(S)\
  2114   (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE))
  2115 
  2116 #define is_page_aligned(S)\
  2117    (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
  2118 #define is_granularity_aligned(S)\
  2119    (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
  2120 
  2121 /*  True if segment S holds address A */
  2122 #define segment_holds(S, A)\
  2123   ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
  2124 
  2125 /* Return segment holding given address */
  2126 static msegmentptr
  2127 segment_holding(mstate m, char *addr)
  2128 {
  2129     msegmentptr sp = &m->seg;
  2130     for (;;) {
  2131         if (addr >= sp->base && addr < sp->base + sp->size)
  2132             return sp;
  2133         if ((sp = sp->next) == 0)
  2134             return 0;
  2135     }
  2136 }
  2137 
  2138 /* Return true if segment contains a segment link */
  2139 static int
  2140 has_segment_link(mstate m, msegmentptr ss)
  2141 {
  2142     msegmentptr sp = &m->seg;
  2143     for (;;) {
  2144         if ((char *) sp >= ss->base && (char *) sp < ss->base + ss->size)
  2145             return 1;
  2146         if ((sp = sp->next) == 0)
  2147             return 0;
  2148     }
  2149 }
  2150 
  2151 #ifndef MORECORE_CANNOT_TRIM
  2152 #define should_trim(M,s)  ((s) > (M)->trim_check)
  2153 #else /* MORECORE_CANNOT_TRIM */
  2154 #define should_trim(M,s)  (0)
  2155 #endif /* MORECORE_CANNOT_TRIM */
  2156 
  2157 /*
  2158   TOP_FOOT_SIZE is padding at the end of a segment, including space
  2159   that may be needed to place segment records and fenceposts when new
  2160   noncontiguous segments are added.
  2161 */
  2162 #define TOP_FOOT_SIZE\
  2163   (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
  2164 
  2165 
  2166 /* -------------------------------  Hooks -------------------------------- */
  2167 
  2168 /*
  2169   PREACTION should be defined to return 0 on success, and nonzero on
  2170   failure. If you are not using locking, you can redefine these to do
  2171   anything you like.
  2172 */
  2173 
  2174 #if USE_LOCKS
  2175 
  2176 /* Ensure locks are initialized */
  2177 #define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams())
  2178 
  2179 #define PREACTION(M)  ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
  2180 #define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
  2181 #else /* USE_LOCKS */
  2182 
  2183 #ifndef PREACTION
  2184 #define PREACTION(M) (0)
  2185 #endif /* PREACTION */
  2186 
  2187 #ifndef POSTACTION
  2188 #define POSTACTION(M)
  2189 #endif /* POSTACTION */
  2190 
  2191 #endif /* USE_LOCKS */
  2192 
  2193 /*
  2194   CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
  2195   USAGE_ERROR_ACTION is triggered on detected bad frees and
  2196   reallocs. The argument p is an address that might have triggered the
  2197   fault. It is ignored by the two predefined actions, but might be
  2198   useful in custom actions that try to help diagnose errors.
  2199 */
  2200 
  2201 #if PROCEED_ON_ERROR
  2202 
  2203 /* A count of the number of corruption errors causing resets */
  2204 int malloc_corruption_error_count;
  2205 
  2206 /* default corruption action */
  2207 static void reset_on_error(mstate m);
  2208 
  2209 #define CORRUPTION_ERROR_ACTION(m)  reset_on_error(m)
  2210 #define USAGE_ERROR_ACTION(m, p)
  2211 
  2212 #else /* PROCEED_ON_ERROR */
  2213 
  2214 #ifndef CORRUPTION_ERROR_ACTION
  2215 #define CORRUPTION_ERROR_ACTION(m) ABORT
  2216 #endif /* CORRUPTION_ERROR_ACTION */
  2217 
  2218 #ifndef USAGE_ERROR_ACTION
  2219 #define USAGE_ERROR_ACTION(m,p) ABORT
  2220 #endif /* USAGE_ERROR_ACTION */
  2221 
  2222 #endif /* PROCEED_ON_ERROR */
  2223 
  2224 /* -------------------------- Debugging setup ---------------------------- */
  2225 
  2226 #if ! DEBUG
  2227 
  2228 #define check_free_chunk(M,P)
  2229 #define check_inuse_chunk(M,P)
  2230 #define check_malloced_chunk(M,P,N)
  2231 #define check_mmapped_chunk(M,P)
  2232 #define check_malloc_state(M)
  2233 #define check_top_chunk(M,P)
  2234 
  2235 #else /* DEBUG */
  2236 #define check_free_chunk(M,P)       do_check_free_chunk(M,P)
  2237 #define check_inuse_chunk(M,P)      do_check_inuse_chunk(M,P)
  2238 #define check_top_chunk(M,P)        do_check_top_chunk(M,P)
  2239 #define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
  2240 #define check_mmapped_chunk(M,P)    do_check_mmapped_chunk(M,P)
  2241 #define check_malloc_state(M)       do_check_malloc_state(M)
  2242 
  2243 static void do_check_any_chunk(mstate m, mchunkptr p);
  2244 static void do_check_top_chunk(mstate m, mchunkptr p);
  2245 static void do_check_mmapped_chunk(mstate m, mchunkptr p);
  2246 static void do_check_inuse_chunk(mstate m, mchunkptr p);
  2247 static void do_check_free_chunk(mstate m, mchunkptr p);
  2248 static void do_check_malloced_chunk(mstate m, void *mem, size_t s);
  2249 static void do_check_tree(mstate m, tchunkptr t);
  2250 static void do_check_treebin(mstate m, bindex_t i);
  2251 static void do_check_smallbin(mstate m, bindex_t i);
  2252 static void do_check_malloc_state(mstate m);
  2253 static int bin_find(mstate m, mchunkptr x);
  2254 static size_t traverse_and_check(mstate m);
  2255 #endif /* DEBUG */
  2256 
  2257 /* ---------------------------- Indexing Bins ---------------------------- */
  2258 
  2259 #define is_small(s)         (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
  2260 #define small_index(s)      ((s)  >> SMALLBIN_SHIFT)
  2261 #define small_index2size(i) ((i)  << SMALLBIN_SHIFT)
  2262 #define MIN_SMALL_INDEX     (small_index(MIN_CHUNK_SIZE))
  2263 
  2264 /* addressing by index. See above about smallbin repositioning */
  2265 #define smallbin_at(M, i)   ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
  2266 #define treebin_at(M,i)     (&((M)->treebins[i]))
  2267 
  2268 /* assign tree index for size S to variable I */
  2269 #if defined(__GNUC__) && defined(i386)
  2270 #define compute_tree_index(S, I)\
  2271 {\
  2272   size_t X = S >> TREEBIN_SHIFT;\
  2273   if (X == 0)\
  2274     I = 0;\
  2275   else if (X > 0xFFFF)\
  2276     I = NTREEBINS-1;\
  2277   else {\
  2278     unsigned int K;\
  2279     __asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm"  (X));\
  2280     I =  (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
  2281   }\
  2282 }
  2283 #else /* GNUC */
  2284 #define compute_tree_index(S, I)\
  2285 {\
  2286   size_t X = S >> TREEBIN_SHIFT;\
  2287   if (X == 0)\
  2288     I = 0;\
  2289   else if (X > 0xFFFF)\
  2290     I = NTREEBINS-1;\
  2291   else {\
  2292     unsigned int Y = (unsigned int)X;\
  2293     unsigned int N = ((Y - 0x100) >> 16) & 8;\
  2294     unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
  2295     N += K;\
  2296     N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
  2297     K = 14 - N + ((Y <<= K) >> 15);\
  2298     I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
  2299   }\
  2300 }
  2301 #endif /* GNUC */
  2302 
  2303 /* Bit representing maximum resolved size in a treebin at i */
  2304 #define bit_for_tree_index(i) \
  2305    (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
  2306 
  2307 /* Shift placing maximum resolved bit in a treebin at i as sign bit */
  2308 #define leftshift_for_tree_index(i) \
  2309    ((i == NTREEBINS-1)? 0 : \
  2310     ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
  2311 
  2312 /* The size of the smallest chunk held in bin with index i */
  2313 #define minsize_for_tree_index(i) \
  2314    ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) |  \
  2315    (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
  2316 
  2317 
  2318 /* ------------------------ Operations on bin maps ----------------------- */
  2319 
  2320 /* bit corresponding to given index */
  2321 #define idx2bit(i)              ((binmap_t)(1) << (i))
  2322 
  2323 /* Mark/Clear bits with given index */
  2324 #define mark_smallmap(M,i)      ((M)->smallmap |=  idx2bit(i))
  2325 #define clear_smallmap(M,i)     ((M)->smallmap &= ~idx2bit(i))
  2326 #define smallmap_is_marked(M,i) ((M)->smallmap &   idx2bit(i))
  2327 
  2328 #define mark_treemap(M,i)       ((M)->treemap  |=  idx2bit(i))
  2329 #define clear_treemap(M,i)      ((M)->treemap  &= ~idx2bit(i))
  2330 #define treemap_is_marked(M,i)  ((M)->treemap  &   idx2bit(i))
  2331 
  2332 /* index corresponding to given bit */
  2333 
  2334 #if defined(__GNUC__) && defined(i386)
  2335 #define compute_bit2idx(X, I)\
  2336 {\
  2337   unsigned int J;\
  2338   __asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\
  2339   I = (bindex_t)J;\
  2340 }
  2341 
  2342 #else /* GNUC */
  2343 #if  USE_BUILTIN_FFS
  2344 #define compute_bit2idx(X, I) I = ffs(X)-1
  2345 
  2346 #else /* USE_BUILTIN_FFS */
  2347 #define compute_bit2idx(X, I)\
  2348 {\
  2349   unsigned int Y = X - 1;\
  2350   unsigned int K = Y >> (16-4) & 16;\
  2351   unsigned int N = K;        Y >>= K;\
  2352   N += K = Y >> (8-3) &  8;  Y >>= K;\
  2353   N += K = Y >> (4-2) &  4;  Y >>= K;\
  2354   N += K = Y >> (2-1) &  2;  Y >>= K;\
  2355   N += K = Y >> (1-0) &  1;  Y >>= K;\
  2356   I = (bindex_t)(N + Y);\
  2357 }
  2358 #endif /* USE_BUILTIN_FFS */
  2359 #endif /* GNUC */
  2360 
  2361 /* isolate the least set bit of a bitmap */
  2362 #define least_bit(x)         ((x) & -(x))
  2363 
  2364 /* mask with all bits to left of least bit of x on */
  2365 #define left_bits(x)         ((x<<1) | -(x<<1))
  2366 
  2367 /* mask with all bits to left of or equal to least bit of x on */
  2368 #define same_or_left_bits(x) ((x) | -(x))
  2369 
  2370 
  2371 /* ----------------------- Runtime Check Support ------------------------- */
  2372 
  2373 /*
  2374   For security, the main invariant is that malloc/free/etc never
  2375   writes to a static address other than malloc_state, unless static
  2376   malloc_state itself has been corrupted, which cannot occur via
  2377   malloc (because of these checks). In essence this means that we
  2378   believe all pointers, sizes, maps etc held in malloc_state, but
  2379   check all of those linked or offsetted from other embedded data
  2380   structures.  These checks are interspersed with main code in a way
  2381   that tends to minimize their run-time cost.
  2382 
  2383   When FOOTERS is defined, in addition to range checking, we also
  2384   verify footer fields of inuse chunks, which can be used guarantee
  2385   that the mstate controlling malloc/free is intact.  This is a
  2386   streamlined version of the approach described by William Robertson
  2387   et al in "Run-time Detection of Heap-based Overflows" LISA'03
  2388   http://www.usenix.org/events/lisa03/tech/robertson.html The footer
  2389   of an inuse chunk holds the xor of its mstate and a random seed,
  2390   that is checked upon calls to free() and realloc().  This is
  2391   (probablistically) unguessable from outside the program, but can be
  2392   computed by any code successfully malloc'ing any chunk, so does not
  2393   itself provide protection against code that has already broken
  2394   security through some other means.  Unlike Robertson et al, we
  2395   always dynamically check addresses of all offset chunks (previous,
  2396   next, etc). This turns out to be cheaper than relying on hashes.
  2397 */
  2398 
  2399 #if !INSECURE
  2400 /* Check if address a is at least as high as any from MORECORE or MMAP */
  2401 #define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
  2402 /* Check if address of next chunk n is higher than base chunk p */
  2403 #define ok_next(p, n)    ((char*)(p) < (char*)(n))
  2404 /* Check if p has its cinuse bit on */
  2405 #define ok_cinuse(p)     cinuse(p)
  2406 /* Check if p has its pinuse bit on */
  2407 #define ok_pinuse(p)     pinuse(p)
  2408 
  2409 #else /* !INSECURE */
  2410 #define ok_address(M, a) (1)
  2411 #define ok_next(b, n)    (1)
  2412 #define ok_cinuse(p)     (1)
  2413 #define ok_pinuse(p)     (1)
  2414 #endif /* !INSECURE */
  2415 
  2416 #if (FOOTERS && !INSECURE)
  2417 /* Check if (alleged) mstate m has expected magic field */
  2418 #define ok_magic(M)      ((M)->magic == mparams.magic)
  2419 #else /* (FOOTERS && !INSECURE) */
  2420 #define ok_magic(M)      (1)
  2421 #endif /* (FOOTERS && !INSECURE) */
  2422 
  2423 
  2424 /* In gcc, use __builtin_expect to minimize impact of checks */
  2425 #if !INSECURE
  2426 #if defined(__GNUC__) && __GNUC__ >= 3
  2427 #define RTCHECK(e)  __builtin_expect(e, 1)
  2428 #else /* GNUC */
  2429 #define RTCHECK(e)  (e)
  2430 #endif /* GNUC */
  2431 #else /* !INSECURE */
  2432 #define RTCHECK(e)  (1)
  2433 #endif /* !INSECURE */
  2434 
  2435 /* macros to set up inuse chunks with or without footers */
  2436 
  2437 #if !FOOTERS
  2438 
  2439 #define mark_inuse_foot(M,p,s)
  2440 
  2441 /* Set cinuse bit and pinuse bit of next chunk */
  2442 #define set_inuse(M,p,s)\
  2443   ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
  2444   ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
  2445 
  2446 /* Set cinuse and pinuse of this chunk and pinuse of next chunk */
  2447 #define set_inuse_and_pinuse(M,p,s)\
  2448   ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
  2449   ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
  2450 
  2451 /* Set size, cinuse and pinuse bit of this chunk */
  2452 #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
  2453   ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
  2454 
  2455 #else /* FOOTERS */
  2456 
  2457 /* Set foot of inuse chunk to be xor of mstate and seed */
  2458 #define mark_inuse_foot(M,p,s)\
  2459   (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
  2460 
  2461 #define get_mstate_for(p)\
  2462   ((mstate)(((mchunkptr)((char*)(p) +\
  2463     (chunksize(p))))->prev_foot ^ mparams.magic))
  2464 
  2465 #define set_inuse(M,p,s)\
  2466   ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
  2467   (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
  2468   mark_inuse_foot(M,p,s))
  2469 
  2470 #define set_inuse_and_pinuse(M,p,s)\
  2471   ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
  2472   (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
  2473  mark_inuse_foot(M,p,s))
  2474 
  2475 #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
  2476   ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
  2477   mark_inuse_foot(M, p, s))
  2478 
  2479 #endif /* !FOOTERS */
  2480 
  2481 /* ---------------------------- setting mparams -------------------------- */
  2482 
  2483 /* Initialize mparams */
  2484 static int
  2485 init_mparams(void)
  2486 {
  2487     if (mparams.page_size == 0) {
  2488         size_t s;
  2489 
  2490         mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
  2491         mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
  2492 #if MORECORE_CONTIGUOUS
  2493         mparams.default_mflags = USE_LOCK_BIT | USE_MMAP_BIT;
  2494 #else /* MORECORE_CONTIGUOUS */
  2495         mparams.default_mflags =
  2496             USE_LOCK_BIT | USE_MMAP_BIT | USE_NONCONTIGUOUS_BIT;
  2497 #endif /* MORECORE_CONTIGUOUS */
  2498 
  2499 #if (FOOTERS && !INSECURE)
  2500         {
  2501 #if USE_DEV_RANDOM
  2502             int fd;
  2503             unsigned char buf[sizeof(size_t)];
  2504             /* Try to use /dev/urandom, else fall back on using time */
  2505             if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
  2506                 read(fd, buf, sizeof(buf)) == sizeof(buf)) {
  2507                 s = *((size_t *) buf);
  2508                 close(fd);
  2509             } else
  2510 #endif /* USE_DEV_RANDOM */
  2511                 s = (size_t) (time(0) ^ (size_t) 0x55555555U);
  2512 
  2513             s |= (size_t) 8U;   /* ensure nonzero */
  2514             s &= ~(size_t) 7U;  /* improve chances of fault for bad values */
  2515 
  2516         }
  2517 #else /* (FOOTERS && !INSECURE) */
  2518         s = (size_t) 0x58585858U;
  2519 #endif /* (FOOTERS && !INSECURE) */
  2520         ACQUIRE_MAGIC_INIT_LOCK();
  2521         if (mparams.magic == 0) {
  2522             mparams.magic = s;
  2523             /* Set up lock for main malloc area */
  2524             INITIAL_LOCK(&gm->mutex);
  2525             gm->mflags = mparams.default_mflags;
  2526         }
  2527         RELEASE_MAGIC_INIT_LOCK();
  2528 
  2529 #ifndef WIN32
  2530         mparams.page_size = malloc_getpagesize;
  2531         mparams.granularity = ((DEFAULT_GRANULARITY != 0) ?
  2532                                DEFAULT_GRANULARITY : mparams.page_size);
  2533 #else /* WIN32 */
  2534         {
  2535             SYSTEM_INFO system_info;
  2536             GetSystemInfo(&system_info);
  2537             mparams.page_size = system_info.dwPageSize;
  2538             mparams.granularity = system_info.dwAllocationGranularity;
  2539         }
  2540 #endif /* WIN32 */
  2541 
  2542         /* Sanity-check configuration:
  2543            size_t must be unsigned and as wide as pointer type.
  2544            ints must be at least 4 bytes.
  2545            alignment must be at least 8.
  2546            Alignment, min chunk size, and page size must all be powers of 2.
  2547          */
  2548         if ((sizeof(size_t) != sizeof(char *)) ||
  2549             (MAX_SIZE_T < MIN_CHUNK_SIZE) ||
  2550             (sizeof(int) < 4) ||
  2551             (MALLOC_ALIGNMENT < (size_t) 8U) ||
  2552             ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - SIZE_T_ONE)) != 0) ||
  2553             ((MCHUNK_SIZE & (MCHUNK_SIZE - SIZE_T_ONE)) != 0) ||
  2554             ((mparams.granularity & (mparams.granularity - SIZE_T_ONE)) != 0)
  2555             || ((mparams.page_size & (mparams.page_size - SIZE_T_ONE)) != 0))
  2556             ABORT;
  2557     }
  2558     return 0;
  2559 }
  2560 
  2561 /* support for mallopt */
  2562 static int
  2563 change_mparam(int param_number, int value)
  2564 {
  2565     size_t val = (size_t) value;
  2566     init_mparams();
  2567     switch (param_number) {
  2568     case M_TRIM_THRESHOLD:
  2569         mparams.trim_threshold = val;
  2570         return 1;
  2571     case M_GRANULARITY:
  2572         if (val >= mparams.page_size && ((val & (val - 1)) == 0)) {
  2573             mparams.granularity = val;
  2574             return 1;
  2575         } else
  2576             return 0;
  2577     case M_MMAP_THRESHOLD:
  2578         mparams.mmap_threshold = val;
  2579         return 1;
  2580     default:
  2581         return 0;
  2582     }
  2583 }
  2584 
  2585 #if DEBUG
  2586 /* ------------------------- Debugging Support --------------------------- */
  2587 
  2588 /* Check properties of any chunk, whether free, inuse, mmapped etc  */
  2589 static void
  2590 do_check_any_chunk(mstate m, mchunkptr p)
  2591 {
  2592     assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
  2593     assert(ok_address(m, p));
  2594 }
  2595 
  2596 /* Check properties of top chunk */
  2597 static void
  2598 do_check_top_chunk(mstate m, mchunkptr p)
  2599 {
  2600     msegmentptr sp = segment_holding(m, (char *) p);
  2601     size_t sz = chunksize(p);
  2602     assert(sp != 0);
  2603     assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
  2604     assert(ok_address(m, p));
  2605     assert(sz == m->topsize);
  2606     assert(sz > 0);
  2607     assert(sz == ((sp->base + sp->size) - (char *) p) - TOP_FOOT_SIZE);
  2608     assert(pinuse(p));
  2609     assert(!next_pinuse(p));
  2610 }
  2611 
  2612 /* Check properties of (inuse) mmapped chunks */
  2613 static void
  2614 do_check_mmapped_chunk(mstate m, mchunkptr p)
  2615 {
  2616     size_t sz = chunksize(p);
  2617     size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD);
  2618     assert(is_mmapped(p));
  2619     assert(use_mmap(m));
  2620     assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
  2621     assert(ok_address(m, p));
  2622     assert(!is_small(sz));
  2623     assert((len & (mparams.page_size - SIZE_T_ONE)) == 0);
  2624     assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
  2625     assert(chunk_plus_offset(p, sz + SIZE_T_SIZE)->head == 0);
  2626 }
  2627 
  2628 /* Check properties of inuse chunks */
  2629 static void
  2630 do_check_inuse_chunk(mstate m, mchunkptr p)
  2631 {
  2632     do_check_any_chunk(m, p);
  2633     assert(cinuse(p));
  2634     assert(next_pinuse(p));
  2635     /* If not pinuse and not mmapped, previous chunk has OK offset */
  2636     assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
  2637     if (is_mmapped(p))
  2638         do_check_mmapped_chunk(m, p);
  2639 }
  2640 
  2641 /* Check properties of free chunks */
  2642 static void
  2643 do_check_free_chunk(mstate m, mchunkptr p)
  2644 {
  2645     size_t sz = p->head & ~(PINUSE_BIT | CINUSE_BIT);
  2646     mchunkptr next = chunk_plus_offset(p, sz);
  2647     do_check_any_chunk(m, p);
  2648     assert(!cinuse(p));
  2649     assert(!next_pinuse(p));
  2650     assert(!is_mmapped(p));
  2651     if (p != m->dv && p != m->top) {
  2652         if (sz >= MIN_CHUNK_SIZE) {
  2653             assert((sz & CHUNK_ALIGN_MASK) == 0);
  2654             assert(is_aligned(chunk2mem(p)));
  2655             assert(next->prev_foot == sz);
  2656             assert(pinuse(p));
  2657             assert(next == m->top || cinuse(next));
  2658             assert(p->fd->bk == p);
  2659             assert(p->bk->fd == p);
  2660         } else                  /* markers are always of size SIZE_T_SIZE */
  2661             assert(sz == SIZE_T_SIZE);
  2662     }
  2663 }
  2664 
  2665 /* Check properties of malloced chunks at the point they are malloced */
  2666 static void
  2667 do_check_malloced_chunk(mstate m, void *mem, size_t s)
  2668 {
  2669     if (mem != 0) {
  2670         mchunkptr p = mem2chunk(mem);
  2671         size_t sz = p->head & ~(PINUSE_BIT | CINUSE_BIT);
  2672         do_check_inuse_chunk(m, p);
  2673         assert((sz & CHUNK_ALIGN_MASK) == 0);
  2674         assert(sz >= MIN_CHUNK_SIZE);
  2675         assert(sz >= s);
  2676         /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
  2677         assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
  2678     }
  2679 }
  2680 
  2681 /* Check a tree and its subtrees.  */
  2682 static void
  2683 do_check_tree(mstate m, tchunkptr t)
  2684 {
  2685     tchunkptr head = 0;
  2686     tchunkptr u = t;
  2687     bindex_t tindex = t->index;
  2688     size_t tsize = chunksize(t);
  2689     bindex_t idx;
  2690     compute_tree_index(tsize, idx);
  2691     assert(tindex == idx);
  2692     assert(tsize >= MIN_LARGE_SIZE);
  2693     assert(tsize >= minsize_for_tree_index(idx));
  2694     assert((idx == NTREEBINS - 1)
  2695            || (tsize < minsize_for_tree_index((idx + 1))));
  2696 
  2697     do {                        /* traverse through chain of same-sized nodes */
  2698         do_check_any_chunk(m, ((mchunkptr) u));
  2699         assert(u->index == tindex);
  2700         assert(chunksize(u) == tsize);
  2701         assert(!cinuse(u));
  2702         assert(!next_pinuse(u));
  2703         assert(u->fd->bk == u);
  2704         assert(u->bk->fd == u);
  2705         if (u->parent == 0) {
  2706             assert(u->child[0] == 0);
  2707             assert(u->child[1] == 0);
  2708         } else {
  2709             assert(head == 0);  /* only one node on chain has parent */
  2710             head = u;
  2711             assert(u->parent != u);
  2712             assert(u->parent->child[0] == u ||
  2713                    u->parent->child[1] == u ||
  2714                    *((tbinptr *) (u->parent)) == u);
  2715             if (u->child[0] != 0) {
  2716                 assert(u->child[0]->parent == u);
  2717                 assert(u->child[0] != u);
  2718                 do_check_tree(m, u->child[0]);
  2719             }
  2720             if (u->child[1] != 0) {
  2721                 assert(u->child[1]->parent == u);
  2722                 assert(u->child[1] != u);
  2723                 do_check_tree(m, u->child[1]);
  2724             }
  2725             if (u->child[0] != 0 && u->child[1] != 0) {
  2726                 assert(chunksize(u->child[0]) < chunksize(u->child[1]));
  2727             }
  2728         }
  2729         u = u->fd;
  2730     } while (u != t);
  2731     assert(head != 0);
  2732 }
  2733 
  2734 /*  Check all the chunks in a treebin.  */
  2735 static void
  2736 do_check_treebin(mstate m, bindex_t i)
  2737 {
  2738     tbinptr *tb = treebin_at(m, i);
  2739     tchunkptr t = *tb;
  2740     int empty = (m->treemap & (1U << i)) == 0;
  2741     if (t == 0)
  2742         assert(empty);
  2743     if (!empty)
  2744         do_check_tree(m, t);
  2745 }
  2746 
  2747 /*  Check all the chunks in a smallbin.  */
  2748 static void
  2749 do_check_smallbin(mstate m, bindex_t i)
  2750 {
  2751     sbinptr b = smallbin_at(m, i);
  2752     mchunkptr p = b->bk;
  2753     unsigned int empty = (m->smallmap & (1U << i)) == 0;
  2754     if (p == b)
  2755         assert(empty);
  2756     if (!empty) {
  2757         for (; p != b; p = p->bk) {
  2758             size_t size = chunksize(p);
  2759             mchunkptr q;
  2760             /* each chunk claims to be free */
  2761             do_check_free_chunk(m, p);
  2762             /* chunk belongs in bin */
  2763             assert(small_index(size) == i);
  2764             assert(p->bk == b || chunksize(p->bk) == chunksize(p));
  2765             /* chunk is followed by an inuse chunk */
  2766             q = next_chunk(p);
  2767             if (q->head != FENCEPOST_HEAD)
  2768                 do_check_inuse_chunk(m, q);
  2769         }
  2770     }
  2771 }
  2772 
  2773 /* Find x in a bin. Used in other check functions. */
  2774 static int
  2775 bin_find(mstate m, mchunkptr x)
  2776 {
  2777     size_t size = chunksize(x);
  2778     if (is_small(size)) {
  2779         bindex_t sidx = small_index(size);
  2780         sbinptr b = smallbin_at(m, sidx);
  2781         if (smallmap_is_marked(m, sidx)) {
  2782             mchunkptr p = b;
  2783             do {
  2784                 if (p == x)
  2785                     return 1;
  2786             } while ((p = p->fd) != b);
  2787         }
  2788     } else {
  2789         bindex_t tidx;
  2790         compute_tree_index(size, tidx);
  2791         if (treemap_is_marked(m, tidx)) {
  2792             tchunkptr t = *treebin_at(m, tidx);
  2793             size_t sizebits = size << leftshift_for_tree_index(tidx);
  2794             while (t != 0 && chunksize(t) != size) {
  2795                 t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1];
  2796                 sizebits <<= 1;
  2797             }
  2798             if (t != 0) {
  2799                 tchunkptr u = t;
  2800                 do {
  2801                     if (u == (tchunkptr) x)
  2802                         return 1;
  2803                 } while ((u = u->fd) != t);
  2804             }
  2805         }
  2806     }
  2807     return 0;
  2808 }
  2809 
  2810 /* Traverse each chunk and check it; return total */
  2811 static size_t
  2812 traverse_and_check(mstate m)
  2813 {
  2814     size_t sum = 0;
  2815     if (is_initialized(m)) {
  2816         msegmentptr s = &m->seg;
  2817         sum += m->topsize + TOP_FOOT_SIZE;
  2818         while (s != 0) {
  2819             mchunkptr q = align_as_chunk(s->base);
  2820             mchunkptr lastq = 0;
  2821             assert(pinuse(q));
  2822             while (segment_holds(s, q) &&
  2823                    q != m->top && q->head != FENCEPOST_HEAD) {
  2824                 sum += chunksize(q);
  2825                 if (cinuse(q)) {
  2826                     assert(!bin_find(m, q));
  2827                     do_check_inuse_chunk(m, q);
  2828                 } else {
  2829                     assert(q == m->dv || bin_find(m, q));
  2830                     assert(lastq == 0 || cinuse(lastq));        /* Not 2 consecutive free */
  2831                     do_check_free_chunk(m, q);
  2832                 }
  2833                 lastq = q;
  2834                 q = next_chunk(q);
  2835             }
  2836             s = s->next;
  2837         }
  2838     }
  2839     return sum;
  2840 }
  2841 
  2842 /* Check all properties of malloc_state. */
  2843 static void
  2844 do_check_malloc_state(mstate m)
  2845 {
  2846     bindex_t i;
  2847     size_t total;
  2848     /* check bins */
  2849     for (i = 0; i < NSMALLBINS; ++i)
  2850         do_check_smallbin(m, i);
  2851     for (i = 0; i < NTREEBINS; ++i)
  2852         do_check_treebin(m, i);
  2853 
  2854     if (m->dvsize != 0) {       /* check dv chunk */
  2855         do_check_any_chunk(m, m->dv);
  2856         assert(m->dvsize == chunksize(m->dv));
  2857         assert(m->dvsize >= MIN_CHUNK_SIZE);
  2858         assert(bin_find(m, m->dv) == 0);
  2859     }
  2860 
  2861     if (m->top != 0) {          /* check top chunk */
  2862         do_check_top_chunk(m, m->top);
  2863         assert(m->topsize == chunksize(m->top));
  2864         assert(m->topsize > 0);
  2865         assert(bin_find(m, m->top) == 0);
  2866     }
  2867 
  2868     total = traverse_and_check(m);
  2869     assert(total <= m->footprint);
  2870     assert(m->footprint <= m->max_footprint);
  2871 }
  2872 #endif /* DEBUG */
  2873 
  2874 /* ----------------------------- statistics ------------------------------ */
  2875 
  2876 #if !NO_MALLINFO
  2877 static struct mallinfo
  2878 internal_mallinfo(mstate m)
  2879 {
  2880     struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  2881     if (!PREACTION(m)) {
  2882         check_malloc_state(m);
  2883         if (is_initialized(m)) {
  2884             size_t nfree = SIZE_T_ONE;  /* top always free */
  2885             size_t mfree = m->topsize + TOP_FOOT_SIZE;
  2886             size_t sum = mfree;
  2887             msegmentptr s = &m->seg;
  2888             while (s != 0) {
  2889                 mchunkptr q = align_as_chunk(s->base);
  2890                 while (segment_holds(s, q) &&
  2891                        q != m->top && q->head != FENCEPOST_HEAD) {
  2892                     size_t sz = chunksize(q);
  2893                     sum += sz;
  2894                     if (!cinuse(q)) {
  2895                         mfree += sz;
  2896                         ++nfree;
  2897                     }
  2898                     q = next_chunk(q);
  2899                 }
  2900                 s = s->next;
  2901             }
  2902 
  2903             nm.arena = sum;
  2904             nm.ordblks = nfree;
  2905             nm.hblkhd = m->footprint - sum;
  2906             nm.usmblks = m->max_footprint;
  2907             nm.uordblks = m->footprint - mfree;
  2908             nm.fordblks = mfree;
  2909             nm.keepcost = m->topsize;
  2910         }
  2911 
  2912         POSTACTION(m);
  2913     }
  2914     return nm;
  2915 }
  2916 #endif /* !NO_MALLINFO */
  2917 
  2918 static void
  2919 internal_malloc_stats(mstate m)
  2920 {
  2921     if (!PREACTION(m)) {
  2922         size_t maxfp = 0;
  2923         size_t fp = 0;
  2924         size_t used = 0;
  2925         check_malloc_state(m);
  2926         if (is_initialized(m)) {
  2927             msegmentptr s = &m->seg;
  2928             maxfp = m->max_footprint;
  2929             fp = m->footprint;
  2930             used = fp - (m->topsize + TOP_FOOT_SIZE);
  2931 
  2932             while (s != 0) {
  2933                 mchunkptr q = align_as_chunk(s->base);
  2934                 while (segment_holds(s, q) &&
  2935                        q != m->top && q->head != FENCEPOST_HEAD) {
  2936                     if (!cinuse(q))
  2937                         used -= chunksize(q);
  2938                     q = next_chunk(q);
  2939                 }
  2940                 s = s->next;
  2941             }
  2942         }
  2943 #ifndef LACKS_STDIO_H
  2944         fprintf(stderr, "max system bytes = %10lu\n",
  2945                 (unsigned long) (maxfp));
  2946         fprintf(stderr, "system bytes     = %10lu\n", (unsigned long) (fp));
  2947         fprintf(stderr, "in use bytes     = %10lu\n", (unsigned long) (used));
  2948 #endif
  2949 
  2950         POSTACTION(m);
  2951     }
  2952 }
  2953 
  2954 /* ----------------------- Operations on smallbins ----------------------- */
  2955 
  2956 /*
  2957   Various forms of linking and unlinking are defined as macros.  Even
  2958   the ones for trees, which are very long but have very short typical
  2959   paths.  This is ugly but reduces reliance on inlining support of
  2960   compilers.
  2961 */
  2962 
  2963 /* Link a free chunk into a smallbin  */
  2964 #define insert_small_chunk(M, P, S) {\
  2965   bindex_t I  = small_index(S);\
  2966   mchunkptr B = smallbin_at(M, I);\
  2967   mchunkptr F = B;\
  2968   assert(S >= MIN_CHUNK_SIZE);\
  2969   if (!smallmap_is_marked(M, I))\
  2970     mark_smallmap(M, I);\
  2971   else if (RTCHECK(ok_address(M, B->fd)))\
  2972     F = B->fd;\
  2973   else {\
  2974     CORRUPTION_ERROR_ACTION(M);\
  2975   }\
  2976   B->fd = P;\
  2977   F->bk = P;\
  2978   P->fd = F;\
  2979   P->bk = B;\
  2980 }
  2981 
  2982 /* Unlink a chunk from a smallbin  */
  2983 #define unlink_small_chunk(M, P, S) {\
  2984   mchunkptr F = P->fd;\
  2985   mchunkptr B = P->bk;\
  2986   bindex_t I = small_index(S);\
  2987   assert(P != B);\
  2988   assert(P != F);\
  2989   assert(chunksize(P) == small_index2size(I));\
  2990   if (F == B)\
  2991     clear_smallmap(M, I);\
  2992   else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
  2993                    (B == smallbin_at(M,I) || ok_address(M, B)))) {\
  2994     F->bk = B;\
  2995     B->fd = F;\
  2996   }\
  2997   else {\
  2998     CORRUPTION_ERROR_ACTION(M);\
  2999   }\
  3000 }
  3001 
  3002 /* Unlink the first chunk from a smallbin */
  3003 #define unlink_first_small_chunk(M, B, P, I) {\
  3004   mchunkptr F = P->fd;\
  3005   assert(P != B);\
  3006   assert(P != F);\
  3007   assert(chunksize(P) == small_index2size(I));\
  3008   if (B == F)\
  3009     clear_smallmap(M, I);\
  3010   else if (RTCHECK(ok_address(M, F))) {\
  3011     B->fd = F;\
  3012     F->bk = B;\
  3013   }\
  3014   else {\
  3015     CORRUPTION_ERROR_ACTION(M);\
  3016   }\
  3017 }
  3018 
  3019 /* Replace dv node, binning the old one */
  3020 /* Used only when dvsize known to be small */
  3021 #define replace_dv(M, P, S) {\
  3022   size_t DVS = M->dvsize;\
  3023   if (DVS != 0) {\
  3024     mchunkptr DV = M->dv;\
  3025     assert(is_small(DVS));\
  3026     insert_small_chunk(M, DV, DVS);\
  3027   }\
  3028   M->dvsize = S;\
  3029   M->dv = P;\
  3030 }
  3031 
  3032 /* ------------------------- Operations on trees ------------------------- */
  3033 
  3034 /* Insert chunk into tree */
  3035 #define insert_large_chunk(M, X, S) {\
  3036   tbinptr* H;\
  3037   bindex_t I;\
  3038   compute_tree_index(S, I);\
  3039   H = treebin_at(M, I);\
  3040   X->index = I;\
  3041   X->child[0] = X->child[1] = 0;\
  3042   if (!treemap_is_marked(M, I)) {\
  3043     mark_treemap(M, I);\
  3044     *H = X;\
  3045     X->parent = (tchunkptr)H;\
  3046     X->fd = X->bk = X;\
  3047   }\
  3048   else {\
  3049     tchunkptr T = *H;\
  3050     size_t K = S << leftshift_for_tree_index(I);\
  3051     for (;;) {\
  3052       if (chunksize(T) != S) {\
  3053         tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
  3054         K <<= 1;\
  3055         if (*C != 0)\
  3056           T = *C;\
  3057         else if (RTCHECK(ok_address(M, C))) {\
  3058           *C = X;\
  3059           X->parent = T;\
  3060           X->fd = X->bk = X;\
  3061           break;\
  3062         }\
  3063         else {\
  3064           CORRUPTION_ERROR_ACTION(M);\
  3065           break;\
  3066         }\
  3067       }\
  3068       else {\
  3069         tchunkptr F = T->fd;\
  3070         if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
  3071           T->fd = F->bk = X;\
  3072           X->fd = F;\
  3073           X->bk = T;\
  3074           X->parent = 0;\
  3075           break;\
  3076         }\
  3077         else {\
  3078           CORRUPTION_ERROR_ACTION(M);\
  3079           break;\
  3080         }\
  3081       }\
  3082     }\
  3083   }\
  3084 }
  3085 
  3086 /*
  3087   Unlink steps:
  3088 
  3089   1. If x is a chained node, unlink it from its same-sized fd/bk links
  3090      and choose its bk node as its replacement.
  3091   2. If x was the last node of its size, but not a leaf node, it must
  3092      be replaced with a leaf node (not merely one with an open left or
  3093      right), to make sure that lefts and rights of descendents
  3094      correspond properly to bit masks.  We use the rightmost descendent
  3095      of x.  We could use any other leaf, but this is easy to locate and
  3096      tends to counteract removal of leftmosts elsewhere, and so keeps
  3097      paths shorter than minimally guaranteed.  This doesn't loop much
  3098      because on average a node in a tree is near the bottom.
  3099   3. If x is the base of a chain (i.e., has parent links) relink
  3100      x's parent and children to x's replacement (or null if none).
  3101 */
  3102 
  3103 #define unlink_large_chunk(M, X) {\
  3104   tchunkptr XP = X->parent;\
  3105   tchunkptr R;\
  3106   if (X->bk != X) {\
  3107     tchunkptr F = X->fd;\
  3108     R = X->bk;\
  3109     if (RTCHECK(ok_address(M, F))) {\
  3110       F->bk = R;\
  3111       R->fd = F;\
  3112     }\
  3113     else {\
  3114       CORRUPTION_ERROR_ACTION(M);\
  3115     }\
  3116   }\
  3117   else {\
  3118     tchunkptr* RP;\
  3119     if (((R = *(RP = &(X->child[1]))) != 0) ||\
  3120         ((R = *(RP = &(X->child[0]))) != 0)) {\
  3121       tchunkptr* CP;\
  3122       while ((*(CP = &(R->child[1])) != 0) ||\
  3123              (*(CP = &(R->child[0])) != 0)) {\
  3124         R = *(RP = CP);\
  3125       }\
  3126       if (RTCHECK(ok_address(M, RP)))\
  3127         *RP = 0;\
  3128       else {\
  3129         CORRUPTION_ERROR_ACTION(M);\
  3130       }\
  3131     }\
  3132   }\
  3133   if (XP != 0) {\
  3134     tbinptr* H = treebin_at(M, X->index);\
  3135     if (X == *H) {\
  3136       if ((*H = R) == 0) \
  3137         clear_treemap(M, X->index);\
  3138     }\
  3139     else if (RTCHECK(ok_address(M, XP))) {\
  3140       if (XP->child[0] == X) \
  3141         XP->child[0] = R;\
  3142       else \
  3143         XP->child[1] = R;\
  3144     }\
  3145     else\
  3146       CORRUPTION_ERROR_ACTION(M);\
  3147     if (R != 0) {\
  3148       if (RTCHECK(ok_address(M, R))) {\
  3149         tchunkptr C0, C1;\
  3150         R->parent = XP;\
  3151         if ((C0 = X->child[0]) != 0) {\
  3152           if (RTCHECK(ok_address(M, C0))) {\
  3153             R->child[0] = C0;\
  3154             C0->parent = R;\
  3155           }\
  3156           else\
  3157             CORRUPTION_ERROR_ACTION(M);\
  3158         }\
  3159         if ((C1 = X->child[1]) != 0) {\
  3160           if (RTCHECK(ok_address(M, C1))) {\
  3161             R->child[1] = C1;\
  3162             C1->parent = R;\
  3163           }\
  3164           else\
  3165             CORRUPTION_ERROR_ACTION(M);\
  3166         }\
  3167       }\
  3168       else\
  3169         CORRUPTION_ERROR_ACTION(M);\
  3170     }\
  3171   }\
  3172 }
  3173 
  3174 /* Relays to large vs small bin operations */
  3175 
  3176 #define insert_chunk(M, P, S)\
  3177   if (is_small(S)) insert_small_chunk(M, P, S)\
  3178   else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
  3179 
  3180 #define unlink_chunk(M, P, S)\
  3181   if (is_small(S)) unlink_small_chunk(M, P, S)\
  3182   else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
  3183 
  3184 
  3185 /* Relays to internal calls to malloc/free from realloc, memalign etc */
  3186 
  3187 #if ONLY_MSPACES
  3188 #define internal_malloc(m, b) mspace_malloc(m, b)
  3189 #define internal_free(m, mem) mspace_free(m,mem);
  3190 #else /* ONLY_MSPACES */
  3191 #if MSPACES
  3192 #define internal_malloc(m, b)\
  3193    (m == gm)? dlmalloc(b) : mspace_malloc(m, b)
  3194 #define internal_free(m, mem)\
  3195    if (m == gm) dlfree(mem); else mspace_free(m,mem);
  3196 #else /* MSPACES */
  3197 #define internal_malloc(m, b) dlmalloc(b)
  3198 #define internal_free(m, mem) dlfree(mem)
  3199 #endif /* MSPACES */
  3200 #endif /* ONLY_MSPACES */
  3201 
  3202 /* -----------------------  Direct-mmapping chunks ----------------------- */
  3203 
  3204 /*
  3205   Directly mmapped chunks are set up with an offset to the start of
  3206   the mmapped region stored in the prev_foot field of the chunk. This
  3207   allows reconstruction of the required argument to MUNMAP when freed,
  3208   and also allows adjustment of the returned chunk to meet alignment
  3209   requirements (especially in memalign).  There is also enough space
  3210   allocated to hold a fake next chunk of size SIZE_T_SIZE to maintain
  3211   the PINUSE bit so frees can be checked.
  3212 */
  3213 
  3214 /* Malloc using mmap */
  3215 static void *
  3216 mmap_alloc(mstate m, size_t nb)
  3217 {
  3218     size_t mmsize =
  3219         granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
  3220     if (mmsize > nb) {          /* Check for wrap around 0 */
  3221         char *mm = (char *) (DIRECT_MMAP(mmsize));
  3222         if (mm != CMFAIL) {
  3223             size_t offset = align_offset(chunk2mem(mm));
  3224             size_t psize = mmsize - offset - MMAP_FOOT_PAD;
  3225             mchunkptr p = (mchunkptr) (mm + offset);
  3226             p->prev_foot = offset | IS_MMAPPED_BIT;
  3227             (p)->head = (psize | CINUSE_BIT);
  3228             mark_inuse_foot(m, p, psize);
  3229             chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
  3230             chunk_plus_offset(p, psize + SIZE_T_SIZE)->head = 0;
  3231 
  3232             if (mm < m->least_addr)
  3233                 m->least_addr = mm;
  3234             if ((m->footprint += mmsize) > m->max_footprint)
  3235                 m->max_footprint = m->footprint;
  3236             assert(is_aligned(chunk2mem(p)));
  3237             check_mmapped_chunk(m, p);
  3238             return chunk2mem(p);
  3239         }
  3240     }
  3241     return 0;
  3242 }
  3243 
  3244 /* Realloc using mmap */
  3245 static mchunkptr
  3246 mmap_resize(mstate m, mchunkptr oldp, size_t nb)
  3247 {
  3248     size_t oldsize = chunksize(oldp);
  3249     if (is_small(nb))           /* Can't shrink mmap regions below small size */
  3250         return 0;
  3251     /* Keep old chunk if big enough but not too big */
  3252     if (oldsize >= nb + SIZE_T_SIZE &&
  3253         (oldsize - nb) <= (mparams.granularity << 1))
  3254         return oldp;
  3255     else {
  3256         size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT;
  3257         size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
  3258         size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES +
  3259                                              CHUNK_ALIGN_MASK);
  3260         char *cp = (char *) CALL_MREMAP((char *) oldp - offset,
  3261                                         oldmmsize, newmmsize, 1);
  3262         if (cp != CMFAIL) {
  3263             mchunkptr newp = (mchunkptr) (cp + offset);
  3264             size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
  3265             newp->head = (psize | CINUSE_BIT);
  3266             mark_inuse_foot(m, newp, psize);
  3267             chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
  3268             chunk_plus_offset(newp, psize + SIZE_T_SIZE)->head = 0;
  3269 
  3270             if (cp < m->least_addr)
  3271                 m->least_addr = cp;
  3272             if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
  3273                 m->max_footprint = m->footprint;
  3274             check_mmapped_chunk(m, newp);
  3275             return newp;
  3276         }
  3277     }
  3278     return 0;
  3279 }
  3280 
  3281 /* -------------------------- mspace management -------------------------- */
  3282 
  3283 /* Initialize top chunk and its size */
  3284 static void
  3285 init_top(mstate m, mchunkptr p, size_t psize)
  3286 {
  3287     /* Ensure alignment */
  3288     size_t offset = align_offset(chunk2mem(p));
  3289     p = (mchunkptr) ((char *) p + offset);
  3290     psize -= offset;
  3291 
  3292     m->top = p;
  3293     m->topsize = psize;
  3294     p->head = psize | PINUSE_BIT;
  3295     /* set size of fake trailing chunk holding overhead space only once */
  3296     chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
  3297     m->trim_check = mparams.trim_threshold;     /* reset on each update */
  3298 }
  3299 
  3300 /* Initialize bins for a new mstate that is otherwise zeroed out */
  3301 static void
  3302 init_bins(mstate m)
  3303 {
  3304     /* Establish circular links for smallbins */
  3305     bindex_t i;
  3306     for (i = 0; i < NSMALLBINS; ++i) {
  3307         sbinptr bin = smallbin_at(m, i);
  3308         bin->fd = bin->bk = bin;
  3309     }
  3310 }
  3311 
  3312 #if PROCEED_ON_ERROR
  3313 
  3314 /* default corruption action */
  3315 static void
  3316 reset_on_error(mstate m)
  3317 {
  3318     int i;
  3319     ++malloc_corruption_error_count;
  3320     /* Reinitialize fields to forget about all memory */
  3321     m->smallbins = m->treebins = 0;
  3322     m->dvsize = m->topsize = 0;
  3323     m->seg.base = 0;
  3324     m->seg.size = 0;
  3325     m->seg.next = 0;
  3326     m->top = m->dv = 0;
  3327     for (i = 0; i < NTREEBINS; ++i)
  3328         *treebin_at(m, i) = 0;
  3329     init_bins(m);
  3330 }
  3331 #endif /* PROCEED_ON_ERROR */
  3332 
  3333 /* Allocate chunk and prepend remainder with chunk in successor base. */
  3334 static void *
  3335 prepend_alloc(mstate m, char *newbase, char *oldbase, size_t nb)
  3336 {
  3337     mchunkptr p = align_as_chunk(newbase);
  3338     mchunkptr oldfirst = align_as_chunk(oldbase);
  3339     size_t psize = (char *) oldfirst - (char *) p;
  3340     mchunkptr q = chunk_plus_offset(p, nb);
  3341     size_t qsize = psize - nb;
  3342     set_size_and_pinuse_of_inuse_chunk(m, p, nb);
  3343 
  3344     assert((char *) oldfirst > (char *) q);
  3345     assert(pinuse(oldfirst));
  3346     assert(qsize >= MIN_CHUNK_SIZE);
  3347 
  3348     /* consolidate remainder with first chunk of old base */
  3349     if (oldfirst == m->top) {
  3350         size_t tsize = m->topsize += qsize;
  3351         m->top = q;
  3352         q->head = tsize | PINUSE_BIT;
  3353         check_top_chunk(m, q);
  3354     } else if (oldfirst == m->dv) {
  3355         size_t dsize = m->dvsize += qsize;
  3356         m->dv = q;
  3357         set_size_and_pinuse_of_free_chunk(q, dsize);
  3358     } else {
  3359         if (!cinuse(oldfirst)) {
  3360             size_t nsize = chunksize(oldfirst);
  3361             unlink_chunk(m, oldfirst, nsize);
  3362             oldfirst = chunk_plus_offset(oldfirst, nsize);
  3363             qsize += nsize;
  3364         }
  3365         set_free_with_pinuse(q, qsize, oldfirst);
  3366         insert_chunk(m, q, qsize);
  3367         check_free_chunk(m, q);
  3368     }
  3369 
  3370     check_malloced_chunk(m, chunk2mem(p), nb);
  3371     return chunk2mem(p);
  3372 }
  3373 
  3374 
  3375 /* Add a segment to hold a new noncontiguous region */
  3376 static void
  3377 add_segment(mstate m, char *tbase, size_t tsize, flag_t mmapped)
  3378 {
  3379     /* Determine locations and sizes of segment, fenceposts, old top */
  3380     char *old_top = (char *) m->top;
  3381     msegmentptr oldsp = segment_holding(m, old_top);
  3382     char *old_end = oldsp->base + oldsp->size;
  3383     size_t ssize = pad_request(sizeof(struct malloc_segment));
  3384     char *rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
  3385     size_t offset = align_offset(chunk2mem(rawsp));
  3386     char *asp = rawsp + offset;
  3387     char *csp = (asp < (old_top + MIN_CHUNK_SIZE)) ? old_top : asp;
  3388     mchunkptr sp = (mchunkptr) csp;
  3389     msegmentptr ss = (msegmentptr) (chunk2mem(sp));
  3390     mchunkptr tnext = chunk_plus_offset(sp, ssize);
  3391     mchunkptr p = tnext;
  3392     int nfences = 0;
  3393 
  3394     /* reset top to new space */
  3395     init_top(m, (mchunkptr) tbase, tsize - TOP_FOOT_SIZE);
  3396 
  3397     /* Set up segment record */
  3398     assert(is_aligned(ss));
  3399     set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
  3400     *ss = m->seg;               /* Push current record */
  3401     m->seg.base = tbase;
  3402     m->seg.size = tsize;
  3403     m->seg.sflags = mmapped;
  3404     m->seg.next = ss;
  3405 
  3406     /* Insert trailing fenceposts */
  3407     for (;;) {
  3408         mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
  3409         p->head = FENCEPOST_HEAD;
  3410         ++nfences;
  3411         if ((char *) (&(nextp->head)) < old_end)
  3412             p = nextp;
  3413         else
  3414             break;
  3415     }
  3416     assert(nfences >= 2);
  3417 
  3418     /* Insert the rest of old top into a bin as an ordinary free chunk */
  3419     if (csp != old_top) {
  3420         mchunkptr q = (mchunkptr) old_top;
  3421         size_t psize = csp - old_top;
  3422         mchunkptr tn = chunk_plus_offset(q, psize);
  3423         set_free_with_pinuse(q, psize, tn);
  3424         insert_chunk(m, q, psize);
  3425     }
  3426 
  3427     check_top_chunk(m, m->top);
  3428 }
  3429 
  3430 /* -------------------------- System allocation -------------------------- */
  3431 
  3432 /* Get memory from system using MORECORE or MMAP */
  3433 static void *
  3434 sys_alloc(mstate m, size_t nb)
  3435 {
  3436     char *tbase = CMFAIL;
  3437     size_t tsize = 0;
  3438     flag_t mmap_flag = 0;
  3439 
  3440     init_mparams();
  3441 
  3442     /* Directly map large chunks */
  3443     if (use_mmap(m) && nb >= mparams.mmap_threshold) {
  3444         void *mem = mmap_alloc(m, nb);
  3445         if (mem != 0)
  3446             return mem;
  3447     }
  3448 
  3449     /*
  3450        Try getting memory in any of three ways (in most-preferred to
  3451        least-preferred order):
  3452        1. A call to MORECORE that can normally contiguously extend memory.
  3453        (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
  3454        or main space is mmapped or a previous contiguous call failed)
  3455        2. A call to MMAP new space (disabled if not HAVE_MMAP).
  3456        Note that under the default settings, if MORECORE is unable to
  3457        fulfill a request, and HAVE_MMAP is true, then mmap is
  3458        used as a noncontiguous system allocator. This is a useful backup
  3459        strategy for systems with holes in address spaces -- in this case
  3460        sbrk cannot contiguously expand the heap, but mmap may be able to
  3461        find space.
  3462        3. A call to MORECORE that cannot usually contiguously extend memory.
  3463        (disabled if not HAVE_MORECORE)
  3464      */
  3465 
  3466     if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
  3467         char *br = CMFAIL;
  3468         msegmentptr ss =
  3469             (m->top == 0) ? 0 : segment_holding(m, (char *) m->top);
  3470         size_t asize = 0;
  3471         ACQUIRE_MORECORE_LOCK();
  3472 
  3473         if (ss == 0) {          /* First time through or recovery */
  3474             char *base = (char *) CALL_MORECORE(0);
  3475             if (base != CMFAIL) {
  3476                 asize =
  3477                     granularity_align(nb + TOP_FOOT_SIZE + MALLOC_ALIGNMENT +
  3478                                       SIZE_T_ONE);
  3479                 /* Adjust to end on a page boundary */
  3480                 if (!is_page_aligned(base))
  3481                     asize += (page_align((size_t) base) - (size_t) base);
  3482                 /* Can't call MORECORE if size is negative when treated as signed */
  3483                 if (asize < HALF_MAX_SIZE_T &&
  3484                     (br = (char *) (CALL_MORECORE(asize))) == base) {
  3485                     tbase = base;
  3486                     tsize = asize;
  3487                 }
  3488             }
  3489         } else {
  3490             /* Subtract out existing available top space from MORECORE request. */
  3491             asize =
  3492                 granularity_align(nb - m->topsize + TOP_FOOT_SIZE +
  3493                                   MALLOC_ALIGNMENT + SIZE_T_ONE);
  3494             /* Use mem here only if it did continuously extend old space */
  3495             if (asize < HALF_MAX_SIZE_T &&
  3496                 (br =
  3497                  (char *) (CALL_MORECORE(asize))) == ss->base + ss->size) {
  3498                 tbase = br;
  3499                 tsize = asize;
  3500             }
  3501         }
  3502 
  3503         if (tbase == CMFAIL) {  /* Cope with partial failure */
  3504             if (br != CMFAIL) { /* Try to use/extend the space we did get */
  3505                 if (asize < HALF_MAX_SIZE_T &&
  3506                     asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) {
  3507                     size_t esize =
  3508                         granularity_align(nb + TOP_FOOT_SIZE +
  3509                                           MALLOC_ALIGNMENT + SIZE_T_ONE -
  3510                                           asize);
  3511                     if (esize < HALF_MAX_SIZE_T) {
  3512                         char *end = (char *) CALL_MORECORE(esize);
  3513                         if (end != CMFAIL)
  3514                             asize += esize;
  3515                         else {  /* Can't use; try to release */
  3516                             end = (char *) CALL_MORECORE(-asize);
  3517                             br = CMFAIL;
  3518                         }
  3519                     }
  3520                 }
  3521             }
  3522             if (br != CMFAIL) { /* Use the space we did get */
  3523                 tbase = br;
  3524                 tsize = asize;
  3525             } else
  3526                 disable_contiguous(m);  /* Don't try contiguous path in the future */
  3527         }
  3528 
  3529         RELEASE_MORECORE_LOCK();
  3530     }
  3531 
  3532     if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */
  3533         size_t req = nb + TOP_FOOT_SIZE + MALLOC_ALIGNMENT + SIZE_T_ONE;
  3534         size_t rsize = granularity_align(req);
  3535         if (rsize > nb) {       /* Fail if wraps around zero */
  3536             char *mp = (char *) (CALL_MMAP(rsize));
  3537             if (mp != CMFAIL) {
  3538                 tbase = mp;
  3539                 tsize = rsize;
  3540                 mmap_flag = IS_MMAPPED_BIT;
  3541             }
  3542         }
  3543     }
  3544 
  3545     if (HAVE_MORECORE && tbase == CMFAIL) {     /* Try noncontiguous MORECORE */
  3546         size_t asize =
  3547             granularity_align(nb + TOP_FOOT_SIZE + MALLOC_ALIGNMENT +
  3548                               SIZE_T_ONE);
  3549         if (asize < HALF_MAX_SIZE_T) {
  3550             char *br = CMFAIL;
  3551             char *end = CMFAIL;
  3552             ACQUIRE_MORECORE_LOCK();
  3553             br = (char *) (CALL_MORECORE(asize));
  3554             end = (char *) (CALL_MORECORE(0));
  3555             RELEASE_MORECORE_LOCK();
  3556             if (br != CMFAIL && end != CMFAIL && br < end) {
  3557                 size_t ssize = end - br;
  3558                 if (ssize > nb + TOP_FOOT_SIZE) {
  3559                     tbase = br;
  3560                     tsize = ssize;
  3561                 }
  3562             }
  3563         }
  3564     }
  3565 
  3566     if (tbase != CMFAIL) {
  3567 
  3568         if ((m->footprint += tsize) > m->max_footprint)
  3569             m->max_footprint = m->footprint;
  3570 
  3571         if (!is_initialized(m)) {       /* first-time initialization */
  3572             m->seg.base = m->least_addr = tbase;
  3573             m->seg.size = tsize;
  3574             m->seg.sflags = mmap_flag;
  3575             m->magic = mparams.magic;
  3576             init_bins(m);
  3577             if (is_global(m))
  3578                 init_top(m, (mchunkptr) tbase, tsize - TOP_FOOT_SIZE);
  3579             else {
  3580                 /* Offset top by embedded malloc_state */
  3581                 mchunkptr mn = next_chunk(mem2chunk(m));
  3582                 init_top(m, mn,
  3583                          (size_t) ((tbase + tsize) - (char *) mn) -
  3584                          TOP_FOOT_SIZE);
  3585             }
  3586         }
  3587 
  3588         else {
  3589             /* Try to merge with an existing segment */
  3590             msegmentptr sp = &m->seg;
  3591             while (sp != 0 && tbase != sp->base + sp->size)
  3592                 sp = sp->next;
  3593             if (sp != 0 && !is_extern_segment(sp) && (sp->sflags & IS_MMAPPED_BIT) == mmap_flag && segment_holds(sp, m->top)) { /* append */
  3594                 sp->size += tsize;
  3595                 init_top(m, m->top, m->topsize + tsize);
  3596             } else {
  3597                 if (tbase < m->least_addr)
  3598                     m->least_addr = tbase;
  3599                 sp = &m->seg;
  3600                 while (sp != 0 && sp->base != tbase + tsize)
  3601                     sp = sp->next;
  3602                 if (sp != 0 &&
  3603                     !is_extern_segment(sp) &&
  3604                     (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) {
  3605                     char *oldbase = sp->base;
  3606                     sp->base = tbase;
  3607                     sp->size += tsize;
  3608                     return prepend_alloc(m, tbase, oldbase, nb);
  3609                 } else
  3610                     add_segment(m, tbase, tsize, mmap_flag);
  3611             }
  3612         }
  3613 
  3614         if (nb < m->topsize) {  /* Allocate from new or extended top space */
  3615             size_t rsize = m->topsize -= nb;
  3616             mchunkptr p = m->top;
  3617             mchunkptr r = m->top = chunk_plus_offset(p, nb);
  3618             r->head = rsize | PINUSE_BIT;
  3619             set_size_and_pinuse_of_inuse_chunk(m, p, nb);
  3620             check_top_chunk(m, m->top);
  3621             check_malloced_chunk(m, chunk2mem(p), nb);
  3622             return chunk2mem(p);
  3623         }
  3624     }
  3625 
  3626     MALLOC_FAILURE_ACTION;
  3627     return 0;
  3628 }
  3629 
  3630 /* -----------------------  system deallocation -------------------------- */
  3631 
  3632 /* Unmap and unlink any mmapped segments that don't contain used chunks */
  3633 static size_t
  3634 release_unused_segments(mstate m)
  3635 {
  3636     size_t released = 0;
  3637     msegmentptr pred = &m->seg;
  3638     msegmentptr sp = pred->next;
  3639     while (sp != 0) {
  3640         char *base = sp->base;
  3641         size_t size = sp->size;
  3642         msegmentptr next = sp->next;
  3643         if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
  3644             mchunkptr p = align_as_chunk(base);
  3645             size_t psize = chunksize(p);
  3646             /* Can unmap if first chunk holds entire segment and not pinned */
  3647             if (!cinuse(p)
  3648                 && (char *) p + psize >= base + size - TOP_FOOT_SIZE) {
  3649                 tchunkptr tp = (tchunkptr) p;
  3650                 assert(segment_holds(sp, (char *) sp));
  3651                 if (p == m->dv) {
  3652                     m->dv = 0;
  3653                     m->dvsize = 0;
  3654                 } else {
  3655                     unlink_large_chunk(m, tp);
  3656                 }
  3657                 if (CALL_MUNMAP(base, size) == 0) {
  3658                     released += size;
  3659                     m->footprint -= size;
  3660                     /* unlink obsoleted record */
  3661                     sp = pred;
  3662                     sp->next = next;
  3663                 } else {        /* back out if cannot unmap */
  3664                     insert_large_chunk(m, tp, psize);
  3665                 }
  3666             }
  3667         }
  3668         pred = sp;
  3669         sp = next;
  3670     }
  3671     return released;
  3672 }
  3673 
  3674 static int
  3675 sys_trim(mstate m, size_t pad)
  3676 {
  3677     size_t released = 0;
  3678     if (pad < MAX_REQUEST && is_initialized(m)) {
  3679         pad += TOP_FOOT_SIZE;   /* ensure enough room for segment overhead */
  3680 
  3681         if (m->topsize > pad) {
  3682             /* Shrink top space in granularity-size units, keeping at least one */
  3683             size_t unit = mparams.granularity;
  3684             size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
  3685                             SIZE_T_ONE) * unit;
  3686             msegmentptr sp = segment_holding(m, (char *) m->top);
  3687 
  3688             if (!is_extern_segment(sp)) {
  3689                 if (is_mmapped_segment(sp)) {
  3690                     if (HAVE_MMAP && sp->size >= extra && !has_segment_link(m, sp)) {   /* can't shrink if pinned */
  3691                         size_t newsize = sp->size - extra;
  3692                         /* Prefer mremap, fall back to munmap */
  3693                         if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) !=
  3694                              MFAIL)
  3695                             || (CALL_MUNMAP(sp->base + newsize, extra) ==
  3696                                 0)) {
  3697                             released = extra;
  3698                         }
  3699                     }
  3700                 } else if (HAVE_MORECORE) {
  3701                     if (extra >= HALF_MAX_SIZE_T)       /* Avoid wrapping negative */
  3702                         extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
  3703                     ACQUIRE_MORECORE_LOCK();
  3704                     {
  3705                         /* Make sure end of memory is where we last set it. */
  3706                         char *old_br = (char *) (CALL_MORECORE(0));
  3707                         if (old_br == sp->base + sp->size) {
  3708                             char *rel_br = (char *) (CALL_MORECORE(-extra));
  3709                             char *new_br = (char *) (CALL_MORECORE(0));
  3710                             if (rel_br != CMFAIL && new_br < old_br)
  3711                                 released = old_br - new_br;
  3712                         }
  3713                     }
  3714                     RELEASE_MORECORE_LOCK();
  3715                 }
  3716             }
  3717 
  3718             if (released != 0) {
  3719                 sp->size -= released;
  3720                 m->footprint -= released;
  3721                 init_top(m, m->top, m->topsize - released);
  3722                 check_top_chunk(m, m->top);
  3723             }
  3724         }
  3725 
  3726         /* Unmap any unused mmapped segments */
  3727         if (HAVE_MMAP)
  3728             released += release_unused_segments(m);
  3729 
  3730         /* On failure, disable autotrim to avoid repeated failed future calls */
  3731         if (released == 0)
  3732             m->trim_check = MAX_SIZE_T;
  3733     }
  3734 
  3735     return (released != 0) ? 1 : 0;
  3736 }
  3737 
  3738 /* ---------------------------- malloc support --------------------------- */
  3739 
  3740 /* allocate a large request from the best fitting chunk in a treebin */
  3741 static void *
  3742 tmalloc_large(mstate m, size_t nb)
  3743 {
  3744     tchunkptr v = 0;
  3745     size_t rsize = -nb;         /* Unsigned negation */
  3746     tchunkptr t;
  3747     bindex_t idx;
  3748     compute_tree_index(nb, idx);
  3749 
  3750     if ((t = *treebin_at(m, idx)) != 0) {
  3751         /* Traverse tree for this bin looking for node with size == nb */
  3752         size_t sizebits = nb << leftshift_for_tree_index(idx);
  3753         tchunkptr rst = 0;      /* The deepest untaken right subtree */
  3754         for (;;) {
  3755             tchunkptr rt;
  3756             size_t trem = chunksize(t) - nb;
  3757             if (trem < rsize) {
  3758                 v = t;
  3759                 if ((rsize = trem) == 0)
  3760                     break;
  3761             }
  3762             rt = t->child[1];
  3763             t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1];
  3764             if (rt != 0 && rt != t)
  3765                 rst = rt;
  3766             if (t == 0) {
  3767                 t = rst;        /* set t to least subtree holding sizes > nb */
  3768                 break;
  3769             }
  3770             sizebits <<= 1;
  3771         }
  3772     }
  3773 
  3774     if (t == 0 && v == 0) {     /* set t to root of next non-empty treebin */
  3775         binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
  3776         if (leftbits != 0) {
  3777             bindex_t i;
  3778             binmap_t leastbit = least_bit(leftbits);
  3779             compute_bit2idx(leastbit, i);
  3780             t = *treebin_at(m, i);
  3781         }
  3782     }
  3783 
  3784     while (t != 0) {            /* find smallest of tree or subtree */
  3785         size_t trem = chunksize(t) - nb;
  3786         if (trem < rsize) {
  3787             rsize = trem;
  3788             v = t;
  3789         }
  3790         t = leftmost_child(t);
  3791     }
  3792 
  3793     /*  If dv is a better fit, return 0 so malloc will use it */
  3794     if (v != 0 && rsize < (size_t) (m->dvsize - nb)) {
  3795         if (RTCHECK(ok_address(m, v))) {        /* split */
  3796             mchunkptr r = chunk_plus_offset(v, nb);
  3797             assert(chunksize(v) == rsize + nb);
  3798             if (RTCHECK(ok_next(v, r))) {
  3799                 unlink_large_chunk(m, v);
  3800                 if (rsize < MIN_CHUNK_SIZE)
  3801                     set_inuse_and_pinuse(m, v, (rsize + nb));
  3802                 else {
  3803                     set_size_and_pinuse_of_inuse_chunk(m, v, nb);
  3804                     set_size_and_pinuse_of_free_chunk(r, rsize);
  3805                     insert_chunk(m, r, rsize);
  3806                 }
  3807                 return chunk2mem(v);
  3808             }
  3809         }
  3810         CORRUPTION_ERROR_ACTION(m);
  3811     }
  3812     return 0;
  3813 }
  3814 
  3815 /* allocate a small request from the best fitting chunk in a treebin */
  3816 static void *
  3817 tmalloc_small(mstate m, size_t nb)
  3818 {
  3819     tchunkptr t, v;
  3820     size_t rsize;
  3821     bindex_t i;
  3822     binmap_t leastbit = least_bit(m->treemap);
  3823     compute_bit2idx(leastbit, i);
  3824 
  3825     v = t = *treebin_at(m, i);
  3826     rsize = chunksize(t) - nb;
  3827 
  3828     while ((t = leftmost_child(t)) != 0) {
  3829         size_t trem = chunksize(t) - nb;
  3830         if (trem < rsize) {
  3831             rsize = trem;
  3832             v = t;
  3833         }
  3834     }
  3835 
  3836     if (RTCHECK(ok_address(m, v))) {
  3837         mchunkptr r = chunk_plus_offset(v, nb);
  3838         assert(chunksize(v) == rsize + nb);
  3839         if (RTCHECK(ok_next(v, r))) {
  3840             unlink_large_chunk(m, v);
  3841             if (rsize < MIN_CHUNK_SIZE)
  3842                 set_inuse_and_pinuse(m, v, (rsize + nb));
  3843             else {
  3844                 set_size_and_pinuse_of_inuse_chunk(m, v, nb);
  3845                 set_size_and_pinuse_of_free_chunk(r, rsize);
  3846                 replace_dv(m, r, rsize);
  3847             }
  3848             return chunk2mem(v);
  3849         }
  3850     }
  3851 
  3852     CORRUPTION_ERROR_ACTION(m);
  3853     return 0;
  3854 }
  3855 
  3856 /* --------------------------- realloc support --------------------------- */
  3857 
  3858 static void *
  3859 internal_realloc(mstate m, void *oldmem, size_t bytes)
  3860 {
  3861     if (bytes >= MAX_REQUEST) {
  3862         MALLOC_FAILURE_ACTION;
  3863         return 0;
  3864     }
  3865     if (!PREACTION(m)) {
  3866         mchunkptr oldp = mem2chunk(oldmem);
  3867         size_t oldsize = chunksize(oldp);
  3868         mchunkptr next = chunk_plus_offset(oldp, oldsize);
  3869         mchunkptr newp = 0;
  3870         void *extra = 0;
  3871 
  3872         /* Try to either shrink or extend into top. Else malloc-copy-free */
  3873 
  3874         if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) &&
  3875                     ok_next(oldp, next) && ok_pinuse(next))) {
  3876             size_t nb = request2size(bytes);
  3877             if (is_mmapped(oldp))
  3878                 newp = mmap_resize(m, oldp, nb);
  3879             else if (oldsize >= nb) {   /* already big enough */
  3880                 size_t rsize = oldsize - nb;
  3881                 newp = oldp;
  3882                 if (rsize >= MIN_CHUNK_SIZE) {
  3883                     mchunkptr remainder = chunk_plus_offset(newp, nb);
  3884                     set_inuse(m, newp, nb);
  3885                     set_inuse(m, remainder, rsize);
  3886                     extra = chunk2mem(remainder);
  3887                 }
  3888             } else if (next == m->top && oldsize + m->topsize > nb) {
  3889                 /* Expand into top */
  3890                 size_t newsize = oldsize + m->topsize;
  3891                 size_t newtopsize = newsize - nb;
  3892                 mchunkptr newtop = chunk_plus_offset(oldp, nb);
  3893                 set_inuse(m, oldp, nb);
  3894                 newtop->head = newtopsize | PINUSE_BIT;
  3895                 m->top = newtop;
  3896                 m->topsize = newtopsize;
  3897                 newp = oldp;
  3898             }
  3899         } else {
  3900             USAGE_ERROR_ACTION(m, oldmem);
  3901             POSTACTION(m);
  3902             return 0;
  3903         }
  3904 
  3905         POSTACTION(m);
  3906 
  3907         if (newp != 0) {
  3908             if (extra != 0) {
  3909                 internal_free(m, extra);
  3910             }
  3911             check_inuse_chunk(m, newp);
  3912             return chunk2mem(newp);
  3913         } else {
  3914             void *newmem = internal_malloc(m, bytes);
  3915             if (newmem != 0) {
  3916                 size_t oc = oldsize - overhead_for(oldp);
  3917                 memcpy(newmem, oldmem, (oc < bytes) ? oc : bytes);
  3918                 internal_free(m, oldmem);
  3919             }
  3920             return newmem;
  3921         }
  3922     }
  3923     return 0;
  3924 }
  3925 
  3926 /* --------------------------- memalign support -------------------------- */
  3927 
  3928 static void *
  3929 internal_memalign(mstate m, size_t alignment, size_t bytes)
  3930 {
  3931     if (alignment <= MALLOC_ALIGNMENT)  /* Can just use malloc */
  3932         return internal_malloc(m, bytes);
  3933     if (alignment < MIN_CHUNK_SIZE)     /* must be at least a minimum chunk size */
  3934         alignment = MIN_CHUNK_SIZE;
  3935     if ((alignment & (alignment - SIZE_T_ONE)) != 0) {  /* Ensure a power of 2 */
  3936         size_t a = MALLOC_ALIGNMENT << 1;
  3937         while (a < alignment)
  3938             a <<= 1;
  3939         alignment = a;
  3940     }
  3941 
  3942     if (bytes >= MAX_REQUEST - alignment) {
  3943         if (m != 0) {           /* Test isn't needed but avoids compiler warning */
  3944             MALLOC_FAILURE_ACTION;
  3945         }
  3946     } else {
  3947         size_t nb = request2size(bytes);
  3948         size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
  3949         char *mem = (char *) internal_malloc(m, req);
  3950         if (mem != 0) {
  3951             void *leader = 0;
  3952             void *trailer = 0;
  3953             mchunkptr p = mem2chunk(mem);
  3954 
  3955             if (PREACTION(m))
  3956                 return 0;
  3957             if ((((size_t) (mem)) % alignment) != 0) {  /* misaligned */
  3958                 /*
  3959                    Find an aligned spot inside chunk.  Since we need to give
  3960                    back leading space in a chunk of at least MIN_CHUNK_SIZE, if
  3961                    the first calculation places us at a spot with less than
  3962                    MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
  3963                    We've allocated enough total room so that this is always
  3964                    possible.
  3965                  */
  3966                 char *br = (char *) mem2chunk((size_t) (((size_t) (mem +
  3967                                                                    alignment -
  3968                                                                    SIZE_T_ONE))
  3969                                                         & -alignment));
  3970                 char *pos =
  3971                     ((size_t) (br - (char *) (p)) >=
  3972                      MIN_CHUNK_SIZE) ? br : br + alignment;
  3973                 mchunkptr newp = (mchunkptr) pos;
  3974                 size_t leadsize = pos - (char *) (p);
  3975                 size_t newsize = chunksize(p) - leadsize;
  3976 
  3977                 if (is_mmapped(p)) {    /* For mmapped chunks, just adjust offset */
  3978                     newp->prev_foot = p->prev_foot + leadsize;
  3979                     newp->head = (newsize | CINUSE_BIT);
  3980                 } else {        /* Otherwise, give back leader, use the rest */
  3981                     set_inuse(m, newp, newsize);
  3982                     set_inuse(m, p, leadsize);
  3983                     leader = chunk2mem(p);
  3984                 }
  3985                 p = newp;
  3986             }
  3987 
  3988             /* Give back spare room at the end */
  3989             if (!is_mmapped(p)) {
  3990                 size_t size = chunksize(p);
  3991                 if (size > nb + MIN_CHUNK_SIZE) {
  3992                     size_t remainder_size = size - nb;
  3993                     mchunkptr remainder = chunk_plus_offset(p, nb);
  3994                     set_inuse(m, p, nb);
  3995                     set_inuse(m, remainder, remainder_size);
  3996                     trailer = chunk2mem(remainder);
  3997                 }
  3998             }
  3999 
  4000             assert(chunksize(p) >= nb);
  4001             assert((((size_t) (chunk2mem(p))) % alignment) == 0);
  4002             check_inuse_chunk(m, p);
  4003             POSTACTION(m);
  4004             if (leader != 0) {
  4005                 internal_free(m, leader);
  4006             }
  4007             if (trailer != 0) {
  4008                 internal_free(m, trailer);
  4009             }
  4010             return chunk2mem(p);
  4011         }
  4012     }
  4013     return 0;
  4014 }
  4015 
  4016 /* ------------------------ comalloc/coalloc support --------------------- */
  4017 
  4018 static void **
  4019 ialloc(mstate m, size_t n_elements, size_t * sizes, int opts, void *chunks[])
  4020 {
  4021     /*
  4022        This provides common support for independent_X routines, handling
  4023        all of the combinations that can result.
  4024 
  4025        The opts arg has:
  4026        bit 0 set if all elements are same size (using sizes[0])
  4027        bit 1 set if elements should be zeroed
  4028      */
  4029 
  4030     size_t element_size;        /* chunksize of each element, if all same */
  4031     size_t contents_size;       /* total size of elements */
  4032     size_t array_size;          /* request size of pointer array */
  4033     void *mem;                  /* malloced aggregate space */
  4034     mchunkptr p;                /* corresponding chunk */
  4035     size_t remainder_size;      /* remaining bytes while splitting */
  4036     void **marray;              /* either "chunks" or malloced ptr array */
  4037     mchunkptr array_chunk;      /* chunk for malloced ptr array */
  4038     flag_t was_enabled;         /* to disable mmap */
  4039     size_t size;
  4040     size_t i;
  4041 
  4042     /* compute array length, if needed */
  4043     if (chunks != 0) {
  4044         if (n_elements == 0)
  4045             return chunks;      /* nothing to do */
  4046         marray = chunks;
  4047         array_size = 0;
  4048     } else {
  4049         /* if empty req, must still return chunk representing empty array */
  4050         if (n_elements == 0)
  4051             return (void **) internal_malloc(m, 0);
  4052         marray = 0;
  4053         array_size = request2size(n_elements * (sizeof(void *)));
  4054     }
  4055 
  4056     /* compute total element size */
  4057     if (opts & 0x1) {           /* all-same-size */
  4058         element_size = request2size(*sizes);
  4059         contents_size = n_elements * element_size;
  4060     } else {                    /* add up all the sizes */
  4061         element_size = 0;
  4062         contents_size = 0;
  4063         for (i = 0; i != n_elements; ++i)
  4064             contents_size += request2size(sizes[i]);
  4065     }
  4066 
  4067     size = contents_size + array_size;
  4068 
  4069     /*
  4070        Allocate the aggregate chunk.  First disable direct-mmapping so
  4071        malloc won't use it, since we would not be able to later
  4072        free/realloc space internal to a segregated mmap region.
  4073      */
  4074     was_enabled = use_mmap(m);
  4075     disable_mmap(m);
  4076     mem = internal_malloc(m, size - CHUNK_OVERHEAD);
  4077     if (was_enabled)
  4078         enable_mmap(m);
  4079     if (mem == 0)
  4080         return 0;
  4081 
  4082     if (PREACTION(m))
  4083         return 0;
  4084     p = mem2chunk(mem);
  4085     remainder_size = chunksize(p);
  4086 
  4087     assert(!is_mmapped(p));
  4088 
  4089     if (opts & 0x2) {           /* optionally clear the elements */
  4090         memset((size_t *) mem, 0, remainder_size - SIZE_T_SIZE - array_size);
  4091     }
  4092 
  4093     /* If not provided, allocate the pointer array as final part of chunk */
  4094     if (marray == 0) {
  4095         size_t array_chunk_size;
  4096         array_chunk = chunk_plus_offset(p, contents_size);
  4097         array_chunk_size = remainder_size - contents_size;
  4098         marray = (void **) (chunk2mem(array_chunk));
  4099         set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
  4100         remainder_size = contents_size;
  4101     }
  4102 
  4103     /* split out elements */
  4104     for (i = 0;; ++i) {
  4105         marray[i] = chunk2mem(p);
  4106         if (i != n_elements - 1) {
  4107             if (element_size != 0)
  4108                 size = element_size;
  4109             else
  4110                 size = request2size(sizes[i]);
  4111             remainder_size -= size;
  4112             set_size_and_pinuse_of_inuse_chunk(m, p, size);
  4113             p = chunk_plus_offset(p, size);
  4114         } else {                /* the final element absorbs any overallocation slop */
  4115             set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
  4116             break;
  4117         }
  4118     }
  4119 
  4120 #if DEBUG
  4121     if (marray != chunks) {
  4122         /* final element must have exactly exhausted chunk */
  4123         if (element_size != 0) {
  4124             assert(remainder_size == element_size);
  4125         } else {
  4126             assert(remainder_size == request2size(sizes[i]));
  4127         }
  4128         check_inuse_chunk(m, mem2chunk(marray));
  4129     }
  4130     for (i = 0; i != n_elements; ++i)
  4131         check_inuse_chunk(m, mem2chunk(marray[i]));
  4132 
  4133 #endif /* DEBUG */
  4134 
  4135     POSTACTION(m);
  4136     return marray;
  4137 }
  4138 
  4139 
  4140 /* -------------------------- public routines ---------------------------- */
  4141 
  4142 #if !ONLY_MSPACES
  4143 
  4144 void *
  4145 dlmalloc(size_t bytes)
  4146 {
  4147     /*
  4148        Basic algorithm:
  4149        If a small request (< 256 bytes minus per-chunk overhead):
  4150        1. If one exists, use a remainderless chunk in associated smallbin.
  4151        (Remainderless means that there are too few excess bytes to
  4152        represent as a chunk.)
  4153        2. If it is big enough, use the dv chunk, which is normally the
  4154        chunk adjacent to the one used for the most recent small request.
  4155        3. If one exists, split the smallest available chunk in a bin,
  4156        saving remainder in dv.
  4157        4. If it is big enough, use the top chunk.
  4158        5. If available, get memory from system and use it
  4159        Otherwise, for a large request:
  4160        1. Find the smallest available binned chunk that fits, and use it
  4161        if it is better fitting than dv chunk, splitting if necessary.
  4162        2. If better fitting than any binned chunk, use the dv chunk.
  4163        3. If it is big enough, use the top chunk.
  4164        4. If request size >= mmap threshold, try to directly mmap this chunk.
  4165        5. If available, get memory from system and use it
  4166 
  4167        The ugly goto's here ensure that postaction occurs along all paths.
  4168      */
  4169 
  4170     if (!PREACTION(gm)) {
  4171         void *mem;
  4172         size_t nb;
  4173         if (bytes <= MAX_SMALL_REQUEST) {
  4174             bindex_t idx;
  4175             binmap_t smallbits;
  4176             nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes);
  4177             idx = small_index(nb);
  4178             smallbits = gm->smallmap >> idx;
  4179 
  4180             if ((smallbits & 0x3U) != 0) {      /* Remainderless fit to a smallbin. */
  4181                 mchunkptr b, p;
  4182                 idx += ~smallbits & 1;  /* Uses next bin if idx empty */
  4183                 b = smallbin_at(gm, idx);
  4184                 p = b->fd;
  4185                 assert(chunksize(p) == small_index2size(idx));
  4186                 unlink_first_small_chunk(gm, b, p, idx);
  4187                 set_inuse_and_pinuse(gm, p, small_index2size(idx));
  4188                 mem = chunk2mem(p);
  4189                 check_malloced_chunk(gm, mem, nb);
  4190                 goto postaction;
  4191             }
  4192 
  4193             else if (nb > gm->dvsize) {
  4194                 if (smallbits != 0) {   /* Use chunk in next nonempty smallbin */
  4195                     mchunkptr b, p, r;
  4196                     size_t rsize;
  4197                     bindex_t i;
  4198                     binmap_t leftbits =
  4199                         (smallbits << idx) & left_bits(idx2bit(idx));
  4200                     binmap_t leastbit = least_bit(leftbits);
  4201                     compute_bit2idx(leastbit, i);
  4202                     b = smallbin_at(gm, i);
  4203                     p = b->fd;
  4204                     assert(chunksize(p) == small_index2size(i));
  4205                     unlink_first_small_chunk(gm, b, p, i);
  4206                     rsize = small_index2size(i) - nb;
  4207                     /* Fit here cannot be remainderless if 4byte sizes */
  4208                     if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
  4209                         set_inuse_and_pinuse(gm, p, small_index2size(i));
  4210                     else {
  4211                         set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
  4212                         r = chunk_plus_offset(p, nb);
  4213                         set_size_and_pinuse_of_free_chunk(r, rsize);
  4214                         replace_dv(gm, r, rsize);
  4215                     }
  4216                     mem = chunk2mem(p);
  4217                     check_malloced_chunk(gm, mem, nb);
  4218                     goto postaction;
  4219                 }
  4220 
  4221                 else if (gm->treemap != 0
  4222                          && (mem = tmalloc_small(gm, nb)) != 0) {
  4223                     check_malloced_chunk(gm, mem, nb);
  4224                     goto postaction;
  4225                 }
  4226             }
  4227         } else if (bytes >= MAX_REQUEST)
  4228             nb = MAX_SIZE_T;    /* Too big to allocate. Force failure (in sys alloc) */
  4229         else {
  4230             nb = pad_request(bytes);
  4231             if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
  4232                 check_malloced_chunk(gm, mem, nb);
  4233                 goto postaction;
  4234             }
  4235         }
  4236 
  4237         if (nb <= gm->dvsize) {
  4238             size_t rsize = gm->dvsize - nb;
  4239             mchunkptr p = gm->dv;
  4240             if (rsize >= MIN_CHUNK_SIZE) {      /* split dv */
  4241                 mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
  4242                 gm->dvsize = rsize;
  4243                 set_size_and_pinuse_of_free_chunk(r, rsize);
  4244                 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
  4245             } else {            /* exhaust dv */
  4246                 size_t dvs = gm->dvsize;
  4247                 gm->dvsize = 0;
  4248                 gm->dv = 0;
  4249                 set_inuse_and_pinuse(gm, p, dvs);
  4250             }
  4251             mem = chunk2mem(p);
  4252             check_malloced_chunk(gm, mem, nb);
  4253             goto postaction;
  4254         }
  4255 
  4256         else if (nb < gm->topsize) {    /* Split top */
  4257             size_t rsize = gm->topsize -= nb;
  4258             mchunkptr p = gm->top;
  4259             mchunkptr r = gm->top = chunk_plus_offset(p, nb);
  4260             r->head = rsize | PINUSE_BIT;
  4261             set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
  4262             mem = chunk2mem(p);
  4263             check_top_chunk(gm, gm->top);
  4264             check_malloced_chunk(gm, mem, nb);
  4265             goto postaction;
  4266         }
  4267 
  4268         mem = sys_alloc(gm, nb);
  4269 
  4270       postaction:
  4271         POSTACTION(gm);
  4272         return mem;
  4273     }
  4274 
  4275     return 0;
  4276 }
  4277 
  4278 void
  4279 dlfree(void *mem)
  4280 {
  4281     /*
  4282        Consolidate freed chunks with preceeding or succeeding bordering
  4283        free chunks, if they exist, and then place in a bin.  Intermixed
  4284        with special cases for top, dv, mmapped chunks, and usage errors.
  4285      */
  4286 
  4287     if (mem != 0) {
  4288         mchunkptr p = mem2chunk(mem);
  4289 #if FOOTERS
  4290         mstate fm = get_mstate_for(p);
  4291         if (!ok_magic(fm)) {
  4292             USAGE_ERROR_ACTION(fm, p);
  4293             return;
  4294         }
  4295 #else /* FOOTERS */
  4296 #define fm gm
  4297 #endif /* FOOTERS */
  4298         if (!PREACTION(fm)) {
  4299             check_inuse_chunk(fm, p);
  4300             if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
  4301                 size_t psize = chunksize(p);
  4302                 mchunkptr next = chunk_plus_offset(p, psize);
  4303                 if (!pinuse(p)) {
  4304                     size_t prevsize = p->prev_foot;
  4305                     if ((prevsize & IS_MMAPPED_BIT) != 0) {
  4306                         prevsize &= ~IS_MMAPPED_BIT;
  4307                         psize += prevsize + MMAP_FOOT_PAD;
  4308                         if (CALL_MUNMAP((char *) p - prevsize, psize) == 0)
  4309                             fm->footprint -= psize;
  4310                         goto postaction;
  4311                     } else {
  4312                         mchunkptr prev = chunk_minus_offset(p, prevsize);
  4313                         psize += prevsize;
  4314                         p = prev;
  4315                         if (RTCHECK(ok_address(fm, prev))) {    /* consolidate backward */
  4316                             if (p != fm->dv) {
  4317                                 unlink_chunk(fm, p, prevsize);
  4318                             } else if ((next->head & INUSE_BITS) ==
  4319                                        INUSE_BITS) {
  4320                                 fm->dvsize = psize;
  4321                                 set_free_with_pinuse(p, psize, next);
  4322                                 goto postaction;
  4323                             }
  4324                         } else
  4325                             goto erroraction;
  4326                     }
  4327                 }
  4328 
  4329                 if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
  4330                     if (!cinuse(next)) {        /* consolidate forward */
  4331                         if (next == fm->top) {
  4332                             size_t tsize = fm->topsize += psize;
  4333                             fm->top = p;
  4334                             p->head = tsize | PINUSE_BIT;
  4335                             if (p == fm->dv) {
  4336                                 fm->dv = 0;
  4337                                 fm->dvsize = 0;
  4338                             }
  4339                             if (should_trim(fm, tsize))
  4340                                 sys_trim(fm, 0);
  4341                             goto postaction;
  4342                         } else if (next == fm->dv) {
  4343                             size_t dsize = fm->dvsize += psize;
  4344                             fm->dv = p;
  4345                             set_size_and_pinuse_of_free_chunk(p, dsize);
  4346                             goto postaction;
  4347                         } else {
  4348                             size_t nsize = chunksize(next);
  4349                             psize += nsize;
  4350                             unlink_chunk(fm, next, nsize);
  4351                             set_size_and_pinuse_of_free_chunk(p, psize);
  4352                             if (p == fm->dv) {
  4353                                 fm->dvsize = psize;
  4354                                 goto postaction;
  4355                             }
  4356                         }
  4357                     } else
  4358                         set_free_with_pinuse(p, psize, next);
  4359                     insert_chunk(fm, p, psize);
  4360                     check_free_chunk(fm, p);
  4361                     goto postaction;
  4362                 }
  4363             }
  4364           erroraction:
  4365             USAGE_ERROR_ACTION(fm, p);
  4366           postaction:
  4367             POSTACTION(fm);
  4368         }
  4369     }
  4370 #if !FOOTERS
  4371 #undef fm
  4372 #endif /* FOOTERS */
  4373 }
  4374 
  4375 void *
  4376 dlcalloc(size_t n_elements, size_t elem_size)
  4377 {
  4378     void *mem;
  4379     size_t req = 0;
  4380     if (n_elements != 0) {
  4381         req = n_elements * elem_size;
  4382         if (((n_elements | elem_size) & ~(size_t) 0xffff) &&
  4383             (req / n_elements != elem_size))
  4384             req = MAX_SIZE_T;   /* force downstream failure on overflow */
  4385     }
  4386     mem = dlmalloc(req);
  4387     if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
  4388         memset(mem, 0, req);
  4389     return mem;
  4390 }
  4391 
  4392 void *
  4393 dlrealloc(void *oldmem, size_t bytes)
  4394 {
  4395     if (oldmem == 0)
  4396         return dlmalloc(bytes);
  4397 #ifdef REALLOC_ZERO_BYTES_FREES
  4398     if (bytes == 0) {
  4399         dlfree(oldmem);
  4400         return 0;
  4401     }
  4402 #endif /* REALLOC_ZERO_BYTES_FREES */
  4403     else {
  4404 #if ! FOOTERS
  4405         mstate m = gm;
  4406 #else /* FOOTERS */
  4407         mstate m = get_mstate_for(mem2chunk(oldmem));
  4408         if (!ok_magic(m)) {
  4409             USAGE_ERROR_ACTION(m, oldmem);
  4410             return 0;
  4411         }
  4412 #endif /* FOOTERS */
  4413         return internal_realloc(m, oldmem, bytes);
  4414     }
  4415 }
  4416 
  4417 void *
  4418 dlmemalign(size_t alignment, size_t bytes)
  4419 {
  4420     return internal_memalign(gm, alignment, bytes);
  4421 }
  4422 
  4423 void **
  4424 dlindependent_calloc(size_t n_elements, size_t elem_size, void *chunks[])
  4425 {
  4426     size_t sz = elem_size;      /* serves as 1-element array */
  4427     return ialloc(gm, n_elements, &sz, 3, chunks);
  4428 }
  4429 
  4430 void **
  4431 dlindependent_comalloc(size_t n_elements, size_t sizes[], void *chunks[])
  4432 {
  4433     return ialloc(gm, n_elements, sizes, 0, chunks);
  4434 }
  4435 
  4436 void *
  4437 dlvalloc(size_t bytes)
  4438 {
  4439     size_t pagesz;
  4440     init_mparams();
  4441     pagesz = mparams.page_size;
  4442     return dlmemalign(pagesz, bytes);
  4443 }
  4444 
  4445 void *
  4446 dlpvalloc(size_t bytes)
  4447 {
  4448     size_t pagesz;
  4449     init_mparams();
  4450     pagesz = mparams.page_size;
  4451     return dlmemalign(pagesz,
  4452                       (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
  4453 }
  4454 
  4455 int
  4456 dlmalloc_trim(size_t pad)
  4457 {
  4458     int result = 0;
  4459     if (!PREACTION(gm)) {
  4460         result = sys_trim(gm, pad);
  4461         POSTACTION(gm);
  4462     }
  4463     return result;
  4464 }
  4465 
  4466 size_t
  4467 dlmalloc_footprint(void)
  4468 {
  4469     return gm->footprint;
  4470 }
  4471 
  4472 size_t
  4473 dlmalloc_max_footprint(void)
  4474 {
  4475     return gm->max_footprint;
  4476 }
  4477 
  4478 #if !NO_MALLINFO
  4479 struct mallinfo
  4480 dlmallinfo(void)
  4481 {
  4482     return internal_mallinfo(gm);
  4483 }
  4484 #endif /* NO_MALLINFO */
  4485 
  4486 void
  4487 dlmalloc_stats()
  4488 {
  4489     internal_malloc_stats(gm);
  4490 }
  4491 
  4492 size_t
  4493 dlmalloc_usable_size(void *mem)
  4494 {
  4495     if (mem != 0) {
  4496         mchunkptr p = mem2chunk(mem);
  4497         if (cinuse(p))
  4498             return chunksize(p) - overhead_for(p);
  4499     }
  4500     return 0;
  4501 }
  4502 
  4503 int
  4504 dlmallopt(int param_number, int value)
  4505 {
  4506     return change_mparam(param_number, value);
  4507 }
  4508 
  4509 #endif /* !ONLY_MSPACES */
  4510 
  4511 /* ----------------------------- user mspaces ---------------------------- */
  4512 
  4513 #if MSPACES
  4514 
  4515 static mstate
  4516 init_user_mstate(char *tbase, size_t tsize)
  4517 {
  4518     size_t msize = pad_request(sizeof(struct malloc_state));
  4519     mchunkptr mn;
  4520     mchunkptr msp = align_as_chunk(tbase);
  4521     mstate m = (mstate) (chunk2mem(msp));
  4522     memset(m, 0, msize);
  4523     INITIAL_LOCK(&m->mutex);
  4524     msp->head = (msize | PINUSE_BIT | CINUSE_BIT);
  4525     m->seg.base = m->least_addr = tbase;
  4526     m->seg.size = m->footprint = m->max_footprint = tsize;
  4527     m->magic = mparams.magic;
  4528     m->mflags = mparams.default_mflags;
  4529     disable_contiguous(m);
  4530     init_bins(m);
  4531     mn = next_chunk(mem2chunk(m));
  4532     init_top(m, mn, (size_t) ((tbase + tsize) - (char *) mn) - TOP_FOOT_SIZE);
  4533     check_top_chunk(m, m->top);
  4534     return m;
  4535 }
  4536 
  4537 mspace
  4538 create_mspace(size_t capacity, int locked)
  4539 {
  4540     mstate m = 0;
  4541     size_t msize = pad_request(sizeof(struct malloc_state));
  4542     init_mparams();             /* Ensure pagesize etc initialized */
  4543 
  4544     if (capacity < (size_t) - (msize + TOP_FOOT_SIZE + mparams.page_size)) {
  4545         size_t rs = ((capacity == 0) ? mparams.granularity :
  4546                      (capacity + TOP_FOOT_SIZE + msize));
  4547         size_t tsize = granularity_align(rs);
  4548         char *tbase = (char *) (CALL_MMAP(tsize));
  4549         if (tbase != CMFAIL) {
  4550             m = init_user_mstate(tbase, tsize);
  4551             m->seg.sflags = IS_MMAPPED_BIT;
  4552             set_lock(m, locked);
  4553         }
  4554     }
  4555     return (mspace) m;
  4556 }
  4557 
  4558 mspace
  4559 create_mspace_with_base(void *base, size_t capacity, int locked)
  4560 {
  4561     mstate m = 0;
  4562     size_t msize = pad_request(sizeof(struct malloc_state));
  4563     init_mparams();             /* Ensure pagesize etc initialized */
  4564 
  4565     if (capacity > msize + TOP_FOOT_SIZE &&
  4566         capacity < (size_t) - (msize + TOP_FOOT_SIZE + mparams.page_size)) {
  4567         m = init_user_mstate((char *) base, capacity);
  4568         m->seg.sflags = EXTERN_BIT;
  4569         set_lock(m, locked);
  4570     }
  4571     return (mspace) m;
  4572 }
  4573 
  4574 size_t
  4575 destroy_mspace(mspace msp)
  4576 {
  4577     size_t freed = 0;
  4578     mstate ms = (mstate) msp;
  4579     if (ok_magic(ms)) {
  4580         msegmentptr sp = &ms->seg;
  4581         while (sp != 0) {
  4582             char *base = sp->base;
  4583             size_t size = sp->size;
  4584             flag_t flag = sp->sflags;
  4585             sp = sp->next;
  4586             if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) &&
  4587                 CALL_MUNMAP(base, size) == 0)
  4588                 freed += size;
  4589         }
  4590     } else {
  4591         USAGE_ERROR_ACTION(ms, ms);
  4592     }
  4593     return freed;
  4594 }
  4595 
  4596 /*
  4597   mspace versions of routines are near-clones of the global
  4598   versions. This is not so nice but better than the alternatives.
  4599 */
  4600 
  4601 
  4602 void *
  4603 mspace_malloc(mspace msp, size_t bytes)
  4604 {
  4605     mstate ms = (mstate) msp;
  4606     if (!ok_magic(ms)) {
  4607         USAGE_ERROR_ACTION(ms, ms);
  4608         return 0;
  4609     }
  4610     if (!PREACTION(ms)) {
  4611         void *mem;
  4612         size_t nb;
  4613         if (bytes <= MAX_SMALL_REQUEST) {
  4614             bindex_t idx;
  4615             binmap_t smallbits;
  4616             nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes);
  4617             idx = small_index(nb);
  4618             smallbits = ms->smallmap >> idx;
  4619 
  4620             if ((smallbits & 0x3U) != 0) {      /* Remainderless fit to a smallbin. */
  4621                 mchunkptr b, p;
  4622                 idx += ~smallbits & 1;  /* Uses next bin if idx empty */
  4623                 b = smallbin_at(ms, idx);
  4624                 p = b->fd;
  4625                 assert(chunksize(p) == small_index2size(idx));
  4626                 unlink_first_small_chunk(ms, b, p, idx);
  4627                 set_inuse_and_pinuse(ms, p, small_index2size(idx));
  4628                 mem = chunk2mem(p);
  4629                 check_malloced_chunk(ms, mem, nb);
  4630                 goto postaction;
  4631             }
  4632 
  4633             else if (nb > ms->dvsize) {
  4634                 if (smallbits != 0) {   /* Use chunk in next nonempty smallbin */
  4635                     mchunkptr b, p, r;
  4636                     size_t rsize;
  4637                     bindex_t i;
  4638                     binmap_t leftbits =
  4639                         (smallbits << idx) & left_bits(idx2bit(idx));
  4640                     binmap_t leastbit = least_bit(leftbits);
  4641                     compute_bit2idx(leastbit, i);
  4642                     b = smallbin_at(ms, i);
  4643                     p = b->fd;
  4644                     assert(chunksize(p) == small_index2size(i));
  4645                     unlink_first_small_chunk(ms, b, p, i);
  4646                     rsize = small_index2size(i) - nb;
  4647                     /* Fit here cannot be remainderless if 4byte sizes */
  4648                     if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
  4649                         set_inuse_and_pinuse(ms, p, small_index2size(i));
  4650                     else {
  4651                         set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
  4652                         r = chunk_plus_offset(p, nb);
  4653                         set_size_and_pinuse_of_free_chunk(r, rsize);
  4654                         replace_dv(ms, r, rsize);
  4655                     }
  4656                     mem = chunk2mem(p);
  4657                     check_malloced_chunk(ms, mem, nb);
  4658                     goto postaction;
  4659                 }
  4660 
  4661                 else if (ms->treemap != 0
  4662                          && (mem = tmalloc_small(ms, nb)) != 0) {
  4663                     check_malloced_chunk(ms, mem, nb);
  4664                     goto postaction;
  4665                 }
  4666             }
  4667         } else if (bytes >= MAX_REQUEST)
  4668             nb = MAX_SIZE_T;    /* Too big to allocate. Force failure (in sys alloc) */
  4669         else {
  4670             nb = pad_request(bytes);
  4671             if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
  4672                 check_malloced_chunk(ms, mem, nb);
  4673                 goto postaction;
  4674             }
  4675         }
  4676 
  4677         if (nb <= ms->dvsize) {
  4678             size_t rsize = ms->dvsize - nb;
  4679             mchunkptr p = ms->dv;
  4680             if (rsize >= MIN_CHUNK_SIZE) {      /* split dv */
  4681                 mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
  4682                 ms->dvsize = rsize;
  4683                 set_size_and_pinuse_of_free_chunk(r, rsize);
  4684                 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
  4685             } else {            /* exhaust dv */
  4686                 size_t dvs = ms->dvsize;
  4687                 ms->dvsize = 0;
  4688                 ms->dv = 0;
  4689                 set_inuse_and_pinuse(ms, p, dvs);
  4690             }
  4691             mem = chunk2mem(p);
  4692             check_malloced_chunk(ms, mem, nb);
  4693             goto postaction;
  4694         }
  4695 
  4696         else if (nb < ms->topsize) {    /* Split top */
  4697             size_t rsize = ms->topsize -= nb;
  4698             mchunkptr p = ms->top;
  4699             mchunkptr r = ms->top = chunk_plus_offset(p, nb);
  4700             r->head = rsize | PINUSE_BIT;
  4701             set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
  4702             mem = chunk2mem(p);
  4703             check_top_chunk(ms, ms->top);
  4704             check_malloced_chunk(ms, mem, nb);
  4705             goto postaction;
  4706         }
  4707 
  4708         mem = sys_alloc(ms, nb);
  4709 
  4710       postaction:
  4711         POSTACTION(ms);
  4712         return mem;
  4713     }
  4714 
  4715     return 0;
  4716 }
  4717 
  4718 void
  4719 mspace_free(mspace msp, void *mem)
  4720 {
  4721     if (mem != 0) {
  4722         mchunkptr p = mem2chunk(mem);
  4723 #if FOOTERS
  4724         mstate fm = get_mstate_for(p);
  4725 #else /* FOOTERS */
  4726         mstate fm = (mstate) msp;
  4727 #endif /* FOOTERS */
  4728         if (!ok_magic(fm)) {
  4729             USAGE_ERROR_ACTION(fm, p);
  4730             return;
  4731         }
  4732         if (!PREACTION(fm)) {
  4733             check_inuse_chunk(fm, p);
  4734             if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
  4735                 size_t psize = chunksize(p);
  4736                 mchunkptr next = chunk_plus_offset(p, psize);
  4737                 if (!pinuse(p)) {
  4738                     size_t prevsize = p->prev_foot;
  4739                     if ((prevsize & IS_MMAPPED_BIT) != 0) {
  4740                         prevsize &= ~IS_MMAPPED_BIT;
  4741                         psize += prevsize + MMAP_FOOT_PAD;
  4742                         if (CALL_MUNMAP((char *) p - prevsize, psize) == 0)
  4743                             fm->footprint -= psize;
  4744                         goto postaction;
  4745                     } else {
  4746                         mchunkptr prev = chunk_minus_offset(p, prevsize);
  4747                         psize += prevsize;
  4748                         p = prev;
  4749                         if (RTCHECK(ok_address(fm, prev))) {    /* consolidate backward */
  4750                             if (p != fm->dv) {
  4751                                 unlink_chunk(fm, p, prevsize);
  4752                             } else if ((next->head & INUSE_BITS) ==
  4753                                        INUSE_BITS) {
  4754                                 fm->dvsize = psize;
  4755                                 set_free_with_pinuse(p, psize, next);
  4756                                 goto postaction;
  4757                             }
  4758                         } else
  4759                             goto erroraction;
  4760                     }
  4761                 }
  4762 
  4763                 if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
  4764                     if (!cinuse(next)) {        /* consolidate forward */
  4765                         if (next == fm->top) {
  4766                             size_t tsize = fm->topsize += psize;
  4767                             fm->top = p;
  4768                             p->head = tsize | PINUSE_BIT;
  4769                             if (p == fm->dv) {
  4770                                 fm->dv = 0;
  4771                                 fm->dvsize = 0;
  4772                             }
  4773                             if (should_trim(fm, tsize))
  4774                                 sys_trim(fm, 0);
  4775                             goto postaction;
  4776                         } else if (next == fm->dv) {
  4777                             size_t dsize = fm->dvsize += psize;
  4778                             fm->dv = p;
  4779                             set_size_and_pinuse_of_free_chunk(p, dsize);
  4780                             goto postaction;
  4781                         } else {
  4782                             size_t nsize = chunksize(next);
  4783                             psize += nsize;
  4784                             unlink_chunk(fm, next, nsize);
  4785                             set_size_and_pinuse_of_free_chunk(p, psize);
  4786                             if (p == fm->dv) {
  4787                                 fm->dvsize = psize;
  4788                                 goto postaction;
  4789                             }
  4790                         }
  4791                     } else
  4792                         set_free_with_pinuse(p, psize, next);
  4793                     insert_chunk(fm, p, psize);
  4794                     check_free_chunk(fm, p);
  4795                     goto postaction;
  4796                 }
  4797             }
  4798           erroraction:
  4799             USAGE_ERROR_ACTION(fm, p);
  4800           postaction:
  4801             POSTACTION(fm);
  4802         }
  4803     }
  4804 }
  4805 
  4806 void *
  4807 mspace_calloc(mspace msp, size_t n_elements, size_t elem_size)
  4808 {
  4809     void *mem;
  4810     size_t req = 0;
  4811     mstate ms = (mstate) msp;
  4812     if (!ok_magic(ms)) {
  4813         USAGE_ERROR_ACTION(ms, ms);
  4814         return 0;
  4815     }
  4816     if (n_elements != 0) {
  4817         req = n_elements * elem_size;
  4818         if (((n_elements | elem_size) & ~(size_t) 0xffff) &&
  4819             (req / n_elements != elem_size))
  4820             req = MAX_SIZE_T;   /* force downstream failure on overflow */
  4821     }
  4822     mem = internal_malloc(ms, req);
  4823     if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
  4824         memset(mem, 0, req);
  4825     return mem;
  4826 }
  4827 
  4828 void *
  4829 mspace_realloc(mspace msp, void *oldmem, size_t bytes)
  4830 {
  4831     if (oldmem == 0)
  4832         return mspace_malloc(msp, bytes);
  4833 #ifdef REALLOC_ZERO_BYTES_FREES
  4834     if (bytes == 0) {
  4835         mspace_free(msp, oldmem);
  4836         return 0;
  4837     }
  4838 #endif /* REALLOC_ZERO_BYTES_FREES */
  4839     else {
  4840 #if FOOTERS
  4841         mchunkptr p = mem2chunk(oldmem);
  4842         mstate ms = get_mstate_for(p);
  4843 #else /* FOOTERS */
  4844         mstate ms = (mstate) msp;
  4845 #endif /* FOOTERS */
  4846         if (!ok_magic(ms)) {
  4847             USAGE_ERROR_ACTION(ms, ms);
  4848             return 0;
  4849         }
  4850         return internal_realloc(ms, oldmem, bytes);
  4851     }
  4852 }
  4853 
  4854 void *
  4855 mspace_memalign(mspace msp, size_t alignment, size_t bytes)
  4856 {
  4857     mstate ms = (mstate) msp;
  4858     if (!ok_magic(ms)) {
  4859         USAGE_ERROR_ACTION(ms, ms);
  4860         return 0;
  4861     }
  4862     return internal_memalign(ms, alignment, bytes);
  4863 }
  4864 
  4865 void **
  4866 mspace_independent_calloc(mspace msp, size_t n_elements,
  4867                           size_t elem_size, void *chunks[])
  4868 {
  4869     size_t sz = elem_size;      /* serves as 1-element array */
  4870     mstate ms = (mstate) msp;
  4871     if (!ok_magic(ms)) {
  4872         USAGE_ERROR_ACTION(ms, ms);
  4873         return 0;
  4874     }
  4875     return ialloc(ms, n_elements, &sz, 3, chunks);
  4876 }
  4877 
  4878 void **
  4879 mspace_independent_comalloc(mspace msp, size_t n_elements,
  4880                             size_t sizes[], void *chunks[])
  4881 {
  4882     mstate ms = (mstate) msp;
  4883     if (!ok_magic(ms)) {
  4884         USAGE_ERROR_ACTION(ms, ms);
  4885         return 0;
  4886     }
  4887     return ialloc(ms, n_elements, sizes, 0, chunks);
  4888 }
  4889 
  4890 int
  4891 mspace_trim(mspace msp, size_t pad)
  4892 {
  4893     int result = 0;
  4894     mstate ms = (mstate) msp;
  4895     if (ok_magic(ms)) {
  4896         if (!PREACTION(ms)) {
  4897             result = sys_trim(ms, pad);
  4898             POSTACTION(ms);
  4899         }
  4900     } else {
  4901         USAGE_ERROR_ACTION(ms, ms);
  4902     }
  4903     return result;
  4904 }
  4905 
  4906 void
  4907 mspace_malloc_stats(mspace msp)
  4908 {
  4909     mstate ms = (mstate) msp;
  4910     if (ok_magic(ms)) {
  4911         internal_malloc_stats(ms);
  4912     } else {
  4913         USAGE_ERROR_ACTION(ms, ms);
  4914     }
  4915 }
  4916 
  4917 size_t
  4918 mspace_footprint(mspace msp)
  4919 {
  4920     size_t result;
  4921     mstate ms = (mstate) msp;
  4922     if (ok_magic(ms)) {
  4923         result = ms->footprint;
  4924     }
  4925     USAGE_ERROR_ACTION(ms, ms);
  4926     return result;
  4927 }
  4928 
  4929 
  4930 size_t
  4931 mspace_max_footprint(mspace msp)
  4932 {
  4933     size_t result;
  4934     mstate ms = (mstate) msp;
  4935     if (ok_magic(ms)) {
  4936         result = ms->max_footprint;
  4937     }
  4938     USAGE_ERROR_ACTION(ms, ms);
  4939     return result;
  4940 }
  4941 
  4942 
  4943 #if !NO_MALLINFO
  4944 struct mallinfo
  4945 mspace_mallinfo(mspace msp)
  4946 {
  4947     mstate ms = (mstate) msp;
  4948     if (!ok_magic(ms)) {
  4949         USAGE_ERROR_ACTION(ms, ms);
  4950     }
  4951     return internal_mallinfo(ms);
  4952 }
  4953 #endif /* NO_MALLINFO */
  4954 
  4955 int
  4956 mspace_mallopt(int param_number, int value)
  4957 {
  4958     return change_mparam(param_number, value);
  4959 }
  4960 
  4961 #endif /* MSPACES */
  4962 
  4963 /* -------------------- Alternative MORECORE functions ------------------- */
  4964 
  4965 /*
  4966   Guidelines for creating a custom version of MORECORE:
  4967 
  4968   * For best performance, MORECORE should allocate in multiples of pagesize.
  4969   * MORECORE may allocate more memory than requested. (Or even less,
  4970       but this will usually result in a malloc failure.)
  4971   * MORECORE must not allocate memory when given argument zero, but
  4972       instead return one past the end address of memory from previous
  4973       nonzero call.
  4974   * For best performance, consecutive calls to MORECORE with positive
  4975       arguments should return increasing addresses, indicating that
  4976       space has been contiguously extended.
  4977   * Even though consecutive calls to MORECORE need not return contiguous
  4978       addresses, it must be OK for malloc'ed chunks to span multiple
  4979       regions in those cases where they do happen to be contiguous.
  4980   * MORECORE need not handle negative arguments -- it may instead
  4981       just return MFAIL when given negative arguments.
  4982       Negative arguments are always multiples of pagesize. MORECORE
  4983       must not misinterpret negative args as large positive unsigned
  4984       args. You can suppress all such calls from even occurring by defining
  4985       MORECORE_CANNOT_TRIM,
  4986 
  4987   As an example alternative MORECORE, here is a custom allocator
  4988   kindly contributed for pre-OSX macOS.  It uses virtually but not
  4989   necessarily physically contiguous non-paged memory (locked in,
  4990   present and won't get swapped out).  You can use it by uncommenting
  4991   this section, adding some #includes, and setting up the appropriate
  4992   defines above:
  4993 
  4994       #define MORECORE osMoreCore
  4995 
  4996   There is also a shutdown routine that should somehow be called for
  4997   cleanup upon program exit.
  4998 
  4999   #define MAX_POOL_ENTRIES 100
  5000   #define MINIMUM_MORECORE_SIZE  (64 * 1024U)
  5001   static int next_os_pool;
  5002   void *our_os_pools[MAX_POOL_ENTRIES];
  5003 
  5004   void *osMoreCore(int size)
  5005   {
  5006     void *ptr = 0;
  5007     static void *sbrk_top = 0;
  5008 
  5009     if (size > 0)
  5010     {
  5011       if (size < MINIMUM_MORECORE_SIZE)
  5012          size = MINIMUM_MORECORE_SIZE;
  5013       if (CurrentExecutionLevel() == kTaskLevel)
  5014          ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
  5015       if (ptr == 0)
  5016       {
  5017         return (void *) MFAIL;
  5018       }
  5019       // save ptrs so they can be freed during cleanup
  5020       our_os_pools[next_os_pool] = ptr;
  5021       next_os_pool++;
  5022       ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
  5023       sbrk_top = (char *) ptr + size;
  5024       return ptr;
  5025     }
  5026     else if (size < 0)
  5027     {
  5028       // we don't currently support shrink behavior
  5029       return (void *) MFAIL;
  5030     }
  5031     else
  5032     {
  5033       return sbrk_top;
  5034     }
  5035   }
  5036 
  5037   // cleanup any allocated memory pools
  5038   // called as last thing before shutting down driver
  5039 
  5040   void osCleanupMem(void)
  5041   {
  5042     void **ptr;
  5043 
  5044     for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
  5045       if (*ptr)
  5046       {
  5047          PoolDeallocate(*ptr);
  5048          *ptr = 0;
  5049       }
  5050   }
  5051 
  5052 */
  5053 
  5054 
  5055 /* -----------------------------------------------------------------------
  5056 History:
  5057     V2.8.3 Thu Sep 22 11:16:32 2005  Doug Lea  (dl at gee)
  5058       * Add max_footprint functions
  5059       * Ensure all appropriate literals are size_t
  5060       * Fix conditional compilation problem for some #define settings
  5061       * Avoid concatenating segments with the one provided
  5062         in create_mspace_with_base
  5063       * Rename some variables to avoid compiler shadowing warnings
  5064       * Use explicit lock initialization.
  5065       * Better handling of sbrk interference.
  5066       * Simplify and fix segment insertion, trimming and mspace_destroy
  5067       * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
  5068       * Thanks especially to Dennis Flanagan for help on these.
  5069 
  5070     V2.8.2 Sun Jun 12 16:01:10 2005  Doug Lea  (dl at gee)
  5071       * Fix memalign brace error.
  5072 
  5073     V2.8.1 Wed Jun  8 16:11:46 2005  Doug Lea  (dl at gee)
  5074       * Fix improper #endif nesting in C++
  5075       * Add explicit casts needed for C++
  5076 
  5077     V2.8.0 Mon May 30 14:09:02 2005  Doug Lea  (dl at gee)
  5078       * Use trees for large bins
  5079       * Support mspaces
  5080       * Use segments to unify sbrk-based and mmap-based system allocation,
  5081         removing need for emulation on most platforms without sbrk.
  5082       * Default safety checks
  5083       * Optional footer checks. Thanks to William Robertson for the idea.
  5084       * Internal code refactoring
  5085       * Incorporate suggestions and platform-specific changes.
  5086         Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
  5087         Aaron Bachmann,  Emery Berger, and others.
  5088       * Speed up non-fastbin processing enough to remove fastbins.
  5089       * Remove useless cfree() to avoid conflicts with other apps.
  5090       * Remove internal memcpy, memset. Compilers handle builtins better.
  5091       * Remove some options that no one ever used and rename others.
  5092 
  5093     V2.7.2 Sat Aug 17 09:07:30 2002  Doug Lea  (dl at gee)
  5094       * Fix malloc_state bitmap array misdeclaration
  5095 
  5096     V2.7.1 Thu Jul 25 10:58:03 2002  Doug Lea  (dl at gee)
  5097       * Allow tuning of FIRST_SORTED_BIN_SIZE
  5098       * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
  5099       * Better detection and support for non-contiguousness of MORECORE.
  5100         Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
  5101       * Bypass most of malloc if no frees. Thanks To Emery Berger.
  5102       * Fix freeing of old top non-contiguous chunk im sysmalloc.
  5103       * Raised default trim and map thresholds to 256K.
  5104       * Fix mmap-related #defines. Thanks to Lubos Lunak.
  5105       * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
  5106       * Branch-free bin calculation
  5107       * Default trim and mmap thresholds now 256K.
  5108 
  5109     V2.7.0 Sun Mar 11 14:14:06 2001  Doug Lea  (dl at gee)
  5110       * Introduce independent_comalloc and independent_calloc.
  5111         Thanks to Michael Pachos for motivation and help.
  5112       * Make optional .h file available
  5113       * Allow > 2GB requests on 32bit systems.
  5114       * new WIN32 sbrk, mmap, munmap, lock code from <Walter@GeNeSys-e.de>.
  5115         Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
  5116         and Anonymous.
  5117       * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
  5118         helping test this.)
  5119       * memalign: check alignment arg
  5120       * realloc: don't try to shift chunks backwards, since this
  5121         leads to  more fragmentation in some programs and doesn't
  5122         seem to help in any others.
  5123       * Collect all cases in malloc requiring system memory into sysmalloc
  5124       * Use mmap as backup to sbrk
  5125       * Place all internal state in malloc_state
  5126       * Introduce fastbins (although similar to 2.5.1)
  5127       * Many minor tunings and cosmetic improvements
  5128       * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
  5129       * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
  5130         Thanks to Tony E. Bennett <tbennett@nvidia.com> and others.
  5131       * Include errno.h to support default failure action.
  5132 
  5133     V2.6.6 Sun Dec  5 07:42:19 1999  Doug Lea  (dl at gee)
  5134       * return null for negative arguments
  5135       * Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
  5136          * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
  5137           (e.g. WIN32 platforms)
  5138          * Cleanup header file inclusion for WIN32 platforms
  5139          * Cleanup code to avoid Microsoft Visual C++ compiler complaints
  5140          * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
  5141            memory allocation routines
  5142          * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
  5143          * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
  5144            usage of 'assert' in non-WIN32 code
  5145          * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
  5146            avoid infinite loop
  5147       * Always call 'fREe()' rather than 'free()'
  5148 
  5149     V2.6.5 Wed Jun 17 15:57:31 1998  Doug Lea  (dl at gee)
  5150       * Fixed ordering problem with boundary-stamping
  5151 
  5152     V2.6.3 Sun May 19 08:17:58 1996  Doug Lea  (dl at gee)
  5153       * Added pvalloc, as recommended by H.J. Liu
  5154       * Added 64bit pointer support mainly from Wolfram Gloger
  5155       * Added anonymously donated WIN32 sbrk emulation
  5156       * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
  5157       * malloc_extend_top: fix mask error that caused wastage after
  5158         foreign sbrks
  5159       * Add linux mremap support code from HJ Liu
  5160 
  5161     V2.6.2 Tue Dec  5 06:52:55 1995  Doug Lea  (dl at gee)
  5162       * Integrated most documentation with the code.
  5163       * Add support for mmap, with help from
  5164         Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
  5165       * Use last_remainder in more cases.
  5166       * Pack bins using idea from  colin@nyx10.cs.du.edu
  5167       * Use ordered bins instead of best-fit threshhold
  5168       * Eliminate block-local decls to simplify tracing and debugging.
  5169       * Support another case of realloc via move into top
  5170       * Fix error occuring when initial sbrk_base not word-aligned.
  5171       * Rely on page size for units instead of SBRK_UNIT to
  5172         avoid surprises about sbrk alignment conventions.
  5173       * Add mallinfo, mallopt. Thanks to Raymond Nijssen
  5174         (raymond@es.ele.tue.nl) for the suggestion.
  5175       * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
  5176       * More precautions for cases where other routines call sbrk,
  5177         courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
  5178       * Added macros etc., allowing use in linux libc from
  5179         H.J. Lu (hjl@gnu.ai.mit.edu)
  5180       * Inverted this history list
  5181 
  5182     V2.6.1 Sat Dec  2 14:10:57 1995  Doug Lea  (dl at gee)
  5183       * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
  5184       * Removed all preallocation code since under current scheme
  5185         the work required to undo bad preallocations exceeds
  5186         the work saved in good cases for most test programs.
  5187       * No longer use return list or unconsolidated bins since
  5188         no scheme using them consistently outperforms those that don't
  5189         given above changes.
  5190       * Use best fit for very large chunks to prevent some worst-cases.
  5191       * Added some support for debugging
  5192 
  5193     V2.6.0 Sat Nov  4 07:05:23 1995  Doug Lea  (dl at gee)
  5194       * Removed footers when chunks are in use. Thanks to
  5195         Paul Wilson (wilson@cs.texas.edu) for the suggestion.
  5196 
  5197     V2.5.4 Wed Nov  1 07:54:51 1995  Doug Lea  (dl at gee)
  5198       * Added malloc_trim, with help from Wolfram Gloger
  5199         (wmglo@Dent.MED.Uni-Muenchen.DE).
  5200 
  5201     V2.5.3 Tue Apr 26 10:16:01 1994  Doug Lea  (dl at g)
  5202 
  5203     V2.5.2 Tue Apr  5 16:20:40 1994  Doug Lea  (dl at g)
  5204       * realloc: try to expand in both directions
  5205       * malloc: swap order of clean-bin strategy;
  5206       * realloc: only conditionally expand backwards
  5207       * Try not to scavenge used bins
  5208       * Use bin counts as a guide to preallocation
  5209       * Occasionally bin return list chunks in first scan
  5210       * Add a few optimizations from colin@nyx10.cs.du.edu
  5211 
  5212     V2.5.1 Sat Aug 14 15:40:43 1993  Doug Lea  (dl at g)
  5213       * faster bin computation & slightly different binning
  5214       * merged all consolidations to one part of malloc proper
  5215          (eliminating old malloc_find_space & malloc_clean_bin)
  5216       * Scan 2 returns chunks (not just 1)
  5217       * Propagate failure in realloc if malloc returns 0
  5218       * Add stuff to allow compilation on non-ANSI compilers
  5219           from kpv@research.att.com
  5220 
  5221     V2.5 Sat Aug  7 07:41:59 1993  Doug Lea  (dl at g.oswego.edu)
  5222       * removed potential for odd address access in prev_chunk
  5223       * removed dependency on getpagesize.h
  5224       * misc cosmetics and a bit more internal documentation
  5225       * anticosmetics: mangled names in macros to evade debugger strangeness
  5226       * tested on sparc, hp-700, dec-mips, rs6000
  5227           with gcc & native cc (hp, dec only) allowing
  5228           Detlefs & Zorn comparison study (in SIGPLAN Notices.)
  5229 
  5230     Trial version Fri Aug 28 13:14:29 1992  Doug Lea  (dl at g.oswego.edu)
  5231       * Based loosely on libg++-1.2X malloc. (It retains some of the overall
  5232          structure of old version,  but most details differ.)
  5233  
  5234 */
  5235 
  5236 #endif /* !HAVE_MALLOC */
  5237 
  5238 /* vi: set ts=4 sw=4 expandtab: */