dlmalloc.c
Go to the documentation of this file.
00001 /*
00002   This is a version (aka dlmalloc) of malloc/free/realloc written by
00003   Doug Lea and released to the public domain, as explained at
00004   http://creativecommons.org/licenses/publicdomain.  Send questions,
00005   comments, complaints, performance data, etc to dl@cs.oswego.edu
00006 
00007 * Version 2.8.4 Wed May 27 09:56:23 2009  Doug Lea  (dl at gee)
00008 
00009    Note: There may be an updated version of this malloc obtainable at
00010            ftp://gee.cs.oswego.edu/pub/misc/malloc.c
00011          Check before installing!
00012 
00013 * Quickstart
00014 
00015   This library is all in one file to simplify the most common usage:
00016   ftp it, compile it (-O3), and link it into another program. All of
00017   the compile-time options default to reasonable values for use on
00018   most platforms.  You might later want to step through various
00019   compile-time and dynamic tuning options.
00020 
00021   For convenience, an include file for code using this malloc is at:
00022      ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.4.h
00023   You don't really need this .h file unless you call functions not
00024   defined in your system include files.  The .h file contains only the
00025   excerpts from this file needed for using this malloc on ANSI C/C++
00026   systems, so long as you haven't changed compile-time options about
00027   naming and tuning parameters.  If you do, then you can create your
00028   own malloc.h that does include all settings by cutting at the point
00029   indicated below. Note that you may already by default be using a C
00030   library containing a malloc that is based on some version of this
00031   malloc (for example in linux). You might still want to use the one
00032   in this file to customize settings or to avoid overheads associated
00033   with library versions.
00034 
00035 * Vital statistics:
00036 
00037   Supported pointer/size_t representation:       4 or 8 bytes
00038        size_t MUST be an unsigned type of the same width as
00039        pointers. (If you are using an ancient system that declares
00040        size_t as a signed type, or need it to be a different width
00041        than pointers, you can use a previous release of this malloc
00042        (e.g. 2.7.2) supporting these.)
00043 
00044   Alignment:                                     8 bytes (default)
00045        This suffices for nearly all current machines and C compilers.
00046        However, you can define MALLOC_ALIGNMENT to be wider than this
00047        if necessary (up to 128bytes), at the expense of using more space.
00048 
00049   Minimum overhead per allocated chunk:   4 or  8 bytes (if 4byte sizes)
00050                                           8 or 16 bytes (if 8byte sizes)
00051        Each malloced chunk has a hidden word of overhead holding size
00052        and status information, and additional cross-check word
00053        if FOOTERS is defined.
00054 
00055   Minimum allocated size: 4-byte ptrs:  16 bytes    (including overhead)
00056                           8-byte ptrs:  32 bytes    (including overhead)
00057 
00058        Even a request for zero bytes (i.e., malloc(0)) returns a
00059        pointer to something of the minimum allocatable size.
00060        The maximum overhead wastage (i.e., number of extra bytes
00061        allocated than were requested in malloc) is less than or equal
00062        to the minimum size, except for requests >= mmap_threshold that
00063        are serviced via mmap(), where the worst case wastage is about
00064        32 bytes plus the remainder from a system page (the minimal
00065        mmap unit); typically 4096 or 8192 bytes.
00066 
00067   Security: static-safe; optionally more or less
00068        The "security" of malloc refers to the ability of malicious
00069        code to accentuate the effects of errors (for example, freeing
00070        space that is not currently malloc'ed or overwriting past the
00071        ends of chunks) in code that calls malloc.  This malloc
00072        guarantees not to modify any memory locations below the base of
00073        heap, i.e., static variables, even in the presence of usage
00074        errors.  The routines additionally detect most improper frees
00075        and reallocs.  All this holds as long as the static bookkeeping
00076        for malloc itself is not corrupted by some other means.  This
00077        is only one aspect of security -- these checks do not, and
00078        cannot, detect all possible programming errors.
00079 
00080        If FOOTERS is defined nonzero, then each allocated chunk
00081        carries an additional check word to verify that it was malloced
00082        from its space.  These check words are the same within each
00083        execution of a program using malloc, but differ across
00084        executions, so externally crafted fake chunks cannot be
00085        freed. This improves security by rejecting frees/reallocs that
00086        could corrupt heap memory, in addition to the checks preventing
00087        writes to statics that are always on.  This may further improve
00088        security at the expense of time and space overhead.  (Note that
00089        FOOTERS may also be worth using with MSPACES.)
00090 
00091        By default detected errors cause the program to abort (calling
00092        "abort()"). You can override this to instead proceed past
00093        errors by defining PROCEED_ON_ERROR.  In this case, a bad free
00094        has no effect, and a malloc that encounters a bad address
00095        caused by user overwrites will ignore the bad address by
00096        dropping pointers and indices to all known memory. This may
00097        be appropriate for programs that should continue if at all
00098        possible in the face of programming errors, although they may
00099        run out of memory because dropped memory is never reclaimed.
00100 
00101        If you don't like either of these options, you can define
00102        CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
00103        else. And if if you are sure that your program using malloc has
00104        no errors or vulnerabilities, you can define INSECURE to 1,
00105        which might (or might not) provide a small performance improvement.
00106 
00107   Thread-safety: NOT thread-safe unless USE_LOCKS defined
00108        When USE_LOCKS is defined, each public call to malloc, free,
00109        etc is surrounded with either a pthread mutex or a win32
00110        spinlock (depending on WIN32). This is not especially fast, and
00111        can be a major bottleneck.  It is designed only to provide
00112        minimal protection in concurrent environments, and to provide a
00113        basis for extensions.  If you are using malloc in a concurrent
00114        program, consider instead using nedmalloc
00115        (http://www.nedprod.com/programs/portable/nedmalloc/) or
00116        ptmalloc (See http://www.malloc.de), which are derived
00117        from versions of this malloc.
00118 
00119   System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
00120        This malloc can use unix sbrk or any emulation (invoked using
00121        the CALL_MORECORE macro) and/or mmap/munmap or any emulation
00122        (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
00123        memory.  On most unix systems, it tends to work best if both
00124        MORECORE and MMAP are enabled.  On Win32, it uses emulations
00125        based on VirtualAlloc. It also uses common C library functions
00126        like memset.
00127 
00128   Compliance: I believe it is compliant with the Single Unix Specification
00129        (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
00130        others as well.
00131 
00132 * Overview of algorithms
00133 
00134   This is not the fastest, most space-conserving, most portable, or
00135   most tunable malloc ever written. However it is among the fastest
00136   while also being among the most space-conserving, portable and
00137   tunable.  Consistent balance across these factors results in a good
00138   general-purpose allocator for malloc-intensive programs.
00139 
00140   In most ways, this malloc is a best-fit allocator. Generally, it
00141   chooses the best-fitting existing chunk for a request, with ties
00142   broken in approximately least-recently-used order. (This strategy
00143   normally maintains low fragmentation.) However, for requests less
00144   than 256bytes, it deviates from best-fit when there is not an
00145   exactly fitting available chunk by preferring to use space adjacent
00146   to that used for the previous small request, as well as by breaking
00147   ties in approximately most-recently-used order. (These enhance
00148   locality of series of small allocations.)  And for very large requests
00149   (>= 256Kb by default), it relies on system memory mapping
00150   facilities, if supported.  (This helps avoid carrying around and
00151   possibly fragmenting memory used only for large chunks.)
00152 
00153   All operations (except malloc_stats and mallinfo) have execution
00154   times that are bounded by a constant factor of the number of bits in
00155   a size_t, not counting any clearing in calloc or copying in realloc,
00156   or actions surrounding MORECORE and MMAP that have times
00157   proportional to the number of non-contiguous regions returned by
00158   system allocation routines, which is often just 1. In real-time
00159   applications, you can optionally suppress segment traversals using
00160   NO_SEGMENT_TRAVERSAL, which assures bounded execution even when
00161   system allocators return non-contiguous spaces, at the typical
00162   expense of carrying around more memory and increased fragmentation.
00163 
00164   The implementation is not very modular and seriously overuses
00165   macros. Perhaps someday all C compilers will do as good a job
00166   inlining modular code as can now be done by brute-force expansion,
00167   but now, enough of them seem not to.
00168 
00169   Some compilers issue a lot of warnings about code that is
00170   dead/unreachable only on some platforms, and also about intentional
00171   uses of negation on unsigned types. All known cases of each can be
00172   ignored.
00173 
00174   For a longer but out of date high-level description, see
00175      http://gee.cs.oswego.edu/dl/html/malloc.html
00176 
00177 * MSPACES
00178   If MSPACES is defined, then in addition to malloc, free, etc.,
00179   this file also defines mspace_malloc, mspace_free, etc. These
00180   are versions of malloc routines that take an "mspace" argument
00181   obtained using create_mspace, to control all internal bookkeeping.
00182   If ONLY_MSPACES is defined, only these versions are compiled.
00183   So if you would like to use this allocator for only some allocations,
00184   and your system malloc for others, you can compile with
00185   ONLY_MSPACES and then do something like...
00186     static mspace mymspace = create_mspace(0,0); // for example
00187     #define mymalloc(bytes)  mspace_malloc(mymspace, bytes)
00188 
00189   (Note: If you only need one instance of an mspace, you can instead
00190   use "USE_DL_PREFIX" to relabel the global malloc.)
00191 
00192   You can similarly create thread-local allocators by storing
00193   mspaces as thread-locals. For example:
00194     static __thread mspace tlms = 0;
00195     void*  tlmalloc(size_t bytes) {
00196       if (tlms == 0) tlms = create_mspace(0, 0);
00197       return mspace_malloc(tlms, bytes);
00198     }
00199     void  tlfree(void* mem) { mspace_free(tlms, mem); }
00200 
00201   Unless FOOTERS is defined, each mspace is completely independent.
00202   You cannot allocate from one and free to another (although
00203   conformance is only weakly checked, so usage errors are not always
00204   caught). If FOOTERS is defined, then each chunk carries around a tag
00205   indicating its originating mspace, and frees are directed to their
00206   originating spaces.
00207 
00208  -------------------------  Compile-time options ---------------------------
00209 
00210 Be careful in setting #define values for numerical constants of type
00211 size_t. On some systems, literal values are not automatically extended
00212 to size_t precision unless they are explicitly casted. You can also
00213 use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.
00214 
00215 WIN32                    default: defined if _WIN32 defined
00216   Defining WIN32 sets up defaults for MS environment and compilers.
00217   Otherwise defaults are for unix. Beware that there seem to be some
00218   cases where this malloc might not be a pure drop-in replacement for
00219   Win32 malloc: Random-looking failures from Win32 GDI API's (eg;
00220   SetDIBits()) may be due to bugs in some video driver implementations
00221   when pixel buffers are malloc()ed, and the region spans more than
00222   one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb)
00223   default granularity, pixel buffers may straddle virtual allocation
00224   regions more often than when using the Microsoft allocator.  You can
00225   avoid this by using VirtualAlloc() and VirtualFree() for all pixel
00226   buffers rather than using malloc().  If this is not possible,
00227   recompile this malloc with a larger DEFAULT_GRANULARITY.
00228 
00229 MALLOC_ALIGNMENT         default: (size_t)8
00230   Controls the minimum alignment for malloc'ed chunks.  It must be a
00231   power of two and at least 8, even on machines for which smaller
00232   alignments would suffice. It may be defined as larger than this
00233   though. Note however that code and data structures are optimized for
00234   the case of 8-byte alignment.
00235 
00236 MSPACES                  default: 0 (false)
00237   If true, compile in support for independent allocation spaces.
00238   This is only supported if HAVE_MMAP is true.
00239 
00240 ONLY_MSPACES             default: 0 (false)
00241   If true, only compile in mspace versions, not regular versions.
00242 
00243 USE_LOCKS                default: 0 (false)
00244   Causes each call to each public routine to be surrounded with
00245   pthread or WIN32 mutex lock/unlock. (If set true, this can be
00246   overridden on a per-mspace basis for mspace versions.) If set to a
00247   non-zero value other than 1, locks are used, but their
00248   implementation is left out, so lock functions must be supplied manually,
00249   as described below.
00250 
00251 USE_SPIN_LOCKS           default: 1 iff USE_LOCKS and on x86 using gcc or MSC
00252   If true, uses custom spin locks for locking. This is currently
00253   supported only for x86 platforms using gcc or recent MS compilers.
00254   Otherwise, posix locks or win32 critical sections are used.
00255 
00256 FOOTERS                  default: 0
00257   If true, provide extra checking and dispatching by placing
00258   information in the footers of allocated chunks. This adds
00259   space and time overhead.
00260 
00261 INSECURE                 default: 0
00262   If true, omit checks for usage errors and heap space overwrites.
00263 
00264 USE_DL_PREFIX            default: NOT defined
00265   Causes compiler to prefix all public routines with the string 'dl'.
00266   This can be useful when you only want to use this malloc in one part
00267   of a program, using your regular system malloc elsewhere.
00268 
00269 ABORT                    default: defined as abort()
00270   Defines how to abort on failed checks.  On most systems, a failed
00271   check cannot die with an "assert" or even print an informative
00272   message, because the underlying print routines in turn call malloc,
00273   which will fail again.  Generally, the best policy is to simply call
00274   abort(). It's not very useful to do more than this because many
00275   errors due to overwriting will show up as address faults (null, odd
00276   addresses etc) rather than malloc-triggered checks, so will also
00277   abort.  Also, most compilers know that abort() does not return, so
00278   can better optimize code conditionally calling it.
00279 
00280 PROCEED_ON_ERROR           default: defined as 0 (false)
00281   Controls whether detected bad addresses cause them to bypassed
00282   rather than aborting. If set, detected bad arguments to free and
00283   realloc are ignored. And all bookkeeping information is zeroed out
00284   upon a detected overwrite of freed heap space, thus losing the
00285   ability to ever return it from malloc again, but enabling the
00286   application to proceed. If PROCEED_ON_ERROR is defined, the
00287   static variable malloc_corruption_error_count is compiled in
00288   and can be examined to see if errors have occurred. This option
00289   generates slower code than the default abort policy.
00290 
00291 DEBUG                    default: NOT defined
00292   The DEBUG setting is mainly intended for people trying to modify
00293   this code or diagnose problems when porting to new platforms.
00294   However, it may also be able to better isolate user errors than just
00295   using runtime checks.  The assertions in the check routines spell
00296   out in more detail the assumptions and invariants underlying the
00297   algorithms.  The checking is fairly extensive, and will slow down
00298   execution noticeably. Calling malloc_stats or mallinfo with DEBUG
00299   set will attempt to check every non-mmapped allocated and free chunk
00300   in the course of computing the summaries.
00301 
00302 ABORT_ON_ASSERT_FAILURE   default: defined as 1 (true)
00303   Debugging assertion failures can be nearly impossible if your
00304   version of the assert macro causes malloc to be called, which will
00305   lead to a cascade of further failures, blowing the runtime stack.
00306   ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
00307   which will usually make debugging easier.
00308 
00309 MALLOC_FAILURE_ACTION     default: sets errno to ENOMEM, or no-op on win32
00310   The action to take before "return 0" when malloc fails to be able to
00311   return memory because there is none available.
00312 
00313 HAVE_MORECORE             default: 1 (true) unless win32 or ONLY_MSPACES
00314   True if this system supports sbrk or an emulation of it.
00315 
00316 MORECORE                  default: sbrk
00317   The name of the sbrk-style system routine to call to obtain more
00318   memory.  See below for guidance on writing custom MORECORE
00319   functions. The type of the argument to sbrk/MORECORE varies across
00320   systems.  It cannot be size_t, because it supports negative
00321   arguments, so it is normally the signed type of the same width as
00322   size_t (sometimes declared as "intptr_t").  It doesn't much matter
00323   though. Internally, we only call it with arguments less than half
00324   the max value of a size_t, which should work across all reasonable
00325   possibilities, although sometimes generating compiler warnings.
00326 
00327 MORECORE_CONTIGUOUS       default: 1 (true) if HAVE_MORECORE
00328   If true, take advantage of fact that consecutive calls to MORECORE
00329   with positive arguments always return contiguous increasing
00330   addresses.  This is true of unix sbrk. It does not hurt too much to
00331   set it true anyway, since malloc copes with non-contiguities.
00332   Setting it false when definitely non-contiguous saves time
00333   and possibly wasted space it would take to discover this though.
00334 
00335 MORECORE_CANNOT_TRIM      default: NOT defined
00336   True if MORECORE cannot release space back to the system when given
00337   negative arguments. This is generally necessary only if you are
00338   using a hand-crafted MORECORE function that cannot handle negative
00339   arguments.
00340 
00341 NO_SEGMENT_TRAVERSAL       default: 0
00342   If non-zero, suppresses traversals of memory segments
00343   returned by either MORECORE or CALL_MMAP. This disables
00344   merging of segments that are contiguous, and selectively
00345   releasing them to the OS if unused, but bounds execution times.
00346 
00347 HAVE_MMAP                 default: 1 (true)
00348   True if this system supports mmap or an emulation of it.  If so, and
00349   HAVE_MORECORE is not true, MMAP is used for all system
00350   allocation. If set and HAVE_MORECORE is true as well, MMAP is
00351   primarily used to directly allocate very large blocks. It is also
00352   used as a backup strategy in cases where MORECORE fails to provide
00353   space from system. Note: A single call to MUNMAP is assumed to be
00354   able to unmap memory that may have be allocated using multiple calls
00355   to MMAP, so long as they are adjacent.
00356 
00357 HAVE_MREMAP               default: 1 on linux, else 0
00358   If true realloc() uses mremap() to re-allocate large blocks and
00359   extend or shrink allocation spaces.
00360 
00361 MMAP_CLEARS               default: 1 except on WINCE.
00362   True if mmap clears memory so calloc doesn't need to. This is true
00363   for standard unix mmap using /dev/zero and on WIN32 except for WINCE.
00364 
00365 USE_BUILTIN_FFS            default: 0 (i.e., not used)
00366   Causes malloc to use the builtin ffs() function to compute indices.
00367   Some compilers may recognize and intrinsify ffs to be faster than the
00368   supplied C version. Also, the case of x86 using gcc is special-cased
00369   to an asm instruction, so is already as fast as it can be, and so
00370   this setting has no effect. Similarly for Win32 under recent MS compilers.
00371   (On most x86s, the asm version is only slightly faster than the C version.)
00372 
00373 malloc_getpagesize         default: derive from system includes, or 4096.
00374   The system page size. To the extent possible, this malloc manages
00375   memory from the system in page-size units.  This may be (and
00376   usually is) a function rather than a constant. This is ignored
00377   if WIN32, where page size is determined using getSystemInfo during
00378   initialization.
00379 
00380 USE_DEV_RANDOM             default: 0 (i.e., not used)
00381   Causes malloc to use /dev/random to initialize secure magic seed for
00382   stamping footers. Otherwise, the current time is used.
00383 
00384 NO_MALLINFO                default: 0
00385   If defined, don't compile "mallinfo". This can be a simple way
00386   of dealing with mismatches between system declarations and
00387   those in this file.
00388 
00389 MALLINFO_FIELD_TYPE        default: size_t
00390   The type of the fields in the mallinfo struct. This was originally
00391   defined as "int" in SVID etc, but is more usefully defined as
00392   size_t. The value is used only if  HAVE_USR_INCLUDE_MALLOC_H is not set
00393 
00394 REALLOC_ZERO_BYTES_FREES    default: not defined
00395   This should be set if a call to realloc with zero bytes should
00396   be the same as a call to free. Some people think it should. Otherwise,
00397   since this malloc returns a unique pointer for malloc(0), so does
00398   realloc(p, 0).
00399 
00400 LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
00401 LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H,  LACKS_ERRNO_H
00402 LACKS_STDLIB_H                default: NOT defined unless on WIN32
00403   Define these if your system does not have these header files.
00404   You might need to manually insert some of the declarations they provide.
00405 
00406 DEFAULT_GRANULARITY        default: page size if MORECORE_CONTIGUOUS,
00407                                 system_info.dwAllocationGranularity in WIN32,
00408                                 otherwise 64K.
00409       Also settable using mallopt(M_GRANULARITY, x)
00410   The unit for allocating and deallocating memory from the system.  On
00411   most systems with contiguous MORECORE, there is no reason to
00412   make this more than a page. However, systems with MMAP tend to
00413   either require or encourage larger granularities.  You can increase
00414   this value to prevent system allocation functions to be called so
00415   often, especially if they are slow.  The value must be at least one
00416   page and must be a power of two.  Setting to 0 causes initialization
00417   to either page size or win32 region size.  (Note: In previous
00418   versions of malloc, the equivalent of this option was called
00419   "TOP_PAD")
00420 
00421 DEFAULT_TRIM_THRESHOLD    default: 2MB
00422       Also settable using mallopt(M_TRIM_THRESHOLD, x)
00423   The maximum amount of unused top-most memory to keep before
00424   releasing via malloc_trim in free().  Automatic trimming is mainly
00425   useful in long-lived programs using contiguous MORECORE.  Because
00426   trimming via sbrk can be slow on some systems, and can sometimes be
00427   wasteful (in cases where programs immediately afterward allocate
00428   more large chunks) the value should be high enough so that your
00429   overall system performance would improve by releasing this much
00430   memory.  As a rough guide, you might set to a value close to the
00431   average size of a process (program) running on your system.
00432   Releasing this much memory would allow such a process to run in
00433   memory.  Generally, it is worth tuning trim thresholds when a
00434   program undergoes phases where several large chunks are allocated
00435   and released in ways that can reuse each other's storage, perhaps
00436   mixed with phases where there are no such chunks at all. The trim
00437   value must be greater than page size to have any useful effect.  To
00438   disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
00439   some people use of mallocing a huge space and then freeing it at
00440   program startup, in an attempt to reserve system memory, doesn't
00441   have the intended effect under automatic trimming, since that memory
00442   will immediately be returned to the system.
00443 
00444 DEFAULT_MMAP_THRESHOLD       default: 256K
00445       Also settable using mallopt(M_MMAP_THRESHOLD, x)
00446   The request size threshold for using MMAP to directly service a
00447   request. Requests of at least this size that cannot be allocated
00448   using already-existing space will be serviced via mmap.  (If enough
00449   normal freed space already exists it is used instead.)  Using mmap
00450   segregates relatively large chunks of memory so that they can be
00451   individually obtained and released from the host system. A request
00452   serviced through mmap is never reused by any other request (at least
00453   not directly; the system may just so happen to remap successive
00454   requests to the same locations).  Segregating space in this way has
00455   the benefits that: Mmapped space can always be individually released
00456   back to the system, which helps keep the system level memory demands
00457   of a long-lived program low.  Also, mapped memory doesn't become
00458   `locked' between other chunks, as can happen with normally allocated
00459   chunks, which means that even trimming via malloc_trim would not
00460   release them.  However, it has the disadvantage that the space
00461   cannot be reclaimed, consolidated, and then used to service later
00462   requests, as happens with normal chunks.  The advantages of mmap
00463   nearly always outweigh disadvantages for "large" chunks, but the
00464   value of "large" may vary across systems.  The default is an
00465   empirically derived value that works well in most systems. You can
00466   disable mmap by setting to MAX_SIZE_T.
00467 
00468 MAX_RELEASE_CHECK_RATE   default: 4095 unless not HAVE_MMAP
00469   The number of consolidated frees between checks to release
00470   unused segments when freeing. When using non-contiguous segments,
00471   especially with multiple mspaces, checking only for topmost space
00472   doesn't always suffice to trigger trimming. To compensate for this,
00473   free() will, with a period of MAX_RELEASE_CHECK_RATE (or the
00474   current number of segments, if greater) try to release unused
00475   segments to the OS when freeing chunks that result in
00476   consolidation. The best value for this parameter is a compromise
00477   between slowing down frees with relatively costly checks that
00478   rarely trigger versus holding on to unused memory. To effectively
00479   disable, set to MAX_SIZE_T. This may lead to a very slight speed
00480   improvement at the expense of carrying around more memory.
00481 */
00482 
00483 #define USE_DL_PREFIX
00484 //#define HAVE_USR_INCLUDE_MALLOC_H
00485 //#define MSPACES 1
00486 #define NO_SEGMENT_TRAVERSAL 1
00487 
00488 /* Version identifier to allow people to support multiple versions */
00489 #ifndef DLMALLOC_VERSION
00490 #define DLMALLOC_VERSION 20804
00491 #endif /* DLMALLOC_VERSION */
00492 
00493 #ifndef WIN32
00494 #ifdef _WIN32
00495 #define WIN32 1
00496 #endif  /* _WIN32 */
00497 #ifdef _WIN32_WCE
00498 #define LACKS_FCNTL_H
00499 #define WIN32 1
00500 #endif /* _WIN32_WCE */
00501 #endif  /* WIN32 */
00502 #ifdef WIN32
00503 #define WIN32_LEAN_AND_MEAN
00504 #include <windows.h>
00505 #define HAVE_MMAP 1
00506 #define HAVE_MORECORE 0
00507 #define LACKS_UNISTD_H
00508 #define LACKS_SYS_PARAM_H
00509 #define LACKS_SYS_MMAN_H
00510 #define LACKS_STRING_H
00511 #define LACKS_STRINGS_H
00512 #define LACKS_SYS_TYPES_H
00513 #define LACKS_ERRNO_H
00514 #ifndef MALLOC_FAILURE_ACTION
00515 #define MALLOC_FAILURE_ACTION
00516 #endif /* MALLOC_FAILURE_ACTION */
00517 #ifdef _WIN32_WCE /* WINCE reportedly does not clear */
00518 #define MMAP_CLEARS 0
00519 #else
00520 #define MMAP_CLEARS 1
00521 #endif /* _WIN32_WCE */
00522 #endif  /* WIN32 */
00523 
00524 #if defined(DARWIN) || defined(_DARWIN)
00525 /* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
00526 #ifndef HAVE_MORECORE
00527 #define HAVE_MORECORE 0
00528 #define HAVE_MMAP 1
00529 /* OSX allocators provide 16 byte alignment */
00530 #ifndef MALLOC_ALIGNMENT
00531 #define MALLOC_ALIGNMENT ((size_t)16U)
00532 #endif
00533 #endif  /* HAVE_MORECORE */
00534 #endif  /* DARWIN */
00535 
00536 #ifndef LACKS_SYS_TYPES_H
00537 #include <sys/types.h>  /* For size_t */
00538 #endif  /* LACKS_SYS_TYPES_H */
00539 
00540 #if (defined(__GNUC__) && ((defined(__i386__) || defined(__x86_64__)))) || (defined(_MSC_VER) && _MSC_VER>=1310)
00541 #define SPIN_LOCKS_AVAILABLE 1
00542 #else
00543 #define SPIN_LOCKS_AVAILABLE 0
00544 #endif
00545 
00546 /* The maximum possible size_t value has all bits set */
00547 #define MAX_SIZE_T           (~(size_t)0)
00548 
00549 #ifndef ONLY_MSPACES
00550 #define ONLY_MSPACES 0     /* define to a value */
00551 #else
00552 #define ONLY_MSPACES 1
00553 #endif  /* ONLY_MSPACES */
00554 #ifndef MSPACES
00555 #if ONLY_MSPACES
00556 #define MSPACES 1
00557 #else   /* ONLY_MSPACES */
00558 #define MSPACES 0
00559 #endif  /* ONLY_MSPACES */
00560 #endif  /* MSPACES */
00561 #ifndef MALLOC_ALIGNMENT
00562 #define MALLOC_ALIGNMENT ((size_t)8U)
00563 #endif  /* MALLOC_ALIGNMENT */
00564 #ifndef FOOTERS
00565 #define FOOTERS 0
00566 #endif  /* FOOTERS */
00567 #ifndef ABORT
00568 #define ABORT  abort()
00569 #endif  /* ABORT */
00570 #ifndef ABORT_ON_ASSERT_FAILURE
00571 #define ABORT_ON_ASSERT_FAILURE 1
00572 #endif  /* ABORT_ON_ASSERT_FAILURE */
00573 #ifndef PROCEED_ON_ERROR
00574 #define PROCEED_ON_ERROR 0
00575 #endif  /* PROCEED_ON_ERROR */
00576 #ifndef USE_LOCKS
00577 #define USE_LOCKS 0
00578 #endif  /* USE_LOCKS */
00579 #ifndef USE_SPIN_LOCKS
00580 #if USE_LOCKS && SPIN_LOCKS_AVAILABLE
00581 #define USE_SPIN_LOCKS 1
00582 #else
00583 #define USE_SPIN_LOCKS 0
00584 #endif /* USE_LOCKS && SPIN_LOCKS_AVAILABLE. */
00585 #endif /* USE_SPIN_LOCKS */
00586 #ifndef INSECURE
00587 #define INSECURE 0
00588 #endif  /* INSECURE */
00589 #ifndef HAVE_MMAP
00590 #define HAVE_MMAP 1
00591 #endif  /* HAVE_MMAP */
00592 #ifndef MMAP_CLEARS
00593 #define MMAP_CLEARS 1
00594 #endif  /* MMAP_CLEARS */
00595 #ifndef HAVE_MREMAP
00596 #ifdef linux
00597 #define HAVE_MREMAP 1
00598 #else   /* linux */
00599 #define HAVE_MREMAP 0
00600 #endif  /* linux */
00601 #endif  /* HAVE_MREMAP */
00602 #ifndef MALLOC_FAILURE_ACTION
00603 #define MALLOC_FAILURE_ACTION  errno = ENOMEM;
00604 #endif  /* MALLOC_FAILURE_ACTION */
00605 #ifndef HAVE_MORECORE
00606 #if ONLY_MSPACES
00607 #define HAVE_MORECORE 0
00608 #else   /* ONLY_MSPACES */
00609 #define HAVE_MORECORE 1
00610 #endif  /* ONLY_MSPACES */
00611 #endif  /* HAVE_MORECORE */
00612 #if !HAVE_MORECORE
00613 #define MORECORE_CONTIGUOUS 0
00614 #else   /* !HAVE_MORECORE */
00615 #define MORECORE_DEFAULT sbrk
00616 #ifndef MORECORE_CONTIGUOUS
00617 #define MORECORE_CONTIGUOUS 1
00618 #endif  /* MORECORE_CONTIGUOUS */
00619 #endif  /* HAVE_MORECORE */
00620 #ifndef DEFAULT_GRANULARITY
00621 #if (MORECORE_CONTIGUOUS || defined(WIN32))
00622 #define DEFAULT_GRANULARITY (0)  /* 0 means to compute in init_mparams */
00623 #else   /* MORECORE_CONTIGUOUS */
00624 #define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
00625 #endif  /* MORECORE_CONTIGUOUS */
00626 #endif  /* DEFAULT_GRANULARITY */
00627 #ifndef DEFAULT_TRIM_THRESHOLD
00628 #ifndef MORECORE_CANNOT_TRIM
00629 #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
00630 #else   /* MORECORE_CANNOT_TRIM */
00631 #define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
00632 #endif  /* MORECORE_CANNOT_TRIM */
00633 #endif  /* DEFAULT_TRIM_THRESHOLD */
00634 #ifndef DEFAULT_MMAP_THRESHOLD
00635 #if HAVE_MMAP
00636 #define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
00637 #else   /* HAVE_MMAP */
00638 #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
00639 #endif  /* HAVE_MMAP */
00640 #endif  /* DEFAULT_MMAP_THRESHOLD */
00641 #ifndef MAX_RELEASE_CHECK_RATE
00642 #if HAVE_MMAP
00643 #define MAX_RELEASE_CHECK_RATE 4095
00644 #else
00645 #define MAX_RELEASE_CHECK_RATE MAX_SIZE_T
00646 #endif /* HAVE_MMAP */
00647 #endif /* MAX_RELEASE_CHECK_RATE */
00648 #ifndef USE_BUILTIN_FFS
00649 #define USE_BUILTIN_FFS 0
00650 #endif  /* USE_BUILTIN_FFS */
00651 #ifndef USE_DEV_RANDOM
00652 #define USE_DEV_RANDOM 0
00653 #endif  /* USE_DEV_RANDOM */
00654 #ifndef NO_MALLINFO
00655 #define NO_MALLINFO 0
00656 #endif  /* NO_MALLINFO */
00657 #ifndef MALLINFO_FIELD_TYPE
00658 #define MALLINFO_FIELD_TYPE size_t
00659 #endif  /* MALLINFO_FIELD_TYPE */
00660 #ifndef NO_SEGMENT_TRAVERSAL
00661 #define NO_SEGMENT_TRAVERSAL 0
00662 #endif /* NO_SEGMENT_TRAVERSAL */
00663 
00664 /*
00665   mallopt tuning options.  SVID/XPG defines four standard parameter
00666   numbers for mallopt, normally defined in malloc.h.  None of these
00667   are used in this malloc, so setting them has no effect. But this
00668   malloc does support the following options.
00669 */
00670 
00671 #define M_TRIM_THRESHOLD     (-1)
00672 #define M_GRANULARITY        (-2)
00673 #define M_MMAP_THRESHOLD     (-3)
00674 
00675 /* ------------------------ Mallinfo declarations ------------------------ */
00676 
00677 #if !NO_MALLINFO
00678 /*
00679   This version of malloc supports the standard SVID/XPG mallinfo
00680   routine that returns a struct containing usage properties and
00681   statistics. It should work on any system that has a
00682   /usr/include/malloc.h defining struct mallinfo.  The main
00683   declaration needed is the mallinfo struct that is returned (by-copy)
00684   by mallinfo().  The malloinfo struct contains a bunch of fields that
00685   are not even meaningful in this version of malloc.  These fields are
00686   are instead filled by mallinfo() with other numbers that might be of
00687   interest.
00688 
00689   HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
00690   /usr/include/malloc.h file that includes a declaration of struct
00691   mallinfo.  If so, it is included; else a compliant version is
00692   declared below.  These must be precisely the same for mallinfo() to
00693   work.  The original SVID version of this struct, defined on most
00694   systems with mallinfo, declares all fields as ints. But some others
00695   define as unsigned long. If your system defines the fields using a
00696   type of different width than listed here, you MUST #include your
00697   system version and #define HAVE_USR_INCLUDE_MALLOC_H.
00698 */
00699 
00700 /* #define HAVE_USR_INCLUDE_MALLOC_H */
00701 
00702 #ifdef HAVE_USR_INCLUDE_MALLOC_H
00703 #include "/usr/include/malloc.h"
00704 #else /* HAVE_USR_INCLUDE_MALLOC_H */
00705 #ifndef STRUCT_MALLINFO_DECLARED
00706 #define STRUCT_MALLINFO_DECLARED 1
00707 struct mallinfo {
00708   MALLINFO_FIELD_TYPE arena;    /* non-mmapped space allocated from system */
00709   MALLINFO_FIELD_TYPE ordblks;  /* number of free chunks */
00710   MALLINFO_FIELD_TYPE smblks;   /* always 0 */
00711   MALLINFO_FIELD_TYPE hblks;    /* always 0 */
00712   MALLINFO_FIELD_TYPE hblkhd;   /* space in mmapped regions */
00713   MALLINFO_FIELD_TYPE usmblks;  /* maximum total allocated space */
00714   MALLINFO_FIELD_TYPE fsmblks;  /* always 0 */
00715   MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
00716   MALLINFO_FIELD_TYPE fordblks; /* total free space */
00717   MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
00718 };
00719 #endif /* STRUCT_MALLINFO_DECLARED */
00720 #endif /* HAVE_USR_INCLUDE_MALLOC_H */
00721 #endif /* NO_MALLINFO */
00722 
00723 /*
00724   Try to persuade compilers to inline. The most critical functions for
00725   inlining are defined as macros, so these aren't used for them.
00726 */
00727 
00728 #ifndef FORCEINLINE
00729   #if defined(__GNUC__)
00730 #define FORCEINLINE __inline __attribute__ ((always_inline))
00731   #elif defined(_MSC_VER)
00732     #define FORCEINLINE __forceinline
00733   #endif
00734 #endif
00735 #ifndef NOINLINE
00736   #if defined(__GNUC__)
00737     #define NOINLINE __attribute__ ((noinline))
00738   #elif defined(_MSC_VER)
00739     #define NOINLINE __declspec(noinline)
00740   #else
00741     #define NOINLINE
00742   #endif
00743 #endif
00744 
00745 #ifdef __cplusplus
00746 extern "C" {
00747 #ifndef FORCEINLINE
00748  #define FORCEINLINE inline
00749 #endif
00750 #endif /* __cplusplus */
00751 #ifndef FORCEINLINE
00752  #define FORCEINLINE
00753 #endif
00754 
00755 #if !ONLY_MSPACES
00756 
00757 /* ------------------- Declarations of public routines ------------------- */
00758 
00759 #ifndef USE_DL_PREFIX
00760 #define dlcalloc               calloc
00761 #define dlfree                 free
00762 #define dlmalloc               malloc
00763 #define dlmemalign             memalign
00764 #define dlrealloc              realloc
00765 #define dlvalloc               valloc
00766 #define dlpvalloc              pvalloc
00767 #define dlmallinfo             mallinfo
00768 #define dlmallopt              mallopt
00769 #define dlmalloc_trim          malloc_trim
00770 #define dlmalloc_stats         malloc_stats
00771 #define dlmalloc_usable_size   malloc_usable_size
00772 #define dlmalloc_footprint     malloc_footprint
00773 #define dlmalloc_max_footprint malloc_max_footprint
00774 #define dlindependent_calloc   independent_calloc
00775 #define dlindependent_comalloc independent_comalloc
00776 #endif /* USE_DL_PREFIX */
00777 
00778 
00779 /*
00780   malloc(size_t n)
00781   Returns a pointer to a newly allocated chunk of at least n bytes, or
00782   null if no space is available, in which case errno is set to ENOMEM
00783   on ANSI C systems.
00784 
00785   If n is zero, malloc returns a minimum-sized chunk. (The minimum
00786   size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
00787   systems.)  Note that size_t is an unsigned type, so calls with
00788   arguments that would be negative if signed are interpreted as
00789   requests for huge amounts of space, which will often fail. The
00790   maximum supported value of n differs across systems, but is in all
00791   cases less than the maximum representable value of a size_t.
00792 */
00793 void* dlmalloc(size_t);
00794 
00795 /*
00796   free(void* p)
00797   Releases the chunk of memory pointed to by p, that had been previously
00798   allocated using malloc or a related routine such as realloc.
00799   It has no effect if p is null. If p was not malloced or already
00800   freed, free(p) will by default cause the current program to abort.
00801 */
00802 void  dlfree(void*);
00803 
00804 /*
00805   calloc(size_t n_elements, size_t element_size);
00806   Returns a pointer to n_elements * element_size bytes, with all locations
00807   set to zero.
00808 */
00809 void* dlcalloc(size_t, size_t);
00810 
00811 /*
00812   realloc(void* p, size_t n)
00813   Returns a pointer to a chunk of size n that contains the same data
00814   as does chunk p up to the minimum of (n, p's size) bytes, or null
00815   if no space is available.
00816 
00817   The returned pointer may or may not be the same as p. The algorithm
00818   prefers extending p in most cases when possible, otherwise it
00819   employs the equivalent of a malloc-copy-free sequence.
00820 
00821   If p is null, realloc is equivalent to malloc.
00822 
00823   If space is not available, realloc returns null, errno is set (if on
00824   ANSI) and p is NOT freed.
00825 
00826   if n is for fewer bytes than already held by p, the newly unused
00827   space is lopped off and freed if possible.  realloc with a size
00828   argument of zero (re)allocates a minimum-sized chunk.
00829 
00830   The old unix realloc convention of allowing the last-free'd chunk
00831   to be used as an argument to realloc is not supported.
00832 */
00833 
00834 void* dlrealloc(void*, size_t);
00835 
00836 /*
00837   memalign(size_t alignment, size_t n);
00838   Returns a pointer to a newly allocated chunk of n bytes, aligned
00839   in accord with the alignment argument.
00840 
00841   The alignment argument should be a power of two. If the argument is
00842   not a power of two, the nearest greater power is used.
00843   8-byte alignment is guaranteed by normal malloc calls, so don't
00844   bother calling memalign with an argument of 8 or less.
00845 
00846   Overreliance on memalign is a sure way to fragment space.
00847 */
00848 void* dlmemalign(size_t, size_t);
00849 
00850 /*
00851   valloc(size_t n);
00852   Equivalent to memalign(pagesize, n), where pagesize is the page
00853   size of the system. If the pagesize is unknown, 4096 is used.
00854 */
00855 void* dlvalloc(size_t);
00856 
00857 /*
00858   mallopt(int parameter_number, int parameter_value)
00859   Sets tunable parameters The format is to provide a
00860   (parameter-number, parameter-value) pair.  mallopt then sets the
00861   corresponding parameter to the argument value if it can (i.e., so
00862   long as the value is meaningful), and returns 1 if successful else
00863   0.  To workaround the fact that mallopt is specified to use int,
00864   not size_t parameters, the value -1 is specially treated as the
00865   maximum unsigned size_t value.
00866 
00867   SVID/XPG/ANSI defines four standard param numbers for mallopt,
00868   normally defined in malloc.h.  None of these are use in this malloc,
00869   so setting them has no effect. But this malloc also supports other
00870   options in mallopt. See below for details.  Briefly, supported
00871   parameters are as follows (listed defaults are for "typical"
00872   configurations).
00873 
00874   Symbol            param #  default    allowed param values
00875   M_TRIM_THRESHOLD     -1   2*1024*1024   any   (-1 disables)
00876   M_GRANULARITY        -2     page size   any power of 2 >= page size
00877   M_MMAP_THRESHOLD     -3      256*1024   any   (or 0 if no MMAP support)
00878 */
00879 int dlmallopt(int, int);
00880 
00881 /*
00882   malloc_footprint();
00883   Returns the number of bytes obtained from the system.  The total
00884   number of bytes allocated by malloc, realloc etc., is less than this
00885   value. Unlike mallinfo, this function returns only a precomputed
00886   result, so can be called frequently to monitor memory consumption.
00887   Even if locks are otherwise defined, this function does not use them,
00888   so results might not be up to date.
00889 */
00890 size_t dlmalloc_footprint(void);
00891 
00892 /*
00893   malloc_max_footprint();
00894   Returns the maximum number of bytes obtained from the system. This
00895   value will be greater than current footprint if deallocated space
00896   has been reclaimed by the system. The peak number of bytes allocated
00897   by malloc, realloc etc., is less than this value. Unlike mallinfo,
00898   this function returns only a precomputed result, so can be called
00899   frequently to monitor memory consumption.  Even if locks are
00900   otherwise defined, this function does not use them, so results might
00901   not be up to date.
00902 */
00903 size_t dlmalloc_max_footprint(void);
00904 
00905 #if !NO_MALLINFO
00906 /*
00907   mallinfo()
00908   Returns (by copy) a struct containing various summary statistics:
00909 
00910   arena:     current total non-mmapped bytes allocated from system
00911   ordblks:   the number of free chunks
00912   smblks:    always zero.
00913   hblks:     current number of mmapped regions
00914   hblkhd:    total bytes held in mmapped regions
00915   usmblks:   the maximum total allocated space. This will be greater
00916                 than current total if trimming has occurred.
00917   fsmblks:   always zero
00918   uordblks:  current total allocated space (normal or mmapped)
00919   fordblks:  total free space
00920   keepcost:  the maximum number of bytes that could ideally be released
00921                back to system via malloc_trim. ("ideally" means that
00922                it ignores page restrictions etc.)
00923 
00924   Because these fields are ints, but internal bookkeeping may
00925   be kept as longs, the reported values may wrap around zero and
00926   thus be inaccurate.
00927 */
00928 struct mallinfo dlmallinfo(void);
00929 #endif /* NO_MALLINFO */
00930 
00931 /*
00932   independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
00933 
00934   independent_calloc is similar to calloc, but instead of returning a
00935   single cleared space, it returns an array of pointers to n_elements
00936   independent elements that can hold contents of size elem_size, each
00937   of which starts out cleared, and can be independently freed,
00938   realloc'ed etc. The elements are guaranteed to be adjacently
00939   allocated (this is not guaranteed to occur with multiple callocs or
00940   mallocs), which may also improve cache locality in some
00941   applications.
00942 
00943   The "chunks" argument is optional (i.e., may be null, which is
00944   probably the most typical usage). If it is null, the returned array
00945   is itself dynamically allocated and should also be freed when it is
00946   no longer needed. Otherwise, the chunks array must be of at least
00947   n_elements in length. It is filled in with the pointers to the
00948   chunks.
00949 
00950   In either case, independent_calloc returns this pointer array, or
00951   null if the allocation failed.  If n_elements is zero and "chunks"
00952   is null, it returns a chunk representing an array with zero elements
00953   (which should be freed if not wanted).
00954 
00955   Each element must be individually freed when it is no longer
00956   needed. If you'd like to instead be able to free all at once, you
00957   should instead use regular calloc and assign pointers into this
00958   space to represent elements.  (In this case though, you cannot
00959   independently free elements.)
00960 
00961   independent_calloc simplifies and speeds up implementations of many
00962   kinds of pools.  It may also be useful when constructing large data
00963   structures that initially have a fixed number of fixed-sized nodes,
00964   but the number is not known at compile time, and some of the nodes
00965   may later need to be freed. For example:
00966 
00967   struct Node { int item; struct Node* next; };
00968 
00969   struct Node* build_list() {
00970     struct Node** pool;
00971     int n = read_number_of_nodes_needed();
00972     if (n <= 0) return 0;
00973     pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
00974     if (pool == 0) die();
00975     // organize into a linked list...
00976     struct Node* first = pool[0];
00977     for (i = 0; i < n-1; ++i)
00978       pool[i]->next = pool[i+1];
00979     free(pool);     // Can now free the array (or not, if it is needed later)
00980     return first;
00981   }
00982 */
00983 void** dlindependent_calloc(size_t, size_t, void**);
00984 
00985 /*
00986   independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
00987 
00988   independent_comalloc allocates, all at once, a set of n_elements
00989   chunks with sizes indicated in the "sizes" array.    It returns
00990   an array of pointers to these elements, each of which can be
00991   independently freed, realloc'ed etc. The elements are guaranteed to
00992   be adjacently allocated (this is not guaranteed to occur with
00993   multiple callocs or mallocs), which may also improve cache locality
00994   in some applications.
00995 
00996   The "chunks" argument is optional (i.e., may be null). If it is null
00997   the returned array is itself dynamically allocated and should also
00998   be freed when it is no longer needed. Otherwise, the chunks array
00999   must be of at least n_elements in length. It is filled in with the
01000   pointers to the chunks.
01001 
01002   In either case, independent_comalloc returns this pointer array, or
01003   null if the allocation failed.  If n_elements is zero and chunks is
01004   null, it returns a chunk representing an array with zero elements
01005   (which should be freed if not wanted).
01006 
01007   Each element must be individually freed when it is no longer
01008   needed. If you'd like to instead be able to free all at once, you
01009   should instead use a single regular malloc, and assign pointers at
01010   particular offsets in the aggregate space. (In this case though, you
01011   cannot independently free elements.)
01012 
01013   independent_comallac differs from independent_calloc in that each
01014   element may have a different size, and also that it does not
01015   automatically clear elements.
01016 
01017   independent_comalloc can be used to speed up allocation in cases
01018   where several structs or objects must always be allocated at the
01019   same time.  For example:
01020 
01021   struct Head { ... }
01022   struct Foot { ... }
01023 
01024   void send_message(char* msg) {
01025     int msglen = strlen(msg);
01026     size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
01027     void* chunks[3];
01028     if (independent_comalloc(3, sizes, chunks) == 0)
01029       die();
01030     struct Head* head = (struct Head*)(chunks[0]);
01031     char*        body = (char*)(chunks[1]);
01032     struct Foot* foot = (struct Foot*)(chunks[2]);
01033     // ...
01034   }
01035 
01036   In general though, independent_comalloc is worth using only for
01037   larger values of n_elements. For small values, you probably won't
01038   detect enough difference from series of malloc calls to bother.
01039 
01040   Overuse of independent_comalloc can increase overall memory usage,
01041   since it cannot reuse existing noncontiguous small chunks that
01042   might be available for some of the elements.
01043 */
01044 void** dlindependent_comalloc(size_t, size_t*, void**);
01045 
01046 
01047 /*
01048   pvalloc(size_t n);
01049   Equivalent to valloc(minimum-page-that-holds(n)), that is,
01050   round up n to nearest pagesize.
01051  */
01052 void*  dlpvalloc(size_t);
01053 
01054 /*
01055   malloc_trim(size_t pad);
01056 
01057   If possible, gives memory back to the system (via negative arguments
01058   to sbrk) if there is unused memory at the `high' end of the malloc
01059   pool or in unused MMAP segments. You can call this after freeing
01060   large blocks of memory to potentially reduce the system-level memory
01061   requirements of a program. However, it cannot guarantee to reduce
01062   memory. Under some allocation patterns, some large free blocks of
01063   memory will be locked between two used chunks, so they cannot be
01064   given back to the system.
01065 
01066   The `pad' argument to malloc_trim represents the amount of free
01067   trailing space to leave untrimmed. If this argument is zero, only
01068   the minimum amount of memory to maintain internal data structures
01069   will be left. Non-zero arguments can be supplied to maintain enough
01070   trailing space to service future expected allocations without having
01071   to re-obtain memory from the system.
01072 
01073   Malloc_trim returns 1 if it actually released any memory, else 0.
01074 */
01075 int  dlmalloc_trim(size_t);
01076 
01077 /*
01078   malloc_stats();
01079   Prints on stderr the amount of space obtained from the system (both
01080   via sbrk and mmap), the maximum amount (which may be more than
01081   current if malloc_trim and/or munmap got called), and the current
01082   number of bytes allocated via malloc (or realloc, etc) but not yet
01083   freed. Note that this is the number of bytes allocated, not the
01084   number requested. It will be larger than the number requested
01085   because of alignment and bookkeeping overhead. Because it includes
01086   alignment wastage as being in use, this figure may be greater than
01087   zero even when no user-level chunks are allocated.
01088 
01089   The reported current and maximum system memory can be inaccurate if
01090   a program makes other calls to system memory allocation functions
01091   (normally sbrk) outside of malloc.
01092 
01093   malloc_stats prints only the most commonly interesting statistics.
01094   More information can be obtained by calling mallinfo.
01095 */
01096 void  dlmalloc_stats(void);
01097 
01098 #endif /* ONLY_MSPACES */
01099 
01100 /*
01101   malloc_usable_size(void* p);
01102 
01103   Returns the number of bytes you can actually use in
01104   an allocated chunk, which may be more than you requested (although
01105   often not) due to alignment and minimum size constraints.
01106   You can use this many bytes without worrying about
01107   overwriting other allocated objects. This is not a particularly great
01108   programming practice. malloc_usable_size can be more useful in
01109   debugging and assertions, for example:
01110 
01111   p = malloc(n);
01112   assert(malloc_usable_size(p) >= 256);
01113 */
01114 size_t dlmalloc_usable_size(void*);
01115 
01116 
01117 #if MSPACES
01118 
01119 /*
01120   mspace is an opaque type representing an independent
01121   region of space that supports mspace_malloc, etc.
01122 */
01123 typedef void* mspace;
01124 
01125 /*
01126   create_mspace creates and returns a new independent space with the
01127   given initial capacity, or, if 0, the default granularity size.  It
01128   returns null if there is no system memory available to create the
01129   space.  If argument locked is non-zero, the space uses a separate
01130   lock to control access. The capacity of the space will grow
01131   dynamically as needed to service mspace_malloc requests.  You can
01132   control the sizes of incremental increases of this space by
01133   compiling with a different DEFAULT_GRANULARITY or dynamically
01134   setting with mallopt(M_GRANULARITY, value).
01135 */
01136 mspace create_mspace(size_t capacity, int locked);
01137 
01138 /*
01139   destroy_mspace destroys the given space, and attempts to return all
01140   of its memory back to the system, returning the total number of
01141   bytes freed. After destruction, the results of access to all memory
01142   used by the space become undefined.
01143 */
01144 size_t destroy_mspace(mspace msp);
01145 
01146 /*
01147   create_mspace_with_base uses the memory supplied as the initial base
01148   of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
01149   space is used for bookkeeping, so the capacity must be at least this
01150   large. (Otherwise 0 is returned.) When this initial space is
01151   exhausted, additional memory will be obtained from the system.
01152   Destroying this space will deallocate all additionally allocated
01153   space (if possible) but not the initial base.
01154 */
01155 mspace create_mspace_with_base(void* base, size_t capacity, int locked);
01156 
01157 /*
01158   mspace_track_large_chunks controls whether requests for large chunks
01159   are allocated in their own untracked mmapped regions, separate from
01160   others in this mspace. By default large chunks are not tracked,
01161   which reduces fragmentation. However, such chunks are not
01162   necessarily released to the system upon destroy_mspace.  Enabling
01163   tracking by setting to true may increase fragmentation, but avoids
01164   leakage when relying on destroy_mspace to release all memory
01165   allocated using this space.  The function returns the previous
01166   setting.
01167 */
01168 int mspace_track_large_chunks(mspace msp, int enable);
01169 
01170 
01171 /*
01172   mspace_malloc behaves as malloc, but operates within
01173   the given space.
01174 */
01175 void* mspace_malloc(mspace msp, size_t bytes);
01176 
01177 /*
01178   mspace_free behaves as free, but operates within
01179   the given space.
01180 
01181   If compiled with FOOTERS==1, mspace_free is not actually needed.
01182   free may be called instead of mspace_free because freed chunks from
01183   any space are handled by their originating spaces.
01184 */
01185 void mspace_free(mspace msp, void* mem);
01186 
01187 /*
01188   mspace_realloc behaves as realloc, but operates within
01189   the given space.
01190 
01191   If compiled with FOOTERS==1, mspace_realloc is not actually
01192   needed.  realloc may be called instead of mspace_realloc because
01193   realloced chunks from any space are handled by their originating
01194   spaces.
01195 */
01196 void* mspace_realloc(mspace msp, void* mem, size_t newsize);
01197 
01198 /*
01199   mspace_calloc behaves as calloc, but operates within
01200   the given space.
01201 */
01202 void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
01203 
01204 /*
01205   mspace_memalign behaves as memalign, but operates within
01206   the given space.
01207 */
01208 void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
01209 
01210 /*
01211   mspace_independent_calloc behaves as independent_calloc, but
01212   operates within the given space.
01213 */
01214 void** mspace_independent_calloc(mspace msp, size_t n_elements,
01215                                  size_t elem_size, void* chunks[]);
01216 
01217 /*
01218   mspace_independent_comalloc behaves as independent_comalloc, but
01219   operates within the given space.
01220 */
01221 void** mspace_independent_comalloc(mspace msp, size_t n_elements,
01222                                    size_t sizes[], void* chunks[]);
01223 
01224 /*
01225   mspace_footprint() returns the number of bytes obtained from the
01226   system for this space.
01227 */
01228 size_t mspace_footprint(mspace msp);
01229 
01230 /*
01231   mspace_max_footprint() returns the peak number of bytes obtained from the
01232   system for this space.
01233 */
01234 size_t mspace_max_footprint(mspace msp);
01235 
01236 
01237 #if !NO_MALLINFO
01238 /*
01239   mspace_mallinfo behaves as mallinfo, but reports properties of
01240   the given space.
01241 */
01242 struct mallinfo mspace_mallinfo(mspace msp);
01243 #endif /* NO_MALLINFO */
01244 
01245 /*
01246   malloc_usable_size(void* p) behaves the same as malloc_usable_size;
01247 */
01248   size_t mspace_usable_size(void* mem);
01249 
01250 /*
01251   mspace_malloc_stats behaves as malloc_stats, but reports
01252   properties of the given space.
01253 */
01254 void mspace_malloc_stats(mspace msp);
01255 
01256 /*
01257   mspace_trim behaves as malloc_trim, but
01258   operates within the given space.
01259 */
01260 int mspace_trim(mspace msp, size_t pad);
01261 
01262 /*
01263   An alias for mallopt.
01264 */
01265 int mspace_mallopt(int, int);
01266 
01267 #endif /* MSPACES */
01268 
01269 #ifdef __cplusplus
01270 };  /* end of extern "C" */
01271 #endif /* __cplusplus */
01272 
01273 /*
01274   ========================================================================
01275   To make a fully customizable malloc.h header file, cut everything
01276   above this line, put into file malloc.h, edit to suit, and #include it
01277   on the next line, as well as in programs that use this malloc.
01278   ========================================================================
01279 */
01280 
01281 /* #include "malloc.h" */
01282 
01283 /*------------------------------ internal #includes ---------------------- */
01284 
01285 #ifdef WIN32
01286 #pragma warning( disable : 4146 ) /* no "unsigned" warnings */
01287 #endif /* WIN32 */
01288 
01289 #include <stdio.h>       /* for printing in malloc_stats */
01290 
01291 #ifndef LACKS_ERRNO_H
01292 #include <errno.h>       /* for MALLOC_FAILURE_ACTION */
01293 #endif /* LACKS_ERRNO_H */
01294 /*#if FOOTERS || DEBUG
01295 */
01296 #include <time.h>        /* for magic initialization */
01297 /*#endif*/ /* FOOTERS */
01298 #ifndef LACKS_STDLIB_H
01299 #include <stdlib.h>      /* for abort() */
01300 #endif /* LACKS_STDLIB_H */
01301 #ifdef DEBUG
01302 #if ABORT_ON_ASSERT_FAILURE
01303 #undef assert
01304 #define assert(x) if(!(x)) ABORT
01305 #else /* ABORT_ON_ASSERT_FAILURE */
01306 #include <assert.h>
01307 #endif /* ABORT_ON_ASSERT_FAILURE */
01308 #else  /* DEBUG */
01309 #ifndef assert
01310 #define assert(x)
01311 #endif
01312 #define DEBUG 0
01313 #endif /* DEBUG */
01314 #ifndef LACKS_STRING_H
01315 #include <string.h>      /* for memset etc */
01316 #endif  /* LACKS_STRING_H */
01317 #if USE_BUILTIN_FFS
01318 #ifndef LACKS_STRINGS_H
01319 #include <strings.h>     /* for ffs */
01320 #endif /* LACKS_STRINGS_H */
01321 #endif /* USE_BUILTIN_FFS */
01322 #if HAVE_MMAP
01323 #ifndef LACKS_SYS_MMAN_H
01324 /* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */
01325 #if (defined(linux) && !defined(__USE_GNU))
01326 #define __USE_GNU 1
01327 #include <sys/mman.h>    /* for mmap */
01328 #undef __USE_GNU
01329 #else
01330 #include <sys/mman.h>    /* for mmap */
01331 #endif /* linux */
01332 #endif /* LACKS_SYS_MMAN_H */
01333 #ifndef LACKS_FCNTL_H
01334 #include <fcntl.h>
01335 #endif /* LACKS_FCNTL_H */
01336 #endif /* HAVE_MMAP */
01337 #ifndef LACKS_UNISTD_H
01338 #include <unistd.h>     /* for sbrk, sysconf */
01339 #else /* LACKS_UNISTD_H */
01340 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
01341 extern void*     sbrk(ptrdiff_t);
01342 #endif /* FreeBSD etc */
01343 #endif /* LACKS_UNISTD_H */
01344 
01345 /* Declarations for locking */
01346 #if USE_LOCKS
01347 #ifndef WIN32
01348 #include <pthread.h>
01349 #if defined (__SVR4) && defined (__sun)  /* solaris */
01350 #include <thread.h>
01351 #endif /* solaris */
01352 #else
01353 #ifndef _M_AMD64
01354 /* These are already defined on AMD64 builds */
01355 #ifdef __cplusplus
01356 extern "C" {
01357 #endif /* __cplusplus */
01358 LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp);
01359 LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value);
01360 #ifdef __cplusplus
01361 }
01362 #endif /* __cplusplus */
01363 #endif /* _M_AMD64 */
01364 #pragma intrinsic (_InterlockedCompareExchange)
01365 #pragma intrinsic (_InterlockedExchange)
01366 #define interlockedcompareexchange _InterlockedCompareExchange
01367 #define interlockedexchange _InterlockedExchange
01368 #endif /* Win32 */
01369 #endif /* USE_LOCKS */
01370 
01371 /* Declarations for bit scanning on win32 */
01372 #if defined(_MSC_VER) && _MSC_VER>=1300
01373 #ifndef BitScanForward  /* Try to avoid pulling in WinNT.h */
01374 #ifdef __cplusplus
01375 extern "C" {
01376 #endif /* __cplusplus */
01377 unsigned char _BitScanForward(unsigned long *index, unsigned long mask);
01378 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);
01379 #ifdef __cplusplus
01380 }
01381 #endif /* __cplusplus */
01382 
01383 #define BitScanForward _BitScanForward
01384 #define BitScanReverse _BitScanReverse
01385 #pragma intrinsic(_BitScanForward)
01386 #pragma intrinsic(_BitScanReverse)
01387 #endif /* BitScanForward */
01388 #endif /* defined(_MSC_VER) && _MSC_VER>=1300 */
01389 
01390 #ifndef WIN32
01391 #ifndef malloc_getpagesize
01392 #  ifdef _SC_PAGESIZE         /* some SVR4 systems omit an underscore */
01393 #    ifndef _SC_PAGE_SIZE
01394 #      define _SC_PAGE_SIZE _SC_PAGESIZE
01395 #    endif
01396 #  endif
01397 #  ifdef _SC_PAGE_SIZE
01398 #    define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
01399 #  else
01400 #    if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
01401        extern size_t getpagesize();
01402 #      define malloc_getpagesize getpagesize()
01403 #    else
01404 #      ifdef WIN32 /* use supplied emulation of getpagesize */
01405 #        define malloc_getpagesize getpagesize()
01406 #      else
01407 #        ifndef LACKS_SYS_PARAM_H
01408 #          include <sys/param.h>
01409 #        endif
01410 #        ifdef EXEC_PAGESIZE
01411 #          define malloc_getpagesize EXEC_PAGESIZE
01412 #        else
01413 #          ifdef NBPG
01414 #            ifndef CLSIZE
01415 #              define malloc_getpagesize NBPG
01416 #            else
01417 #              define malloc_getpagesize (NBPG * CLSIZE)
01418 #            endif
01419 #          else
01420 #            ifdef NBPC
01421 #              define malloc_getpagesize NBPC
01422 #            else
01423 #              ifdef PAGESIZE
01424 #                define malloc_getpagesize PAGESIZE
01425 #              else /* just guess */
01426 #                define malloc_getpagesize ((size_t)4096U)
01427 #              endif
01428 #            endif
01429 #          endif
01430 #        endif
01431 #      endif
01432 #    endif
01433 #  endif
01434 #endif
01435 #endif
01436 
01437 
01438 
01439 /* ------------------- size_t and alignment properties -------------------- */
01440 
01441 /* The byte and bit size of a size_t */
01442 #define SIZE_T_SIZE         (sizeof(size_t))
01443 #define SIZE_T_BITSIZE      (sizeof(size_t) << 3)
01444 
01445 /* Some constants coerced to size_t */
01446 /* Annoying but necessary to avoid errors on some platforms */
01447 #define SIZE_T_ZERO         ((size_t)0)
01448 #define SIZE_T_ONE          ((size_t)1)
01449 #define SIZE_T_TWO          ((size_t)2)
01450 #define SIZE_T_FOUR         ((size_t)4)
01451 #define TWO_SIZE_T_SIZES    (SIZE_T_SIZE<<1)
01452 #define FOUR_SIZE_T_SIZES   (SIZE_T_SIZE<<2)
01453 #define SIX_SIZE_T_SIZES    (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
01454 #define HALF_MAX_SIZE_T     (MAX_SIZE_T / 2U)
01455 
01456 /* The bit mask value corresponding to MALLOC_ALIGNMENT */
01457 #define CHUNK_ALIGN_MASK    (MALLOC_ALIGNMENT - SIZE_T_ONE)
01458 
01459 /* True if address a has acceptable alignment */
01460 #define is_aligned(A)       (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
01461 
01462 /* the number of bytes to offset an address to align it */
01463 #define align_offset(A)\
01464  ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
01465   ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
01466 
01467 /* -------------------------- MMAP preliminaries ------------------------- */
01468 
01469 /*
01470    If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
01471    checks to fail so compiler optimizer can delete code rather than
01472    using so many "#if"s.
01473 */
01474 
01475 
01476 /* MORECORE and MMAP must return MFAIL on failure */
01477 #define MFAIL                ((void*)(MAX_SIZE_T))
01478 #define CMFAIL               ((char*)(MFAIL)) /* defined for convenience */
01479 
01480 #if HAVE_MMAP
01481 
01482 #ifndef WIN32
01483 #define MUNMAP_DEFAULT(a, s)  munmap((a), (s))
01484 #define MMAP_PROT            (PROT_READ|PROT_WRITE)
01485 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
01486 #define MAP_ANONYMOUS        MAP_ANON
01487 #endif /* MAP_ANON */
01488 #ifdef MAP_ANONYMOUS
01489 #define MMAP_FLAGS           (MAP_PRIVATE|MAP_ANONYMOUS)
01490 #define MMAP_DEFAULT(s)       mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
01491 #else /* MAP_ANONYMOUS */
01492 /*
01493    Nearly all versions of mmap support MAP_ANONYMOUS, so the following
01494    is unlikely to be needed, but is supplied just in case.
01495 */
01496 #define MMAP_FLAGS           (MAP_PRIVATE)
01497 static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
01498 #define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \
01499            (dev_zero_fd = open("/dev/zero", O_RDWR), \
01500             mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
01501             mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
01502 #endif /* MAP_ANONYMOUS */
01503 
01504 #define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s)
01505 
01506 #else /* WIN32 */
01507 
01508 /* Win32 MMAP via VirtualAlloc */
01509 static FORCEINLINE void* win32mmap(size_t size) {
01510   void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
01511   return (ptr != 0)? ptr: MFAIL;
01512 }
01513 
01514 /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
01515 static FORCEINLINE void* win32direct_mmap(size_t size) {
01516   void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
01517                            PAGE_READWRITE);
01518   return (ptr != 0)? ptr: MFAIL;
01519 }
01520 
01521 /* This function supports releasing coalesed segments */
01522 static FORCEINLINE int win32munmap(void* ptr, size_t size) {
01523   MEMORY_BASIC_INFORMATION minfo;
01524   char* cptr = (char*)ptr;
01525   while (size) {
01526     if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
01527       return -1;
01528     if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
01529         minfo.State != MEM_COMMIT || minfo.RegionSize > size)
01530       return -1;
01531     if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
01532       return -1;
01533     cptr += minfo.RegionSize;
01534     size -= minfo.RegionSize;
01535   }
01536   return 0;
01537 }
01538 
01539 #define MMAP_DEFAULT(s)             win32mmap(s)
01540 #define MUNMAP_DEFAULT(a, s)        win32munmap((a), (s))
01541 #define DIRECT_MMAP_DEFAULT(s)      win32direct_mmap(s)
01542 #endif /* WIN32 */
01543 #endif /* HAVE_MMAP */
01544 
01545 #if HAVE_MREMAP
01546 #ifndef WIN32
01547 #define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
01548 #endif /* WIN32 */
01549 #endif /* HAVE_MREMAP */
01550 
01551 
01555 #if HAVE_MORECORE
01556     #ifdef MORECORE
01557         #define CALL_MORECORE(S)    MORECORE(S)
01558     #else  /* MORECORE */
01559         #define CALL_MORECORE(S)    MORECORE_DEFAULT(S)
01560     #endif /* MORECORE */
01561 #else  /* HAVE_MORECORE */
01562     #define CALL_MORECORE(S)        MFAIL
01563 #endif /* HAVE_MORECORE */
01564 
01568 #if HAVE_MMAP
01569     #define USE_MMAP_BIT            (SIZE_T_ONE)
01570 
01571     #ifdef MMAP
01572         #define CALL_MMAP(s)        MMAP(s)
01573     #else /* MMAP */
01574         #define CALL_MMAP(s)        MMAP_DEFAULT(s)
01575     #endif /* MMAP */
01576     #ifdef MUNMAP
01577         #define CALL_MUNMAP(a, s)   MUNMAP((a), (s))
01578     #else /* MUNMAP */
01579         #define CALL_MUNMAP(a, s)   MUNMAP_DEFAULT((a), (s))
01580     #endif /* MUNMAP */
01581     #ifdef DIRECT_MMAP
01582         #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)
01583     #else /* DIRECT_MMAP */
01584         #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s)
01585     #endif /* DIRECT_MMAP */
01586 #else  /* HAVE_MMAP */
01587     #define USE_MMAP_BIT            (SIZE_T_ZERO)
01588 
01589     #define MMAP(s)                 MFAIL
01590     #define MUNMAP(a, s)            (-1)
01591     #define DIRECT_MMAP(s)          MFAIL
01592     #define CALL_DIRECT_MMAP(s)     DIRECT_MMAP(s)
01593     #define CALL_MMAP(s)            MMAP(s)
01594     #define CALL_MUNMAP(a, s)       MUNMAP((a), (s))
01595 #endif /* HAVE_MMAP */
01596 
01600 #if HAVE_MMAP && HAVE_MREMAP
01601     #ifdef MREMAP
01602         #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv))
01603     #else /* MREMAP */
01604         #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv))
01605     #endif /* MREMAP */
01606 #else  /* HAVE_MMAP && HAVE_MREMAP */
01607     #define CALL_MREMAP(addr, osz, nsz, mv)     MFAIL
01608 #endif /* HAVE_MMAP && HAVE_MREMAP */
01609 
01610 /* mstate bit set if continguous morecore disabled or failed */
01611 #define USE_NONCONTIGUOUS_BIT (4U)
01612 
01613 /* segment bit set in create_mspace_with_base */
01614 #define EXTERN_BIT            (8U)
01615 
01616 
01617 /* --------------------------- Lock preliminaries ------------------------ */
01618 
01619 /*
01620   When locks are defined, there is one global lock, plus
01621   one per-mspace lock.
01622 
01623   The global lock_ensures that mparams.magic and other unique
01624   mparams values are initialized only once. It also protects
01625   sequences of calls to MORECORE.  In many cases sys_alloc requires
01626   two calls, that should not be interleaved with calls by other
01627   threads.  This does not protect against direct calls to MORECORE
01628   by other threads not using this lock, so there is still code to
01629   cope the best we can on interference.
01630 
01631   Per-mspace locks surround calls to malloc, free, etc.  To enable use
01632   in layered extensions, per-mspace locks are reentrant.
01633 
01634   Because lock-protected regions generally have bounded times, it is
01635   OK to use the supplied simple spinlocks in the custom versions for
01636   x86. Spinlocks are likely to improve performance for lightly
01637   contended applications, but worsen performance under heavy
01638   contention.
01639 
01640   If USE_LOCKS is > 1, the definitions of lock routines here are
01641   bypassed, in which case you will need to define the type MLOCK_T,
01642   and at least INITIAL_LOCK, ACQUIRE_LOCK, RELEASE_LOCK and possibly
01643   TRY_LOCK (which is not used in this malloc, but commonly needed in
01644   extensions.)  You must also declare a
01645     static MLOCK_T malloc_global_mutex = { initialization values };.
01646 
01647 */
01648 
01649 #if USE_LOCKS == 1
01650 
01651 #if USE_SPIN_LOCKS && SPIN_LOCKS_AVAILABLE
01652 #ifndef WIN32
01653 
01654 /* Custom pthread-style spin locks on x86 and x64 for gcc */
01655 struct pthread_mlock_t {
01656   volatile unsigned int l;
01657   unsigned int c;
01658   pthread_t threadid;
01659 };
01660 #define MLOCK_T               struct pthread_mlock_t
01661 #define CURRENT_THREAD        pthread_self()
01662 #define INITIAL_LOCK(sl)      ((sl)->threadid = 0, (sl)->l = (sl)->c = 0, 0)
01663 #define ACQUIRE_LOCK(sl)      pthread_acquire_lock(sl)
01664 #define RELEASE_LOCK(sl)      pthread_release_lock(sl)
01665 #define TRY_LOCK(sl)          pthread_try_lock(sl)
01666 #define SPINS_PER_YIELD       63
01667 
01668 static MLOCK_T malloc_global_mutex = { 0, 0, 0};
01669 
01670 static FORCEINLINE int pthread_acquire_lock (MLOCK_T *sl) {
01671   int spins = 0;
01672   volatile unsigned int* lp = &sl->l;
01673   for (;;) {
01674     if (*lp != 0) {
01675       if (sl->threadid == CURRENT_THREAD) {
01676         ++sl->c;
01677         return 0;
01678       }
01679     }
01680     else {
01681       /* place args to cmpxchgl in locals to evade oddities in some gccs */
01682       int cmp = 0;
01683       int val = 1;
01684       int ret;
01685       __asm__ __volatile__  ("lock; cmpxchgl %1, %2"
01686                              : "=a" (ret)
01687                              : "r" (val), "m" (*(lp)), "0"(cmp)
01688                              : "memory", "cc");
01689       if (!ret) {
01690         assert(!sl->threadid);
01691         sl->threadid = CURRENT_THREAD;
01692         sl->c = 1;
01693         return 0;
01694       }
01695     }
01696     if ((++spins & SPINS_PER_YIELD) == 0) {
01697 #if defined (__SVR4) && defined (__sun) /* solaris */
01698       thr_yield();
01699 #else
01700 #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
01701       sched_yield();
01702 #else  /* no-op yield on unknown systems */
01703       ;
01704 #endif /* __linux__ || __FreeBSD__ || __APPLE__ */
01705 #endif /* solaris */
01706     }
01707   }
01708 }
01709 
01710 static FORCEINLINE void pthread_release_lock (MLOCK_T *sl) {
01711   volatile unsigned int* lp = &sl->l;
01712   assert(*lp != 0);
01713   assert(sl->threadid == CURRENT_THREAD);
01714   if (--sl->c == 0) {
01715     sl->threadid = 0;
01716     int prev = 0;
01717     int ret;
01718     __asm__ __volatile__ ("lock; xchgl %0, %1"
01719                           : "=r" (ret)
01720                           : "m" (*(lp)), "0"(prev)
01721                           : "memory");
01722   }
01723 }
01724 
01725 static FORCEINLINE int pthread_try_lock (MLOCK_T *sl) {
01726   volatile unsigned int* lp = &sl->l;
01727   if (*lp != 0) {
01728     if (sl->threadid == CURRENT_THREAD) {
01729       ++sl->c;
01730       return 1;
01731     }
01732   }
01733   else {
01734     int cmp = 0;
01735     int val = 1;
01736     int ret;
01737     __asm__ __volatile__  ("lock; cmpxchgl %1, %2"
01738                            : "=a" (ret)
01739                            : "r" (val), "m" (*(lp)), "0"(cmp)
01740                            : "memory", "cc");
01741     if (!ret) {
01742       assert(!sl->threadid);
01743       sl->threadid = CURRENT_THREAD;
01744       sl->c = 1;
01745       return 1;
01746     }
01747   }
01748   return 0;
01749 }
01750 
01751 
01752 #else /* WIN32 */
01753 /* Custom win32-style spin locks on x86 and x64 for MSC */
01754 struct win32_mlock_t {
01755   volatile long l;
01756   unsigned int c;
01757   long threadid;
01758 };
01759 
01760 #define MLOCK_T               struct win32_mlock_t
01761 #define CURRENT_THREAD        GetCurrentThreadId()
01762 #define INITIAL_LOCK(sl)      ((sl)->threadid = 0, (sl)->l = (sl)->c = 0, 0)
01763 #define ACQUIRE_LOCK(sl)      win32_acquire_lock(sl)
01764 #define RELEASE_LOCK(sl)      win32_release_lock(sl)
01765 #define TRY_LOCK(sl)          win32_try_lock(sl)
01766 #define SPINS_PER_YIELD       63
01767 
01768 static MLOCK_T malloc_global_mutex = { 0, 0, 0};
01769 
01770 static FORCEINLINE int win32_acquire_lock (MLOCK_T *sl) {
01771   int spins = 0;
01772   for (;;) {
01773     if (sl->l != 0) {
01774       if (sl->threadid == CURRENT_THREAD) {
01775         ++sl->c;
01776         return 0;
01777       }
01778     }
01779     else {
01780       if (!interlockedexchange(&sl->l, 1)) {
01781         assert(!sl->threadid);
01782         sl->threadid = CURRENT_THREAD;
01783         sl->c = 1;
01784         return 0;
01785       }
01786     }
01787     if ((++spins & SPINS_PER_YIELD) == 0)
01788       SleepEx(0, FALSE);
01789   }
01790 }
01791 
01792 static FORCEINLINE void win32_release_lock (MLOCK_T *sl) {
01793   assert(sl->threadid == CURRENT_THREAD);
01794   assert(sl->l != 0);
01795   if (--sl->c == 0) {
01796     sl->threadid = 0;
01797     interlockedexchange (&sl->l, 0);
01798   }
01799 }
01800 
01801 static FORCEINLINE int win32_try_lock (MLOCK_T *sl) {
01802   if (sl->l != 0) {
01803     if (sl->threadid == CURRENT_THREAD) {
01804       ++sl->c;
01805       return 1;
01806     }
01807   }
01808   else {
01809     if (!interlockedexchange(&sl->l, 1)){
01810       assert(!sl->threadid);
01811       sl->threadid = CURRENT_THREAD;
01812       sl->c = 1;
01813       return 1;
01814     }
01815   }
01816   return 0;
01817 }
01818 
01819 #endif /* WIN32 */
01820 #else /* USE_SPIN_LOCKS */
01821 
01822 #ifndef WIN32
01823 /* pthreads-based locks */
01824 
01825 #define MLOCK_T               pthread_mutex_t
01826 #define CURRENT_THREAD        pthread_self()
01827 #define INITIAL_LOCK(sl)      pthread_init_lock(sl)
01828 #define ACQUIRE_LOCK(sl)      pthread_mutex_lock(sl)
01829 #define RELEASE_LOCK(sl)      pthread_mutex_unlock(sl)
01830 #define TRY_LOCK(sl)          (!pthread_mutex_trylock(sl))
01831 
01832 static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER;
01833 
01834 /* Cope with old-style linux recursive lock initialization by adding */
01835 /* skipped internal declaration from pthread.h */
01836 #ifdef linux
01837 #ifndef PTHREAD_MUTEX_RECURSIVE
01838 extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr,
01839                                            int __kind));
01840 #define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP
01841 #define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y)
01842 #endif
01843 #endif
01844 
01845 static int pthread_init_lock (MLOCK_T *sl) {
01846   pthread_mutexattr_t attr;
01847   if (pthread_mutexattr_init(&attr)) return 1;
01848   if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1;
01849   if (pthread_mutex_init(sl, &attr)) return 1;
01850   if (pthread_mutexattr_destroy(&attr)) return 1;
01851   return 0;
01852 }
01853 
01854 #else /* WIN32 */
01855 /* Win32 critical sections */
01856 #define MLOCK_T               CRITICAL_SECTION
01857 #define CURRENT_THREAD        GetCurrentThreadId()
01858 #define INITIAL_LOCK(s)       (!InitializeCriticalSectionAndSpinCount((s), 0x80000000|4000))
01859 #define ACQUIRE_LOCK(s)       (EnterCriticalSection(sl), 0)
01860 #define RELEASE_LOCK(s)       LeaveCriticalSection(sl)
01861 #define TRY_LOCK(s)           TryEnterCriticalSection(sl)
01862 #define NEED_GLOBAL_LOCK_INIT
01863 
01864 static MLOCK_T malloc_global_mutex;
01865 static volatile long malloc_global_mutex_status;
01866 
01867 /* Use spin loop to initialize global lock */
01868 static void init_malloc_global_mutex() {
01869   for (;;) {
01870     long stat = malloc_global_mutex_status;
01871     if (stat > 0)
01872       return;
01873     /* transition to < 0 while initializing, then to > 0) */
01874     if (stat == 0 &&
01875         interlockedcompareexchange(&malloc_global_mutex_status, -1, 0) == 0) {
01876       InitializeCriticalSection(&malloc_global_mutex);
01877       interlockedexchange(&malloc_global_mutex_status,1);
01878       return;
01879     }
01880     SleepEx(0, FALSE);
01881   }
01882 }
01883 
01884 #endif /* WIN32 */
01885 #endif /* USE_SPIN_LOCKS */
01886 #endif /* USE_LOCKS == 1 */
01887 
01888 /* -----------------------  User-defined locks ------------------------ */
01889 
01890 #if USE_LOCKS > 1
01891 /* Define your own lock implementation here */
01892 /* #define INITIAL_LOCK(sl)  ... */
01893 /* #define ACQUIRE_LOCK(sl)  ... */
01894 /* #define RELEASE_LOCK(sl)  ... */
01895 /* #define TRY_LOCK(sl) ... */
01896 /* static MLOCK_T malloc_global_mutex = ... */
01897 #endif /* USE_LOCKS > 1 */
01898 
01899 /* -----------------------  Lock-based state ------------------------ */
01900 
01901 #if USE_LOCKS
01902 #define USE_LOCK_BIT               (2U)
01903 #else  /* USE_LOCKS */
01904 #define USE_LOCK_BIT               (0U)
01905 #define INITIAL_LOCK(l)
01906 #endif /* USE_LOCKS */
01907 
01908 #if USE_LOCKS
01909 #ifndef ACQUIRE_MALLOC_GLOBAL_LOCK
01910 #define ACQUIRE_MALLOC_GLOBAL_LOCK()  ACQUIRE_LOCK(&malloc_global_mutex);
01911 #endif
01912 #ifndef RELEASE_MALLOC_GLOBAL_LOCK
01913 #define RELEASE_MALLOC_GLOBAL_LOCK()  RELEASE_LOCK(&malloc_global_mutex);
01914 #endif
01915 #else  /* USE_LOCKS */
01916 #define ACQUIRE_MALLOC_GLOBAL_LOCK()
01917 #define RELEASE_MALLOC_GLOBAL_LOCK()
01918 #endif /* USE_LOCKS */
01919 
01920 
01921 /* -----------------------  Chunk representations ------------------------ */
01922 
01923 /*
01924   (The following includes lightly edited explanations by Colin Plumb.)
01925 
01926   The malloc_chunk declaration below is misleading (but accurate and
01927   necessary).  It declares a "view" into memory allowing access to
01928   necessary fields at known offsets from a given base.
01929 
01930   Chunks of memory are maintained using a `boundary tag' method as
01931   originally described by Knuth.  (See the paper by Paul Wilson
01932   ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
01933   techniques.)  Sizes of free chunks are stored both in the front of
01934   each chunk and at the end.  This makes consolidating fragmented
01935   chunks into bigger chunks fast.  The head fields also hold bits
01936   representing whether chunks are free or in use.
01937 
01938   Here are some pictures to make it clearer.  They are "exploded" to
01939   show that the state of a chunk can be thought of as extending from
01940   the high 31 bits of the head field of its header through the
01941   prev_foot and PINUSE_BIT bit of the following chunk header.
01942 
01943   A chunk that's in use looks like:
01944 
01945    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01946            | Size of previous chunk (if P = 0)                             |
01947            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01948          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
01949          | Size of this chunk                                         1| +-+
01950    mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01951          |                                                               |
01952          +-                                                             -+
01953          |                                                               |
01954          +-                                                             -+
01955          |                                                               :
01956          +-      size - sizeof(size_t) available payload bytes          -+
01957          :                                                               |
01958  chunk-> +-                                                             -+
01959          |                                                               |
01960          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01961        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
01962        | Size of next chunk (may or may not be in use)               | +-+
01963  mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01964 
01965     And if it's free, it looks like this:
01966 
01967    chunk-> +-                                                             -+
01968            | User payload (must be in use, or we would have merged!)       |
01969            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01970          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
01971          | Size of this chunk                                         0| +-+
01972    mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01973          | Next pointer                                                  |
01974          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01975          | Prev pointer                                                  |
01976          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01977          |                                                               :
01978          +-      size - sizeof(struct chunk) unused bytes               -+
01979          :                                                               |
01980  chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01981          | Size of this chunk                                            |
01982          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01983        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
01984        | Size of next chunk (must be in use, or we would have merged)| +-+
01985  mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01986        |                                                               :
01987        +- User payload                                                -+
01988        :                                                               |
01989        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
01990                                                                      |0|
01991                                                                      +-+
01992   Note that since we always merge adjacent free chunks, the chunks
01993   adjacent to a free chunk must be in use.
01994 
01995   Given a pointer to a chunk (which can be derived trivially from the
01996   payload pointer) we can, in O(1) time, find out whether the adjacent
01997   chunks are free, and if so, unlink them from the lists that they
01998   are on and merge them with the current chunk.
01999 
02000   Chunks always begin on even word boundaries, so the mem portion
02001   (which is returned to the user) is also on an even word boundary, and
02002   thus at least double-word aligned.
02003 
02004   The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
02005   chunk size (which is always a multiple of two words), is an in-use
02006   bit for the *previous* chunk.  If that bit is *clear*, then the
02007   word before the current chunk size contains the previous chunk
02008   size, and can be used to find the front of the previous chunk.
02009   The very first chunk allocated always has this bit set, preventing
02010   access to non-existent (or non-owned) memory. If pinuse is set for
02011   any given chunk, then you CANNOT determine the size of the
02012   previous chunk, and might even get a memory addressing fault when
02013   trying to do so.
02014 
02015   The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
02016   the chunk size redundantly records whether the current chunk is
02017   inuse (unless the chunk is mmapped). This redundancy enables usage
02018   checks within free and realloc, and reduces indirection when freeing
02019   and consolidating chunks.
02020 
02021   Each freshly allocated chunk must have both cinuse and pinuse set.
02022   That is, each allocated chunk borders either a previously allocated
02023   and still in-use chunk, or the base of its memory arena. This is
02024   ensured by making all allocations from the the `lowest' part of any
02025   found chunk.  Further, no free chunk physically borders another one,
02026   so each free chunk is known to be preceded and followed by either
02027   inuse chunks or the ends of memory.
02028 
02029   Note that the `foot' of the current chunk is actually represented
02030   as the prev_foot of the NEXT chunk. This makes it easier to
02031   deal with alignments etc but can be very confusing when trying
02032   to extend or adapt this code.
02033 
02034   The exceptions to all this are
02035 
02036      1. The special chunk `top' is the top-most available chunk (i.e.,
02037         the one bordering the end of available memory). It is treated
02038         specially.  Top is never included in any bin, is used only if
02039         no other chunk is available, and is released back to the
02040         system if it is very large (see M_TRIM_THRESHOLD).  In effect,
02041         the top chunk is treated as larger (and thus less well
02042         fitting) than any other available chunk.  The top chunk
02043         doesn't update its trailing size field since there is no next
02044         contiguous chunk that would have to index off it. However,
02045         space is still allocated for it (TOP_FOOT_SIZE) to enable
02046         separation or merging when space is extended.
02047 
02048      3. Chunks allocated via mmap, have both cinuse and pinuse bits
02049         cleared in their head fields.  Because they are allocated
02050         one-by-one, each must carry its own prev_foot field, which is
02051         also used to hold the offset this chunk has within its mmapped
02052         region, which is needed to preserve alignment. Each mmapped
02053         chunk is trailed by the first two fields of a fake next-chunk
02054         for sake of usage checks.
02055 
02056 */
02057 
02058 struct malloc_chunk {
02059   size_t               prev_foot;  /* Size of previous chunk (if free).  */
02060   size_t               head;       /* Size and inuse bits. */
02061   struct malloc_chunk* fd;         /* double links -- used only if free. */
02062   struct malloc_chunk* bk;
02063 };
02064 
02065 typedef struct malloc_chunk  mchunk;
02066 typedef struct malloc_chunk* mchunkptr;
02067 typedef struct malloc_chunk* sbinptr;  /* The type of bins of chunks */
02068 typedef unsigned int bindex_t;         /* Described below */
02069 typedef unsigned int binmap_t;         /* Described below */
02070 typedef unsigned int flag_t;           /* The type of various bit flag sets */
02071 
02072 /* ------------------- Chunks sizes and alignments ----------------------- */
02073 
02074 #define MCHUNK_SIZE         (sizeof(mchunk))
02075 
02076 #if FOOTERS
02077 #define CHUNK_OVERHEAD      (TWO_SIZE_T_SIZES)
02078 #else /* FOOTERS */
02079 #define CHUNK_OVERHEAD      (SIZE_T_SIZE)
02080 #endif /* FOOTERS */
02081 
02082 /* MMapped chunks need a second word of overhead ... */
02083 #define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
02084 /* ... and additional padding for fake next-chunk at foot */
02085 #define MMAP_FOOT_PAD       (FOUR_SIZE_T_SIZES)
02086 
02087 /* The smallest size we can malloc is an aligned minimal chunk */
02088 #define MIN_CHUNK_SIZE\
02089   ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
02090 
02091 /* conversion from malloc headers to user pointers, and back */
02092 #define chunk2mem(p)        ((void*)((char*)(p)       + TWO_SIZE_T_SIZES))
02093 #define mem2chunk(mem)      ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
02094 /* chunk associated with aligned address A */
02095 #define align_as_chunk(A)   (mchunkptr)((A) + align_offset(chunk2mem(A)))
02096 
02097 /* Bounds on request (not chunk) sizes. */
02098 #define MAX_REQUEST         ((-MIN_CHUNK_SIZE) << 2)
02099 #define MIN_REQUEST         (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
02100 
02101 /* pad request bytes into a usable size */
02102 #define pad_request(req) \
02103    (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
02104 
02105 /* pad request, checking for minimum (but not maximum) */
02106 #define request2size(req) \
02107   (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
02108 
02109 
02110 /* ------------------ Operations on head and foot fields ----------------- */
02111 
02112 /*
02113   The head field of a chunk is or'ed with PINUSE_BIT when previous
02114   adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
02115   use, unless mmapped, in which case both bits are cleared.
02116 
02117   FLAG4_BIT is not used by this malloc, but might be useful in extensions.
02118 */
02119 
02120 #define PINUSE_BIT          (SIZE_T_ONE)
02121 #define CINUSE_BIT          (SIZE_T_TWO)
02122 #define FLAG4_BIT           (SIZE_T_FOUR)
02123 #define INUSE_BITS          (PINUSE_BIT|CINUSE_BIT)
02124 #define FLAG_BITS           (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT)
02125 
02126 /* Head value for fenceposts */
02127 #define FENCEPOST_HEAD      (INUSE_BITS|SIZE_T_SIZE)
02128 
02129 /* extraction of fields from head words */
02130 #define cinuse(p)           ((p)->head & CINUSE_BIT)
02131 #define pinuse(p)           ((p)->head & PINUSE_BIT)
02132 #define is_inuse(p)         (((p)->head & INUSE_BITS) != PINUSE_BIT)
02133 #define is_mmapped(p)       (((p)->head & INUSE_BITS) == 0)
02134 
02135 #define chunksize(p)        ((p)->head & ~(FLAG_BITS))
02136 
02137 #define clear_pinuse(p)     ((p)->head &= ~PINUSE_BIT)
02138 
02139 /* Treat space at ptr +/- offset as a chunk */
02140 #define chunk_plus_offset(p, s)  ((mchunkptr)(((char*)(p)) + (s)))
02141 #define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
02142 
02143 /* Ptr to next or previous physical malloc_chunk. */
02144 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS)))
02145 #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
02146 
02147 /* extract next chunk's pinuse bit */
02148 #define next_pinuse(p)  ((next_chunk(p)->head) & PINUSE_BIT)
02149 
02150 /* Get/set size at footer */
02151 #define get_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot)
02152 #define set_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
02153 
02154 /* Set size, pinuse bit, and foot */
02155 #define set_size_and_pinuse_of_free_chunk(p, s)\
02156   ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
02157 
02158 /* Set size, pinuse bit, foot, and clear next pinuse */
02159 #define set_free_with_pinuse(p, s, n)\
02160   (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
02161 
02162 /* Get the internal overhead associated with chunk p */
02163 #define overhead_for(p)\
02164  (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
02165 
02166 /* Return true if malloced space is not necessarily cleared */
02167 #if MMAP_CLEARS
02168 #define calloc_must_clear(p) (!is_mmapped(p))
02169 #else /* MMAP_CLEARS */
02170 #define calloc_must_clear(p) (1)
02171 #endif /* MMAP_CLEARS */
02172 
02173 /* ---------------------- Overlaid data structures ----------------------- */
02174 
02175 /*
02176   When chunks are not in use, they are treated as nodes of either
02177   lists or trees.
02178 
02179   "Small"  chunks are stored in circular doubly-linked lists, and look
02180   like this:
02181 
02182     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02183             |             Size of previous chunk                            |
02184             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02185     `head:' |             Size of chunk, in bytes                         |P|
02186       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02187             |             Forward pointer to next chunk in list             |
02188             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02189             |             Back pointer to previous chunk in list            |
02190             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02191             |             Unused space (may be 0 bytes long)                .
02192             .                                                               .
02193             .                                                               |
02194 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02195     `foot:' |             Size of chunk, in bytes                           |
02196             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02197 
02198   Larger chunks are kept in a form of bitwise digital trees (aka
02199   tries) keyed on chunksizes.  Because malloc_tree_chunks are only for
02200   free chunks greater than 256 bytes, their size doesn't impose any
02201   constraints on user chunk sizes.  Each node looks like:
02202 
02203     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02204             |             Size of previous chunk                            |
02205             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02206     `head:' |             Size of chunk, in bytes                         |P|
02207       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02208             |             Forward pointer to next chunk of same size        |
02209             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02210             |             Back pointer to previous chunk of same size       |
02211             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02212             |             Pointer to left child (child[0])                  |
02213             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02214             |             Pointer to right child (child[1])                 |
02215             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02216             |             Pointer to parent                                 |
02217             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02218             |             bin index of this chunk                           |
02219             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02220             |             Unused space                                      .
02221             .                                                               |
02222 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02223     `foot:' |             Size of chunk, in bytes                           |
02224             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
02225 
02226   Each tree holding treenodes is a tree of unique chunk sizes.  Chunks
02227   of the same size are arranged in a circularly-linked list, with only
02228   the oldest chunk (the next to be used, in our FIFO ordering)
02229   actually in the tree.  (Tree members are distinguished by a non-null
02230   parent pointer.)  If a chunk with the same size an an existing node
02231   is inserted, it is linked off the existing node using pointers that
02232   work in the same way as fd/bk pointers of small chunks.
02233 
02234   Each tree contains a power of 2 sized range of chunk sizes (the
02235   smallest is 0x100 <= x < 0x180), which is is divided in half at each
02236   tree level, with the chunks in the smaller half of the range (0x100
02237   <= x < 0x140 for the top nose) in the left subtree and the larger
02238   half (0x140 <= x < 0x180) in the right subtree.  This is, of course,
02239   done by inspecting individual bits.
02240 
02241   Using these rules, each node's left subtree contains all smaller
02242   sizes than its right subtree.  However, the node at the root of each
02243   subtree has no particular ordering relationship to either.  (The
02244   dividing line between the subtree sizes is based on trie relation.)
02245   If we remove the last chunk of a given size from the interior of the
02246   tree, we need to replace it with a leaf node.  The tree ordering
02247   rules permit a node to be replaced by any leaf below it.
02248 
02249   The smallest chunk in a tree (a common operation in a best-fit
02250   allocator) can be found by walking a path to the leftmost leaf in
02251   the tree.  Unlike a usual binary tree, where we follow left child
02252   pointers until we reach a null, here we follow the right child
02253   pointer any time the left one is null, until we reach a leaf with
02254   both child pointers null. The smallest chunk in the tree will be
02255   somewhere along that path.
02256 
02257   The worst case number of steps to add, find, or remove a node is
02258   bounded by the number of bits differentiating chunks within
02259   bins. Under current bin calculations, this ranges from 6 up to 21
02260   (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
02261   is of course much better.
02262 */
02263 
02264 struct malloc_tree_chunk {
02265   /* The first four fields must be compatible with malloc_chunk */
02266   size_t                    prev_foot;
02267   size_t                    head;
02268   struct malloc_tree_chunk* fd;
02269   struct malloc_tree_chunk* bk;
02270 
02271   struct malloc_tree_chunk* child[2];
02272   struct malloc_tree_chunk* parent;
02273   bindex_t                  index;
02274 };
02275 
02276 typedef struct malloc_tree_chunk  tchunk;
02277 typedef struct malloc_tree_chunk* tchunkptr;
02278 typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
02279 
02280 /* A little helper macro for trees */
02281 #define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
02282 
02283 /* ----------------------------- Segments -------------------------------- */
02284 
02285 /*
02286   Each malloc space may include non-contiguous segments, held in a
02287   list headed by an embedded malloc_segment record representing the
02288   top-most space. Segments also include flags holding properties of
02289   the space. Large chunks that are directly allocated by mmap are not
02290   included in this list. They are instead independently created and
02291   destroyed without otherwise keeping track of them.
02292 
02293   Segment management mainly comes into play for spaces allocated by
02294   MMAP.  Any call to MMAP might or might not return memory that is
02295   adjacent to an existing segment.  MORECORE normally contiguously
02296   extends the current space, so this space is almost always adjacent,
02297   which is simpler and faster to deal with. (This is why MORECORE is
02298   used preferentially to MMAP when both are available -- see
02299   sys_alloc.)  When allocating using MMAP, we don't use any of the
02300   hinting mechanisms (inconsistently) supported in various
02301   implementations of unix mmap, or distinguish reserving from
02302   committing memory. Instead, we just ask for space, and exploit
02303   contiguity when we get it.  It is probably possible to do
02304   better than this on some systems, but no general scheme seems
02305   to be significantly better.
02306 
02307   Management entails a simpler variant of the consolidation scheme
02308   used for chunks to reduce fragmentation -- new adjacent memory is
02309   normally prepended or appended to an existing segment. However,
02310   there are limitations compared to chunk consolidation that mostly
02311   reflect the fact that segment processing is relatively infrequent
02312   (occurring only when getting memory from system) and that we
02313   don't expect to have huge numbers of segments:
02314 
02315   * Segments are not indexed, so traversal requires linear scans.  (It
02316     would be possible to index these, but is not worth the extra
02317     overhead and complexity for most programs on most platforms.)
02318   * New segments are only appended to old ones when holding top-most
02319     memory; if they cannot be prepended to others, they are held in
02320     different segments.
02321 
02322   Except for the top-most segment of an mstate, each segment record
02323   is kept at the tail of its segment. Segments are added by pushing
02324   segment records onto the list headed by &mstate.seg for the
02325   containing mstate.
02326 
02327   Segment flags control allocation/merge/deallocation policies:
02328   * If EXTERN_BIT set, then we did not allocate this segment,
02329     and so should not try to deallocate or merge with others.
02330     (This currently holds only for the initial segment passed
02331     into create_mspace_with_base.)
02332   * If USE_MMAP_BIT set, the segment may be merged with
02333     other surrounding mmapped segments and trimmed/de-allocated
02334     using munmap.
02335   * If neither bit is set, then the segment was obtained using
02336     MORECORE so can be merged with surrounding MORECORE'd segments
02337     and deallocated/trimmed using MORECORE with negative arguments.
02338 */
02339 
02340 struct malloc_segment {
02341   char*        base;             /* base address */
02342   size_t       size;             /* allocated size */
02343   struct malloc_segment* next;   /* ptr to next segment */
02344   flag_t       sflags;           /* mmap and extern flag */
02345 };
02346 
02347 #define is_mmapped_segment(S)  ((S)->sflags & USE_MMAP_BIT)
02348 #define is_extern_segment(S)   ((S)->sflags & EXTERN_BIT)
02349 
02350 typedef struct malloc_segment  msegment;
02351 typedef struct malloc_segment* msegmentptr;
02352 
02353 /* ---------------------------- malloc_state ----------------------------- */
02354 
02355 /*
02356    A malloc_state holds all of the bookkeeping for a space.
02357    The main fields are:
02358 
02359   Top
02360     The topmost chunk of the currently active segment. Its size is
02361     cached in topsize.  The actual size of topmost space is
02362     topsize+TOP_FOOT_SIZE, which includes space reserved for adding
02363     fenceposts and segment records if necessary when getting more
02364     space from the system.  The size at which to autotrim top is
02365     cached from mparams in trim_check, except that it is disabled if
02366     an autotrim fails.
02367 
02368   Designated victim (dv)
02369     This is the preferred chunk for servicing small requests that
02370     don't have exact fits.  It is normally the chunk split off most
02371     recently to service another small request.  Its size is cached in
02372     dvsize. The link fields of this chunk are not maintained since it
02373     is not kept in a bin.
02374 
02375   SmallBins
02376     An array of bin headers for free chunks.  These bins hold chunks
02377     with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
02378     chunks of all the same size, spaced 8 bytes apart.  To simplify
02379     use in double-linked lists, each bin header acts as a malloc_chunk
02380     pointing to the real first node, if it exists (else pointing to
02381     itself).  This avoids special-casing for headers.  But to avoid
02382     waste, we allocate only the fd/bk pointers of bins, and then use
02383     repositioning tricks to treat these as the fields of a chunk.
02384 
02385   TreeBins
02386     Treebins are pointers to the roots of trees holding a range of
02387     sizes. There are 2 equally spaced treebins for each power of two
02388     from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
02389     larger.
02390 
02391   Bin maps
02392     There is one bit map for small bins ("smallmap") and one for
02393     treebins ("treemap).  Each bin sets its bit when non-empty, and
02394     clears the bit when empty.  Bit operations are then used to avoid
02395     bin-by-bin searching -- nearly all "search" is done without ever
02396     looking at bins that won't be selected.  The bit maps
02397     conservatively use 32 bits per map word, even if on 64bit system.
02398     For a good description of some of the bit-based techniques used
02399     here, see Henry S. Warren Jr's book "Hacker's Delight" (and
02400     supplement at http://hackersdelight.org/). Many of these are
02401     intended to reduce the branchiness of paths through malloc etc, as
02402     well as to reduce the number of memory locations read or written.
02403 
02404   Segments
02405     A list of segments headed by an embedded malloc_segment record
02406     representing the initial space.
02407 
02408   Address check support
02409     The least_addr field is the least address ever obtained from
02410     MORECORE or MMAP. Attempted frees and reallocs of any address less
02411     than this are trapped (unless INSECURE is defined).
02412 
02413   Magic tag
02414     A cross-check field that should always hold same value as mparams.magic.
02415 
02416   Flags
02417     Bits recording whether to use MMAP, locks, or contiguous MORECORE
02418 
02419   Statistics
02420     Each space keeps track of current and maximum system memory
02421     obtained via MORECORE or MMAP.
02422 
02423   Trim support
02424     Fields holding the amount of unused topmost memory that should trigger
02425     timming, and a counter to force periodic scanning to release unused
02426     non-topmost segments.
02427 
02428   Locking
02429     If USE_LOCKS is defined, the "mutex" lock is acquired and released
02430     around every public call using this mspace.
02431 
02432   Extension support
02433     A void* pointer and a size_t field that can be used to help implement
02434     extensions to this malloc.
02435 */
02436 
02437 /* Bin types, widths and sizes */
02438 #define NSMALLBINS        (32U)
02439 #define NTREEBINS         (32U)
02440 #define SMALLBIN_SHIFT    (3U)
02441 #define SMALLBIN_WIDTH    (SIZE_T_ONE << SMALLBIN_SHIFT)
02442 #define TREEBIN_SHIFT     (8U)
02443 #define MIN_LARGE_SIZE    (SIZE_T_ONE << TREEBIN_SHIFT)
02444 #define MAX_SMALL_SIZE    (MIN_LARGE_SIZE - SIZE_T_ONE)
02445 #define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
02446 
02447 struct malloc_state {
02448   binmap_t   smallmap;
02449   binmap_t   treemap;
02450   size_t     dvsize;
02451   size_t     topsize;
02452   char*      least_addr;
02453   mchunkptr  dv;
02454   mchunkptr  top;
02455   size_t     trim_check;
02456   size_t     release_checks;
02457   size_t     magic;
02458   mchunkptr  smallbins[(NSMALLBINS+1)*2];
02459   tbinptr    treebins[NTREEBINS];
02460   size_t     footprint;
02461   size_t     max_footprint;
02462   flag_t     mflags;
02463 #if USE_LOCKS
02464   MLOCK_T    mutex;     /* locate lock among fields that rarely change */
02465 #endif /* USE_LOCKS */
02466   msegment   seg;
02467   void*      extp;      /* Unused but available for extensions */
02468   size_t     exts;
02469 };
02470 
02471 typedef struct malloc_state*    mstate;
02472 
02473 /* ------------- Global malloc_state and malloc_params ------------------- */
02474 
02475 /*
02476   malloc_params holds global properties, including those that can be
02477   dynamically set using mallopt. There is a single instance, mparams,
02478   initialized in init_mparams. Note that the non-zeroness of "magic"
02479   also serves as an initialization flag.
02480 */
02481 
02482 struct malloc_params {
02483   volatile size_t magic;
02484   size_t page_size;
02485   size_t granularity;
02486   size_t mmap_threshold;
02487   size_t trim_threshold;
02488   flag_t default_mflags;
02489 };
02490 
02491 static struct malloc_params mparams;
02492 
02493 /* Ensure mparams initialized */
02494 #define ensure_initialization() (void)(mparams.magic != 0 || init_mparams())
02495 
02496 #if !ONLY_MSPACES
02497 
02498 /* The global malloc_state used for all non-"mspace" calls */
02499 static struct malloc_state _gm_;
02500 #define gm                 (&_gm_)
02501 #define is_global(M)       ((M) == &_gm_)
02502 
02503 #endif /* !ONLY_MSPACES */
02504 
02505 #define is_initialized(M)  ((M)->top != 0)
02506 
02507 /* -------------------------- system alloc setup ------------------------- */
02508 
02509 /* Operations on mflags */
02510 
02511 #define use_lock(M)           ((M)->mflags &   USE_LOCK_BIT)
02512 #define enable_lock(M)        ((M)->mflags |=  USE_LOCK_BIT)
02513 #define disable_lock(M)       ((M)->mflags &= ~USE_LOCK_BIT)
02514 
02515 #define use_mmap(M)           ((M)->mflags &   USE_MMAP_BIT)
02516 #define enable_mmap(M)        ((M)->mflags |=  USE_MMAP_BIT)
02517 #define disable_mmap(M)       ((M)->mflags &= ~USE_MMAP_BIT)
02518 
02519 #define use_noncontiguous(M)  ((M)->mflags &   USE_NONCONTIGUOUS_BIT)
02520 #define disable_contiguous(M) ((M)->mflags |=  USE_NONCONTIGUOUS_BIT)
02521 
02522 #define set_lock(M,L)\
02523  ((M)->mflags = (L)?\
02524   ((M)->mflags | USE_LOCK_BIT) :\
02525   ((M)->mflags & ~USE_LOCK_BIT))
02526 
02527 /* page-align a size */
02528 #define page_align(S)\
02529  (((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE))
02530 
02531 /* granularity-align a size */
02532 #define granularity_align(S)\
02533   (((S) + (mparams.granularity - SIZE_T_ONE))\
02534    & ~(mparams.granularity - SIZE_T_ONE))
02535 
02536 
02537 /* For mmap, use granularity alignment on windows, else page-align */
02538 #ifdef WIN32
02539 #define mmap_align(S) granularity_align(S)
02540 #else
02541 #define mmap_align(S) page_align(S)
02542 #endif
02543 
02544 /* For sys_alloc, enough padding to ensure can malloc request on success */
02545 #define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT)
02546 
02547 #define is_page_aligned(S)\
02548    (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
02549 #define is_granularity_aligned(S)\
02550    (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
02551 
02552 /*  True if segment S holds address A */
02553 #define segment_holds(S, A)\
02554   ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
02555 
02556 /* Return segment holding given address */
02557 static msegmentptr segment_holding(mstate m, char* addr) {
02558   msegmentptr sp = &m->seg;
02559   for (;;) {
02560     if (addr >= sp->base && addr < sp->base + sp->size)
02561       return sp;
02562     if ((sp = sp->next) == 0)
02563       return 0;
02564   }
02565 }
02566 
02567 /* Return true if segment contains a segment link */
02568 static int has_segment_link(mstate m, msegmentptr ss) {
02569   msegmentptr sp = &m->seg;
02570   for (;;) {
02571     if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
02572       return 1;
02573     if ((sp = sp->next) == 0)
02574       return 0;
02575   }
02576 }
02577 
02578 #ifndef MORECORE_CANNOT_TRIM
02579 #define should_trim(M,s)  ((s) > (M)->trim_check)
02580 #else  /* MORECORE_CANNOT_TRIM */
02581 #define should_trim(M,s)  (0)
02582 #endif /* MORECORE_CANNOT_TRIM */
02583 
02584 /*
02585   TOP_FOOT_SIZE is padding at the end of a segment, including space
02586   that may be needed to place segment records and fenceposts when new
02587   noncontiguous segments are added.
02588 */
02589 #define TOP_FOOT_SIZE\
02590   (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
02591 
02592 
02593 /* -------------------------------  Hooks -------------------------------- */
02594 
02595 /*
02596   PREACTION should be defined to return 0 on success, and nonzero on
02597   failure. If you are not using locking, you can redefine these to do
02598   anything you like.
02599 */
02600 
02601 #if USE_LOCKS
02602 
02603 #define PREACTION(M)  ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
02604 #define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
02605 #else /* USE_LOCKS */
02606 
02607 #ifndef PREACTION
02608 #define PREACTION(M) (0)
02609 #endif  /* PREACTION */
02610 
02611 #ifndef POSTACTION
02612 #define POSTACTION(M)
02613 #endif  /* POSTACTION */
02614 
02615 #endif /* USE_LOCKS */
02616 
02617 /*
02618   CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
02619   USAGE_ERROR_ACTION is triggered on detected bad frees and
02620   reallocs. The argument p is an address that might have triggered the
02621   fault. It is ignored by the two predefined actions, but might be
02622   useful in custom actions that try to help diagnose errors.
02623 */
02624 
02625 #if PROCEED_ON_ERROR
02626 
02627 /* A count of the number of corruption errors causing resets */
02628 int malloc_corruption_error_count;
02629 
02630 /* default corruption action */
02631 static void reset_on_error(mstate m);
02632 
02633 #define CORRUPTION_ERROR_ACTION(m)  reset_on_error(m)
02634 #define USAGE_ERROR_ACTION(m, p)
02635 
02636 #else /* PROCEED_ON_ERROR */
02637 
02638 #ifndef CORRUPTION_ERROR_ACTION
02639 #define CORRUPTION_ERROR_ACTION(m) ABORT
02640 #endif /* CORRUPTION_ERROR_ACTION */
02641 
02642 #ifndef USAGE_ERROR_ACTION
02643 #define USAGE_ERROR_ACTION(m,p) ABORT
02644 #endif /* USAGE_ERROR_ACTION */
02645 
02646 #endif /* PROCEED_ON_ERROR */
02647 
02648 /* -------------------------- Debugging setup ---------------------------- */
02649 
02650 #if ! DEBUG
02651 
02652 #define check_free_chunk(M,P)
02653 #define check_inuse_chunk(M,P)
02654 #define check_malloced_chunk(M,P,N)
02655 #define check_mmapped_chunk(M,P)
02656 #define check_malloc_state(M)
02657 #define check_top_chunk(M,P)
02658 
02659 #else /* DEBUG */
02660 #define check_free_chunk(M,P)       do_check_free_chunk(M,P)
02661 #define check_inuse_chunk(M,P)      do_check_inuse_chunk(M,P)
02662 #define check_top_chunk(M,P)        do_check_top_chunk(M,P)
02663 #define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
02664 #define check_mmapped_chunk(M,P)    do_check_mmapped_chunk(M,P)
02665 #define check_malloc_state(M)       do_check_malloc_state(M)
02666 
02667 static void   do_check_any_chunk(mstate m, mchunkptr p);
02668 static void   do_check_top_chunk(mstate m, mchunkptr p);
02669 static void   do_check_mmapped_chunk(mstate m, mchunkptr p);
02670 static void   do_check_inuse_chunk(mstate m, mchunkptr p);
02671 static void   do_check_free_chunk(mstate m, mchunkptr p);
02672 static void   do_check_malloced_chunk(mstate m, void* mem, size_t s);
02673 static void   do_check_tree(mstate m, tchunkptr t);
02674 static void   do_check_treebin(mstate m, bindex_t i);
02675 static void   do_check_smallbin(mstate m, bindex_t i);
02676 static void   do_check_malloc_state(mstate m);
02677 static int    bin_find(mstate m, mchunkptr x);
02678 static size_t traverse_and_check(mstate m);
02679 #endif /* DEBUG */
02680 
02681 /* ---------------------------- Indexing Bins ---------------------------- */
02682 
02683 #define is_small(s)         (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
02684 #define small_index(s)      ((s)  >> SMALLBIN_SHIFT)
02685 #define small_index2size(i) ((i)  << SMALLBIN_SHIFT)
02686 #define MIN_SMALL_INDEX     (small_index(MIN_CHUNK_SIZE))
02687 
02688 /* addressing by index. See above about smallbin repositioning */
02689 #define smallbin_at(M, i)   ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
02690 #define treebin_at(M,i)     (&((M)->treebins[i]))
02691 
02692 /* assign tree index for size S to variable I. Use x86 asm if possible  */
02693 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
02694 #define compute_tree_index(S, I)\
02695 {\
02696   unsigned int X = S >> TREEBIN_SHIFT;\
02697   if (X == 0)\
02698     I = 0;\
02699   else if (X > 0xFFFF)\
02700     I = NTREEBINS-1;\
02701   else {\
02702     unsigned int K;\
02703     __asm__("bsrl\t%1, %0\n\t" : "=r" (K) : "g"  (X));\
02704     I =  (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
02705   }\
02706 }
02707 
02708 #elif defined (__INTEL_COMPILER)
02709 #define compute_tree_index(S, I)\
02710 {\
02711   size_t X = S >> TREEBIN_SHIFT;\
02712   if (X == 0)\
02713     I = 0;\
02714   else if (X > 0xFFFF)\
02715     I = NTREEBINS-1;\
02716   else {\
02717     unsigned int K = _bit_scan_reverse (X); \
02718     I =  (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
02719   }\
02720 }
02721 
02722 #elif defined(_MSC_VER) && _MSC_VER>=1300
02723 #define compute_tree_index(S, I)\
02724 {\
02725   size_t X = S >> TREEBIN_SHIFT;\
02726   if (X == 0)\
02727     I = 0;\
02728   else if (X > 0xFFFF)\
02729     I = NTREEBINS-1;\
02730   else {\
02731     unsigned int K;\
02732     _BitScanReverse((DWORD *) &K, X);\
02733     I =  (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
02734   }\
02735 }
02736 
02737 #else /* GNUC */
02738 #define compute_tree_index(S, I)\
02739 {\
02740   size_t X = S >> TREEBIN_SHIFT;\
02741   if (X == 0)\
02742     I = 0;\
02743   else if (X > 0xFFFF)\
02744     I = NTREEBINS-1;\
02745   else {\
02746     unsigned int Y = (unsigned int)X;\
02747     unsigned int N = ((Y - 0x100) >> 16) & 8;\
02748     unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
02749     N += K;\
02750     N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
02751     K = 14 - N + ((Y <<= K) >> 15);\
02752     I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
02753   }\
02754 }
02755 #endif /* GNUC */
02756 
02757 /* Bit representing maximum resolved size in a treebin at i */
02758 #define bit_for_tree_index(i) \
02759    (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
02760 
02761 /* Shift placing maximum resolved bit in a treebin at i as sign bit */
02762 #define leftshift_for_tree_index(i) \
02763    ((i == NTREEBINS-1)? 0 : \
02764     ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
02765 
02766 /* The size of the smallest chunk held in bin with index i */
02767 #define minsize_for_tree_index(i) \
02768    ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) |  \
02769    (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
02770 
02771 
02772 /* ------------------------ Operations on bin maps ----------------------- */
02773 
02774 /* bit corresponding to given index */
02775 #define idx2bit(i)              ((binmap_t)(1) << (i))
02776 
02777 /* Mark/Clear bits with given index */
02778 #define mark_smallmap(M,i)      ((M)->smallmap |=  idx2bit(i))
02779 #define clear_smallmap(M,i)     ((M)->smallmap &= ~idx2bit(i))
02780 #define smallmap_is_marked(M,i) ((M)->smallmap &   idx2bit(i))
02781 
02782 #define mark_treemap(M,i)       ((M)->treemap  |=  idx2bit(i))
02783 #define clear_treemap(M,i)      ((M)->treemap  &= ~idx2bit(i))
02784 #define treemap_is_marked(M,i)  ((M)->treemap  &   idx2bit(i))
02785 
02786 /* isolate the least set bit of a bitmap */
02787 #define least_bit(x)         ((x) & -(x))
02788 
02789 /* mask with all bits to left of least bit of x on */
02790 #define left_bits(x)         ((x<<1) | -(x<<1))
02791 
02792 /* mask with all bits to left of or equal to least bit of x on */
02793 #define same_or_left_bits(x) ((x) | -(x))
02794 
02795 /* index corresponding to given bit. Use x86 asm if possible */
02796 
02797 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
02798 #define compute_bit2idx(X, I)\
02799 {\
02800   unsigned int J;\
02801   __asm__("bsfl\t%1, %0\n\t" : "=r" (J) : "g" (X));\
02802   I = (bindex_t)J;\
02803 }
02804 
02805 #elif defined (__INTEL_COMPILER)
02806 #define compute_bit2idx(X, I)\
02807 {\
02808   unsigned int J;\
02809   J = _bit_scan_forward (X); \
02810   I = (bindex_t)J;\
02811 }
02812 
02813 #elif defined(_MSC_VER) && _MSC_VER>=1300
02814 #define compute_bit2idx(X, I)\
02815 {\
02816   unsigned int J;\
02817   _BitScanForward((DWORD *) &J, X);\
02818   I = (bindex_t)J;\
02819 }
02820 
02821 #elif USE_BUILTIN_FFS
02822 #define compute_bit2idx(X, I) I = ffs(X)-1
02823 
02824 #else
02825 #define compute_bit2idx(X, I)\
02826 {\
02827   unsigned int Y = X - 1;\
02828   unsigned int K = Y >> (16-4) & 16;\
02829   unsigned int N = K;        Y >>= K;\
02830   N += K = Y >> (8-3) &  8;  Y >>= K;\
02831   N += K = Y >> (4-2) &  4;  Y >>= K;\
02832   N += K = Y >> (2-1) &  2;  Y >>= K;\
02833   N += K = Y >> (1-0) &  1;  Y >>= K;\
02834   I = (bindex_t)(N + Y);\
02835 }
02836 #endif /* GNUC */
02837 
02838 
02839 /* ----------------------- Runtime Check Support ------------------------- */
02840 
02841 /*
02842   For security, the main invariant is that malloc/free/etc never
02843   writes to a static address other than malloc_state, unless static
02844   malloc_state itself has been corrupted, which cannot occur via
02845   malloc (because of these checks). In essence this means that we
02846   believe all pointers, sizes, maps etc held in malloc_state, but
02847   check all of those linked or offsetted from other embedded data
02848   structures.  These checks are interspersed with main code in a way
02849   that tends to minimize their run-time cost.
02850 
02851   When FOOTERS is defined, in addition to range checking, we also
02852   verify footer fields of inuse chunks, which can be used guarantee
02853   that the mstate controlling malloc/free is intact.  This is a
02854   streamlined version of the approach described by William Robertson
02855   et al in "Run-time Detection of Heap-based Overflows" LISA'03
02856   http://www.usenix.org/events/lisa03/tech/robertson.html The footer
02857   of an inuse chunk holds the xor of its mstate and a random seed,
02858   that is checked upon calls to free() and realloc().  This is
02859   (probablistically) unguessable from outside the program, but can be
02860   computed by any code successfully malloc'ing any chunk, so does not
02861   itself provide protection against code that has already broken
02862   security through some other means.  Unlike Robertson et al, we
02863   always dynamically check addresses of all offset chunks (previous,
02864   next, etc). This turns out to be cheaper than relying on hashes.
02865 */
02866 
02867 #if !INSECURE
02868 /* Check if address a is at least as high as any from MORECORE or MMAP */
02869 #define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
02870 /* Check if address of next chunk n is higher than base chunk p */
02871 #define ok_next(p, n)    ((char*)(p) < (char*)(n))
02872 /* Check if p has inuse status */
02873 #define ok_inuse(p)     is_inuse(p)
02874 /* Check if p has its pinuse bit on */
02875 #define ok_pinuse(p)     pinuse(p)
02876 
02877 #else /* !INSECURE */
02878 #define ok_address(M, a) (1)
02879 #define ok_next(b, n)    (1)
02880 #define ok_inuse(p)      (1)
02881 #define ok_pinuse(p)     (1)
02882 #endif /* !INSECURE */
02883 
02884 #if (FOOTERS && !INSECURE)
02885 /* Check if (alleged) mstate m has expected magic field */
02886 #define ok_magic(M)      ((M)->magic == mparams.magic)
02887 #else  /* (FOOTERS && !INSECURE) */
02888 #define ok_magic(M)      (1)
02889 #endif /* (FOOTERS && !INSECURE) */
02890 
02891 
02892 /* In gcc, use __builtin_expect to minimize impact of checks */
02893 #if !INSECURE
02894 #if defined(__GNUC__) && __GNUC__ >= 3
02895 #define RTCHECK(e)  __builtin_expect(e, 1)
02896 #else /* GNUC */
02897 #define RTCHECK(e)  (e)
02898 #endif /* GNUC */
02899 #else /* !INSECURE */
02900 #define RTCHECK(e)  (1)
02901 #endif /* !INSECURE */
02902 
02903 /* macros to set up inuse chunks with or without footers */
02904 
02905 #if !FOOTERS
02906 
02907 #define mark_inuse_foot(M,p,s)
02908 
02909 /* Macros for setting head/foot of non-mmapped chunks */
02910 
02911 /* Set cinuse bit and pinuse bit of next chunk */
02912 #define set_inuse(M,p,s)\
02913   ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
02914   ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
02915 
02916 /* Set cinuse and pinuse of this chunk and pinuse of next chunk */
02917 #define set_inuse_and_pinuse(M,p,s)\
02918   ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
02919   ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
02920 
02921 /* Set size, cinuse and pinuse bit of this chunk */
02922 #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
02923   ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
02924 
02925 #else /* FOOTERS */
02926 
02927 /* Set foot of inuse chunk to be xor of mstate and seed */
02928 #define mark_inuse_foot(M,p,s)\
02929   (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
02930 
02931 #define get_mstate_for(p)\
02932   ((mstate)(((mchunkptr)((char*)(p) +\
02933     (chunksize(p))))->prev_foot ^ mparams.magic))
02934 
02935 #define set_inuse(M,p,s)\
02936   ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
02937   (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
02938   mark_inuse_foot(M,p,s))
02939 
02940 #define set_inuse_and_pinuse(M,p,s)\
02941   ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
02942   (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
02943  mark_inuse_foot(M,p,s))
02944 
02945 #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
02946   ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
02947   mark_inuse_foot(M, p, s))
02948 
02949 #endif /* !FOOTERS */
02950 
02951 /* ---------------------------- setting mparams -------------------------- */
02952 
02953 /* Initialize mparams */
02954 static int init_mparams(void) {
02955 #ifdef NEED_GLOBAL_LOCK_INIT
02956   if (malloc_global_mutex_status <= 0)
02957     init_malloc_global_mutex();
02958 #endif
02959 
02960   ACQUIRE_MALLOC_GLOBAL_LOCK();
02961   if (mparams.magic == 0) {
02962     size_t magic;
02963     size_t psize;
02964     size_t gsize;
02965 
02966 #ifndef WIN32
02967     psize = malloc_getpagesize;
02968     gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize);
02969 #else /* WIN32 */
02970     {
02971       SYSTEM_INFO system_info;
02972       GetSystemInfo(&system_info);
02973       psize = system_info.dwPageSize;
02974       gsize = ((DEFAULT_GRANULARITY != 0)?
02975                DEFAULT_GRANULARITY : system_info.dwAllocationGranularity);
02976     }
02977 #endif /* WIN32 */
02978 
02979     /* Sanity-check configuration:
02980        size_t must be unsigned and as wide as pointer type.
02981        ints must be at least 4 bytes.
02982        alignment must be at least 8.
02983        Alignment, min chunk size, and page size must all be powers of 2.
02984     */
02985     if ((sizeof(size_t) != sizeof(char*)) ||
02986         (MAX_SIZE_T < MIN_CHUNK_SIZE)  ||
02987         (sizeof(int) < 4)  ||
02988         (MALLOC_ALIGNMENT < (size_t)8U) ||
02989         ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
02990         ((MCHUNK_SIZE      & (MCHUNK_SIZE-SIZE_T_ONE))      != 0) ||
02991         ((gsize            & (gsize-SIZE_T_ONE))            != 0) ||
02992         ((psize            & (psize-SIZE_T_ONE))            != 0))
02993       ABORT;
02994 
02995     mparams.granularity = gsize;
02996     mparams.page_size = psize;
02997     mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
02998     mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
02999 #if MORECORE_CONTIGUOUS
03000     mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
03001 #else  /* MORECORE_CONTIGUOUS */
03002     mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
03003 #endif /* MORECORE_CONTIGUOUS */
03004 
03005 #if !ONLY_MSPACES
03006     /* Set up lock for main malloc area */
03007     gm->mflags = mparams.default_mflags;
03008     INITIAL_LOCK(&gm->mutex);
03009 #endif
03010 
03011     {
03012 #if USE_DEV_RANDOM
03013       int fd;
03014       unsigned char buf[sizeof(size_t)];
03015       /* Try to use /dev/urandom, else fall back on using time */
03016       if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
03017           read(fd, buf, sizeof(buf)) == sizeof(buf)) {
03018         magic = *((size_t *) buf);
03019         close(fd);
03020       }
03021       else
03022 #endif /* USE_DEV_RANDOM */
03023 #ifdef WIN32
03024         magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U);
03025 #else
03026         magic = (size_t)(time(0) ^ (size_t)0x55555555U);
03027 #endif
03028       magic |= (size_t)8U;    /* ensure nonzero */
03029       magic &= ~(size_t)7U;   /* improve chances of fault for bad values */
03030       mparams.magic = magic;
03031     }
03032   }
03033 
03034   RELEASE_MALLOC_GLOBAL_LOCK();
03035   return 1;
03036 }
03037 
03038 /* support for mallopt */
03039 static int change_mparam(int param_number, int value) {
03040   size_t val;
03041   ensure_initialization();
03042   val = (value == -1)? MAX_SIZE_T : (size_t)value;
03043   switch(param_number) {
03044   case M_TRIM_THRESHOLD:
03045     mparams.trim_threshold = val;
03046     return 1;
03047   case M_GRANULARITY:
03048     if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
03049       mparams.granularity = val;
03050       return 1;
03051     }
03052     else
03053       return 0;
03054   case M_MMAP_THRESHOLD:
03055     mparams.mmap_threshold = val;
03056     return 1;
03057   default:
03058     return 0;
03059   }
03060 }
03061 
03062 #if DEBUG
03063 /* ------------------------- Debugging Support --------------------------- */
03064 
03065 /* Check properties of any chunk, whether free, inuse, mmapped etc  */
03066 static void do_check_any_chunk(mstate m, mchunkptr p) {
03067   assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
03068   assert(ok_address(m, p));
03069 }
03070 
03071 /* Check properties of top chunk */
03072 static void do_check_top_chunk(mstate m, mchunkptr p) {
03073   msegmentptr sp = segment_holding(m, (char*)p);
03074   size_t  sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */
03075   assert(sp != 0);
03076   assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
03077   assert(ok_address(m, p));
03078   assert(sz == m->topsize);
03079   assert(sz > 0);
03080   assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
03081   assert(pinuse(p));
03082   assert(!pinuse(chunk_plus_offset(p, sz)));
03083 }
03084 
03085 /* Check properties of (inuse) mmapped chunks */
03086 static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
03087   size_t  sz = chunksize(p);
03088   size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD);
03089   assert(is_mmapped(p));
03090   assert(use_mmap(m));
03091   assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
03092   assert(ok_address(m, p));
03093   assert(!is_small(sz));
03094   assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
03095   assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
03096   assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
03097 }
03098 
03099 /* Check properties of inuse chunks */
03100 static void do_check_inuse_chunk(mstate m, mchunkptr p) {
03101   do_check_any_chunk(m, p);
03102   assert(is_inuse(p));
03103   assert(next_pinuse(p));
03104   /* If not pinuse and not mmapped, previous chunk has OK offset */
03105   assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
03106   if (is_mmapped(p))
03107     do_check_mmapped_chunk(m, p);
03108 }
03109 
03110 /* Check properties of free chunks */
03111 static void do_check_free_chunk(mstate m, mchunkptr p) {
03112   size_t sz = chunksize(p);
03113   mchunkptr next = chunk_plus_offset(p, sz);
03114   do_check_any_chunk(m, p);
03115   assert(!is_inuse(p));
03116   assert(!next_pinuse(p));
03117   assert (!is_mmapped(p));
03118   if (p != m->dv && p != m->top) {
03119     if (sz >= MIN_CHUNK_SIZE) {
03120       assert((sz & CHUNK_ALIGN_MASK) == 0);
03121       assert(is_aligned(chunk2mem(p)));
03122       assert(next->prev_foot == sz);
03123       assert(pinuse(p));
03124       assert (next == m->top || is_inuse(next));
03125       assert(p->fd->bk == p);
03126       assert(p->bk->fd == p);
03127     }
03128     else  /* markers are always of size SIZE_T_SIZE */
03129       assert(sz == SIZE_T_SIZE);
03130   }
03131 }
03132 
03133 /* Check properties of malloced chunks at the point they are malloced */
03134 static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
03135   if (mem != 0) {
03136     mchunkptr p = mem2chunk(mem);
03137     size_t sz = p->head & ~INUSE_BITS;
03138     do_check_inuse_chunk(m, p);
03139     assert((sz & CHUNK_ALIGN_MASK) == 0);
03140     assert(sz >= MIN_CHUNK_SIZE);
03141     assert(sz >= s);
03142     /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
03143     assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
03144   }
03145 }
03146 
03147 /* Check a tree and its subtrees.  */
03148 static void do_check_tree(mstate m, tchunkptr t) {
03149   tchunkptr head = 0;
03150   tchunkptr u = t;
03151   bindex_t tindex = t->index;
03152   size_t tsize = chunksize(t);
03153   bindex_t idx;
03154   compute_tree_index(tsize, idx);
03155   assert(tindex == idx);
03156   assert(tsize >= MIN_LARGE_SIZE);
03157   assert(tsize >= minsize_for_tree_index(idx));
03158   assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
03159 
03160   do { /* traverse through chain of same-sized nodes */
03161     do_check_any_chunk(m, ((mchunkptr)u));
03162     assert(u->index == tindex);
03163     assert(chunksize(u) == tsize);
03164     assert(!is_inuse(u));
03165     assert(!next_pinuse(u));
03166     assert(u->fd->bk == u);
03167     assert(u->bk->fd == u);
03168     if (u->parent == 0) {
03169       assert(u->child[0] == 0);
03170       assert(u->child[1] == 0);
03171     }
03172     else {
03173       assert(head == 0); /* only one node on chain has parent */
03174       head = u;
03175       assert(u->parent != u);
03176       assert (u->parent->child[0] == u ||
03177               u->parent->child[1] == u ||
03178               *((tbinptr*)(u->parent)) == u);
03179       if (u->child[0] != 0) {
03180         assert(u->child[0]->parent == u);
03181         assert(u->child[0] != u);
03182         do_check_tree(m, u->child[0]);
03183       }
03184       if (u->child[1] != 0) {
03185         assert(u->child[1]->parent == u);
03186         assert(u->child[1] != u);
03187         do_check_tree(m, u->child[1]);
03188       }
03189       if (u->child[0] != 0 && u->child[1] != 0) {
03190         assert(chunksize(u->child[0]) < chunksize(u->child[1]));
03191       }
03192     }
03193     u = u->fd;
03194   } while (u != t);
03195   assert(head != 0);
03196 }
03197 
03198 /*  Check all the chunks in a treebin.  */
03199 static void do_check_treebin(mstate m, bindex_t i) {
03200   tbinptr* tb = treebin_at(m, i);
03201   tchunkptr t = *tb;
03202   int empty = (m->treemap & (1U << i)) == 0;
03203   if (t == 0)
03204     assert(empty);
03205   if (!empty)
03206     do_check_tree(m, t);
03207 }
03208 
03209 /*  Check all the chunks in a smallbin.  */
03210 static void do_check_smallbin(mstate m, bindex_t i) {
03211   sbinptr b = smallbin_at(m, i);
03212   mchunkptr p = b->bk;
03213   unsigned int empty = (m->smallmap & (1U << i)) == 0;
03214   if (p == b)
03215     assert(empty);
03216   if (!empty) {
03217     for (; p != b; p = p->bk) {
03218       size_t size = chunksize(p);
03219       mchunkptr q;
03220       /* each chunk claims to be free */
03221       do_check_free_chunk(m, p);
03222       /* chunk belongs in bin */
03223       assert(small_index(size) == i);
03224       assert(p->bk == b || chunksize(p->bk) == chunksize(p));
03225       /* chunk is followed by an inuse chunk */
03226       q = next_chunk(p);
03227       if (q->head != FENCEPOST_HEAD)
03228         do_check_inuse_chunk(m, q);
03229     }
03230   }
03231 }
03232 
03233 /* Find x in a bin. Used in other check functions. */
03234 static int bin_find(mstate m, mchunkptr x) {
03235   size_t size = chunksize(x);
03236   if (is_small(size)) {
03237     bindex_t sidx = small_index(size);
03238     sbinptr b = smallbin_at(m, sidx);
03239     if (smallmap_is_marked(m, sidx)) {
03240       mchunkptr p = b;
03241       do {
03242         if (p == x)
03243           return 1;
03244       } while ((p = p->fd) != b);
03245     }
03246   }
03247   else {
03248     bindex_t tidx;
03249     compute_tree_index(size, tidx);
03250     if (treemap_is_marked(m, tidx)) {
03251       tchunkptr t = *treebin_at(m, tidx);
03252       size_t sizebits = size << leftshift_for_tree_index(tidx);
03253       while (t != 0 && chunksize(t) != size) {
03254         t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
03255         sizebits <<= 1;
03256       }
03257       if (t != 0) {
03258         tchunkptr u = t;
03259         do {
03260           if (u == (tchunkptr)x)
03261             return 1;
03262         } while ((u = u->fd) != t);
03263       }
03264     }
03265   }
03266   return 0;
03267 }
03268 
03269 /* Traverse each chunk and check it; return total */
03270 static size_t traverse_and_check(mstate m) {
03271   size_t sum = 0;
03272   if (is_initialized(m)) {
03273     msegmentptr s = &m->seg;
03274     sum += m->topsize + TOP_FOOT_SIZE;
03275     while (s != 0) {
03276       mchunkptr q = align_as_chunk(s->base);
03277       mchunkptr lastq = 0;
03278       assert(pinuse(q));
03279       while (segment_holds(s, q) &&
03280              q != m->top && q->head != FENCEPOST_HEAD) {
03281         sum += chunksize(q);
03282         if (is_inuse(q)) {
03283           assert(!bin_find(m, q));
03284           do_check_inuse_chunk(m, q);
03285         }
03286         else {
03287           assert(q == m->dv || bin_find(m, q));
03288           assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */
03289           do_check_free_chunk(m, q);
03290         }
03291         lastq = q;
03292         q = next_chunk(q);
03293       }
03294       s = s->next;
03295     }
03296   }
03297   return sum;
03298 }
03299 
03300 /* Check all properties of malloc_state. */
03301 static void do_check_malloc_state(mstate m) {
03302   bindex_t i;
03303   size_t total;
03304   /* check bins */
03305   for (i = 0; i < NSMALLBINS; ++i)
03306     do_check_smallbin(m, i);
03307   for (i = 0; i < NTREEBINS; ++i)
03308     do_check_treebin(m, i);
03309 
03310   if (m->dvsize != 0) { /* check dv chunk */
03311     do_check_any_chunk(m, m->dv);
03312     assert(m->dvsize == chunksize(m->dv));
03313     assert(m->dvsize >= MIN_CHUNK_SIZE);
03314     assert(bin_find(m, m->dv) == 0);
03315   }
03316 
03317   if (m->top != 0) {   /* check top chunk */
03318     do_check_top_chunk(m, m->top);
03319     /*assert(m->topsize == chunksize(m->top)); redundant */
03320     assert(m->topsize > 0);
03321     assert(bin_find(m, m->top) == 0);
03322   }
03323 
03324   total = traverse_and_check(m);
03325   assert(total <= m->footprint);
03326   assert(m->footprint <= m->max_footprint);
03327 }
03328 #endif /* DEBUG */
03329 
03330 /* ----------------------------- statistics ------------------------------ */
03331 
03332 #if !NO_MALLINFO
03333 static struct mallinfo internal_mallinfo(mstate m) {
03334   struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
03335   ensure_initialization();
03336   if (!PREACTION(m)) {
03337     check_malloc_state(m);
03338     if (is_initialized(m)) {
03339       size_t nfree = SIZE_T_ONE; /* top always free */
03340       size_t mfree = m->topsize + TOP_FOOT_SIZE;
03341       size_t sum = mfree;
03342       msegmentptr s = &m->seg;
03343       while (s != 0) {
03344         mchunkptr q = align_as_chunk(s->base);
03345         while (segment_holds(s, q) &&
03346                q != m->top && q->head != FENCEPOST_HEAD) {
03347           size_t sz = chunksize(q);
03348           sum += sz;
03349           if (!is_inuse(q)) {
03350             mfree += sz;
03351             ++nfree;
03352           }
03353           q = next_chunk(q);
03354         }
03355         s = s->next;
03356       }
03357 
03358       nm.arena    = sum;
03359       nm.ordblks  = nfree;
03360       nm.hblkhd   = m->footprint - sum;
03361       nm.usmblks  = m->max_footprint;
03362       nm.uordblks = m->footprint - mfree;
03363       nm.fordblks = mfree;
03364       nm.keepcost = m->topsize;
03365     }
03366 
03367     POSTACTION(m);
03368   }
03369   return nm;
03370 }
03371 #endif /* !NO_MALLINFO */
03372 
03373 static void internal_malloc_stats(mstate m) {
03374   ensure_initialization();
03375   if (!PREACTION(m)) {
03376     size_t maxfp = 0;
03377     size_t fp = 0;
03378     size_t used = 0;
03379     check_malloc_state(m);
03380     if (is_initialized(m)) {
03381       msegmentptr s = &m->seg;
03382       maxfp = m->max_footprint;
03383       fp = m->footprint;
03384       used = fp - (m->topsize + TOP_FOOT_SIZE);
03385 
03386       while (s != 0) {
03387         mchunkptr q = align_as_chunk(s->base);
03388         while (segment_holds(s, q) &&
03389                q != m->top && q->head != FENCEPOST_HEAD) {
03390           if (!is_inuse(q))
03391             used -= chunksize(q);
03392           q = next_chunk(q);
03393         }
03394         s = s->next;
03395       }
03396     }
03397 
03398     fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));
03399     fprintf(stderr, "system bytes     = %10lu\n", (unsigned long)(fp));
03400     fprintf(stderr, "in use bytes     = %10lu\n", (unsigned long)(used));
03401 
03402     POSTACTION(m);
03403   }
03404 }
03405 
03406 /* ----------------------- Operations on smallbins ----------------------- */
03407 
03408 /*
03409   Various forms of linking and unlinking are defined as macros.  Even
03410   the ones for trees, which are very long but have very short typical
03411   paths.  This is ugly but reduces reliance on inlining support of
03412   compilers.
03413 */
03414 
03415 /* Link a free chunk into a smallbin  */
03416 #define insert_small_chunk(M, P, S) {\
03417   bindex_t I  = small_index(S);\
03418   mchunkptr B = smallbin_at(M, I);\
03419   mchunkptr F = B;\
03420   assert(S >= MIN_CHUNK_SIZE);\
03421   if (!smallmap_is_marked(M, I))\
03422     mark_smallmap(M, I);\
03423   else if (RTCHECK(ok_address(M, B->fd)))\
03424     F = B->fd;\
03425   else {\
03426     CORRUPTION_ERROR_ACTION(M);\
03427   }\
03428   B->fd = P;\
03429   F->bk = P;\
03430   P->fd = F;\
03431   P->bk = B;\
03432 }
03433 
03434 /* Unlink a chunk from a smallbin  */
03435 #define unlink_small_chunk(M, P, S) {\
03436   mchunkptr F = P->fd;\
03437   mchunkptr B = P->bk;\
03438   bindex_t I = small_index(S);\
03439   assert(P != B);\
03440   assert(P != F);\
03441   assert(chunksize(P) == small_index2size(I));\
03442   if (F == B)\
03443     clear_smallmap(M, I);\
03444   else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
03445                    (B == smallbin_at(M,I) || ok_address(M, B)))) {\
03446     F->bk = B;\
03447     B->fd = F;\
03448   }\
03449   else {\
03450     CORRUPTION_ERROR_ACTION(M);\
03451   }\
03452 }
03453 
03454 /* Unlink the first chunk from a smallbin */
03455 #define unlink_first_small_chunk(M, B, P, I) {\
03456   mchunkptr F = P->fd;\
03457   assert(P != B);\
03458   assert(P != F);\
03459   assert(chunksize(P) == small_index2size(I));\
03460   if (B == F)\
03461     clear_smallmap(M, I);\
03462   else if (RTCHECK(ok_address(M, F))) {\
03463     B->fd = F;\
03464     F->bk = B;\
03465   }\
03466   else {\
03467     CORRUPTION_ERROR_ACTION(M);\
03468   }\
03469 }
03470 
03471 
03472 
03473 /* Replace dv node, binning the old one */
03474 /* Used only when dvsize known to be small */
03475 #define replace_dv(M, P, S) {\
03476   size_t DVS = M->dvsize;\
03477   if (DVS != 0) {\
03478     mchunkptr DV = M->dv;\
03479     assert(is_small(DVS));\
03480     insert_small_chunk(M, DV, DVS);\
03481   }\
03482   M->dvsize = S;\
03483   M->dv = P;\
03484 }
03485 
03486 /* ------------------------- Operations on trees ------------------------- */
03487 
03488 /* Insert chunk into tree */
03489 #define insert_large_chunk(M, X, S) {\
03490   tbinptr* H;\
03491   bindex_t I;\
03492   compute_tree_index(S, I);\
03493   H = treebin_at(M, I);\
03494   X->index = I;\
03495   X->child[0] = X->child[1] = 0;\
03496   if (!treemap_is_marked(M, I)) {\
03497     mark_treemap(M, I);\
03498     *H = X;\
03499     X->parent = (tchunkptr)H;\
03500     X->fd = X->bk = X;\
03501   }\
03502   else {\
03503     tchunkptr T = *H;\
03504     size_t K = S << leftshift_for_tree_index(I);\
03505     for (;;) {\
03506       if (chunksize(T) != S) {\
03507         tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
03508         K <<= 1;\
03509         if (*C != 0)\
03510           T = *C;\
03511         else if (RTCHECK(ok_address(M, C))) {\
03512           *C = X;\
03513           X->parent = T;\
03514           X->fd = X->bk = X;\
03515           break;\
03516         }\
03517         else {\
03518           CORRUPTION_ERROR_ACTION(M);\
03519           break;\
03520         }\
03521       }\
03522       else {\
03523         tchunkptr F = T->fd;\
03524         if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
03525           T->fd = F->bk = X;\
03526           X->fd = F;\
03527           X->bk = T;\
03528           X->parent = 0;\
03529           break;\
03530         }\
03531         else {\
03532           CORRUPTION_ERROR_ACTION(M);\
03533           break;\
03534         }\
03535       }\
03536     }\
03537   }\
03538 }
03539 
03540 /*
03541   Unlink steps:
03542 
03543   1. If x is a chained node, unlink it from its same-sized fd/bk links
03544      and choose its bk node as its replacement.
03545   2. If x was the last node of its size, but not a leaf node, it must
03546      be replaced with a leaf node (not merely one with an open left or
03547      right), to make sure that lefts and rights of descendents
03548      correspond properly to bit masks.  We use the rightmost descendent
03549      of x.  We could use any other leaf, but this is easy to locate and
03550      tends to counteract removal of leftmosts elsewhere, and so keeps
03551      paths shorter than minimally guaranteed.  This doesn't loop much
03552      because on average a node in a tree is near the bottom.
03553   3. If x is the base of a chain (i.e., has parent links) relink
03554      x's parent and children to x's replacement (or null if none).
03555 */
03556 
03557 #define unlink_large_chunk(M, X) {\
03558   tchunkptr XP = X->parent;\
03559   tchunkptr R;\
03560   if (X->bk != X) {\
03561     tchunkptr F = X->fd;\
03562     R = X->bk;\
03563     if (RTCHECK(ok_address(M, F))) {\
03564       F->bk = R;\
03565       R->fd = F;\
03566     }\
03567     else {\
03568       CORRUPTION_ERROR_ACTION(M);\
03569     }\
03570   }\
03571   else {\
03572     tchunkptr* RP;\
03573     if (((R = *(RP = &(X->child[1]))) != 0) ||\
03574         ((R = *(RP = &(X->child[0]))) != 0)) {\
03575       tchunkptr* CP;\
03576       while ((*(CP = &(R->child[1])) != 0) ||\
03577              (*(CP = &(R->child[0])) != 0)) {\
03578         R = *(RP = CP);\
03579       }\
03580       if (RTCHECK(ok_address(M, RP)))\
03581         *RP = 0;\
03582       else {\
03583         CORRUPTION_ERROR_ACTION(M);\
03584       }\
03585     }\
03586   }\
03587   if (XP != 0) {\
03588     tbinptr* H = treebin_at(M, X->index);\
03589     if (X == *H) {\
03590       if ((*H = R) == 0) \
03591         clear_treemap(M, X->index);\
03592     }\
03593     else if (RTCHECK(ok_address(M, XP))) {\
03594       if (XP->child[0] == X) \
03595         XP->child[0] = R;\
03596       else \
03597         XP->child[1] = R;\
03598     }\
03599     else\
03600       CORRUPTION_ERROR_ACTION(M);\
03601     if (R != 0) {\
03602       if (RTCHECK(ok_address(M, R))) {\
03603         tchunkptr C0, C1;\
03604         R->parent = XP;\
03605         if ((C0 = X->child[0]) != 0) {\
03606           if (RTCHECK(ok_address(M, C0))) {\
03607             R->child[0] = C0;\
03608             C0->parent = R;\
03609           }\
03610           else\
03611             CORRUPTION_ERROR_ACTION(M);\
03612         }\
03613         if ((C1 = X->child[1]) != 0) {\
03614           if (RTCHECK(ok_address(M, C1))) {\
03615             R->child[1] = C1;\
03616             C1->parent = R;\
03617           }\
03618           else\
03619             CORRUPTION_ERROR_ACTION(M);\
03620         }\
03621       }\
03622       else\
03623         CORRUPTION_ERROR_ACTION(M);\
03624     }\
03625   }\
03626 }
03627 
03628 /* Relays to large vs small bin operations */
03629 
03630 #define insert_chunk(M, P, S)\
03631   if (is_small(S)) insert_small_chunk(M, P, S)\
03632   else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
03633 
03634 #define unlink_chunk(M, P, S)\
03635   if (is_small(S)) unlink_small_chunk(M, P, S)\
03636   else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
03637 
03638 
03639 /* Relays to internal calls to malloc/free from realloc, memalign etc */
03640 
03641 #if ONLY_MSPACES
03642 #define internal_malloc(m, b) mspace_malloc(m, b)
03643 #define internal_free(m, mem) mspace_free(m,mem);
03644 #else /* ONLY_MSPACES */
03645 #if MSPACES
03646 #define internal_malloc(m, b)\
03647    (m == gm)? dlmalloc(b) : mspace_malloc(m, b)
03648 #define internal_free(m, mem)\
03649    if (m == gm) dlfree(mem); else mspace_free(m,mem);
03650 #else /* MSPACES */
03651 #define internal_malloc(m, b) dlmalloc(b)
03652 #define internal_free(m, mem) dlfree(mem)
03653 #endif /* MSPACES */
03654 #endif /* ONLY_MSPACES */
03655 
03656 /* -----------------------  Direct-mmapping chunks ----------------------- */
03657 
03658 /*
03659   Directly mmapped chunks are set up with an offset to the start of
03660   the mmapped region stored in the prev_foot field of the chunk. This
03661   allows reconstruction of the required argument to MUNMAP when freed,
03662   and also allows adjustment of the returned chunk to meet alignment
03663   requirements (especially in memalign).
03664 */
03665 
03666 /* Malloc using mmap */
03667 static void* mmap_alloc(mstate m, size_t nb) {
03668   size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
03669   if (mmsize > nb) {     /* Check for wrap around 0 */
03670     char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));
03671     if (mm != CMFAIL) {
03672       size_t offset = align_offset(chunk2mem(mm));
03673       size_t psize = mmsize - offset - MMAP_FOOT_PAD;
03674       mchunkptr p = (mchunkptr)(mm + offset);
03675       p->prev_foot = offset;
03676       p->head = psize;
03677       mark_inuse_foot(m, p, psize);
03678       chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
03679       chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
03680 
03681       if (m->least_addr == 0 || mm < m->least_addr)
03682         m->least_addr = mm;
03683       if ((m->footprint += mmsize) > m->max_footprint)
03684         m->max_footprint = m->footprint;
03685       assert(is_aligned(chunk2mem(p)));
03686       check_mmapped_chunk(m, p);
03687       return chunk2mem(p);
03688     }
03689   }
03690   return 0;
03691 }
03692 
03693 /* Realloc using mmap */
03694 static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) {
03695   size_t oldsize = chunksize(oldp);
03696   if (is_small(nb)) /* Can't shrink mmap regions below small size */
03697     return 0;
03698   /* Keep old chunk if big enough but not too big */
03699   if (oldsize >= nb + SIZE_T_SIZE &&
03700       (oldsize - nb) <= (mparams.granularity << 1))
03701     return oldp;
03702   else {
03703     size_t offset = oldp->prev_foot;
03704     size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
03705     size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
03706     char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
03707                                   oldmmsize, newmmsize, 1);
03708     if (cp != CMFAIL) {
03709       mchunkptr newp = (mchunkptr)(cp + offset);
03710       size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
03711       newp->head = psize;
03712       mark_inuse_foot(m, newp, psize);
03713       chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
03714       chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
03715 
03716       if (cp < m->least_addr)
03717         m->least_addr = cp;
03718       if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
03719         m->max_footprint = m->footprint;
03720       check_mmapped_chunk(m, newp);
03721       return newp;
03722     }
03723   }
03724   return 0;
03725 }
03726 
03727 /* -------------------------- mspace management -------------------------- */
03728 
03729 /* Initialize top chunk and its size */
03730 static void init_top(mstate m, mchunkptr p, size_t psize) {
03731   /* Ensure alignment */
03732   size_t offset = align_offset(chunk2mem(p));
03733   p = (mchunkptr)((char*)p + offset);
03734   psize -= offset;
03735 
03736   m->top = p;
03737   m->topsize = psize;
03738   p->head = psize | PINUSE_BIT;
03739   /* set size of fake trailing chunk holding overhead space only once */
03740   chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
03741   m->trim_check = mparams.trim_threshold; /* reset on each update */
03742 }
03743 
03744 /* Initialize bins for a new mstate that is otherwise zeroed out */
03745 static void init_bins(mstate m) {
03746   /* Establish circular links for smallbins */
03747   bindex_t i;
03748   for (i = 0; i < NSMALLBINS; ++i) {
03749     sbinptr bin = smallbin_at(m,i);
03750     bin->fd = bin->bk = bin;
03751   }
03752 }
03753 
03754 #if PROCEED_ON_ERROR
03755 
03756 /* default corruption action */
03757 static void reset_on_error(mstate m) {
03758   int i;
03759   ++malloc_corruption_error_count;
03760   /* Reinitialize fields to forget about all memory */
03761   m->smallbins = m->treebins = 0;
03762   m->dvsize = m->topsize = 0;
03763   m->seg.base = 0;
03764   m->seg.size = 0;
03765   m->seg.next = 0;
03766   m->top = m->dv = 0;
03767   for (i = 0; i < NTREEBINS; ++i)
03768     *treebin_at(m, i) = 0;
03769   init_bins(m);
03770 }
03771 #endif /* PROCEED_ON_ERROR */
03772 
03773 /* Allocate chunk and prepend remainder with chunk in successor base. */
03774 static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
03775                            size_t nb) {
03776   mchunkptr p = align_as_chunk(newbase);
03777   mchunkptr oldfirst = align_as_chunk(oldbase);
03778   size_t psize = (char*)oldfirst - (char*)p;
03779   mchunkptr q = chunk_plus_offset(p, nb);
03780   size_t qsize = psize - nb;
03781   set_size_and_pinuse_of_inuse_chunk(m, p, nb);
03782 
03783   assert((char*)oldfirst > (char*)q);
03784   assert(pinuse(oldfirst));
03785   assert(qsize >= MIN_CHUNK_SIZE);
03786 
03787   /* consolidate remainder with first chunk of old base */
03788   if (oldfirst == m->top) {
03789     size_t tsize = m->topsize += qsize;
03790     m->top = q;
03791     q->head = tsize | PINUSE_BIT;
03792     check_top_chunk(m, q);
03793   }
03794   else if (oldfirst == m->dv) {
03795     size_t dsize = m->dvsize += qsize;
03796     m->dv = q;
03797     set_size_and_pinuse_of_free_chunk(q, dsize);
03798   }
03799   else {
03800     if (!is_inuse(oldfirst)) {
03801       size_t nsize = chunksize(oldfirst);
03802       unlink_chunk(m, oldfirst, nsize);
03803       oldfirst = chunk_plus_offset(oldfirst, nsize);
03804       qsize += nsize;
03805     }
03806     set_free_with_pinuse(q, qsize, oldfirst);
03807     insert_chunk(m, q, qsize);
03808     check_free_chunk(m, q);
03809   }
03810 
03811   check_malloced_chunk(m, chunk2mem(p), nb);
03812   return chunk2mem(p);
03813 }
03814 
03815 /* Add a segment to hold a new noncontiguous region */
03816 static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
03817   /* Determine locations and sizes of segment, fenceposts, old top */
03818   char* old_top = (char*)m->top;
03819   msegmentptr oldsp = segment_holding(m, old_top);
03820   char* old_end = oldsp->base + oldsp->size;
03821   size_t ssize = pad_request(sizeof(struct malloc_segment));
03822   char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
03823   size_t offset = align_offset(chunk2mem(rawsp));
03824   char* asp = rawsp + offset;
03825   char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
03826   mchunkptr sp = (mchunkptr)csp;
03827   msegmentptr ss = (msegmentptr)(chunk2mem(sp));
03828   mchunkptr tnext = chunk_plus_offset(sp, ssize);
03829   mchunkptr p = tnext;
03830   int nfences = 0;
03831 
03832   /* reset top to new space */
03833   init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
03834 
03835   /* Set up segment record */
03836   assert(is_aligned(ss));
03837   set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
03838   *ss = m->seg; /* Push current record */
03839   m->seg.base = tbase;
03840   m->seg.size = tsize;
03841   m->seg.sflags = mmapped;
03842   m->seg.next = ss;
03843 
03844   /* Insert trailing fenceposts */
03845   for (;;) {
03846     mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
03847     p->head = FENCEPOST_HEAD;
03848     ++nfences;
03849     if ((char*)(&(nextp->head)) < old_end)
03850       p = nextp;
03851     else
03852       break;
03853   }
03854   assert(nfences >= 2);
03855 
03856   /* Insert the rest of old top into a bin as an ordinary free chunk */
03857   if (csp != old_top) {
03858     mchunkptr q = (mchunkptr)old_top;
03859     size_t psize = csp - old_top;
03860     mchunkptr tn = chunk_plus_offset(q, psize);
03861     set_free_with_pinuse(q, psize, tn);
03862     insert_chunk(m, q, psize);
03863   }
03864 
03865   check_top_chunk(m, m->top);
03866 }
03867 
03868 /* -------------------------- System allocation -------------------------- */
03869 
03870 /* Get memory from system using MORECORE or MMAP */
03871 static void* sys_alloc(mstate m, size_t nb) {
03872   char* tbase = CMFAIL;
03873   size_t tsize = 0;
03874   flag_t mmap_flag = 0;
03875 
03876   ensure_initialization();
03877 
03878   /* Directly map large chunks, but only if already initialized */
03879   if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) {
03880     void* mem = mmap_alloc(m, nb);
03881     if (mem != 0)
03882       return mem;
03883   }
03884 
03885   /*
03886     Try getting memory in any of three ways (in most-preferred to
03887     least-preferred order):
03888     1. A call to MORECORE that can normally contiguously extend memory.
03889        (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
03890        or main space is mmapped or a previous contiguous call failed)
03891     2. A call to MMAP new space (disabled if not HAVE_MMAP).
03892        Note that under the default settings, if MORECORE is unable to
03893        fulfill a request, and HAVE_MMAP is true, then mmap is
03894        used as a noncontiguous system allocator. This is a useful backup
03895        strategy for systems with holes in address spaces -- in this case
03896        sbrk cannot contiguously expand the heap, but mmap may be able to
03897        find space.
03898     3. A call to MORECORE that cannot usually contiguously extend memory.
03899        (disabled if not HAVE_MORECORE)
03900 
03901    In all cases, we need to request enough bytes from system to ensure
03902    we can malloc nb bytes upon success, so pad with enough space for
03903    top_foot, plus alignment-pad to make sure we don't lose bytes if
03904    not on boundary, and round this up to a granularity unit.
03905   */
03906 
03907   if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
03908     char* br = CMFAIL;
03909     msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
03910     size_t asize = 0;
03911     ACQUIRE_MALLOC_GLOBAL_LOCK();
03912 
03913     if (ss == 0) {  /* First time through or recovery */
03914       char* base = (char*)CALL_MORECORE(0);
03915       if (base != CMFAIL) {
03916         asize = granularity_align(nb + SYS_ALLOC_PADDING);
03917         /* Adjust to end on a page boundary */
03918         if (!is_page_aligned(base))
03919           asize += (page_align((size_t)base) - (size_t)base);
03920         /* Can't call MORECORE if size is negative when treated as signed */
03921         if (asize < HALF_MAX_SIZE_T &&
03922             (br = (char*)(CALL_MORECORE(asize))) == base) {
03923           tbase = base;
03924           tsize = asize;
03925         }
03926       }
03927     }
03928     else {
03929       /* Subtract out existing available top space from MORECORE request. */
03930       asize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING);
03931       /* Use mem here only if it did continuously extend old space */
03932       if (asize < HALF_MAX_SIZE_T &&
03933           (br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) {
03934         tbase = br;
03935         tsize = asize;
03936       }
03937     }
03938 
03939     if (tbase == CMFAIL) {    /* Cope with partial failure */
03940       if (br != CMFAIL) {    /* Try to use/extend the space we did get */
03941         if (asize < HALF_MAX_SIZE_T &&
03942             asize < nb + SYS_ALLOC_PADDING) {
03943           size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - asize);
03944           if (esize < HALF_MAX_SIZE_T) {
03945             char* end = (char*)CALL_MORECORE(esize);
03946             if (end != CMFAIL)
03947               asize += esize;
03948             else {            /* Can't use; try to release */
03949               (void) CALL_MORECORE(-asize);
03950               br = CMFAIL;
03951             }
03952           }
03953         }
03954       }
03955       if (br != CMFAIL) {    /* Use the space we did get */
03956         tbase = br;
03957         tsize = asize;
03958       }
03959       else
03960         disable_contiguous(m); /* Don't try contiguous path in the future */
03961     }
03962 
03963     RELEASE_MALLOC_GLOBAL_LOCK();
03964   }
03965 
03966   if (HAVE_MMAP && tbase == CMFAIL) {  /* Try MMAP */
03967     size_t rsize = granularity_align(nb + SYS_ALLOC_PADDING);
03968     if (rsize > nb) { /* Fail if wraps around zero */
03969       char* mp = (char*)(CALL_MMAP(rsize));
03970       if (mp != CMFAIL) {
03971         tbase = mp;
03972         tsize = rsize;
03973         mmap_flag = USE_MMAP_BIT;
03974       }
03975     }
03976   }
03977 
03978   if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
03979     size_t asize = granularity_align(nb + SYS_ALLOC_PADDING);
03980     if (asize < HALF_MAX_SIZE_T) {
03981       char* br = CMFAIL;
03982       char* end = CMFAIL;
03983       ACQUIRE_MALLOC_GLOBAL_LOCK();
03984       br = (char*)(CALL_MORECORE(asize));
03985       end = (char*)(CALL_MORECORE(0));
03986       RELEASE_MALLOC_GLOBAL_LOCK();
03987       if (br != CMFAIL && end != CMFAIL && br < end) {
03988         size_t ssize = end - br;
03989         if (ssize > nb + TOP_FOOT_SIZE) {
03990           tbase = br;
03991           tsize = ssize;
03992         }
03993       }
03994     }
03995   }
03996 
03997   if (tbase != CMFAIL) {
03998 
03999     if ((m->footprint += tsize) > m->max_footprint)
04000       m->max_footprint = m->footprint;
04001 
04002     if (!is_initialized(m)) { /* first-time initialization */
04003       if (m->least_addr == 0 || tbase < m->least_addr)
04004         m->least_addr = tbase;
04005       m->seg.base = tbase;
04006       m->seg.size = tsize;
04007       m->seg.sflags = mmap_flag;
04008       m->magic = mparams.magic;
04009       m->release_checks = MAX_RELEASE_CHECK_RATE;
04010       init_bins(m);
04011 #if !ONLY_MSPACES
04012       if (is_global(m))
04013         init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
04014       else
04015 #endif
04016       {
04017         /* Offset top by embedded malloc_state */
04018         mchunkptr mn = next_chunk(mem2chunk(m));
04019         init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
04020       }
04021     }
04022 
04023     else {
04024       /* Try to merge with an existing segment */
04025       msegmentptr sp = &m->seg;
04026       /* Only consider most recent segment if traversal suppressed */
04027       while (sp != 0 && tbase != sp->base + sp->size)
04028         sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
04029       if (sp != 0 &&
04030           !is_extern_segment(sp) &&
04031           (sp->sflags & USE_MMAP_BIT) == mmap_flag &&
04032           segment_holds(sp, m->top)) { /* append */
04033         sp->size += tsize;
04034         init_top(m, m->top, m->topsize + tsize);
04035       }
04036       else {
04037         if (tbase < m->least_addr)
04038           m->least_addr = tbase;
04039         sp = &m->seg;
04040         while (sp != 0 && sp->base != tbase + tsize)
04041           sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
04042         if (sp != 0 &&
04043             !is_extern_segment(sp) &&
04044             (sp->sflags & USE_MMAP_BIT) == mmap_flag) {
04045           char* oldbase = sp->base;
04046           sp->base = tbase;
04047           sp->size += tsize;
04048           return prepend_alloc(m, tbase, oldbase, nb);
04049         }
04050         else
04051           add_segment(m, tbase, tsize, mmap_flag);
04052       }
04053     }
04054 
04055     if (nb < m->topsize) { /* Allocate from new or extended top space */
04056       size_t rsize = m->topsize -= nb;
04057       mchunkptr p = m->top;
04058       mchunkptr r = m->top = chunk_plus_offset(p, nb);
04059       r->head = rsize | PINUSE_BIT;
04060       set_size_and_pinuse_of_inuse_chunk(m, p, nb);
04061       check_top_chunk(m, m->top);
04062       check_malloced_chunk(m, chunk2mem(p), nb);
04063       return chunk2mem(p);
04064     }
04065   }
04066 
04067   MALLOC_FAILURE_ACTION;
04068   return 0;
04069 }
04070 
04071 /* -----------------------  system deallocation -------------------------- */
04072 
04073 /* Unmap and unlink any mmapped segments that don't contain used chunks */
04074 static size_t release_unused_segments(mstate m) {
04075   size_t released = 0;
04076   int nsegs = 0;
04077   msegmentptr pred = &m->seg;
04078   msegmentptr sp = pred->next;
04079   while (sp != 0) {
04080     char* base = sp->base;
04081     size_t size = sp->size;
04082     msegmentptr next = sp->next;
04083     ++nsegs;
04084     if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
04085       mchunkptr p = align_as_chunk(base);
04086       size_t psize = chunksize(p);
04087       /* Can unmap if first chunk holds entire segment and not pinned */
04088       if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
04089         tchunkptr tp = (tchunkptr)p;
04090         assert(segment_holds(sp, (char*)sp));
04091         if (p == m->dv) {
04092           m->dv = 0;
04093           m->dvsize = 0;
04094         }
04095         else {
04096           unlink_large_chunk(m, tp);
04097         }
04098         if (CALL_MUNMAP(base, size) == 0) {
04099           released += size;
04100           m->footprint -= size;
04101           /* unlink obsoleted record */
04102           sp = pred;
04103           sp->next = next;
04104         }
04105         else { /* back out if cannot unmap */
04106           insert_large_chunk(m, tp, psize);
04107         }
04108       }
04109     }
04110     if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */
04111       break;
04112     pred = sp;
04113     sp = next;
04114   }
04115   /* Reset check counter */
04116   m->release_checks = ((nsegs > MAX_RELEASE_CHECK_RATE)?
04117                        nsegs : MAX_RELEASE_CHECK_RATE);
04118   return released;
04119 }
04120 
04121 static int sys_trim(mstate m, size_t pad) {
04122   size_t released = 0;
04123   ensure_initialization();
04124   if (pad < MAX_REQUEST && is_initialized(m)) {
04125     pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
04126 
04127     if (m->topsize > pad) {
04128       /* Shrink top space in granularity-size units, keeping at least one */
04129       size_t unit = mparams.granularity;
04130       size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
04131                       SIZE_T_ONE) * unit;
04132       msegmentptr sp = segment_holding(m, (char*)m->top);
04133 
04134       if (!is_extern_segment(sp)) {
04135         if (is_mmapped_segment(sp)) {
04136           if (HAVE_MMAP &&
04137               sp->size >= extra &&
04138               !has_segment_link(m, sp)) { /* can't shrink if pinned */
04139             size_t newsize = sp->size - extra;
04140             /* Prefer mremap, fall back to munmap */
04141             if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
04142                 (CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
04143               released = extra;
04144             }
04145           }
04146         }
04147         else if (HAVE_MORECORE) {
04148           if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
04149             extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
04150           ACQUIRE_MALLOC_GLOBAL_LOCK();
04151           {
04152             /* Make sure end of memory is where we last set it. */
04153             char* old_br = (char*)(CALL_MORECORE(0));
04154             if (old_br == sp->base + sp->size) {
04155               char* rel_br = (char*)(CALL_MORECORE(-extra));
04156               char* new_br = (char*)(CALL_MORECORE(0));
04157               if (rel_br != CMFAIL && new_br < old_br)
04158                 released = old_br - new_br;
04159             }
04160           }
04161           RELEASE_MALLOC_GLOBAL_LOCK();
04162         }
04163       }
04164 
04165       if (released != 0) {
04166         sp->size -= released;
04167         m->footprint -= released;
04168         init_top(m, m->top, m->topsize - released);
04169         check_top_chunk(m, m->top);
04170       }
04171     }
04172 
04173     /* Unmap any unused mmapped segments */
04174     if (HAVE_MMAP)
04175       released += release_unused_segments(m);
04176 
04177     /* On failure, disable autotrim to avoid repeated failed future calls */
04178     if (released == 0 && m->topsize > m->trim_check)
04179       m->trim_check = MAX_SIZE_T;
04180   }
04181 
04182   return (released != 0)? 1 : 0;
04183 }
04184 
04185 
04186 /* ---------------------------- malloc support --------------------------- */
04187 
04188 /* allocate a large request from the best fitting chunk in a treebin */
04189 static void* tmalloc_large(mstate m, size_t nb) {
04190   tchunkptr v = 0;
04191   size_t rsize = -nb; /* Unsigned negation */
04192   tchunkptr t;
04193   bindex_t idx;
04194   compute_tree_index(nb, idx);
04195   if ((t = *treebin_at(m, idx)) != 0) {
04196     /* Traverse tree for this bin looking for node with size == nb */
04197     size_t sizebits = nb << leftshift_for_tree_index(idx);
04198     tchunkptr rst = 0;  /* The deepest untaken right subtree */
04199     for (;;) {
04200       tchunkptr rt;
04201       size_t trem = chunksize(t) - nb;
04202       if (trem < rsize) {
04203         v = t;
04204         if ((rsize = trem) == 0)
04205           break;
04206       }
04207       rt = t->child[1];
04208       t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
04209       if (rt != 0 && rt != t)
04210         rst = rt;
04211       if (t == 0) {
04212         t = rst; /* set t to least subtree holding sizes > nb */
04213         break;
04214       }
04215       sizebits <<= 1;
04216     }
04217   }
04218   if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
04219     binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
04220     if (leftbits != 0) {
04221       bindex_t i;
04222       binmap_t leastbit = least_bit(leftbits);
04223       compute_bit2idx(leastbit, i);
04224       t = *treebin_at(m, i);
04225     }
04226   }
04227 
04228   while (t != 0) { /* find smallest of tree or subtree */
04229     size_t trem = chunksize(t) - nb;
04230     if (trem < rsize) {
04231       rsize = trem;
04232       v = t;
04233     }
04234     t = leftmost_child(t);
04235   }
04236 
04237   /*  If dv is a better fit, return 0 so malloc will use it */
04238   if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
04239     if (RTCHECK(ok_address(m, v))) { /* split */
04240       mchunkptr r = chunk_plus_offset(v, nb);
04241       assert(chunksize(v) == rsize + nb);
04242       if (RTCHECK(ok_next(v, r))) {
04243         unlink_large_chunk(m, v);
04244         if (rsize < MIN_CHUNK_SIZE)
04245           set_inuse_and_pinuse(m, v, (rsize + nb));
04246         else {
04247           set_size_and_pinuse_of_inuse_chunk(m, v, nb);
04248           set_size_and_pinuse_of_free_chunk(r, rsize);
04249           insert_chunk(m, r, rsize);
04250         }
04251         return chunk2mem(v);
04252       }
04253     }
04254     CORRUPTION_ERROR_ACTION(m);
04255   }
04256   return 0;
04257 }
04258 
04259 /* allocate a small request from the best fitting chunk in a treebin */
04260 static void* tmalloc_small(mstate m, size_t nb) {
04261   tchunkptr t, v;
04262   size_t rsize;
04263   bindex_t i;
04264   binmap_t leastbit = least_bit(m->treemap);
04265   compute_bit2idx(leastbit, i);
04266   v = t = *treebin_at(m, i);
04267   rsize = chunksize(t) - nb;
04268 
04269   while ((t = leftmost_child(t)) != 0) {
04270     size_t trem = chunksize(t) - nb;
04271     if (trem < rsize) {
04272       rsize = trem;
04273       v = t;
04274     }
04275   }
04276 
04277   if (RTCHECK(ok_address(m, v))) {
04278     mchunkptr r = chunk_plus_offset(v, nb);
04279     assert(chunksize(v) == rsize + nb);
04280     if (RTCHECK(ok_next(v, r))) {
04281       unlink_large_chunk(m, v);
04282       if (rsize < MIN_CHUNK_SIZE)
04283         set_inuse_and_pinuse(m, v, (rsize + nb));
04284       else {
04285         set_size_and_pinuse_of_inuse_chunk(m, v, nb);
04286         set_size_and_pinuse_of_free_chunk(r, rsize);
04287         replace_dv(m, r, rsize);
04288       }
04289       return chunk2mem(v);
04290     }
04291   }
04292 
04293   CORRUPTION_ERROR_ACTION(m);
04294   return 0;
04295 }
04296 
04297 /* --------------------------- realloc support --------------------------- */
04298 
04299 static void* internal_realloc(mstate m, void* oldmem, size_t bytes) {
04300   if (bytes >= MAX_REQUEST) {
04301     MALLOC_FAILURE_ACTION;
04302     return 0;
04303   }
04304   if (!PREACTION(m)) {
04305     mchunkptr oldp = mem2chunk(oldmem);
04306     size_t oldsize = chunksize(oldp);
04307     mchunkptr next = chunk_plus_offset(oldp, oldsize);
04308     mchunkptr newp = 0;
04309     void* extra = 0;
04310 
04311     /* Try to either shrink or extend into top. Else malloc-copy-free */
04312 
04313     if (RTCHECK(ok_address(m, oldp) && ok_inuse(oldp) &&
04314                 ok_next(oldp, next) && ok_pinuse(next))) {
04315       size_t nb = request2size(bytes);
04316       if (is_mmapped(oldp))
04317         newp = mmap_resize(m, oldp, nb);
04318       else if (oldsize >= nb) { /* already big enough */
04319         size_t rsize = oldsize - nb;
04320         newp = oldp;
04321         if (rsize >= MIN_CHUNK_SIZE) {
04322           mchunkptr remainder = chunk_plus_offset(newp, nb);
04323           set_inuse(m, newp, nb);
04324           set_inuse_and_pinuse(m, remainder, rsize);
04325           extra = chunk2mem(remainder);
04326         }
04327       }
04328       else if (next == m->top && oldsize + m->topsize > nb) {
04329         /* Expand into top */
04330         size_t newsize = oldsize + m->topsize;
04331         size_t newtopsize = newsize - nb;
04332         mchunkptr newtop = chunk_plus_offset(oldp, nb);
04333         set_inuse(m, oldp, nb);
04334         newtop->head = newtopsize |PINUSE_BIT;
04335         m->top = newtop;
04336         m->topsize = newtopsize;
04337         newp = oldp;
04338       }
04339     }
04340     else {
04341       USAGE_ERROR_ACTION(m, oldmem);
04342       POSTACTION(m);
04343       return 0;
04344     }
04345 #if DEBUG
04346     if (newp != 0) {
04347       check_inuse_chunk(m, newp); /* Check requires lock */
04348     }
04349 #endif
04350 
04351     POSTACTION(m);
04352 
04353     if (newp != 0) {
04354       if (extra != 0) {
04355         internal_free(m, extra);
04356       }
04357       return chunk2mem(newp);
04358     }
04359     else {
04360       void* newmem = internal_malloc(m, bytes);
04361       if (newmem != 0) {
04362         size_t oc = oldsize - overhead_for(oldp);
04363         memcpy(newmem, oldmem, (oc < bytes)? oc : bytes);
04364         internal_free(m, oldmem);
04365       }
04366       return newmem;
04367     }
04368   }
04369   return 0;
04370 }
04371 
04372 /* --------------------------- memalign support -------------------------- */
04373 
04374 static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
04375   if (alignment <= MALLOC_ALIGNMENT)    /* Can just use malloc */
04376     return internal_malloc(m, bytes);
04377   if (alignment <  MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
04378     alignment = MIN_CHUNK_SIZE;
04379   if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
04380     size_t a = MALLOC_ALIGNMENT << 1;
04381     while (a < alignment) a <<= 1;
04382     alignment = a;
04383   }
04384 
04385   if (bytes >= MAX_REQUEST - alignment) {
04386     if (m != 0)  { /* Test isn't needed but avoids compiler warning */
04387       MALLOC_FAILURE_ACTION;
04388     }
04389   }
04390   else {
04391     size_t nb = request2size(bytes);
04392     size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
04393     char* mem = (char*)internal_malloc(m, req);
04394     if (mem != 0) {
04395       void* leader = 0;
04396       void* trailer = 0;
04397       mchunkptr p = mem2chunk(mem);
04398 
04399       if (PREACTION(m)) return 0;
04400       if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */
04401         /*
04402           Find an aligned spot inside chunk.  Since we need to give
04403           back leading space in a chunk of at least MIN_CHUNK_SIZE, if
04404           the first calculation places us at a spot with less than
04405           MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
04406           We've allocated enough total room so that this is always
04407           possible.
04408         */
04409         char* br = (char*)mem2chunk((size_t)(((size_t)(mem +
04410                                                        alignment -
04411                                                        SIZE_T_ONE)) &
04412                                              -alignment));
04413         char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
04414           br : br+alignment;
04415         mchunkptr newp = (mchunkptr)pos;
04416         size_t leadsize = pos - (char*)(p);
04417         size_t newsize = chunksize(p) - leadsize;
04418 
04419         if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
04420           newp->prev_foot = p->prev_foot + leadsize;
04421           newp->head = newsize;
04422         }
04423         else { /* Otherwise, give back leader, use the rest */
04424           set_inuse(m, newp, newsize);
04425           set_inuse(m, p, leadsize);
04426           leader = chunk2mem(p);
04427         }
04428         p = newp;
04429       }
04430 
04431       /* Give back spare room at the end */
04432       if (!is_mmapped(p)) {
04433         size_t size = chunksize(p);
04434         if (size > nb + MIN_CHUNK_SIZE) {
04435           size_t remainder_size = size - nb;
04436           mchunkptr remainder = chunk_plus_offset(p, nb);
04437           set_inuse(m, p, nb);
04438           set_inuse(m, remainder, remainder_size);
04439           trailer = chunk2mem(remainder);
04440         }
04441       }
04442 
04443       assert (chunksize(p) >= nb);
04444       assert((((size_t)(chunk2mem(p))) % alignment) == 0);
04445       check_inuse_chunk(m, p);
04446       POSTACTION(m);
04447       if (leader != 0) {
04448         internal_free(m, leader);
04449       }
04450       if (trailer != 0) {
04451         internal_free(m, trailer);
04452       }
04453       return chunk2mem(p);
04454     }
04455   }
04456   return 0;
04457 }
04458 
04459 /* ------------------------ comalloc/coalloc support --------------------- */
04460 
04461 static void** ialloc(mstate m,
04462                      size_t n_elements,
04463                      size_t* sizes,
04464                      int opts,
04465                      void* chunks[]) {
04466   /*
04467     This provides common support for independent_X routines, handling
04468     all of the combinations that can result.
04469 
04470     The opts arg has:
04471     bit 0 set if all elements are same size (using sizes[0])
04472     bit 1 set if elements should be zeroed
04473   */
04474 
04475   size_t    element_size;   /* chunksize of each element, if all same */
04476   size_t    contents_size;  /* total size of elements */
04477   size_t    array_size;     /* request size of pointer array */
04478   void*     mem;            /* malloced aggregate space */
04479   mchunkptr p;              /* corresponding chunk */
04480   size_t    remainder_size; /* remaining bytes while splitting */
04481   void**    marray;         /* either "chunks" or malloced ptr array */
04482   mchunkptr array_chunk;    /* chunk for malloced ptr array */
04483   flag_t    was_enabled;    /* to disable mmap */
04484   size_t    size;
04485   size_t    i;
04486 
04487   ensure_initialization();
04488   /* compute array length, if needed */
04489   if (chunks != 0) {
04490     if (n_elements == 0)
04491       return chunks; /* nothing to do */
04492     marray = chunks;
04493     array_size = 0;
04494   }
04495   else {
04496     /* if empty req, must still return chunk representing empty array */
04497     if (n_elements == 0)
04498       return (void**)internal_malloc(m, 0);
04499     marray = 0;
04500     array_size = request2size(n_elements * (sizeof(void*)));
04501   }
04502 
04503   /* compute total element size */
04504   if (opts & 0x1) { /* all-same-size */
04505     element_size = request2size(*sizes);
04506     contents_size = n_elements * element_size;
04507   }
04508   else { /* add up all the sizes */
04509     element_size = 0;
04510     contents_size = 0;
04511     for (i = 0; i != n_elements; ++i)
04512       contents_size += request2size(sizes[i]);
04513   }
04514 
04515   size = contents_size + array_size;
04516 
04517   /*
04518      Allocate the aggregate chunk.  First disable direct-mmapping so
04519      malloc won't use it, since we would not be able to later
04520      free/realloc space internal to a segregated mmap region.
04521   */
04522   was_enabled = use_mmap(m);
04523   disable_mmap(m);
04524   mem = internal_malloc(m, size - CHUNK_OVERHEAD);
04525   if (was_enabled)
04526     enable_mmap(m);
04527   if (mem == 0)
04528     return 0;
04529 
04530   if (PREACTION(m)) return 0;
04531   p = mem2chunk(mem);
04532   remainder_size = chunksize(p);
04533 
04534   assert(!is_mmapped(p));
04535 
04536   if (opts & 0x2) {       /* optionally clear the elements */
04537     memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
04538   }
04539 
04540   /* If not provided, allocate the pointer array as final part of chunk */
04541   if (marray == 0) {
04542     size_t  array_chunk_size;
04543     array_chunk = chunk_plus_offset(p, contents_size);
04544     array_chunk_size = remainder_size - contents_size;
04545     marray = (void**) (chunk2mem(array_chunk));
04546     set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
04547     remainder_size = contents_size;
04548   }
04549 
04550   /* split out elements */
04551   for (i = 0; ; ++i) {
04552     marray[i] = chunk2mem(p);
04553     if (i != n_elements-1) {
04554       if (element_size != 0)
04555         size = element_size;
04556       else
04557         size = request2size(sizes[i]);
04558       remainder_size -= size;
04559       set_size_and_pinuse_of_inuse_chunk(m, p, size);
04560       p = chunk_plus_offset(p, size);
04561     }
04562     else { /* the final element absorbs any overallocation slop */
04563       set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
04564       break;
04565     }
04566   }
04567 
04568 #if DEBUG
04569   if (marray != chunks) {
04570     /* final element must have exactly exhausted chunk */
04571     if (element_size != 0) {
04572       assert(remainder_size == element_size);
04573     }
04574     else {
04575       assert(remainder_size == request2size(sizes[i]));
04576     }
04577     check_inuse_chunk(m, mem2chunk(marray));
04578   }
04579   for (i = 0; i != n_elements; ++i)
04580     check_inuse_chunk(m, mem2chunk(marray[i]));
04581 
04582 #endif /* DEBUG */
04583 
04584   POSTACTION(m);
04585   return marray;
04586 }
04587 
04588 
04589 /* -------------------------- public routines ---------------------------- */
04590 
04591 #if !ONLY_MSPACES
04592 
04593 void* dlmalloc(size_t bytes) {
04594   /*
04595      Basic algorithm:
04596      If a small request (< 256 bytes minus per-chunk overhead):
04597        1. If one exists, use a remainderless chunk in associated smallbin.
04598           (Remainderless means that there are too few excess bytes to
04599           represent as a chunk.)
04600        2. If it is big enough, use the dv chunk, which is normally the
04601           chunk adjacent to the one used for the most recent small request.
04602        3. If one exists, split the smallest available chunk in a bin,
04603           saving remainder in dv.
04604        4. If it is big enough, use the top chunk.
04605        5. If available, get memory from system and use it
04606      Otherwise, for a large request:
04607        1. Find the smallest available binned chunk that fits, and use it
04608           if it is better fitting than dv chunk, splitting if necessary.
04609        2. If better fitting than any binned chunk, use the dv chunk.
04610        3. If it is big enough, use the top chunk.
04611        4. If request size >= mmap threshold, try to directly mmap this chunk.
04612        5. If available, get memory from system and use it
04613 
04614      The ugly goto's here ensure that postaction occurs along all paths.
04615   */
04616 
04617 #if USE_LOCKS
04618   ensure_initialization(); /* initialize in sys_alloc if not using locks */
04619 #endif
04620 
04621   if (!PREACTION(gm)) {
04622     void* mem;
04623     size_t nb;
04624     if (bytes <= MAX_SMALL_REQUEST) {
04625       bindex_t idx;
04626       binmap_t smallbits;
04627       nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
04628       idx = small_index(nb);
04629       smallbits = gm->smallmap >> idx;
04630 
04631       if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
04632         mchunkptr b, p;
04633         idx += ~smallbits & 1;       /* Uses next bin if idx empty */
04634         b = smallbin_at(gm, idx);
04635         p = b->fd;
04636         assert(chunksize(p) == small_index2size(idx));
04637         unlink_first_small_chunk(gm, b, p, idx);
04638         set_inuse_and_pinuse(gm, p, small_index2size(idx));
04639         mem = chunk2mem(p);
04640         check_malloced_chunk(gm, mem, nb);
04641         goto postaction;
04642       }
04643 
04644       else if (nb > gm->dvsize) {
04645         if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
04646           mchunkptr b, p, r;
04647           size_t rsize;
04648           bindex_t i;
04649           binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
04650           binmap_t leastbit = least_bit(leftbits);
04651           compute_bit2idx(leastbit, i);
04652           b = smallbin_at(gm, i);
04653           p = b->fd;
04654           assert(chunksize(p) == small_index2size(i));
04655           unlink_first_small_chunk(gm, b, p, i);
04656           rsize = small_index2size(i) - nb;
04657           /* Fit here cannot be remainderless if 4byte sizes */
04658           if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
04659             set_inuse_and_pinuse(gm, p, small_index2size(i));
04660           else {
04661             set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
04662             r = chunk_plus_offset(p, nb);
04663             set_size_and_pinuse_of_free_chunk(r, rsize);
04664             replace_dv(gm, r, rsize);
04665           }
04666           mem = chunk2mem(p);
04667           check_malloced_chunk(gm, mem, nb);
04668           goto postaction;
04669         }
04670 
04671         else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
04672           check_malloced_chunk(gm, mem, nb);
04673           goto postaction;
04674         }
04675       }
04676     }
04677     else if (bytes >= MAX_REQUEST)
04678       nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
04679     else {
04680       nb = pad_request(bytes);
04681       if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
04682         check_malloced_chunk(gm, mem, nb);
04683         goto postaction;
04684       }
04685     }
04686 
04687     if (nb <= gm->dvsize) {
04688       size_t rsize = gm->dvsize - nb;
04689       mchunkptr p = gm->dv;
04690       if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
04691         mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
04692         gm->dvsize = rsize;
04693         set_size_and_pinuse_of_free_chunk(r, rsize);
04694         set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
04695       }
04696       else { /* exhaust dv */
04697         size_t dvs = gm->dvsize;
04698         gm->dvsize = 0;
04699         gm->dv = 0;
04700         set_inuse_and_pinuse(gm, p, dvs);
04701       }
04702       mem = chunk2mem(p);
04703       check_malloced_chunk(gm, mem, nb);
04704       goto postaction;
04705     }
04706 
04707     else if (nb < gm->topsize) { /* Split top */
04708       size_t rsize = gm->topsize -= nb;
04709       mchunkptr p = gm->top;
04710       mchunkptr r = gm->top = chunk_plus_offset(p, nb);
04711       r->head = rsize | PINUSE_BIT;
04712       set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
04713       mem = chunk2mem(p);
04714       check_top_chunk(gm, gm->top);
04715       check_malloced_chunk(gm, mem, nb);
04716       goto postaction;
04717     }
04718 
04719     mem = sys_alloc(gm, nb);
04720 
04721   postaction:
04722     POSTACTION(gm);
04723     return mem;
04724   }
04725 
04726   return 0;
04727 }
04728 
04729 void dlfree(void* mem) {
04730   /*
04731      Consolidate freed chunks with preceeding or succeeding bordering
04732      free chunks, if they exist, and then place in a bin.  Intermixed
04733      with special cases for top, dv, mmapped chunks, and usage errors.
04734   */
04735 
04736   if (mem != 0) {
04737     mchunkptr p  = mem2chunk(mem);
04738 #if FOOTERS
04739     mstate fm = get_mstate_for(p);
04740     if (!ok_magic(fm)) {
04741       USAGE_ERROR_ACTION(fm, p);
04742       return;
04743     }
04744 #else /* FOOTERS */
04745 #define fm gm
04746 #endif /* FOOTERS */
04747     if (!PREACTION(fm)) {
04748       check_inuse_chunk(fm, p);
04749       if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
04750         size_t psize = chunksize(p);
04751         mchunkptr next = chunk_plus_offset(p, psize);
04752         if (!pinuse(p)) {
04753           size_t prevsize = p->prev_foot;
04754           if (is_mmapped(p)) {
04755             psize += prevsize + MMAP_FOOT_PAD;
04756             if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
04757               fm->footprint -= psize;
04758             goto postaction;
04759           }
04760           else {
04761             mchunkptr prev = chunk_minus_offset(p, prevsize);
04762             psize += prevsize;
04763             p = prev;
04764             if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
04765               if (p != fm->dv) {
04766                 unlink_chunk(fm, p, prevsize);
04767               }
04768               else if ((next->head & INUSE_BITS) == INUSE_BITS) {
04769                 fm->dvsize = psize;
04770                 set_free_with_pinuse(p, psize, next);
04771                 goto postaction;
04772               }
04773             }
04774             else
04775               goto erroraction;
04776           }
04777         }
04778 
04779         if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
04780           if (!cinuse(next)) {  /* consolidate forward */
04781             if (next == fm->top) {
04782               size_t tsize = fm->topsize += psize;
04783               fm->top = p;
04784               p->head = tsize | PINUSE_BIT;
04785               if (p == fm->dv) {
04786                 fm->dv = 0;
04787                 fm->dvsize = 0;
04788               }
04789               if (should_trim(fm, tsize))
04790                 sys_trim(fm, 0);
04791               goto postaction;
04792             }
04793             else if (next == fm->dv) {
04794               size_t dsize = fm->dvsize += psize;
04795               fm->dv = p;
04796               set_size_and_pinuse_of_free_chunk(p, dsize);
04797               goto postaction;
04798             }
04799             else {
04800               size_t nsize = chunksize(next);
04801               psize += nsize;
04802               unlink_chunk(fm, next, nsize);
04803               set_size_and_pinuse_of_free_chunk(p, psize);
04804               if (p == fm->dv) {
04805                 fm->dvsize = psize;
04806                 goto postaction;
04807               }
04808             }
04809           }
04810           else
04811             set_free_with_pinuse(p, psize, next);
04812 
04813           if (is_small(psize)) {
04814             insert_small_chunk(fm, p, psize);
04815             check_free_chunk(fm, p);
04816           }
04817           else {
04818             tchunkptr tp = (tchunkptr)p;
04819             insert_large_chunk(fm, tp, psize);
04820             check_free_chunk(fm, p);
04821             if (--fm->release_checks == 0)
04822               release_unused_segments(fm);
04823           }
04824           goto postaction;
04825         }
04826       }
04827     erroraction:
04828       USAGE_ERROR_ACTION(fm, p);
04829     postaction:
04830       POSTACTION(fm);
04831     }
04832   }
04833 #if !FOOTERS
04834 #undef fm
04835 #endif /* FOOTERS */
04836 }
04837 
04838 void* dlcalloc(size_t n_elements, size_t elem_size) {
04839   void* mem;
04840   size_t req = 0;
04841   if (n_elements != 0) {
04842     req = n_elements * elem_size;
04843     if (((n_elements | elem_size) & ~(size_t)0xffff) &&
04844         (req / n_elements != elem_size))
04845       req = MAX_SIZE_T; /* force downstream failure on overflow */
04846   }
04847   mem = dlmalloc(req);
04848   if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
04849     memset(mem, 0, req);
04850   return mem;
04851 }
04852 
04853 void* dlrealloc(void* oldmem, size_t bytes) {
04854   if (oldmem == 0)
04855     return dlmalloc(bytes);
04856 #ifdef REALLOC_ZERO_BYTES_FREES
04857   if (bytes == 0) {
04858     dlfree(oldmem);
04859     return 0;
04860   }
04861 #endif /* REALLOC_ZERO_BYTES_FREES */
04862   else {
04863 #if ! FOOTERS
04864     mstate m = gm;
04865 #else /* FOOTERS */
04866     mstate m = get_mstate_for(mem2chunk(oldmem));
04867     if (!ok_magic(m)) {
04868       USAGE_ERROR_ACTION(m, oldmem);
04869       return 0;
04870     }
04871 #endif /* FOOTERS */
04872     return internal_realloc(m, oldmem, bytes);
04873   }
04874 }
04875 
04876 void* dlmemalign(size_t alignment, size_t bytes) {
04877   return internal_memalign(gm, alignment, bytes);
04878 }
04879 
04880 void** dlindependent_calloc(size_t n_elements, size_t elem_size,
04881                                  void* chunks[]) {
04882   size_t sz = elem_size; /* serves as 1-element array */
04883   return ialloc(gm, n_elements, &sz, 3, chunks);
04884 }
04885 
04886 void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
04887                                    void* chunks[]) {
04888   return ialloc(gm, n_elements, sizes, 0, chunks);
04889 }
04890 
04891 void* dlvalloc(size_t bytes) {
04892   size_t pagesz;
04893   ensure_initialization();
04894   pagesz = mparams.page_size;
04895   return dlmemalign(pagesz, bytes);
04896 }
04897 
04898 void* dlpvalloc(size_t bytes) {
04899   size_t pagesz;
04900   ensure_initialization();
04901   pagesz = mparams.page_size;
04902   return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
04903 }
04904 
04905 int dlmalloc_trim(size_t pad) {
04906   int result = 0;
04907   ensure_initialization();
04908   if (!PREACTION(gm)) {
04909     result = sys_trim(gm, pad);
04910     POSTACTION(gm);
04911   }
04912   return result;
04913 }
04914 
04915 size_t dlmalloc_footprint(void) {
04916   return gm->footprint;
04917 }
04918 
04919 size_t dlmalloc_max_footprint(void) {
04920   return gm->max_footprint;
04921 }
04922 
04923 #if !NO_MALLINFO
04924 struct mallinfo dlmallinfo(void) {
04925   return internal_mallinfo(gm);
04926 }
04927 #endif /* NO_MALLINFO */
04928 
04929 void dlmalloc_stats() {
04930   internal_malloc_stats(gm);
04931 }
04932 
04933 int dlmallopt(int param_number, int value) {
04934   return change_mparam(param_number, value);
04935 }
04936 
04937 #endif /* !ONLY_MSPACES */
04938 
04939 size_t dlmalloc_usable_size(void* mem) {
04940   if (mem != 0) {
04941     mchunkptr p = mem2chunk(mem);
04942     if (is_inuse(p))
04943       return chunksize(p) - overhead_for(p);
04944   }
04945   return 0;
04946 }
04947 
04948 /* ----------------------------- user mspaces ---------------------------- */
04949 
04950 #if MSPACES
04951 
04952 static mstate init_user_mstate(char* tbase, size_t tsize) {
04953   size_t msize = pad_request(sizeof(struct malloc_state));
04954   mchunkptr mn;
04955   mchunkptr msp = align_as_chunk(tbase);
04956   mstate m = (mstate)(chunk2mem(msp));
04957   memset(m, 0, msize);
04958   INITIAL_LOCK(&m->mutex);
04959   msp->head = (msize|INUSE_BITS);
04960   m->seg.base = m->least_addr = tbase;
04961   m->seg.size = m->footprint = m->max_footprint = tsize;
04962   m->magic = mparams.magic;
04963   m->release_checks = MAX_RELEASE_CHECK_RATE;
04964   m->mflags = mparams.default_mflags;
04965   m->extp = 0;
04966   m->exts = 0;
04967   disable_contiguous(m);
04968   init_bins(m);
04969   mn = next_chunk(mem2chunk(m));
04970   init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
04971   check_top_chunk(m, m->top);
04972   return m;
04973 }
04974 
04975 mspace create_mspace(size_t capacity, int locked) {
04976   mstate m = 0;
04977   size_t msize;
04978   ensure_initialization();
04979   msize = pad_request(sizeof(struct malloc_state));
04980   if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
04981     size_t rs = ((capacity == 0)? mparams.granularity :
04982                  (capacity + TOP_FOOT_SIZE + msize));
04983     size_t tsize = granularity_align(rs);
04984     char* tbase = (char*)(CALL_MMAP(tsize));
04985     if (tbase != CMFAIL) {
04986       m = init_user_mstate(tbase, tsize);
04987       m->seg.sflags = USE_MMAP_BIT;
04988       set_lock(m, locked);
04989     }
04990   }
04991   return (mspace)m;
04992 }
04993 
04994 mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
04995   mstate m = 0;
04996   size_t msize;
04997   ensure_initialization();
04998   msize = pad_request(sizeof(struct malloc_state));
04999   if (capacity > msize + TOP_FOOT_SIZE &&
05000       capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
05001     m = init_user_mstate((char*)base, capacity);
05002     m->seg.sflags = EXTERN_BIT;
05003     set_lock(m, locked);
05004   }
05005   return (mspace)m;
05006 }
05007 
05008 int mspace_track_large_chunks(mspace msp, int enable) {
05009   int ret = 0;
05010   mstate ms = (mstate)msp;
05011   if (!PREACTION(ms)) {
05012     if (!use_mmap(ms))
05013       ret = 1;
05014     if (!enable)
05015       enable_mmap(ms);
05016     else
05017       disable_mmap(ms);
05018     POSTACTION(ms);
05019   }
05020   return ret;
05021 }
05022 
05023 size_t destroy_mspace(mspace msp) {
05024   size_t freed = 0;
05025   mstate ms = (mstate)msp;
05026   if (ok_magic(ms)) {
05027     msegmentptr sp = &ms->seg;
05028     while (sp != 0) {
05029       char* base = sp->base;
05030       size_t size = sp->size;
05031       flag_t flag = sp->sflags;
05032       sp = sp->next;
05033       if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) &&
05034           CALL_MUNMAP(base, size) == 0)
05035         freed += size;
05036     }
05037   }
05038   else {
05039     USAGE_ERROR_ACTION(ms,ms);
05040   }
05041   return freed;
05042 }
05043 
05044 /*
05045   mspace versions of routines are near-clones of the global
05046   versions. This is not so nice but better than the alternatives.
05047 */
05048 
05049 
05050 void* mspace_malloc(mspace msp, size_t bytes) {
05051   mstate ms = (mstate)msp;
05052   if (!ok_magic(ms)) {
05053     USAGE_ERROR_ACTION(ms,ms);
05054     return 0;
05055   }
05056   if (!PREACTION(ms)) {
05057     void* mem;
05058     size_t nb;
05059     if (bytes <= MAX_SMALL_REQUEST) {
05060       bindex_t idx;
05061       binmap_t smallbits;
05062       nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
05063       idx = small_index(nb);
05064       smallbits = ms->smallmap >> idx;
05065 
05066       if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
05067         mchunkptr b, p;
05068         idx += ~smallbits & 1;       /* Uses next bin if idx empty */
05069         b = smallbin_at(ms, idx);
05070         p = b->fd;
05071         assert(chunksize(p) == small_index2size(idx));
05072         unlink_first_small_chunk(ms, b, p, idx);
05073         set_inuse_and_pinuse(ms, p, small_index2size(idx));
05074         mem = chunk2mem(p);
05075         check_malloced_chunk(ms, mem, nb);
05076         goto postaction;
05077       }
05078 
05079       else if (nb > ms->dvsize) {
05080         if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
05081           mchunkptr b, p, r;
05082           size_t rsize;
05083           bindex_t i;
05084           binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
05085           binmap_t leastbit = least_bit(leftbits);
05086           compute_bit2idx(leastbit, i);
05087           b = smallbin_at(ms, i);
05088           p = b->fd;
05089           assert(chunksize(p) == small_index2size(i));
05090           unlink_first_small_chunk(ms, b, p, i);
05091           rsize = small_index2size(i) - nb;
05092           /* Fit here cannot be remainderless if 4byte sizes */
05093           if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
05094             set_inuse_and_pinuse(ms, p, small_index2size(i));
05095           else {
05096             set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
05097             r = chunk_plus_offset(p, nb);
05098             set_size_and_pinuse_of_free_chunk(r, rsize);
05099             replace_dv(ms, r, rsize);
05100           }
05101           mem = chunk2mem(p);
05102           check_malloced_chunk(ms, mem, nb);
05103           goto postaction;
05104         }
05105 
05106         else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
05107           check_malloced_chunk(ms, mem, nb);
05108           goto postaction;
05109         }
05110       }
05111     }
05112     else if (bytes >= MAX_REQUEST)
05113       nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
05114     else {
05115       nb = pad_request(bytes);
05116       if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
05117         check_malloced_chunk(ms, mem, nb);
05118         goto postaction;
05119       }
05120     }
05121 
05122     if (nb <= ms->dvsize) {
05123       size_t rsize = ms->dvsize - nb;
05124       mchunkptr p = ms->dv;
05125       if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
05126         mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
05127         ms->dvsize = rsize;
05128         set_size_and_pinuse_of_free_chunk(r, rsize);
05129         set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
05130       }
05131       else { /* exhaust dv */
05132         size_t dvs = ms->dvsize;
05133         ms->dvsize = 0;
05134         ms->dv = 0;
05135         set_inuse_and_pinuse(ms, p, dvs);
05136       }
05137       mem = chunk2mem(p);
05138       check_malloced_chunk(ms, mem, nb);
05139       goto postaction;
05140     }
05141 
05142     else if (nb < ms->topsize) { /* Split top */
05143       size_t rsize = ms->topsize -= nb;
05144       mchunkptr p = ms->top;
05145       mchunkptr r = ms->top = chunk_plus_offset(p, nb);
05146       r->head = rsize | PINUSE_BIT;
05147       set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
05148       mem = chunk2mem(p);
05149       check_top_chunk(ms, ms->top);
05150       check_malloced_chunk(ms, mem, nb);
05151       goto postaction;
05152     }
05153 
05154     mem = sys_alloc(ms, nb);
05155 
05156   postaction:
05157     POSTACTION(ms);
05158     return mem;
05159   }
05160 
05161   return 0;
05162 }
05163 
05164 void mspace_free(mspace msp, void* mem) {
05165   if (mem != 0) {
05166     mchunkptr p  = mem2chunk(mem);
05167 #if FOOTERS
05168     mstate fm = get_mstate_for(p);
05169     msp = msp; /* placate people compiling -Wunused */
05170 #else /* FOOTERS */
05171     mstate fm = (mstate)msp;
05172 #endif /* FOOTERS */
05173     if (!ok_magic(fm)) {
05174       USAGE_ERROR_ACTION(fm, p);
05175       return;
05176     }
05177     if (!PREACTION(fm)) {
05178       check_inuse_chunk(fm, p);
05179       if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
05180         size_t psize = chunksize(p);
05181         mchunkptr next = chunk_plus_offset(p, psize);
05182         if (!pinuse(p)) {
05183           size_t prevsize = p->prev_foot;
05184           if (is_mmapped(p)) {
05185             psize += prevsize + MMAP_FOOT_PAD;
05186             if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
05187               fm->footprint -= psize;
05188             goto postaction;
05189           }
05190           else {
05191             mchunkptr prev = chunk_minus_offset(p, prevsize);
05192             psize += prevsize;
05193             p = prev;
05194             if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
05195               if (p != fm->dv) {
05196                 unlink_chunk(fm, p, prevsize);
05197               }
05198               else if ((next->head & INUSE_BITS) == INUSE_BITS) {
05199                 fm->dvsize = psize;
05200                 set_free_with_pinuse(p, psize, next);
05201                 goto postaction;
05202               }
05203             }
05204             else
05205               goto erroraction;
05206           }
05207         }
05208 
05209         if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
05210           if (!cinuse(next)) {  /* consolidate forward */
05211             if (next == fm->top) {
05212               size_t tsize = fm->topsize += psize;
05213               fm->top = p;
05214               p->head = tsize | PINUSE_BIT;
05215               if (p == fm->dv) {
05216                 fm->dv = 0;
05217                 fm->dvsize = 0;
05218               }
05219               if (should_trim(fm, tsize))
05220                 sys_trim(fm, 0);
05221               goto postaction;
05222             }
05223             else if (next == fm->dv) {
05224               size_t dsize = fm->dvsize += psize;
05225               fm->dv = p;
05226               set_size_and_pinuse_of_free_chunk(p, dsize);
05227               goto postaction;
05228             }
05229             else {
05230               size_t nsize = chunksize(next);
05231               psize += nsize;
05232               unlink_chunk(fm, next, nsize);
05233               set_size_and_pinuse_of_free_chunk(p, psize);
05234               if (p == fm->dv) {
05235                 fm->dvsize = psize;
05236                 goto postaction;
05237               }
05238             }
05239           }
05240           else
05241             set_free_with_pinuse(p, psize, next);
05242 
05243           if (is_small(psize)) {
05244             insert_small_chunk(fm, p, psize);
05245             check_free_chunk(fm, p);
05246           }
05247           else {
05248             tchunkptr tp = (tchunkptr)p;
05249             insert_large_chunk(fm, tp, psize);
05250             check_free_chunk(fm, p);
05251             if (--fm->release_checks == 0)
05252               release_unused_segments(fm);
05253           }
05254           goto postaction;
05255         }
05256       }
05257     erroraction:
05258       USAGE_ERROR_ACTION(fm, p);
05259     postaction:
05260       POSTACTION(fm);
05261     }
05262   }
05263 }
05264 
05265 void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
05266   void* mem;
05267   size_t req = 0;
05268   mstate ms = (mstate)msp;
05269   if (!ok_magic(ms)) {
05270     USAGE_ERROR_ACTION(ms,ms);
05271     return 0;
05272   }
05273   if (n_elements != 0) {
05274     req = n_elements * elem_size;
05275     if (((n_elements | elem_size) & ~(size_t)0xffff) &&
05276         (req / n_elements != elem_size))
05277       req = MAX_SIZE_T; /* force downstream failure on overflow */
05278   }
05279   mem = internal_malloc(ms, req);
05280   if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
05281     memset(mem, 0, req);
05282   return mem;
05283 }
05284 
05285 void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
05286   if (oldmem == 0)
05287     return mspace_malloc(msp, bytes);
05288 #ifdef REALLOC_ZERO_BYTES_FREES
05289   if (bytes == 0) {
05290     mspace_free(msp, oldmem);
05291     return 0;
05292   }
05293 #endif /* REALLOC_ZERO_BYTES_FREES */
05294   else {
05295 #if FOOTERS
05296     mchunkptr p  = mem2chunk(oldmem);
05297     mstate ms = get_mstate_for(p);
05298 #else /* FOOTERS */
05299     mstate ms = (mstate)msp;
05300 #endif /* FOOTERS */
05301     if (!ok_magic(ms)) {
05302       USAGE_ERROR_ACTION(ms,ms);
05303       return 0;
05304     }
05305     return internal_realloc(ms, oldmem, bytes);
05306   }
05307 }
05308 
05309 void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
05310   mstate ms = (mstate)msp;
05311   if (!ok_magic(ms)) {
05312     USAGE_ERROR_ACTION(ms,ms);
05313     return 0;
05314   }
05315   return internal_memalign(ms, alignment, bytes);
05316 }
05317 
05318 void** mspace_independent_calloc(mspace msp, size_t n_elements,
05319                                  size_t elem_size, void* chunks[]) {
05320   size_t sz = elem_size; /* serves as 1-element array */
05321   mstate ms = (mstate)msp;
05322   if (!ok_magic(ms)) {
05323     USAGE_ERROR_ACTION(ms,ms);
05324     return 0;
05325   }
05326   return ialloc(ms, n_elements, &sz, 3, chunks);
05327 }
05328 
05329 void** mspace_independent_comalloc(mspace msp, size_t n_elements,
05330                                    size_t sizes[], void* chunks[]) {
05331   mstate ms = (mstate)msp;
05332   if (!ok_magic(ms)) {
05333     USAGE_ERROR_ACTION(ms,ms);
05334     return 0;
05335   }
05336   return ialloc(ms, n_elements, sizes, 0, chunks);
05337 }
05338 
05339 int mspace_trim(mspace msp, size_t pad) {
05340   int result = 0;
05341   mstate ms = (mstate)msp;
05342   if (ok_magic(ms)) {
05343     if (!PREACTION(ms)) {
05344       result = sys_trim(ms, pad);
05345       POSTACTION(ms);
05346     }
05347   }
05348   else {
05349     USAGE_ERROR_ACTION(ms,ms);
05350   }
05351   return result;
05352 }
05353 
05354 void mspace_malloc_stats(mspace msp) {
05355   mstate ms = (mstate)msp;
05356   if (ok_magic(ms)) {
05357     internal_malloc_stats(ms);
05358   }
05359   else {
05360     USAGE_ERROR_ACTION(ms,ms);
05361   }
05362 }
05363 
05364 size_t mspace_footprint(mspace msp) {
05365   size_t result = 0;
05366   mstate ms = (mstate)msp;
05367   if (ok_magic(ms)) {
05368     result = ms->footprint;
05369   }
05370   else {
05371     USAGE_ERROR_ACTION(ms,ms);
05372   }
05373   return result;
05374 }
05375 
05376 
05377 size_t mspace_max_footprint(mspace msp) {
05378   size_t result = 0;
05379   mstate ms = (mstate)msp;
05380   if (ok_magic(ms)) {
05381     result = ms->max_footprint;
05382   }
05383   else {
05384     USAGE_ERROR_ACTION(ms,ms);
05385   }
05386   return result;
05387 }
05388 
05389 
05390 #if !NO_MALLINFO
05391 struct mallinfo mspace_mallinfo(mspace msp) {
05392   mstate ms = (mstate)msp;
05393   if (!ok_magic(ms)) {
05394     USAGE_ERROR_ACTION(ms,ms);
05395   }
05396   return internal_mallinfo(ms);
05397 }
05398 #endif /* NO_MALLINFO */
05399 
05400 size_t mspace_usable_size(void* mem) {
05401   if (mem != 0) {
05402     mchunkptr p = mem2chunk(mem);
05403     if (is_inuse(p))
05404       return chunksize(p) - overhead_for(p);
05405   }
05406   return 0;
05407 }
05408 
05409 int mspace_mallopt(int param_number, int value) {
05410   return change_mparam(param_number, value);
05411 }
05412 
05413 #endif /* MSPACES */
05414 
05415 
05416 /* -------------------- Alternative MORECORE functions ------------------- */
05417 
05418 /*
05419   Guidelines for creating a custom version of MORECORE:
05420 
05421   * For best performance, MORECORE should allocate in multiples of pagesize.
05422   * MORECORE may allocate more memory than requested. (Or even less,
05423       but this will usually result in a malloc failure.)
05424   * MORECORE must not allocate memory when given argument zero, but
05425       instead return one past the end address of memory from previous
05426       nonzero call.
05427   * For best performance, consecutive calls to MORECORE with positive
05428       arguments should return increasing addresses, indicating that
05429       space has been contiguously extended.
05430   * Even though consecutive calls to MORECORE need not return contiguous
05431       addresses, it must be OK for malloc'ed chunks to span multiple
05432       regions in those cases where they do happen to be contiguous.
05433   * MORECORE need not handle negative arguments -- it may instead
05434       just return MFAIL when given negative arguments.
05435       Negative arguments are always multiples of pagesize. MORECORE
05436       must not misinterpret negative args as large positive unsigned
05437       args. You can suppress all such calls from even occurring by defining
05438       MORECORE_CANNOT_TRIM,
05439 
05440   As an example alternative MORECORE, here is a custom allocator
05441   kindly contributed for pre-OSX macOS.  It uses virtually but not
05442   necessarily physically contiguous non-paged memory (locked in,
05443   present and won't get swapped out).  You can use it by uncommenting
05444   this section, adding some #includes, and setting up the appropriate
05445   defines above:
05446 
05447       #define MORECORE osMoreCore
05448 
05449   There is also a shutdown routine that should somehow be called for
05450   cleanup upon program exit.
05451 
05452   #define MAX_POOL_ENTRIES 100
05453   #define MINIMUM_MORECORE_SIZE  (64 * 1024U)
05454   static int next_os_pool;
05455   void *our_os_pools[MAX_POOL_ENTRIES];
05456 
05457   void *osMoreCore(int size)
05458   {
05459     void *ptr = 0;
05460     static void *sbrk_top = 0;
05461 
05462     if (size > 0)
05463     {
05464       if (size < MINIMUM_MORECORE_SIZE)
05465          size = MINIMUM_MORECORE_SIZE;
05466       if (CurrentExecutionLevel() == kTaskLevel)
05467          ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
05468       if (ptr == 0)
05469       {
05470         return (void *) MFAIL;
05471       }
05472       // save ptrs so they can be freed during cleanup
05473       our_os_pools[next_os_pool] = ptr;
05474       next_os_pool++;
05475       ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
05476       sbrk_top = (char *) ptr + size;
05477       return ptr;
05478     }
05479     else if (size < 0)
05480     {
05481       // we don't currently support shrink behavior
05482       return (void *) MFAIL;
05483     }
05484     else
05485     {
05486       return sbrk_top;
05487     }
05488   }
05489 
05490   // cleanup any allocated memory pools
05491   // called as last thing before shutting down driver
05492 
05493   void osCleanupMem(void)
05494   {
05495     void **ptr;
05496 
05497     for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
05498       if (*ptr)
05499       {
05500          PoolDeallocate(*ptr);
05501          *ptr = 0;
05502       }
05503   }
05504 
05505 */
05506 
05507 
05508 /* -----------------------------------------------------------------------
05509 History:
05510     V2.8.4 Wed May 27 09:56:23 2009  Doug Lea  (dl at gee)
05511       * Use zeros instead of prev foot for is_mmapped
05512       * Add mspace_track_large_chunks; thanks to Jean Brouwers
05513       * Fix set_inuse in internal_realloc; thanks to Jean Brouwers
05514       * Fix insufficient sys_alloc padding when using 16byte alignment
05515       * Fix bad error check in mspace_footprint
05516       * Adaptations for ptmalloc; thanks to Wolfram Gloger.
05517       * Reentrant spin locks; thanks to Earl Chew and others
05518       * Win32 improvements; thanks to Niall Douglas and Earl Chew
05519       * Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options
05520       * Extension hook in malloc_state
05521       * Various small adjustments to reduce warnings on some compilers
05522       * Various configuration extensions/changes for more platforms. Thanks
05523          to all who contributed these.
05524 
05525     V2.8.3 Thu Sep 22 11:16:32 2005  Doug Lea  (dl at gee)
05526       * Add max_footprint functions
05527       * Ensure all appropriate literals are size_t
05528       * Fix conditional compilation problem for some #define settings
05529       * Avoid concatenating segments with the one provided
05530         in create_mspace_with_base
05531       * Rename some variables to avoid compiler shadowing warnings
05532       * Use explicit lock initialization.
05533       * Better handling of sbrk interference.
05534       * Simplify and fix segment insertion, trimming and mspace_destroy
05535       * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
05536       * Thanks especially to Dennis Flanagan for help on these.
05537 
05538     V2.8.2 Sun Jun 12 16:01:10 2005  Doug Lea  (dl at gee)
05539       * Fix memalign brace error.
05540 
05541     V2.8.1 Wed Jun  8 16:11:46 2005  Doug Lea  (dl at gee)
05542       * Fix improper #endif nesting in C++
05543       * Add explicit casts needed for C++
05544 
05545     V2.8.0 Mon May 30 14:09:02 2005  Doug Lea  (dl at gee)
05546       * Use trees for large bins
05547       * Support mspaces
05548       * Use segments to unify sbrk-based and mmap-based system allocation,
05549         removing need for emulation on most platforms without sbrk.
05550       * Default safety checks
05551       * Optional footer checks. Thanks to William Robertson for the idea.
05552       * Internal code refactoring
05553       * Incorporate suggestions and platform-specific changes.
05554         Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
05555         Aaron Bachmann,  Emery Berger, and others.
05556       * Speed up non-fastbin processing enough to remove fastbins.
05557       * Remove useless cfree() to avoid conflicts with other apps.
05558       * Remove internal memcpy, memset. Compilers handle builtins better.
05559       * Remove some options that no one ever used and rename others.
05560 
05561     V2.7.2 Sat Aug 17 09:07:30 2002  Doug Lea  (dl at gee)
05562       * Fix malloc_state bitmap array misdeclaration
05563 
05564     V2.7.1 Thu Jul 25 10:58:03 2002  Doug Lea  (dl at gee)
05565       * Allow tuning of FIRST_SORTED_BIN_SIZE
05566       * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
05567       * Better detection and support for non-contiguousness of MORECORE.
05568         Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
05569       * Bypass most of malloc if no frees. Thanks To Emery Berger.
05570       * Fix freeing of old top non-contiguous chunk im sysmalloc.
05571       * Raised default trim and map thresholds to 256K.
05572       * Fix mmap-related #defines. Thanks to Lubos Lunak.
05573       * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
05574       * Branch-free bin calculation
05575       * Default trim and mmap thresholds now 256K.
05576 
05577     V2.7.0 Sun Mar 11 14:14:06 2001  Doug Lea  (dl at gee)
05578       * Introduce independent_comalloc and independent_calloc.
05579         Thanks to Michael Pachos for motivation and help.
05580       * Make optional .h file available
05581       * Allow > 2GB requests on 32bit systems.
05582       * new WIN32 sbrk, mmap, munmap, lock code from <Walter@GeNeSys-e.de>.
05583         Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
05584         and Anonymous.
05585       * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
05586         helping test this.)
05587       * memalign: check alignment arg
05588       * realloc: don't try to shift chunks backwards, since this
05589         leads to  more fragmentation in some programs and doesn't
05590         seem to help in any others.
05591       * Collect all cases in malloc requiring system memory into sysmalloc
05592       * Use mmap as backup to sbrk
05593       * Place all internal state in malloc_state
05594       * Introduce fastbins (although similar to 2.5.1)
05595       * Many minor tunings and cosmetic improvements
05596       * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
05597       * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
05598         Thanks to Tony E. Bennett <tbennett@nvidia.com> and others.
05599       * Include errno.h to support default failure action.
05600 
05601     V2.6.6 Sun Dec  5 07:42:19 1999  Doug Lea  (dl at gee)
05602       * return null for negative arguments
05603       * Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
05604          * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
05605           (e.g. WIN32 platforms)
05606          * Cleanup header file inclusion for WIN32 platforms
05607          * Cleanup code to avoid Microsoft Visual C++ compiler complaints
05608          * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
05609            memory allocation routines
05610          * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
05611          * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
05612            usage of 'assert' in non-WIN32 code
05613          * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
05614            avoid infinite loop
05615       * Always call 'fREe()' rather than 'free()'
05616 
05617     V2.6.5 Wed Jun 17 15:57:31 1998  Doug Lea  (dl at gee)
05618       * Fixed ordering problem with boundary-stamping
05619 
05620     V2.6.3 Sun May 19 08:17:58 1996  Doug Lea  (dl at gee)
05621       * Added pvalloc, as recommended by H.J. Liu
05622       * Added 64bit pointer support mainly from Wolfram Gloger
05623       * Added anonymously donated WIN32 sbrk emulation
05624       * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
05625       * malloc_extend_top: fix mask error that caused wastage after
05626         foreign sbrks
05627       * Add linux mremap support code from HJ Liu
05628 
05629     V2.6.2 Tue Dec  5 06:52:55 1995  Doug Lea  (dl at gee)
05630       * Integrated most documentation with the code.
05631       * Add support for mmap, with help from
05632         Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
05633       * Use last_remainder in more cases.
05634       * Pack bins using idea from  colin@nyx10.cs.du.edu
05635       * Use ordered bins instead of best-fit threshhold
05636       * Eliminate block-local decls to simplify tracing and debugging.
05637       * Support another case of realloc via move into top
05638       * Fix error occuring when initial sbrk_base not word-aligned.
05639       * Rely on page size for units instead of SBRK_UNIT to
05640         avoid surprises about sbrk alignment conventions.
05641       * Add mallinfo, mallopt. Thanks to Raymond Nijssen
05642         (raymond@es.ele.tue.nl) for the suggestion.
05643       * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
05644       * More precautions for cases where other routines call sbrk,
05645         courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
05646       * Added macros etc., allowing use in linux libc from
05647         H.J. Lu (hjl@gnu.ai.mit.edu)
05648       * Inverted this history list
05649 
05650     V2.6.1 Sat Dec  2 14:10:57 1995  Doug Lea  (dl at gee)
05651       * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
05652       * Removed all preallocation code since under current scheme
05653         the work required to undo bad preallocations exceeds
05654         the work saved in good cases for most test programs.
05655       * No longer use return list or unconsolidated bins since
05656         no scheme using them consistently outperforms those that don't
05657         given above changes.
05658       * Use best fit for very large chunks to prevent some worst-cases.
05659       * Added some support for debugging
05660 
05661     V2.6.0 Sat Nov  4 07:05:23 1995  Doug Lea  (dl at gee)
05662       * Removed footers when chunks are in use. Thanks to
05663         Paul Wilson (wilson@cs.texas.edu) for the suggestion.
05664 
05665     V2.5.4 Wed Nov  1 07:54:51 1995  Doug Lea  (dl at gee)
05666       * Added malloc_trim, with help from Wolfram Gloger
05667         (wmglo@Dent.MED.Uni-Muenchen.DE).
05668 
05669     V2.5.3 Tue Apr 26 10:16:01 1994  Doug Lea  (dl at g)
05670 
05671     V2.5.2 Tue Apr  5 16:20:40 1994  Doug Lea  (dl at g)
05672       * realloc: try to expand in both directions
05673       * malloc: swap order of clean-bin strategy;
05674       * realloc: only conditionally expand backwards
05675       * Try not to scavenge used bins
05676       * Use bin counts as a guide to preallocation
05677       * Occasionally bin return list chunks in first scan
05678       * Add a few optimizations from colin@nyx10.cs.du.edu
05679 
05680     V2.5.1 Sat Aug 14 15:40:43 1993  Doug Lea  (dl at g)
05681       * faster bin computation & slightly different binning
05682       * merged all consolidations to one part of malloc proper
05683          (eliminating old malloc_find_space & malloc_clean_bin)
05684       * Scan 2 returns chunks (not just 1)
05685       * Propagate failure in realloc if malloc returns 0
05686       * Add stuff to allow compilation on non-ANSI compilers
05687           from kpv@research.att.com
05688 
05689     V2.5 Sat Aug  7 07:41:59 1993  Doug Lea  (dl at g.oswego.edu)
05690       * removed potential for odd address access in prev_chunk
05691       * removed dependency on getpagesize.h
05692       * misc cosmetics and a bit more internal documentation
05693       * anticosmetics: mangled names in macros to evade debugger strangeness
05694       * tested on sparc, hp-700, dec-mips, rs6000
05695           with gcc & native cc (hp, dec only) allowing
05696           Detlefs & Zorn comparison study (in SIGPLAN Notices.)
05697 
05698     Trial version Fri Aug 28 13:14:29 1992  Doug Lea  (dl at g.oswego.edu)
05699       * Based loosely on libg++-1.2X malloc. (It retains some of the overall
05700          structure of old version,  but most details differ.)
05701 
05702 */
05703 


libicr
Author(s): Robert Krug
autogenerated on Mon Jan 6 2014 11:32:37