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