Path: blob/master/waterbox/libc/functions/_dlmalloc/dlmalloc.c
2 views
/*1This is a version (aka dlmalloc) of malloc/free/realloc written by2Doug Lea and released to the public domain, as explained at3http://creativecommons.org/publicdomain/zero/1.0/ Send questions,4comments, complaints, performance data, etc to [email protected]56* Version 2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee)78Note: There may be an updated version of this malloc obtainable at9ftp://gee.cs.oswego.edu/pub/misc/malloc.c10Check before installing!1112* Quickstart1314This library is all in one file to simplify the most common usage:15ftp it, compile it (-O3), and link it into another program. All of16the compile-time options default to reasonable values for use on17most platforms. You might later want to step through various18compile-time and dynamic tuning options.1920For convenience, an include file for code using this malloc is at:21ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.5.h22You don't really need this .h file unless you call functions not23defined in your system include files. The .h file contains only the24excerpts from this file needed for using this malloc on ANSI C/C++25systems, so long as you haven't changed compile-time options about26naming and tuning parameters. If you do, then you can create your27own malloc.h that does include all settings by cutting at the point28indicated below. Note that you may already by default be using a C29library containing a malloc that is based on some version of this30malloc (for example in linux). You might still want to use the one31in this file to customize settings or to avoid overheads associated32with library versions.3334* Vital statistics:3536Supported pointer/size_t representation: 4 or 8 bytes37size_t MUST be an unsigned type of the same width as38pointers. (If you are using an ancient system that declares39size_t as a signed type, or need it to be a different width40than pointers, you can use a previous release of this malloc41(e.g. 2.7.2) supporting these.)4243Alignment: 8 bytes (default)44This suffices for nearly all current machines and C compilers.45However, you can define MALLOC_ALIGNMENT to be wider than this46if necessary (up to 128bytes), at the expense of using more space.4748Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)498 or 16 bytes (if 8byte sizes)50Each malloced chunk has a hidden word of overhead holding size51and status information, and additional cross-check word52if FOOTERS is defined.5354Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)558-byte ptrs: 32 bytes (including overhead)5657Even a request for zero bytes (i.e., malloc(0)) returns a58pointer to something of the minimum allocatable size.59The maximum overhead wastage (i.e., number of extra bytes60allocated than were requested in malloc) is less than or equal61to the minimum size, except for requests >= mmap_threshold that62are serviced via mmap(), where the worst case wastage is about6332 bytes plus the remainder from a system page (the minimal64mmap unit); typically 4096 or 8192 bytes.6566Security: static-safe; optionally more or less67The "security" of malloc refers to the ability of malicious68code to accentuate the effects of errors (for example, freeing69space that is not currently malloc'ed or overwriting past the70ends of chunks) in code that calls malloc. This malloc71guarantees not to modify any memory locations below the base of72heap, i.e., static variables, even in the presence of usage73errors. The routines additionally detect most improper frees74and reallocs. All this holds as long as the static bookkeeping75for malloc itself is not corrupted by some other means. This76is only one aspect of security -- these checks do not, and77cannot, detect all possible programming errors.7879If FOOTERS is defined nonzero, then each allocated chunk80carries an additional check word to verify that it was malloced81from its space. These check words are the same within each82execution of a program using malloc, but differ across83executions, so externally crafted fake chunks cannot be84freed. This improves security by rejecting frees/reallocs that85could corrupt heap memory, in addition to the checks preventing86writes to statics that are always on. This may further improve87security at the expense of time and space overhead. (Note that88FOOTERS may also be worth using with MSPACES.)8990By default detected errors cause the program to abort (calling91"abort()"). You can override this to instead proceed past92errors by defining PROCEED_ON_ERROR. In this case, a bad free93has no effect, and a malloc that encounters a bad address94caused by user overwrites will ignore the bad address by95dropping pointers and indices to all known memory. This may96be appropriate for programs that should continue if at all97possible in the face of programming errors, although they may98run out of memory because dropped memory is never reclaimed.99100If you don't like either of these options, you can define101CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything102else. And if if you are sure that your program using malloc has103no errors or vulnerabilities, you can define INSECURE to 1,104which might (or might not) provide a small performance improvement.105106It is also possible to limit the maximum total allocatable107space, using malloc_set_footprint_limit. This is not108designed as a security feature in itself (calls to set limits109are not screened or privileged), but may be useful as one110aspect of a secure implementation.111112Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero113When USE_LOCKS is defined, each public call to malloc, free,114etc is surrounded with a lock. By default, this uses a plain115pthread mutex, win32 critical section, or a spin-lock if if116available for the platform and not disabled by setting117USE_SPIN_LOCKS=0. However, if USE_RECURSIVE_LOCKS is defined,118recursive versions are used instead (which are not required for119base functionality but may be needed in layered extensions).120Using a global lock is not especially fast, and can be a major121bottleneck. It is designed only to provide minimal protection122in concurrent environments, and to provide a basis for123extensions. If you are using malloc in a concurrent program,124consider instead using nedmalloc125(http://www.nedprod.com/programs/portable/nedmalloc/) or126ptmalloc (See http://www.malloc.de), which are derived from127versions of this malloc.128129System requirements: Any combination of MORECORE and/or MMAP/MUNMAP130This malloc can use unix sbrk or any emulation (invoked using131the CALL_MORECORE macro) and/or mmap/munmap or any emulation132(invoked using CALL_MMAP/CALL_MUNMAP) to get and release system133memory. On most unix systems, it tends to work best if both134MORECORE and MMAP are enabled. On Win32, it uses emulations135based on VirtualAlloc. It also uses common C library functions136like memset.137138Compliance: I believe it is compliant with the Single Unix Specification139(See http://www.unix.org). Also SVID/XPG, ANSI C, and probably140others as well.141142* Overview of algorithms143144This is not the fastest, most space-conserving, most portable, or145most tunable malloc ever written. However it is among the fastest146while also being among the most space-conserving, portable and147tunable. Consistent balance across these factors results in a good148general-purpose allocator for malloc-intensive programs.149150In most ways, this malloc is a best-fit allocator. Generally, it151chooses the best-fitting existing chunk for a request, with ties152broken in approximately least-recently-used order. (This strategy153normally maintains low fragmentation.) However, for requests less154than 256bytes, it deviates from best-fit when there is not an155exactly fitting available chunk by preferring to use space adjacent156to that used for the previous small request, as well as by breaking157ties in approximately most-recently-used order. (These enhance158locality of series of small allocations.) And for very large requests159(>= 256Kb by default), it relies on system memory mapping160facilities, if supported. (This helps avoid carrying around and161possibly fragmenting memory used only for large chunks.)162163All operations (except malloc_stats and mallinfo) have execution164times that are bounded by a constant factor of the number of bits in165a size_t, not counting any clearing in calloc or copying in realloc,166or actions surrounding MORECORE and MMAP that have times167proportional to the number of non-contiguous regions returned by168system allocation routines, which is often just 1. In real-time169applications, you can optionally suppress segment traversals using170NO_SEGMENT_TRAVERSAL, which assures bounded execution even when171system allocators return non-contiguous spaces, at the typical172expense of carrying around more memory and increased fragmentation.173174The implementation is not very modular and seriously overuses175macros. Perhaps someday all C compilers will do as good a job176inlining modular code as can now be done by brute-force expansion,177but now, enough of them seem not to.178179Some compilers issue a lot of warnings about code that is180dead/unreachable only on some platforms, and also about intentional181uses of negation on unsigned types. All known cases of each can be182ignored.183184For a longer but out of date high-level description, see185http://gee.cs.oswego.edu/dl/html/malloc.html186187* MSPACES188If MSPACES is defined, then in addition to malloc, free, etc.,189this file also defines mspace_malloc, mspace_free, etc. These190are versions of malloc routines that take an "mspace" argument191obtained using create_mspace, to control all internal bookkeeping.192If ONLY_MSPACES is defined, only these versions are compiled.193So if you would like to use this allocator for only some allocations,194and your system malloc for others, you can compile with195ONLY_MSPACES and then do something like...196static mspace mymspace = create_mspace(0,0); // for example197#define mymalloc(bytes) mspace_malloc(mymspace, bytes)198199(Note: If you only need one instance of an mspace, you can instead200use "USE_DL_PREFIX" to relabel the global malloc.)201202You can similarly create thread-local allocators by storing203mspaces as thread-locals. For example:204static __thread mspace tlms = 0;205void* tlmalloc(size_t bytes) {206if (tlms == 0) tlms = create_mspace(0, 0);207return mspace_malloc(tlms, bytes);208}209void tlfree(void* mem) { mspace_free(tlms, mem); }210211Unless FOOTERS is defined, each mspace is completely independent.212You cannot allocate from one and free to another (although213conformance is only weakly checked, so usage errors are not always214caught). If FOOTERS is defined, then each chunk carries around a tag215indicating its originating mspace, and frees are directed to their216originating spaces. Normally, this requires use of locks.217218------------------------- Compile-time options ---------------------------219220Be careful in setting #define values for numerical constants of type221size_t. On some systems, literal values are not automatically extended222to size_t precision unless they are explicitly casted. You can also223use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.224225WIN32 default: defined if _WIN32 defined226Defining WIN32 sets up defaults for MS environment and compilers.227Otherwise defaults are for unix. Beware that there seem to be some228cases where this malloc might not be a pure drop-in replacement for229Win32 malloc: Random-looking failures from Win32 GDI API's (eg;230SetDIBits()) may be due to bugs in some video driver implementations231when pixel buffers are malloc()ed, and the region spans more than232one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb)233default granularity, pixel buffers may straddle virtual allocation234regions more often than when using the Microsoft allocator. You can235avoid this by using VirtualAlloc() and VirtualFree() for all pixel236buffers rather than using malloc(). If this is not possible,237recompile this malloc with a larger DEFAULT_GRANULARITY. Note:238in cases where MSC and gcc (cygwin) are known to differ on WIN32,239conditions use _MSC_VER to distinguish them.240241DLMALLOC_EXPORT default: extern242Defines how public APIs are declared. If you want to export via a243Windows DLL, you might define this as244#define DLMALLOC_EXPORT extern __declspace(dllexport)245If you want a POSIX ELF shared object, you might use246#define DLMALLOC_EXPORT extern __attribute__((visibility("default")))247248MALLOC_ALIGNMENT default: (size_t)8249Controls the minimum alignment for malloc'ed chunks. It must be a250power of two and at least 8, even on machines for which smaller251alignments would suffice. It may be defined as larger than this252though. Note however that code and data structures are optimized for253the case of 8-byte alignment.254255MSPACES default: 0 (false)256If true, compile in support for independent allocation spaces.257This is only supported if HAVE_MMAP is true.258259ONLY_MSPACES default: 0 (false)260If true, only compile in mspace versions, not regular versions.261262USE_LOCKS default: 0 (false)263Causes each call to each public routine to be surrounded with264pthread or WIN32 mutex lock/unlock. (If set true, this can be265overridden on a per-mspace basis for mspace versions.) If set to a266non-zero value other than 1, locks are used, but their267implementation is left out, so lock functions must be supplied manually,268as described below.269270USE_SPIN_LOCKS default: 1 iff USE_LOCKS and spin locks available271If true, uses custom spin locks for locking. This is currently272supported only gcc >= 4.1, older gccs on x86 platforms, and recent273MS compilers. Otherwise, posix locks or win32 critical sections are274used.275276USE_RECURSIVE_LOCKS default: not defined277If defined nonzero, uses recursive (aka reentrant) locks, otherwise278uses plain mutexes. This is not required for malloc proper, but may279be needed for layered allocators such as nedmalloc.280281FOOTERS default: 0282If true, provide extra checking and dispatching by placing283information in the footers of allocated chunks. This adds284space and time overhead.285286INSECURE default: 0287If true, omit checks for usage errors and heap space overwrites.288289USE_DL_PREFIX default: NOT defined290Causes compiler to prefix all public routines with the string 'dl'.291This can be useful when you only want to use this malloc in one part292of a program, using your regular system malloc elsewhere.293294MALLOC_INSPECT_ALL default: NOT defined295If defined, compiles malloc_inspect_all and mspace_inspect_all, that296perform traversal of all heap space. Unless access to these297functions is otherwise restricted, you probably do not want to298include them in secure implementations.299300ABORT default: defined as abort()301Defines how to abort on failed checks. On most systems, a failed302check cannot die with an "assert" or even print an informative303message, because the underlying print routines in turn call malloc,304which will fail again. Generally, the best policy is to simply call305abort(). It's not very useful to do more than this because many306errors due to overwriting will show up as address faults (null, odd307addresses etc) rather than malloc-triggered checks, so will also308abort. Also, most compilers know that abort() does not return, so309can better optimize code conditionally calling it.310311PROCEED_ON_ERROR default: defined as 0 (false)312Controls whether detected bad addresses cause them to bypassed313rather than aborting. If set, detected bad arguments to free and314realloc are ignored. And all bookkeeping information is zeroed out315upon a detected overwrite of freed heap space, thus losing the316ability to ever return it from malloc again, but enabling the317application to proceed. If PROCEED_ON_ERROR is defined, the318static variable malloc_corruption_error_count is compiled in319and can be examined to see if errors have occurred. This option320generates slower code than the default abort policy.321322DEBUG default: NOT defined323The DEBUG setting is mainly intended for people trying to modify324this code or diagnose problems when porting to new platforms.325However, it may also be able to better isolate user errors than just326using runtime checks. The assertions in the check routines spell327out in more detail the assumptions and invariants underlying the328algorithms. The checking is fairly extensive, and will slow down329execution noticeably. Calling malloc_stats or mallinfo with DEBUG330set will attempt to check every non-mmapped allocated and free chunk331in the course of computing the summaries.332333ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)334Debugging assertion failures can be nearly impossible if your335version of the assert macro causes malloc to be called, which will336lead to a cascade of further failures, blowing the runtime stack.337ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),338which will usually make debugging easier.339340MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32341The action to take before "return 0" when malloc fails to be able to342return memory because there is none available.343344HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES345True if this system supports sbrk or an emulation of it.346347MORECORE default: sbrk348The name of the sbrk-style system routine to call to obtain more349memory. See below for guidance on writing custom MORECORE350functions. The type of the argument to sbrk/MORECORE varies across351systems. It cannot be size_t, because it supports negative352arguments, so it is normally the signed type of the same width as353size_t (sometimes declared as "intptr_t"). It doesn't much matter354though. Internally, we only call it with arguments less than half355the max value of a size_t, which should work across all reasonable356possibilities, although sometimes generating compiler warnings.357358MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE359If true, take advantage of fact that consecutive calls to MORECORE360with positive arguments always return contiguous increasing361addresses. This is true of unix sbrk. It does not hurt too much to362set it true anyway, since malloc copes with non-contiguities.363Setting it false when definitely non-contiguous saves time364and possibly wasted space it would take to discover this though.365366MORECORE_CANNOT_TRIM default: NOT defined367True if MORECORE cannot release space back to the system when given368negative arguments. This is generally necessary only if you are369using a hand-crafted MORECORE function that cannot handle negative370arguments.371372NO_SEGMENT_TRAVERSAL default: 0373If non-zero, suppresses traversals of memory segments374returned by either MORECORE or CALL_MMAP. This disables375merging of segments that are contiguous, and selectively376releasing them to the OS if unused, but bounds execution times.377378HAVE_MMAP default: 1 (true)379True if this system supports mmap or an emulation of it. If so, and380HAVE_MORECORE is not true, MMAP is used for all system381allocation. If set and HAVE_MORECORE is true as well, MMAP is382primarily used to directly allocate very large blocks. It is also383used as a backup strategy in cases where MORECORE fails to provide384space from system. Note: A single call to MUNMAP is assumed to be385able to unmap memory that may have be allocated using multiple calls386to MMAP, so long as they are adjacent.387388HAVE_MREMAP default: 1 on linux, else 0389If true realloc() uses mremap() to re-allocate large blocks and390extend or shrink allocation spaces.391392MMAP_CLEARS default: 1 except on WINCE.393True if mmap clears memory so calloc doesn't need to. This is true394for standard unix mmap using /dev/zero and on WIN32 except for WINCE.395396USE_BUILTIN_FFS default: 0 (i.e., not used)397Causes malloc to use the builtin ffs() function to compute indices.398Some compilers may recognize and intrinsify ffs to be faster than the399supplied C version. Also, the case of x86 using gcc is special-cased400to an asm instruction, so is already as fast as it can be, and so401this setting has no effect. Similarly for Win32 under recent MS compilers.402(On most x86s, the asm version is only slightly faster than the C version.)403404malloc_getpagesize default: derive from system includes, or 4096.405The system page size. To the extent possible, this malloc manages406memory from the system in page-size units. This may be (and407usually is) a function rather than a constant. This is ignored408if WIN32, where page size is determined using getSystemInfo during409initialization.410411USE_DEV_RANDOM default: 0 (i.e., not used)412Causes malloc to use /dev/random to initialize secure magic seed for413stamping footers. Otherwise, the current time is used.414415NO_MALLINFO default: 0416If defined, don't compile "mallinfo". This can be a simple way417of dealing with mismatches between system declarations and418those in this file.419420MALLINFO_FIELD_TYPE default: size_t421The type of the fields in the mallinfo struct. This was originally422defined as "int" in SVID etc, but is more usefully defined as423size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set424425NO_MALLOC_STATS default: 0426If defined, don't compile "malloc_stats". This avoids calls to427fprintf and bringing in stdio dependencies you might not want.428429REALLOC_ZERO_BYTES_FREES default: not defined430This should be set if a call to realloc with zero bytes should431be the same as a call to free. Some people think it should. Otherwise,432since this malloc returns a unique pointer for malloc(0), so does433realloc(p, 0).434435LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H436LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H437LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H default: NOT defined unless on WIN32438Define these if your system does not have these header files.439You might need to manually insert some of the declarations they provide.440441DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,442system_info.dwAllocationGranularity in WIN32,443otherwise 64K.444Also settable using mallopt(M_GRANULARITY, x)445The unit for allocating and deallocating memory from the system. On446most systems with contiguous MORECORE, there is no reason to447make this more than a page. However, systems with MMAP tend to448either require or encourage larger granularities. You can increase449this value to prevent system allocation functions to be called so450often, especially if they are slow. The value must be at least one451page and must be a power of two. Setting to 0 causes initialization452to either page size or win32 region size. (Note: In previous453versions of malloc, the equivalent of this option was called454"TOP_PAD")455456DEFAULT_TRIM_THRESHOLD default: 2MB457Also settable using mallopt(M_TRIM_THRESHOLD, x)458The maximum amount of unused top-most memory to keep before459releasing via malloc_trim in free(). Automatic trimming is mainly460useful in long-lived programs using contiguous MORECORE. Because461trimming via sbrk can be slow on some systems, and can sometimes be462wasteful (in cases where programs immediately afterward allocate463more large chunks) the value should be high enough so that your464overall system performance would improve by releasing this much465memory. As a rough guide, you might set to a value close to the466average size of a process (program) running on your system.467Releasing this much memory would allow such a process to run in468memory. Generally, it is worth tuning trim thresholds when a469program undergoes phases where several large chunks are allocated470and released in ways that can reuse each other's storage, perhaps471mixed with phases where there are no such chunks at all. The trim472value must be greater than page size to have any useful effect. To473disable trimming completely, you can set to MAX_SIZE_T. Note that the trick474some people use of mallocing a huge space and then freeing it at475program startup, in an attempt to reserve system memory, doesn't476have the intended effect under automatic trimming, since that memory477will immediately be returned to the system.478479DEFAULT_MMAP_THRESHOLD default: 256K480Also settable using mallopt(M_MMAP_THRESHOLD, x)481The request size threshold for using MMAP to directly service a482request. Requests of at least this size that cannot be allocated483using already-existing space will be serviced via mmap. (If enough484normal freed space already exists it is used instead.) Using mmap485segregates relatively large chunks of memory so that they can be486individually obtained and released from the host system. A request487serviced through mmap is never reused by any other request (at least488not directly; the system may just so happen to remap successive489requests to the same locations). Segregating space in this way has490the benefits that: Mmapped space can always be individually released491back to the system, which helps keep the system level memory demands492of a long-lived program low. Also, mapped memory doesn't become493`locked' between other chunks, as can happen with normally allocated494chunks, which means that even trimming via malloc_trim would not495release them. However, it has the disadvantage that the space496cannot be reclaimed, consolidated, and then used to service later497requests, as happens with normal chunks. The advantages of mmap498nearly always outweigh disadvantages for "large" chunks, but the499value of "large" may vary across systems. The default is an500empirically derived value that works well in most systems. You can501disable mmap by setting to MAX_SIZE_T.502503MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP504The number of consolidated frees between checks to release505unused segments when freeing. When using non-contiguous segments,506especially with multiple mspaces, checking only for topmost space507doesn't always suffice to trigger trimming. To compensate for this,508free() will, with a period of MAX_RELEASE_CHECK_RATE (or the509current number of segments, if greater) try to release unused510segments to the OS when freeing chunks that result in511consolidation. The best value for this parameter is a compromise512between slowing down frees with relatively costly checks that513rarely trigger versus holding on to unused memory. To effectively514disable, set to MAX_SIZE_T. This may lead to a very slight speed515improvement at the expense of carrying around more memory.516*/517518#ifndef REGTEST519#include "dlmalloc.h"520521/* Version identifier to allow people to support multiple versions */522#ifndef DLMALLOC_VERSION523#define DLMALLOC_VERSION 20805524#endif /* DLMALLOC_VERSION */525526#ifndef DLMALLOC_EXPORT527#define DLMALLOC_EXPORT extern528#endif529530531#ifndef LACKS_SYS_TYPES_H532#include <sys/types.h> /* For size_t */533#endif /* LACKS_SYS_TYPES_H */534535/* The maximum possible size_t value has all bits set */536#define MAX_SIZE_T (~(size_t)0)537538#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */539#define USE_LOCKS ((defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \540(defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0))541#endif /* USE_LOCKS */542543#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86, MSC >= 1310 */544#if ((defined(__GNUC__) && \545((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \546defined(__i386__) || defined(__x86_64__))) || \547(defined(_MSC_VER) && _MSC_VER>=1310))548#ifndef USE_SPIN_LOCKS549#define USE_SPIN_LOCKS 1550#endif /* USE_SPIN_LOCKS */551#elif USE_SPIN_LOCKS552#error "USE_SPIN_LOCKS defined without implementation"553#endif /* ... locks available... */554#elif !defined(USE_SPIN_LOCKS)555#define USE_SPIN_LOCKS 0556#endif /* USE_LOCKS */557558#ifndef ONLY_MSPACES559#define ONLY_MSPACES 0560#endif /* ONLY_MSPACES */561#ifndef MSPACES562#if ONLY_MSPACES563#define MSPACES 1564#else /* ONLY_MSPACES */565#define MSPACES 0566#endif /* ONLY_MSPACES */567#endif /* MSPACES */568#ifndef MALLOC_ALIGNMENT569#define MALLOC_ALIGNMENT ((size_t)8U)570#endif /* MALLOC_ALIGNMENT */571#ifndef FOOTERS572#define FOOTERS 0573#endif /* FOOTERS */574#ifndef ABORT575#define ABORT abort()576#endif /* ABORT */577#ifndef ABORT_ON_ASSERT_FAILURE578#define ABORT_ON_ASSERT_FAILURE 1579#endif /* ABORT_ON_ASSERT_FAILURE */580#ifndef PROCEED_ON_ERROR581#define PROCEED_ON_ERROR 0582#endif /* PROCEED_ON_ERROR */583584#ifndef INSECURE585#define INSECURE 0586#endif /* INSECURE */587#ifndef MALLOC_INSPECT_ALL588#define MALLOC_INSPECT_ALL 0589#endif /* MALLOC_INSPECT_ALL */590#ifndef HAVE_MMAP591#define HAVE_MMAP 1592#endif /* HAVE_MMAP */593#ifndef MMAP_CLEARS594#define MMAP_CLEARS 1595#endif /* MMAP_CLEARS */596#ifndef HAVE_MREMAP597#ifdef linux598#define HAVE_MREMAP 1599#define _GNU_SOURCE /* Turns on mremap() definition */600#else /* linux */601#define HAVE_MREMAP 0602#endif /* linux */603#endif /* HAVE_MREMAP */604#ifndef MALLOC_FAILURE_ACTION605#define MALLOC_FAILURE_ACTION errno = ENOMEM;606#endif /* MALLOC_FAILURE_ACTION */607#ifndef HAVE_MORECORE608#if ONLY_MSPACES609#define HAVE_MORECORE 0610#else /* ONLY_MSPACES */611#define HAVE_MORECORE 1612#endif /* ONLY_MSPACES */613#endif /* HAVE_MORECORE */614#if !HAVE_MORECORE615#define MORECORE_CONTIGUOUS 0616#else /* !HAVE_MORECORE */617#define MORECORE_DEFAULT sbrk618#ifndef MORECORE_CONTIGUOUS619#define MORECORE_CONTIGUOUS 1620#endif /* MORECORE_CONTIGUOUS */621#endif /* HAVE_MORECORE */622#ifndef DEFAULT_GRANULARITY623#if (MORECORE_CONTIGUOUS || defined(WIN32))624#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */625#else /* MORECORE_CONTIGUOUS */626#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)627#endif /* MORECORE_CONTIGUOUS */628#endif /* DEFAULT_GRANULARITY */629#ifndef DEFAULT_TRIM_THRESHOLD630#ifndef MORECORE_CANNOT_TRIM631#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)632#else /* MORECORE_CANNOT_TRIM */633#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T634#endif /* MORECORE_CANNOT_TRIM */635#endif /* DEFAULT_TRIM_THRESHOLD */636#ifndef DEFAULT_MMAP_THRESHOLD637#if HAVE_MMAP638#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)639#else /* HAVE_MMAP */640#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T641#endif /* HAVE_MMAP */642#endif /* DEFAULT_MMAP_THRESHOLD */643#ifndef MAX_RELEASE_CHECK_RATE644#if HAVE_MMAP645#define MAX_RELEASE_CHECK_RATE 4095646#else647#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T648#endif /* HAVE_MMAP */649#endif /* MAX_RELEASE_CHECK_RATE */650#ifndef USE_BUILTIN_FFS651#define USE_BUILTIN_FFS 0652#endif /* USE_BUILTIN_FFS */653#ifndef USE_DEV_RANDOM654#define USE_DEV_RANDOM 0655#endif /* USE_DEV_RANDOM */656#ifndef NO_MALLINFO657#define NO_MALLINFO 0658#endif /* NO_MALLINFO */659#ifndef MALLINFO_FIELD_TYPE660#define MALLINFO_FIELD_TYPE size_t661#endif /* MALLINFO_FIELD_TYPE */662#ifndef NO_MALLOC_STATS663#define NO_MALLOC_STATS 0664#endif /* NO_MALLOC_STATS */665#ifndef NO_SEGMENT_TRAVERSAL666#define NO_SEGMENT_TRAVERSAL 0667#endif /* NO_SEGMENT_TRAVERSAL */668669/*670mallopt tuning options. SVID/XPG defines four standard parameter671numbers for mallopt, normally defined in malloc.h. None of these672are used in this malloc, so setting them has no effect. But this673malloc does support the following options.674*/675676#define M_TRIM_THRESHOLD (-1)677#define M_GRANULARITY (-2)678#define M_MMAP_THRESHOLD (-3)679680/* ------------------------ Mallinfo declarations ------------------------ */681682#if !NO_MALLINFO683/*684This version of malloc supports the standard SVID/XPG mallinfo685routine that returns a struct containing usage properties and686statistics. It should work on any system that has a687/usr/include/malloc.h defining struct mallinfo. The main688declaration needed is the mallinfo struct that is returned (by-copy)689by mallinfo(). The malloinfo struct contains a bunch of fields that690are not even meaningful in this version of malloc. These fields are691are instead filled by mallinfo() with other numbers that might be of692interest.693694HAVE_USR_INCLUDE_MALLOC_H should be set if you have a695/usr/include/malloc.h file that includes a declaration of struct696mallinfo. If so, it is included; else a compliant version is697declared below. These must be precisely the same for mallinfo() to698work. The original SVID version of this struct, defined on most699systems with mallinfo, declares all fields as ints. But some others700define as unsigned long. If your system defines the fields using a701type of different width than listed here, you MUST #include your702system version and #define HAVE_USR_INCLUDE_MALLOC_H.703*/704705/* #define HAVE_USR_INCLUDE_MALLOC_H */706707#ifdef HAVE_USR_INCLUDE_MALLOC_H708#include "/usr/include/malloc.h"709#else /* HAVE_USR_INCLUDE_MALLOC_H */710#ifndef STRUCT_MALLINFO_DECLARED711/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */712#define _STRUCT_MALLINFO713#define STRUCT_MALLINFO_DECLARED 1714struct mallinfo {715MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */716MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */717MALLINFO_FIELD_TYPE smblks; /* always 0 */718MALLINFO_FIELD_TYPE hblks; /* always 0 */719MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */720MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */721MALLINFO_FIELD_TYPE fsmblks; /* always 0 */722MALLINFO_FIELD_TYPE uordblks; /* total allocated space */723MALLINFO_FIELD_TYPE fordblks; /* total free space */724MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */725};726#endif /* STRUCT_MALLINFO_DECLARED */727#endif /* HAVE_USR_INCLUDE_MALLOC_H */728#endif /* NO_MALLINFO */729730/*731Try to persuade compilers to inline. The most critical functions for732inlining are defined as macros, so these aren't used for them.733*/734735#ifndef FORCEINLINE736#if defined(__GNUC__)737#define FORCEINLINE __inline __attribute__ ((always_inline))738#elif defined(_MSC_VER)739#define FORCEINLINE __forceinline740#endif741#endif742#ifndef NOINLINE743#if defined(__GNUC__)744#define NOINLINE __attribute__ ((noinline))745#elif defined(_MSC_VER)746#define NOINLINE __declspec(noinline)747#else748#define NOINLINE749#endif750#endif751752#ifdef __cplusplus753extern "C" {754#ifndef FORCEINLINE755#define FORCEINLINE inline756#endif757#endif /* __cplusplus */758#ifndef FORCEINLINE759#define FORCEINLINE760#endif761762#if !ONLY_MSPACES763764/* ------------------- Declarations of public routines ------------------- */765766#ifndef USE_DL_PREFIX767#define dlcalloc calloc768#define dlfree free769#define dlmalloc malloc770#define dlmemalign aligned_alloc771#define dlposix_memalign posix_memalign772#define dlrealloc realloc773#define dlrealloc_in_place realloc_in_place774#define dlvalloc valloc775#define dlpvalloc pvalloc776#define dlmallinfo mallinfo777#define dlmallopt mallopt778#define dlmalloc_trim malloc_trim779#define dlmalloc_stats malloc_stats780#define dlmalloc_usable_size malloc_usable_size781#define dlmalloc_footprint malloc_footprint782#define dlmalloc_max_footprint malloc_max_footprint783#define dlmalloc_footprint_limit malloc_footprint_limit784#define dlmalloc_set_footprint_limit malloc_set_footprint_limit785#define dlmalloc_inspect_all malloc_inspect_all786#define dlindependent_calloc independent_calloc787#define dlindependent_comalloc independent_comalloc788#define dlbulk_free bulk_free789#endif /* USE_DL_PREFIX */790791#if 0 // Redeclaration warnings as PDCLib already declares these in <stdio.h>792793/*794malloc(size_t n)795Returns a pointer to a newly allocated chunk of at least n bytes, or796null if no space is available, in which case errno is set to ENOMEM797on ANSI C systems.798799If n is zero, malloc returns a minimum-sized chunk. (The minimum800size is 16 bytes on most 32bit systems, and 32 bytes on 64bit801systems.) Note that size_t is an unsigned type, so calls with802arguments that would be negative if signed are interpreted as803requests for huge amounts of space, which will often fail. The804maximum supported value of n differs across systems, but is in all805cases less than the maximum representable value of a size_t.806*/807DLMALLOC_EXPORT void* dlmalloc(size_t);808809/*810free(void* p)811Releases the chunk of memory pointed to by p, that had been previously812allocated using malloc or a related routine such as realloc.813It has no effect if p is null. If p was not malloced or already814freed, free(p) will by default cause the current program to abort.815*/816DLMALLOC_EXPORT void dlfree(void*);817818/*819calloc(size_t n_elements, size_t element_size);820Returns a pointer to n_elements * element_size bytes, with all locations821set to zero.822*/823DLMALLOC_EXPORT void* dlcalloc(size_t, size_t);824825/*826realloc(void* p, size_t n)827Returns a pointer to a chunk of size n that contains the same data828as does chunk p up to the minimum of (n, p's size) bytes, or null829if no space is available.830831The returned pointer may or may not be the same as p. The algorithm832prefers extending p in most cases when possible, otherwise it833employs the equivalent of a malloc-copy-free sequence.834835If p is null, realloc is equivalent to malloc.836837If space is not available, realloc returns null, errno is set (if on838ANSI) and p is NOT freed.839840if n is for fewer bytes than already held by p, the newly unused841space is lopped off and freed if possible. realloc with a size842argument of zero (re)allocates a minimum-sized chunk.843844The old unix realloc convention of allowing the last-free'd chunk845to be used as an argument to realloc is not supported.846*/847DLMALLOC_EXPORT void* dlrealloc(void*, size_t);848849#endif850851/*852realloc_in_place(void* p, size_t n)853Resizes the space allocated for p to size n, only if this can be854done without moving p (i.e., only if there is adjacent space855available if n is greater than p's current allocated size, or n is856less than or equal to p's size). This may be used instead of plain857realloc if an alternative allocation strategy is needed upon failure858to expand space; for example, reallocation of a buffer that must be859memory-aligned or cleared. You can use realloc_in_place to trigger860these alternatives only when needed.861862Returns p if successful; otherwise null.863*/864DLMALLOC_EXPORT void* dlrealloc_in_place(void*, size_t);865866#if 0 // Redeclaration warnings as PDCLib already declares these in <stdio.h>867868/*869memalign(size_t alignment, size_t n);870Returns a pointer to a newly allocated chunk of n bytes, aligned871in accord with the alignment argument.872873The alignment argument should be a power of two. If the argument is874not a power of two, the nearest greater power is used.8758-byte alignment is guaranteed by normal malloc calls, so don't876bother calling memalign with an argument of 8 or less.877878Overreliance on memalign is a sure way to fragment space.879*/880DLMALLOC_EXPORT void* dlmemalign(size_t, size_t);881882#endif883884/*885int posix_memalign(void** pp, size_t alignment, size_t n);886Allocates a chunk of n bytes, aligned in accord with the alignment887argument. Differs from memalign only in that it (1) assigns the888allocated memory to *pp rather than returning it, (2) fails and889returns EINVAL if the alignment is not a power of two (3) fails and890returns ENOMEM if memory cannot be allocated.891*/892DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t);893894/*895valloc(size_t n);896Equivalent to memalign(pagesize, n), where pagesize is the page897size of the system. If the pagesize is unknown, 4096 is used.898*/899DLMALLOC_EXPORT void* dlvalloc(size_t);900901/*902mallopt(int parameter_number, int parameter_value)903Sets tunable parameters The format is to provide a904(parameter-number, parameter-value) pair. mallopt then sets the905corresponding parameter to the argument value if it can (i.e., so906long as the value is meaningful), and returns 1 if successful else9070. To workaround the fact that mallopt is specified to use int,908not size_t parameters, the value -1 is specially treated as the909maximum unsigned size_t value.910911SVID/XPG/ANSI defines four standard param numbers for mallopt,912normally defined in malloc.h. None of these are use in this malloc,913so setting them has no effect. But this malloc also supports other914options in mallopt. See below for details. Briefly, supported915parameters are as follows (listed defaults are for "typical"916configurations).917918Symbol param # default allowed param values919M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables)920M_GRANULARITY -2 page size any power of 2 >= page size921M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)922*/923DLMALLOC_EXPORT int dlmallopt(int, int);924925/*926malloc_footprint();927Returns the number of bytes obtained from the system. The total928number of bytes allocated by malloc, realloc etc., is less than this929value. Unlike mallinfo, this function returns only a precomputed930result, so can be called frequently to monitor memory consumption.931Even if locks are otherwise defined, this function does not use them,932so results might not be up to date.933*/934DLMALLOC_EXPORT size_t dlmalloc_footprint(void);935936/*937malloc_max_footprint();938Returns the maximum number of bytes obtained from the system. This939value will be greater than current footprint if deallocated space940has been reclaimed by the system. The peak number of bytes allocated941by malloc, realloc etc., is less than this value. Unlike mallinfo,942this function returns only a precomputed result, so can be called943frequently to monitor memory consumption. Even if locks are944otherwise defined, this function does not use them, so results might945not be up to date.946*/947DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void);948949/*950malloc_footprint_limit();951Returns the number of bytes that the heap is allowed to obtain from952the system, returning the last value returned by953malloc_set_footprint_limit, or the maximum size_t value if954never set. The returned value reflects a permission. There is no955guarantee that this number of bytes can actually be obtained from956the system.957*/958DLMALLOC_EXPORT size_t dlmalloc_footprint_limit(void);959960/*961malloc_set_footprint_limit();962Sets the maximum number of bytes to obtain from the system, causing963failure returns from malloc and related functions upon attempts to964exceed this value. The argument value may be subject to page965rounding to an enforceable limit; this actual value is returned.966Using an argument of the maximum possible size_t effectively967disables checks. If the argument is less than or equal to the968current malloc_footprint, then all future allocations that require969additional system memory will fail. However, invocation cannot970retroactively deallocate existing used memory.971*/972DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes);973974#if MALLOC_INSPECT_ALL975/*976malloc_inspect_all(void(*handler)(void *start,977void *end,978size_t used_bytes,979void* callback_arg),980void* arg);981Traverses the heap and calls the given handler for each managed982region, skipping all bytes that are (or may be) used for bookkeeping983purposes. Traversal does not include include chunks that have been984directly memory mapped. Each reported region begins at the start985address, and continues up to but not including the end address. The986first used_bytes of the region contain allocated data. If987used_bytes is zero, the region is unallocated. The handler is988invoked with the given callback argument. If locks are defined, they989are held during the entire traversal. It is a bad idea to invoke990other malloc functions from within the handler.991992For example, to count the number of in-use chunks with size greater993than 1000, you could write:994static int count = 0;995void count_chunks(void* start, void* end, size_t used, void* arg) {996if (used >= 1000) ++count;997}998then:999malloc_inspect_all(count_chunks, NULL);10001001malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined.1002*/1003DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*),1004void* arg);10051006#endif /* MALLOC_INSPECT_ALL */10071008#if !NO_MALLINFO1009/*1010mallinfo()1011Returns (by copy) a struct containing various summary statistics:10121013arena: current total non-mmapped bytes allocated from system1014ordblks: the number of free chunks1015smblks: always zero.1016hblks: current number of mmapped regions1017hblkhd: total bytes held in mmapped regions1018usmblks: the maximum total allocated space. This will be greater1019than current total if trimming has occurred.1020fsmblks: always zero1021uordblks: current total allocated space (normal or mmapped)1022fordblks: total free space1023keepcost: the maximum number of bytes that could ideally be released1024back to system via malloc_trim. ("ideally" means that1025it ignores page restrictions etc.)10261027Because these fields are ints, but internal bookkeeping may1028be kept as longs, the reported values may wrap around zero and1029thus be inaccurate.1030*/1031DLMALLOC_EXPORT struct mallinfo dlmallinfo(void);1032#endif /* NO_MALLINFO */10331034/*1035independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);10361037independent_calloc is similar to calloc, but instead of returning a1038single cleared space, it returns an array of pointers to n_elements1039independent elements that can hold contents of size elem_size, each1040of which starts out cleared, and can be independently freed,1041realloc'ed etc. The elements are guaranteed to be adjacently1042allocated (this is not guaranteed to occur with multiple callocs or1043mallocs), which may also improve cache locality in some1044applications.10451046The "chunks" argument is optional (i.e., may be null, which is1047probably the most typical usage). If it is null, the returned array1048is itself dynamically allocated and should also be freed when it is1049no longer needed. Otherwise, the chunks array must be of at least1050n_elements in length. It is filled in with the pointers to the1051chunks.10521053In either case, independent_calloc returns this pointer array, or1054null if the allocation failed. If n_elements is zero and "chunks"1055is null, it returns a chunk representing an array with zero elements1056(which should be freed if not wanted).10571058Each element must be freed when it is no longer needed. This can be1059done all at once using bulk_free.10601061independent_calloc simplifies and speeds up implementations of many1062kinds of pools. It may also be useful when constructing large data1063structures that initially have a fixed number of fixed-sized nodes,1064but the number is not known at compile time, and some of the nodes1065may later need to be freed. For example:10661067struct Node { int item; struct Node* next; };10681069struct Node* build_list() {1070struct Node** pool;1071int n = read_number_of_nodes_needed();1072if (n <= 0) return 0;1073pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);1074if (pool == 0) die();1075// organize into a linked list...1076struct Node* first = pool[0];1077for (i = 0; i < n-1; ++i)1078pool[i]->next = pool[i+1];1079free(pool); // Can now free the array (or not, if it is needed later)1080return first;1081}1082*/1083DLMALLOC_EXPORT void** dlindependent_calloc(size_t, size_t, void**);10841085/*1086independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);10871088independent_comalloc allocates, all at once, a set of n_elements1089chunks with sizes indicated in the "sizes" array. It returns1090an array of pointers to these elements, each of which can be1091independently freed, realloc'ed etc. The elements are guaranteed to1092be adjacently allocated (this is not guaranteed to occur with1093multiple callocs or mallocs), which may also improve cache locality1094in some applications.10951096The "chunks" argument is optional (i.e., may be null). If it is null1097the returned array is itself dynamically allocated and should also1098be freed when it is no longer needed. Otherwise, the chunks array1099must be of at least n_elements in length. It is filled in with the1100pointers to the chunks.11011102In either case, independent_comalloc returns this pointer array, or1103null if the allocation failed. If n_elements is zero and chunks is1104null, it returns a chunk representing an array with zero elements1105(which should be freed if not wanted).11061107Each element must be freed when it is no longer needed. This can be1108done all at once using bulk_free.11091110independent_comallac differs from independent_calloc in that each1111element may have a different size, and also that it does not1112automatically clear elements.11131114independent_comalloc can be used to speed up allocation in cases1115where several structs or objects must always be allocated at the1116same time. For example:11171118struct Head { ... }1119struct Foot { ... }11201121void send_message(char* msg) {1122int msglen = strlen(msg);1123size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };1124void* chunks[3];1125if (independent_comalloc(3, sizes, chunks) == 0)1126die();1127struct Head* head = (struct Head*)(chunks[0]);1128char* body = (char*)(chunks[1]);1129struct Foot* foot = (struct Foot*)(chunks[2]);1130// ...1131}11321133In general though, independent_comalloc is worth using only for1134larger values of n_elements. For small values, you probably won't1135detect enough difference from series of malloc calls to bother.11361137Overuse of independent_comalloc can increase overall memory usage,1138since it cannot reuse existing noncontiguous small chunks that1139might be available for some of the elements.1140*/1141DLMALLOC_EXPORT void** dlindependent_comalloc(size_t, size_t*, void**);11421143/*1144bulk_free(void* array[], size_t n_elements)1145Frees and clears (sets to null) each non-null pointer in the given1146array. This is likely to be faster than freeing them one-by-one.1147If footers are used, pointers that have been allocated in different1148mspaces are not freed or cleared, and the count of all such pointers1149is returned. For large arrays of pointers with poor locality, it1150may be worthwhile to sort this array before calling bulk_free.1151*/1152DLMALLOC_EXPORT size_t dlbulk_free(void**, size_t n_elements);11531154/*1155pvalloc(size_t n);1156Equivalent to valloc(minimum-page-that-holds(n)), that is,1157round up n to nearest pagesize.1158*/1159DLMALLOC_EXPORT void* dlpvalloc(size_t);11601161/*1162malloc_trim(size_t pad);11631164If possible, gives memory back to the system (via negative arguments1165to sbrk) if there is unused memory at the `high' end of the malloc1166pool or in unused MMAP segments. You can call this after freeing1167large blocks of memory to potentially reduce the system-level memory1168requirements of a program. However, it cannot guarantee to reduce1169memory. Under some allocation patterns, some large free blocks of1170memory will be locked between two used chunks, so they cannot be1171given back to the system.11721173The `pad' argument to malloc_trim represents the amount of free1174trailing space to leave untrimmed. If this argument is zero, only1175the minimum amount of memory to maintain internal data structures1176will be left. Non-zero arguments can be supplied to maintain enough1177trailing space to service future expected allocations without having1178to re-obtain memory from the system.11791180Malloc_trim returns 1 if it actually released any memory, else 0.1181*/1182DLMALLOC_EXPORT int dlmalloc_trim(size_t);11831184/*1185malloc_stats();1186Prints on stderr the amount of space obtained from the system (both1187via sbrk and mmap), the maximum amount (which may be more than1188current if malloc_trim and/or munmap got called), and the current1189number of bytes allocated via malloc (or realloc, etc) but not yet1190freed. Note that this is the number of bytes allocated, not the1191number requested. It will be larger than the number requested1192because of alignment and bookkeeping overhead. Because it includes1193alignment wastage as being in use, this figure may be greater than1194zero even when no user-level chunks are allocated.11951196The reported current and maximum system memory can be inaccurate if1197a program makes other calls to system memory allocation functions1198(normally sbrk) outside of malloc.11991200malloc_stats prints only the most commonly interesting statistics.1201More information can be obtained by calling mallinfo.1202*/1203DLMALLOC_EXPORT void dlmalloc_stats(void);12041205#endif /* ONLY_MSPACES */12061207/*1208malloc_usable_size(void* p);12091210Returns the number of bytes you can actually use in1211an allocated chunk, which may be more than you requested (although1212often not) due to alignment and minimum size constraints.1213You can use this many bytes without worrying about1214overwriting other allocated objects. This is not a particularly great1215programming practice. malloc_usable_size can be more useful in1216debugging and assertions, for example:12171218p = malloc(n);1219assert(malloc_usable_size(p) >= 256);1220*/1221size_t dlmalloc_usable_size(void*);12221223#if MSPACES12241225/*1226mspace is an opaque type representing an independent1227region of space that supports mspace_malloc, etc.1228*/1229typedef void* mspace;12301231/*1232create_mspace creates and returns a new independent space with the1233given initial capacity, or, if 0, the default granularity size. It1234returns null if there is no system memory available to create the1235space. If argument locked is non-zero, the space uses a separate1236lock to control access. The capacity of the space will grow1237dynamically as needed to service mspace_malloc requests. You can1238control the sizes of incremental increases of this space by1239compiling with a different DEFAULT_GRANULARITY or dynamically1240setting with mallopt(M_GRANULARITY, value).1241*/1242DLMALLOC_EXPORT mspace create_mspace(size_t capacity, int locked);12431244/*1245destroy_mspace destroys the given space, and attempts to return all1246of its memory back to the system, returning the total number of1247bytes freed. After destruction, the results of access to all memory1248used by the space become undefined.1249*/1250DLMALLOC_EXPORT size_t destroy_mspace(mspace msp);12511252/*1253create_mspace_with_base uses the memory supplied as the initial base1254of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this1255space is used for bookkeeping, so the capacity must be at least this1256large. (Otherwise 0 is returned.) When this initial space is1257exhausted, additional memory will be obtained from the system.1258Destroying this space will deallocate all additionally allocated1259space (if possible) but not the initial base.1260*/1261DLMALLOC_EXPORT mspace create_mspace_with_base(void* base, size_t capacity, int locked);12621263/*1264mspace_track_large_chunks controls whether requests for large chunks1265are allocated in their own untracked mmapped regions, separate from1266others in this mspace. By default large chunks are not tracked,1267which reduces fragmentation. However, such chunks are not1268necessarily released to the system upon destroy_mspace. Enabling1269tracking by setting to true may increase fragmentation, but avoids1270leakage when relying on destroy_mspace to release all memory1271allocated using this space. The function returns the previous1272setting.1273*/1274DLMALLOC_EXPORT int mspace_track_large_chunks(mspace msp, int enable);127512761277/*1278mspace_malloc behaves as malloc, but operates within1279the given space.1280*/1281DLMALLOC_EXPORT void* mspace_malloc(mspace msp, size_t bytes);12821283/*1284mspace_free behaves as free, but operates within1285the given space.12861287If compiled with FOOTERS==1, mspace_free is not actually needed.1288free may be called instead of mspace_free because freed chunks from1289any space are handled by their originating spaces.1290*/1291DLMALLOC_EXPORT void mspace_free(mspace msp, void* mem);12921293/*1294mspace_realloc behaves as realloc, but operates within1295the given space.12961297If compiled with FOOTERS==1, mspace_realloc is not actually1298needed. realloc may be called instead of mspace_realloc because1299realloced chunks from any space are handled by their originating1300spaces.1301*/1302DLMALLOC_EXPORT void* mspace_realloc(mspace msp, void* mem, size_t newsize);13031304/*1305mspace_calloc behaves as calloc, but operates within1306the given space.1307*/1308DLMALLOC_EXPORT void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);13091310/*1311mspace_memalign behaves as memalign, but operates within1312the given space.1313*/1314DLMALLOC_EXPORT void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);13151316/*1317mspace_independent_calloc behaves as independent_calloc, but1318operates within the given space.1319*/1320DLMALLOC_EXPORT void** mspace_independent_calloc(mspace msp, size_t n_elements,1321size_t elem_size, void* chunks[]);13221323/*1324mspace_independent_comalloc behaves as independent_comalloc, but1325operates within the given space.1326*/1327DLMALLOC_EXPORT void** mspace_independent_comalloc(mspace msp, size_t n_elements,1328size_t sizes[], void* chunks[]);13291330/*1331mspace_footprint() returns the number of bytes obtained from the1332system for this space.1333*/1334DLMALLOC_EXPORT size_t mspace_footprint(mspace msp);13351336/*1337mspace_max_footprint() returns the peak number of bytes obtained from the1338system for this space.1339*/1340DLMALLOC_EXPORT size_t mspace_max_footprint(mspace msp);134113421343#if !NO_MALLINFO1344/*1345mspace_mallinfo behaves as mallinfo, but reports properties of1346the given space.1347*/1348DLMALLOC_EXPORT struct mallinfo mspace_mallinfo(mspace msp);1349#endif /* NO_MALLINFO */13501351/*1352malloc_usable_size(void* p) behaves the same as malloc_usable_size;1353*/1354DLMALLOC_EXPORT size_t mspace_usable_size(void* mem);13551356/*1357mspace_malloc_stats behaves as malloc_stats, but reports1358properties of the given space.1359*/1360DLMALLOC_EXPORT void mspace_malloc_stats(mspace msp);13611362/*1363mspace_trim behaves as malloc_trim, but1364operates within the given space.1365*/1366DLMALLOC_EXPORT int mspace_trim(mspace msp, size_t pad);13671368/*1369An alias for mallopt.1370*/1371DLMALLOC_EXPORT int mspace_mallopt(int, int);13721373#endif /* MSPACES */13741375#ifdef __cplusplus1376} /* end of extern "C" */1377#endif /* __cplusplus */13781379/*1380========================================================================1381To make a fully customizable malloc.h header file, cut everything1382above this line, put into file malloc.h, edit to suit, and #include it1383on the next line, as well as in programs that use this malloc.1384========================================================================1385*/13861387/* #include "malloc.h" */13881389/*------------------------------ internal #includes ---------------------- */13901391#ifdef _MSC_VER1392#pragma warning( disable : 4146 ) /* no "unsigned" warnings */1393#endif /* _MSC_VER */1394#if !NO_MALLOC_STATS1395#include <stdio.h> /* for printing in malloc_stats */1396#endif /* NO_MALLOC_STATS */1397#ifndef LACKS_ERRNO_H1398#include <errno.h> /* for MALLOC_FAILURE_ACTION */1399#endif /* LACKS_ERRNO_H */1400#ifdef DEBUG1401#if ABORT_ON_ASSERT_FAILURE1402#undef assert1403#define assert(x) if(!(x)) ABORT1404#else /* ABORT_ON_ASSERT_FAILURE */1405#include <assert.h>1406#endif /* ABORT_ON_ASSERT_FAILURE */1407#else /* DEBUG */1408#ifndef assert1409#define assert(x)1410#endif1411#define DEBUG 01412#endif /* DEBUG */1413#if !defined(WIN32) && !defined(LACKS_TIME_H)1414#include <time.h> /* for magic initialization */1415#endif /* WIN32 */1416#ifndef LACKS_STDLIB_H1417#include <stdlib.h> /* for abort() */1418#endif /* LACKS_STDLIB_H */1419#ifndef LACKS_STRING_H1420#include <string.h> /* for memset etc */1421#endif /* LACKS_STRING_H */1422#if USE_BUILTIN_FFS1423#ifndef LACKS_STRINGS_H1424#include <strings.h> /* for ffs */1425#endif /* LACKS_STRINGS_H */1426#endif /* USE_BUILTIN_FFS */1427#if HAVE_MMAP1428#ifndef LACKS_SYS_MMAN_H1429/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */1430#if (defined(linux) && !defined(__USE_GNU))1431#define __USE_GNU 11432#include <sys/mman.h> /* for mmap */1433#undef __USE_GNU1434#else1435#include <sys/mman.h> /* for mmap */1436#endif /* linux */1437#endif /* LACKS_SYS_MMAN_H */1438#ifndef LACKS_FCNTL_H1439#include <fcntl.h>1440#endif /* LACKS_FCNTL_H */1441#endif /* HAVE_MMAP */1442#ifndef LACKS_UNISTD_H1443#include <unistd.h> /* for sbrk, sysconf */1444#else /* LACKS_UNISTD_H */1445#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)1446/*extern void* sbrk(ptrdiff_t);*/1447#endif /* FreeBSD etc */1448#endif /* LACKS_UNISTD_H */14491450/* Declarations for locking */1451#if USE_LOCKS1452#ifndef WIN321453#if defined (__SVR4) && defined (__sun) /* solaris */1454#include <thread.h>1455#elif !defined(LACKS_SCHED_H)1456#include <sched.h>1457#endif /* solaris or LACKS_SCHED_H */1458#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS1459/*#include <pthread.h>*/1460#endif /* USE_RECURSIVE_LOCKS ... */1461#elif defined(_MSC_VER)1462#ifndef _M_AMD641463/* These are already defined on AMD64 builds */1464#ifdef __cplusplus1465extern "C" {1466#endif /* __cplusplus */1467LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp);1468LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value);1469#ifdef __cplusplus1470}1471#endif /* __cplusplus */1472#endif /* _M_AMD64 */1473#pragma intrinsic (_InterlockedCompareExchange)1474#pragma intrinsic (_InterlockedExchange)1475#define interlockedcompareexchange _InterlockedCompareExchange1476#define interlockedexchange _InterlockedExchange1477#elif defined(WIN32) && defined(__GNUC__)1478#define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b)1479#define interlockedexchange __sync_lock_test_and_set1480#endif /* Win32 */1481#endif /* USE_LOCKS */14821483/* Declarations for bit scanning on win32 */1484#if defined(_MSC_VER) && _MSC_VER>=13001485#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */1486#ifdef __cplusplus1487extern "C" {1488#endif /* __cplusplus */1489unsigned char _BitScanForward(unsigned long *index, unsigned long mask);1490unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);1491#ifdef __cplusplus1492}1493#endif /* __cplusplus */14941495#define BitScanForward _BitScanForward1496#define BitScanReverse _BitScanReverse1497#pragma intrinsic(_BitScanForward)1498#pragma intrinsic(_BitScanReverse)1499#endif /* BitScanForward */1500#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */15011502#ifndef WIN321503#ifndef malloc_getpagesize1504# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */1505# ifndef _SC_PAGE_SIZE1506# define _SC_PAGE_SIZE _SC_PAGESIZE1507# endif1508# endif1509# ifdef _SC_PAGE_SIZE1510# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)1511# else1512# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)1513extern size_t getpagesize();1514# define malloc_getpagesize getpagesize()1515# else1516# ifdef WIN32 /* use supplied emulation of getpagesize */1517# define malloc_getpagesize getpagesize()1518# else1519# ifndef LACKS_SYS_PARAM_H1520# include <sys/param.h>1521# endif1522# ifdef EXEC_PAGESIZE1523# define malloc_getpagesize EXEC_PAGESIZE1524# else1525# ifdef NBPG1526# ifndef CLSIZE1527# define malloc_getpagesize NBPG1528# else1529# define malloc_getpagesize (NBPG * CLSIZE)1530# endif1531# else1532# ifdef NBPC1533# define malloc_getpagesize NBPC1534# else1535# ifdef PAGESIZE1536# define malloc_getpagesize PAGESIZE1537# else /* just guess */1538# define malloc_getpagesize ((size_t)4096U)1539# endif1540# endif1541# endif1542# endif1543# endif1544# endif1545# endif1546#endif1547#endif15481549/* ------------------- size_t and alignment properties -------------------- */15501551/* The byte and bit size of a size_t */1552#define SIZE_T_SIZE (sizeof(size_t))1553#define SIZE_T_BITSIZE (sizeof(size_t) << 3)15541555/* Some constants coerced to size_t */1556/* Annoying but necessary to avoid errors on some platforms */1557#define SIZE_T_ZERO ((size_t)0)1558#define SIZE_T_ONE ((size_t)1)1559#define SIZE_T_TWO ((size_t)2)1560#define SIZE_T_FOUR ((size_t)4)1561#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)1562#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)1563#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)1564#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)15651566/* The bit mask value corresponding to MALLOC_ALIGNMENT */1567#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)15681569/* True if address a has acceptable alignment */1570#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)15711572/* the number of bytes to offset an address to align it */1573#define align_offset(A)\1574((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\1575((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))15761577/* -------------------------- MMAP preliminaries ------------------------- */15781579/*1580If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and1581checks to fail so compiler optimizer can delete code rather than1582using so many "#if"s.1583*/158415851586/* MORECORE and MMAP must return MFAIL on failure */1587#define MFAIL ((void*)(MAX_SIZE_T))1588#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */15891590#if HAVE_MMAP15911592#ifdef MMAP_DEFAULT1593#elif !defined(WIN32)1594#define MUNMAP_DEFAULT(a, s) munmap((a), (s))1595#define MMAP_PROT (PROT_READ|PROT_WRITE)1596#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)1597#define MAP_ANONYMOUS MAP_ANON1598#endif /* MAP_ANON */1599#ifdef MAP_ANONYMOUS1600#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)1601#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)1602#else /* MAP_ANONYMOUS */1603/*1604Nearly all versions of mmap support MAP_ANONYMOUS, so the following1605is unlikely to be needed, but is supplied just in case.1606*/1607#define MMAP_FLAGS (MAP_PRIVATE)1608#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \1609(dev_zero_fd = open("/dev/zero", O_RDWR), \1610mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \1611mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))1612#endif /* MAP_ANONYMOUS */16131614#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s)16151616#else /* WIN32 */16171618/* Win32 MMAP via VirtualAlloc */1619static FORCEINLINE void* win32mmap(size_t size) {1620void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);1621return (ptr != 0)? ptr: MFAIL;1622}16231624/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */1625static FORCEINLINE void* win32direct_mmap(size_t size) {1626void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,1627PAGE_READWRITE);1628return (ptr != 0)? ptr: MFAIL;1629}16301631/* This function supports releasing coalesed segments */1632static FORCEINLINE int win32munmap(void* ptr, size_t size) {1633MEMORY_BASIC_INFORMATION minfo;1634char* cptr = (char*)ptr;1635while (size) {1636if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)1637return -1;1638if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||1639minfo.State != MEM_COMMIT || minfo.RegionSize > size)1640return -1;1641if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)1642return -1;1643cptr += minfo.RegionSize;1644size -= minfo.RegionSize;1645}1646return 0;1647}16481649#define MMAP_DEFAULT(s) win32mmap(s)1650#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s))1651#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s)1652#endif /* WIN32 */1653#endif /* HAVE_MMAP */16541655#if HAVE_MREMAP && !defined(MREMAP_DEFAULT)1656#ifndef WIN321657#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))1658#endif /* WIN32 */1659#endif /* HAVE_MREMAP */16601661/**1662* Define CALL_MORECORE1663*/1664#if HAVE_MORECORE1665#ifdef MORECORE1666#define CALL_MORECORE(S) MORECORE(S)1667#else /* MORECORE */1668#define CALL_MORECORE(S) MORECORE_DEFAULT(S)1669#endif /* MORECORE */1670#else /* HAVE_MORECORE */1671#define CALL_MORECORE(S) MFAIL1672#endif /* HAVE_MORECORE */16731674/**1675* Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP1676*/1677#if HAVE_MMAP1678#define USE_MMAP_BIT (SIZE_T_ONE)16791680#ifdef MMAP1681#define CALL_MMAP(s) MMAP(s)1682#else /* MMAP */1683#define CALL_MMAP(s) MMAP_DEFAULT(s)1684#endif /* MMAP */1685#ifdef MUNMAP1686#define CALL_MUNMAP(a, s) MUNMAP((a), (s))1687#else /* MUNMAP */1688#define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s))1689#endif /* MUNMAP */1690#ifdef DIRECT_MMAP1691#define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)1692#else /* DIRECT_MMAP */1693#define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s)1694#endif /* DIRECT_MMAP */1695#else /* HAVE_MMAP */1696#define USE_MMAP_BIT (SIZE_T_ZERO)16971698#define MMAP(s) MFAIL1699#define MUNMAP(a, s) (-1)1700#define DIRECT_MMAP(s) MFAIL1701#define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)1702#define CALL_MMAP(s) MMAP(s)1703#define CALL_MUNMAP(a, s) MUNMAP((a), (s))1704#endif /* HAVE_MMAP */17051706/**1707* Define CALL_MREMAP1708*/1709#if HAVE_MMAP && HAVE_MREMAP1710#ifdef MREMAP1711#define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv))1712#else /* MREMAP */1713#define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv))1714#endif /* MREMAP */1715#else /* HAVE_MMAP && HAVE_MREMAP */1716#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL1717#endif /* HAVE_MMAP && HAVE_MREMAP */17181719/* mstate bit set if continguous morecore disabled or failed */1720#define USE_NONCONTIGUOUS_BIT (4U)17211722/* segment bit set in create_mspace_with_base */1723#define EXTERN_BIT (8U)172417251726/* --------------------------- Lock preliminaries ------------------------ */17271728/*1729When locks are defined, there is one global lock, plus1730one per-mspace lock.17311732The global lock_ensures that mparams.magic and other unique1733mparams values are initialized only once. It also protects1734sequences of calls to MORECORE. In many cases sys_alloc requires1735two calls, that should not be interleaved with calls by other1736threads. This does not protect against direct calls to MORECORE1737by other threads not using this lock, so there is still code to1738cope the best we can on interference.17391740Per-mspace locks surround calls to malloc, free, etc.1741By default, locks are simple non-reentrant mutexes.17421743Because lock-protected regions generally have bounded times, it is1744OK to use the supplied simple spinlocks. Spinlocks are likely to1745improve performance for lightly contended applications, but worsen1746performance under heavy contention.17471748If USE_LOCKS is > 1, the definitions of lock routines here are1749bypassed, in which case you will need to define the type MLOCK_T,1750and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK1751and TRY_LOCK. You must also declare a1752static MLOCK_T malloc_global_mutex = { initialization values };.17531754*/17551756#if !USE_LOCKS1757#define USE_LOCK_BIT (0U)1758#define INITIAL_LOCK(l) (0)1759#define DESTROY_LOCK(l) (0)1760#define ACQUIRE_MALLOC_GLOBAL_LOCK()1761#define RELEASE_MALLOC_GLOBAL_LOCK()17621763#else1764#if USE_LOCKS > 11765/* ----------------------- User-defined locks ------------------------ */1766/* Define your own lock implementation here */1767/* #define INITIAL_LOCK(lk) ... */1768/* #define DESTROY_LOCK(lk) ... */1769/* #define ACQUIRE_LOCK(lk) ... */1770/* #define RELEASE_LOCK(lk) ... */1771/* #define TRY_LOCK(lk) ... */1772/* static MLOCK_T malloc_global_mutex = ... */17731774#elif USE_SPIN_LOCKS17751776/* First, define CAS_LOCK and CLEAR_LOCK on ints */1777/* Note CAS_LOCK defined to return 0 on success */17781779#if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1))1780#define CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1)1781#define CLEAR_LOCK(sl) __sync_lock_release(sl)17821783#elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))1784/* Custom spin locks for older gcc on x86 */1785static FORCEINLINE int x86_cas_lock(int *sl) {1786int ret;1787int val = 1;1788int cmp = 0;1789__asm__ __volatile__ ("lock; cmpxchgl %1, %2"1790: "=a" (ret)1791: "r" (val), "m" (*(sl)), "0"(cmp)1792: "memory", "cc");1793return ret;1794}17951796static FORCEINLINE void x86_clear_lock(int* sl) {1797assert(*sl != 0);1798int prev = 0;1799int ret;1800__asm__ __volatile__ ("lock; xchgl %0, %1"1801: "=r" (ret)1802: "m" (*(sl)), "0"(prev)1803: "memory");1804}18051806#define CAS_LOCK(sl) x86_cas_lock(sl)1807#define CLEAR_LOCK(sl) x86_clear_lock(sl)18081809#else /* Win32 MSC */1810#define CAS_LOCK(sl) interlockedexchange(sl, 1)1811#define CLEAR_LOCK(sl) interlockedexchange (sl, 0)18121813#endif /* ... gcc spins locks ... */18141815/* How to yield for a spin lock */1816#define SPINS_PER_YIELD 631817#if defined(_MSC_VER)1818#define SLEEP_EX_DURATION 50 /* delay for yield/sleep */1819#define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE)1820#elif defined (__SVR4) && defined (__sun) /* solaris */1821#define SPIN_LOCK_YIELD thr_yield();1822#elif !defined(LACKS_SCHED_H)1823#define SPIN_LOCK_YIELD sched_yield();1824#else1825#define SPIN_LOCK_YIELD1826#endif /* ... yield ... */18271828#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 01829/* Plain spin locks use single word (embedded in malloc_states) */1830static int spin_acquire_lock(int *sl) {1831int spins = 0;1832while (*(volatile int *)sl != 0 || CAS_LOCK(sl)) {1833if ((++spins & SPINS_PER_YIELD) == 0) {1834SPIN_LOCK_YIELD;1835}1836}1837return 0;1838}18391840#define MLOCK_T int1841#define TRY_LOCK(sl) !CAS_LOCK(sl)1842#define RELEASE_LOCK(sl) CLEAR_LOCK(sl)1843#define ACQUIRE_LOCK(sl) (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0)1844#define INITIAL_LOCK(sl) (*sl = 0)1845#define DESTROY_LOCK(sl) (0)1846static MLOCK_T malloc_global_mutex = 0;18471848#else /* USE_RECURSIVE_LOCKS */1849/* types for lock owners */1850#ifdef WIN321851#define THREAD_ID_T DWORD1852#define CURRENT_THREAD GetCurrentThreadId()1853#define EQ_OWNER(X,Y) ((X) == (Y))1854#else1855/*1856Note: the following assume that pthread_t is a type that can be1857initialized to (casted) zero. If this is not the case, you will need to1858somehow redefine these or not use spin locks.1859*/1860#define THREAD_ID_T pthread_t1861#define CURRENT_THREAD pthread_self()1862#define EQ_OWNER(X,Y) pthread_equal(X, Y)1863#endif18641865struct malloc_recursive_lock {1866int sl;1867unsigned int c;1868THREAD_ID_T threadid;1869};18701871#define MLOCK_T struct malloc_recursive_lock1872static MLOCK_T malloc_global_mutex = { 0, 0, (THREAD_ID_T)0};18731874static FORCEINLINE void recursive_release_lock(MLOCK_T *lk) {1875assert(lk->sl != 0);1876if (--lk->c == 0) {1877CLEAR_LOCK(&lk->sl);1878}1879}18801881static FORCEINLINE int recursive_acquire_lock(MLOCK_T *lk) {1882THREAD_ID_T mythreadid = CURRENT_THREAD;1883int spins = 0;1884for (;;) {1885if (*((volatile int *)(&lk->sl)) == 0) {1886if (!CAS_LOCK(&lk->sl)) {1887lk->threadid = mythreadid;1888lk->c = 1;1889return 0;1890}1891}1892else if (EQ_OWNER(lk->threadid, mythreadid)) {1893++lk->c;1894return 0;1895}1896if ((++spins & SPINS_PER_YIELD) == 0) {1897SPIN_LOCK_YIELD;1898}1899}1900}19011902static FORCEINLINE int recursive_try_lock(MLOCK_T *lk) {1903THREAD_ID_T mythreadid = CURRENT_THREAD;1904if (*((volatile int *)(&lk->sl)) == 0) {1905if (!CAS_LOCK(&lk->sl)) {1906lk->threadid = mythreadid;1907lk->c = 1;1908return 1;1909}1910}1911else if (EQ_OWNER(lk->threadid, mythreadid)) {1912++lk->c;1913return 1;1914}1915return 0;1916}19171918#define RELEASE_LOCK(lk) recursive_release_lock(lk)1919#define TRY_LOCK(lk) recursive_try_lock(lk)1920#define ACQUIRE_LOCK(lk) recursive_acquire_lock(lk)1921#define INITIAL_LOCK(lk) ((lk)->threadid = (THREAD_ID_T)0, (lk)->sl = 0, (lk)->c = 0)1922#define DESTROY_LOCK(lk) (0)1923#endif /* USE_RECURSIVE_LOCKS */19241925#elif defined(WIN32) /* Win32 critical sections */1926#define MLOCK_T CRITICAL_SECTION1927#define ACQUIRE_LOCK(lk) (EnterCriticalSection(lk), 0)1928#define RELEASE_LOCK(lk) LeaveCriticalSection(lk)1929#define TRY_LOCK(lk) TryEnterCriticalSection(lk)1930#define INITIAL_LOCK(lk) (!InitializeCriticalSectionAndSpinCount((lk), 0x80000000|4000))1931#define DESTROY_LOCK(lk) (DeleteCriticalSection(lk), 0)1932#define NEED_GLOBAL_LOCK_INIT19331934static MLOCK_T malloc_global_mutex;1935static volatile long malloc_global_mutex_status;19361937/* Use spin loop to initialize global lock */1938static void init_malloc_global_mutex() {1939for (;;) {1940long stat = malloc_global_mutex_status;1941if (stat > 0)1942return;1943/* transition to < 0 while initializing, then to > 0) */1944if (stat == 0 &&1945interlockedcompareexchange(&malloc_global_mutex_status, -1, 0) == 0) {1946InitializeCriticalSection(&malloc_global_mutex);1947interlockedexchange(&malloc_global_mutex_status,1);1948return;1949}1950SleepEx(0, FALSE);1951}1952}19531954#else /* pthreads-based locks */1955#define MLOCK_T pthread_mutex_t1956#define ACQUIRE_LOCK(lk) pthread_mutex_lock(lk)1957#define RELEASE_LOCK(lk) pthread_mutex_unlock(lk)1958#define TRY_LOCK(lk) (!pthread_mutex_trylock(lk))1959#define INITIAL_LOCK(lk) pthread_init_lock(lk)1960#define DESTROY_LOCK(lk) pthread_mutex_destroy(lk)19611962#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 && defined(linux) && !defined(PTHREAD_MUTEX_RECURSIVE)1963/* Cope with old-style linux recursive lock initialization by adding */1964/* skipped internal declaration from pthread.h */1965extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr,1966int __kind));1967#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP1968#define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y)1969#endif /* USE_RECURSIVE_LOCKS ... */19701971static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER;19721973static int pthread_init_lock (MLOCK_T *lk) {1974pthread_mutexattr_t attr;1975if (pthread_mutexattr_init(&attr)) return 1;1976#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 01977if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1;1978#endif1979if (pthread_mutex_init(lk, &attr)) return 1;1980if (pthread_mutexattr_destroy(&attr)) return 1;1981return 0;1982}19831984#endif /* ... lock types ... */19851986/* Common code for all lock types */1987#define USE_LOCK_BIT (2U)19881989#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK1990#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex);1991#endif19921993#ifndef RELEASE_MALLOC_GLOBAL_LOCK1994#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex);1995#endif19961997#endif /* USE_LOCKS */19981999/* ----------------------- Chunk representations ------------------------ */20002001/*2002(The following includes lightly edited explanations by Colin Plumb.)20032004The malloc_chunk declaration below is misleading (but accurate and2005necessary). It declares a "view" into memory allowing access to2006necessary fields at known offsets from a given base.20072008Chunks of memory are maintained using a `boundary tag' method as2009originally described by Knuth. (See the paper by Paul Wilson2010ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such2011techniques.) Sizes of free chunks are stored both in the front of2012each chunk and at the end. This makes consolidating fragmented2013chunks into bigger chunks fast. The head fields also hold bits2014representing whether chunks are free or in use.20152016Here are some pictures to make it clearer. They are "exploded" to2017show that the state of a chunk can be thought of as extending from2018the high 31 bits of the head field of its header through the2019prev_foot and PINUSE_BIT bit of the following chunk header.20202021A chunk that's in use looks like:20222023chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2024| Size of previous chunk (if P = 0) |2025+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2026+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|2027| Size of this chunk 1| +-+2028mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2029| |2030+- -+2031| |2032+- -+2033| :2034+- size - sizeof(size_t) available payload bytes -+2035: |2036chunk-> +- -+2037| |2038+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2039+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|2040| Size of next chunk (may or may not be in use) | +-+2041mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+20422043And if it's free, it looks like this:20442045chunk-> +- -+2046| User payload (must be in use, or we would have merged!) |2047+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2048+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|2049| Size of this chunk 0| +-+2050mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2051| Next pointer |2052+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2053| Prev pointer |2054+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2055| :2056+- size - sizeof(struct chunk) unused bytes -+2057: |2058chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2059| Size of this chunk |2060+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2061+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|2062| Size of next chunk (must be in use, or we would have merged)| +-+2063mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2064| :2065+- User payload -+2066: |2067+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2068|0|2069+-+2070Note that since we always merge adjacent free chunks, the chunks2071adjacent to a free chunk must be in use.20722073Given a pointer to a chunk (which can be derived trivially from the2074payload pointer) we can, in O(1) time, find out whether the adjacent2075chunks are free, and if so, unlink them from the lists that they2076are on and merge them with the current chunk.20772078Chunks always begin on even word boundaries, so the mem portion2079(which is returned to the user) is also on an even word boundary, and2080thus at least double-word aligned.20812082The P (PINUSE_BIT) bit, stored in the unused low-order bit of the2083chunk size (which is always a multiple of two words), is an in-use2084bit for the *previous* chunk. If that bit is *clear*, then the2085word before the current chunk size contains the previous chunk2086size, and can be used to find the front of the previous chunk.2087The very first chunk allocated always has this bit set, preventing2088access to non-existent (or non-owned) memory. If pinuse is set for2089any given chunk, then you CANNOT determine the size of the2090previous chunk, and might even get a memory addressing fault when2091trying to do so.20922093The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of2094the chunk size redundantly records whether the current chunk is2095inuse (unless the chunk is mmapped). This redundancy enables usage2096checks within free and realloc, and reduces indirection when freeing2097and consolidating chunks.20982099Each freshly allocated chunk must have both cinuse and pinuse set.2100That is, each allocated chunk borders either a previously allocated2101and still in-use chunk, or the base of its memory arena. This is2102ensured by making all allocations from the `lowest' part of any2103found chunk. Further, no free chunk physically borders another one,2104so each free chunk is known to be preceded and followed by either2105inuse chunks or the ends of memory.21062107Note that the `foot' of the current chunk is actually represented2108as the prev_foot of the NEXT chunk. This makes it easier to2109deal with alignments etc but can be very confusing when trying2110to extend or adapt this code.21112112The exceptions to all this are211321141. The special chunk `top' is the top-most available chunk (i.e.,2115the one bordering the end of available memory). It is treated2116specially. Top is never included in any bin, is used only if2117no other chunk is available, and is released back to the2118system if it is very large (see M_TRIM_THRESHOLD). In effect,2119the top chunk is treated as larger (and thus less well2120fitting) than any other available chunk. The top chunk2121doesn't update its trailing size field since there is no next2122contiguous chunk that would have to index off it. However,2123space is still allocated for it (TOP_FOOT_SIZE) to enable2124separation or merging when space is extended.212521263. Chunks allocated via mmap, have both cinuse and pinuse bits2127cleared in their head fields. Because they are allocated2128one-by-one, each must carry its own prev_foot field, which is2129also used to hold the offset this chunk has within its mmapped2130region, which is needed to preserve alignment. Each mmapped2131chunk is trailed by the first two fields of a fake next-chunk2132for sake of usage checks.21332134*/21352136struct malloc_chunk {2137size_t prev_foot; /* Size of previous chunk (if free). */2138size_t head; /* Size and inuse bits. */2139struct malloc_chunk* fd; /* double links -- used only if free. */2140struct malloc_chunk* bk;2141};21422143typedef struct malloc_chunk mchunk;2144typedef struct malloc_chunk* mchunkptr;2145typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */2146typedef unsigned int bindex_t; /* Described below */2147typedef unsigned int binmap_t; /* Described below */2148typedef unsigned int flag_t; /* The type of various bit flag sets */21492150/* ------------------- Chunks sizes and alignments ----------------------- */21512152#define MCHUNK_SIZE (sizeof(mchunk))21532154#if FOOTERS2155#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)2156#else /* FOOTERS */2157#define CHUNK_OVERHEAD (SIZE_T_SIZE)2158#endif /* FOOTERS */21592160/* MMapped chunks need a second word of overhead ... */2161#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)2162/* ... and additional padding for fake next-chunk at foot */2163#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)21642165/* The smallest size we can malloc is an aligned minimal chunk */2166#define MIN_CHUNK_SIZE\2167((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)21682169/* conversion from malloc headers to user pointers, and back */2170#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))2171#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))2172/* chunk associated with aligned address A */2173#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))21742175/* Bounds on request (not chunk) sizes. */2176#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)2177#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)21782179/* pad request bytes into a usable size */2180#define pad_request(req) \2181(((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)21822183/* pad request, checking for minimum (but not maximum) */2184#define request2size(req) \2185(((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))218621872188/* ------------------ Operations on head and foot fields ----------------- */21892190/*2191The head field of a chunk is or'ed with PINUSE_BIT when previous2192adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in2193use, unless mmapped, in which case both bits are cleared.21942195FLAG4_BIT is not used by this malloc, but might be useful in extensions.2196*/21972198#define PINUSE_BIT (SIZE_T_ONE)2199#define CINUSE_BIT (SIZE_T_TWO)2200#define FLAG4_BIT (SIZE_T_FOUR)2201#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)2202#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT)22032204/* Head value for fenceposts */2205#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)22062207/* extraction of fields from head words */2208#define cinuse(p) ((p)->head & CINUSE_BIT)2209#define pinuse(p) ((p)->head & PINUSE_BIT)2210#define flag4inuse(p) ((p)->head & FLAG4_BIT)2211#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT)2212#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0)22132214#define chunksize(p) ((p)->head & ~(FLAG_BITS))22152216#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)2217#define set_flag4(p) ((p)->head |= FLAG4_BIT)2218#define clear_flag4(p) ((p)->head &= ~FLAG4_BIT)22192220/* Treat space at ptr +/- offset as a chunk */2221#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))2222#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))22232224/* Ptr to next or previous physical malloc_chunk. */2225#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS)))2226#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))22272228/* extract next chunk's pinuse bit */2229#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)22302231/* Get/set size at footer */2232#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)2233#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))22342235/* Set size, pinuse bit, and foot */2236#define set_size_and_pinuse_of_free_chunk(p, s)\2237((p)->head = (s|PINUSE_BIT), set_foot(p, s))22382239/* Set size, pinuse bit, foot, and clear next pinuse */2240#define set_free_with_pinuse(p, s, n)\2241(clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))22422243/* Get the internal overhead associated with chunk p */2244#define overhead_for(p)\2245(is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)22462247/* Return true if malloced space is not necessarily cleared */2248#if MMAP_CLEARS2249#define calloc_must_clear(p) (!is_mmapped(p))2250#else /* MMAP_CLEARS */2251#define calloc_must_clear(p) (1)2252#endif /* MMAP_CLEARS */22532254/* ---------------------- Overlaid data structures ----------------------- */22552256/*2257When chunks are not in use, they are treated as nodes of either2258lists or trees.22592260"Small" chunks are stored in circular doubly-linked lists, and look2261like this:22622263chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2264| Size of previous chunk |2265+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2266`head:' | Size of chunk, in bytes |P|2267mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2268| Forward pointer to next chunk in list |2269+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2270| Back pointer to previous chunk in list |2271+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2272| Unused space (may be 0 bytes long) .2273. .2274. |2275nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2276`foot:' | Size of chunk, in bytes |2277+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+22782279Larger chunks are kept in a form of bitwise digital trees (aka2280tries) keyed on chunksizes. Because malloc_tree_chunks are only for2281free chunks greater than 256 bytes, their size doesn't impose any2282constraints on user chunk sizes. Each node looks like:22832284chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2285| Size of previous chunk |2286+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2287`head:' | Size of chunk, in bytes |P|2288mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2289| Forward pointer to next chunk of same size |2290+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2291| Back pointer to previous chunk of same size |2292+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2293| Pointer to left child (child[0]) |2294+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2295| Pointer to right child (child[1]) |2296+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2297| Pointer to parent |2298+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2299| bin index of this chunk |2300+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2301| Unused space .2302. |2303nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2304`foot:' | Size of chunk, in bytes |2305+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+23062307Each tree holding treenodes is a tree of unique chunk sizes. Chunks2308of the same size are arranged in a circularly-linked list, with only2309the oldest chunk (the next to be used, in our FIFO ordering)2310actually in the tree. (Tree members are distinguished by a non-null2311parent pointer.) If a chunk with the same size an an existing node2312is inserted, it is linked off the existing node using pointers that2313work in the same way as fd/bk pointers of small chunks.23142315Each tree contains a power of 2 sized range of chunk sizes (the2316smallest is 0x100 <= x < 0x180), which is is divided in half at each2317tree level, with the chunks in the smaller half of the range (0x1002318<= x < 0x140 for the top nose) in the left subtree and the larger2319half (0x140 <= x < 0x180) in the right subtree. This is, of course,2320done by inspecting individual bits.23212322Using these rules, each node's left subtree contains all smaller2323sizes than its right subtree. However, the node at the root of each2324subtree has no particular ordering relationship to either. (The2325dividing line between the subtree sizes is based on trie relation.)2326If we remove the last chunk of a given size from the interior of the2327tree, we need to replace it with a leaf node. The tree ordering2328rules permit a node to be replaced by any leaf below it.23292330The smallest chunk in a tree (a common operation in a best-fit2331allocator) can be found by walking a path to the leftmost leaf in2332the tree. Unlike a usual binary tree, where we follow left child2333pointers until we reach a null, here we follow the right child2334pointer any time the left one is null, until we reach a leaf with2335both child pointers null. The smallest chunk in the tree will be2336somewhere along that path.23372338The worst case number of steps to add, find, or remove a node is2339bounded by the number of bits differentiating chunks within2340bins. Under current bin calculations, this ranges from 6 up to 212341(for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case2342is of course much better.2343*/23442345struct malloc_tree_chunk {2346/* The first four fields must be compatible with malloc_chunk */2347size_t prev_foot;2348size_t head;2349struct malloc_tree_chunk* fd;2350struct malloc_tree_chunk* bk;23512352struct malloc_tree_chunk* child[2];2353struct malloc_tree_chunk* parent;2354bindex_t index;2355};23562357typedef struct malloc_tree_chunk tchunk;2358typedef struct malloc_tree_chunk* tchunkptr;2359typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */23602361/* A little helper macro for trees */2362#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])23632364/* ----------------------------- Segments -------------------------------- */23652366/*2367Each malloc space may include non-contiguous segments, held in a2368list headed by an embedded malloc_segment record representing the2369top-most space. Segments also include flags holding properties of2370the space. Large chunks that are directly allocated by mmap are not2371included in this list. They are instead independently created and2372destroyed without otherwise keeping track of them.23732374Segment management mainly comes into play for spaces allocated by2375MMAP. Any call to MMAP might or might not return memory that is2376adjacent to an existing segment. MORECORE normally contiguously2377extends the current space, so this space is almost always adjacent,2378which is simpler and faster to deal with. (This is why MORECORE is2379used preferentially to MMAP when both are available -- see2380sys_alloc.) When allocating using MMAP, we don't use any of the2381hinting mechanisms (inconsistently) supported in various2382implementations of unix mmap, or distinguish reserving from2383committing memory. Instead, we just ask for space, and exploit2384contiguity when we get it. It is probably possible to do2385better than this on some systems, but no general scheme seems2386to be significantly better.23872388Management entails a simpler variant of the consolidation scheme2389used for chunks to reduce fragmentation -- new adjacent memory is2390normally prepended or appended to an existing segment. However,2391there are limitations compared to chunk consolidation that mostly2392reflect the fact that segment processing is relatively infrequent2393(occurring only when getting memory from system) and that we2394don't expect to have huge numbers of segments:23952396* Segments are not indexed, so traversal requires linear scans. (It2397would be possible to index these, but is not worth the extra2398overhead and complexity for most programs on most platforms.)2399* New segments are only appended to old ones when holding top-most2400memory; if they cannot be prepended to others, they are held in2401different segments.24022403Except for the top-most segment of an mstate, each segment record2404is kept at the tail of its segment. Segments are added by pushing2405segment records onto the list headed by &mstate.seg for the2406containing mstate.24072408Segment flags control allocation/merge/deallocation policies:2409* If EXTERN_BIT set, then we did not allocate this segment,2410and so should not try to deallocate or merge with others.2411(This currently holds only for the initial segment passed2412into create_mspace_with_base.)2413* If USE_MMAP_BIT set, the segment may be merged with2414other surrounding mmapped segments and trimmed/de-allocated2415using munmap.2416* If neither bit is set, then the segment was obtained using2417MORECORE so can be merged with surrounding MORECORE'd segments2418and deallocated/trimmed using MORECORE with negative arguments.2419*/24202421struct malloc_segment {2422char* base; /* base address */2423size_t size; /* allocated size */2424struct malloc_segment* next; /* ptr to next segment */2425flag_t sflags; /* mmap and extern flag */2426};24272428#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT)2429#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)24302431typedef struct malloc_segment msegment;2432typedef struct malloc_segment* msegmentptr;24332434/* ---------------------------- malloc_state ----------------------------- */24352436/*2437A malloc_state holds all of the bookkeeping for a space.2438The main fields are:24392440Top2441The topmost chunk of the currently active segment. Its size is2442cached in topsize. The actual size of topmost space is2443topsize+TOP_FOOT_SIZE, which includes space reserved for adding2444fenceposts and segment records if necessary when getting more2445space from the system. The size at which to autotrim top is2446cached from mparams in trim_check, except that it is disabled if2447an autotrim fails.24482449Designated victim (dv)2450This is the preferred chunk for servicing small requests that2451don't have exact fits. It is normally the chunk split off most2452recently to service another small request. Its size is cached in2453dvsize. The link fields of this chunk are not maintained since it2454is not kept in a bin.24552456SmallBins2457An array of bin headers for free chunks. These bins hold chunks2458with sizes less than MIN_LARGE_SIZE bytes. Each bin contains2459chunks of all the same size, spaced 8 bytes apart. To simplify2460use in double-linked lists, each bin header acts as a malloc_chunk2461pointing to the real first node, if it exists (else pointing to2462itself). This avoids special-casing for headers. But to avoid2463waste, we allocate only the fd/bk pointers of bins, and then use2464repositioning tricks to treat these as the fields of a chunk.24652466TreeBins2467Treebins are pointers to the roots of trees holding a range of2468sizes. There are 2 equally spaced treebins for each power of two2469from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything2470larger.24712472Bin maps2473There is one bit map for small bins ("smallmap") and one for2474treebins ("treemap). Each bin sets its bit when non-empty, and2475clears the bit when empty. Bit operations are then used to avoid2476bin-by-bin searching -- nearly all "search" is done without ever2477looking at bins that won't be selected. The bit maps2478conservatively use 32 bits per map word, even if on 64bit system.2479For a good description of some of the bit-based techniques used2480here, see Henry S. Warren Jr's book "Hacker's Delight" (and2481supplement at http://hackersdelight.org/). Many of these are2482intended to reduce the branchiness of paths through malloc etc, as2483well as to reduce the number of memory locations read or written.24842485Segments2486A list of segments headed by an embedded malloc_segment record2487representing the initial space.24882489Address check support2490The least_addr field is the least address ever obtained from2491MORECORE or MMAP. Attempted frees and reallocs of any address less2492than this are trapped (unless INSECURE is defined).24932494Magic tag2495A cross-check field that should always hold same value as mparams.magic.24962497Max allowed footprint2498The maximum allowed bytes to allocate from system (zero means no limit)24992500Flags2501Bits recording whether to use MMAP, locks, or contiguous MORECORE25022503Statistics2504Each space keeps track of current and maximum system memory2505obtained via MORECORE or MMAP.25062507Trim support2508Fields holding the amount of unused topmost memory that should trigger2509trimming, and a counter to force periodic scanning to release unused2510non-topmost segments.25112512Locking2513If USE_LOCKS is defined, the "mutex" lock is acquired and released2514around every public call using this mspace.25152516Extension support2517A void* pointer and a size_t field that can be used to help implement2518extensions to this malloc.2519*/25202521/* Bin types, widths and sizes */2522#define NSMALLBINS (32U)2523#define NTREEBINS (32U)2524#define SMALLBIN_SHIFT (3U)2525#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)2526#define TREEBIN_SHIFT (8U)2527#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)2528#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)2529#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)25302531struct malloc_state {2532binmap_t smallmap;2533binmap_t treemap;2534size_t dvsize;2535size_t topsize;2536char* least_addr;2537mchunkptr dv;2538mchunkptr top;2539size_t trim_check;2540size_t release_checks;2541size_t magic;2542mchunkptr smallbins[(NSMALLBINS+1)*2];2543tbinptr treebins[NTREEBINS];2544size_t footprint;2545size_t max_footprint;2546size_t footprint_limit; /* zero means no limit */2547flag_t mflags;2548#if USE_LOCKS2549MLOCK_T mutex; /* locate lock among fields that rarely change */2550#endif /* USE_LOCKS */2551msegment seg;2552void* extp; /* Unused but available for extensions */2553size_t exts;2554};25552556typedef struct malloc_state* mstate;25572558/* ------------- Global malloc_state and malloc_params ------------------- */25592560/*2561malloc_params holds global properties, including those that can be2562dynamically set using mallopt. There is a single instance, mparams,2563initialized in init_mparams. Note that the non-zeroness of "magic"2564also serves as an initialization flag.2565*/25662567struct malloc_params {2568size_t magic;2569size_t page_size;2570size_t granularity;2571size_t mmap_threshold;2572size_t trim_threshold;2573flag_t default_mflags;2574};25752576static struct malloc_params mparams;25772578/* Ensure mparams initialized */2579#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams())25802581#if !ONLY_MSPACES25822583/* The global malloc_state used for all non-"mspace" calls */2584static struct malloc_state _gm_;2585#define gm (&_gm_)2586#define is_global(M) ((M) == &_gm_)25872588#endif /* !ONLY_MSPACES */25892590#define is_initialized(M) ((M)->top != 0)25912592/* -------------------------- system alloc setup ------------------------- */25932594/* Operations on mflags */25952596#define use_lock(M) ((M)->mflags & USE_LOCK_BIT)2597#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)2598#if USE_LOCKS2599#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)2600#else2601#define disable_lock(M)2602#endif26032604#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)2605#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)2606#if HAVE_MMAP2607#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)2608#else2609#define disable_mmap(M)2610#endif26112612#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)2613#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)26142615#define set_lock(M,L)\2616((M)->mflags = (L)?\2617((M)->mflags | USE_LOCK_BIT) :\2618((M)->mflags & ~USE_LOCK_BIT))26192620/* page-align a size */2621#define page_align(S)\2622(((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE))26232624/* granularity-align a size */2625#define granularity_align(S)\2626(((S) + (mparams.granularity - SIZE_T_ONE))\2627& ~(mparams.granularity - SIZE_T_ONE))262826292630/* For mmap, use granularity alignment on windows, else page-align */2631#ifdef WIN322632#define mmap_align(S) granularity_align(S)2633#else2634#define mmap_align(S) page_align(S)2635#endif26362637/* For sys_alloc, enough padding to ensure can malloc request on success */2638#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT)26392640#define is_page_aligned(S)\2641(((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)2642#define is_granularity_aligned(S)\2643(((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)26442645/* True if segment S holds address A */2646#define segment_holds(S, A)\2647((char*)(A) >= S->base && (char*)(A) < S->base + S->size)26482649/* Return segment holding given address */2650static msegmentptr segment_holding(mstate m, char* addr) {2651msegmentptr sp = &m->seg;2652for (;;) {2653if (addr >= sp->base && addr < sp->base + sp->size)2654return sp;2655if ((sp = sp->next) == 0)2656return 0;2657}2658}26592660/* Return true if segment contains a segment link */2661static int has_segment_link(mstate m, msegmentptr ss) {2662msegmentptr sp = &m->seg;2663for (;;) {2664if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)2665return 1;2666if ((sp = sp->next) == 0)2667return 0;2668}2669}26702671#ifndef MORECORE_CANNOT_TRIM2672#define should_trim(M,s) ((s) > (M)->trim_check)2673#else /* MORECORE_CANNOT_TRIM */2674#define should_trim(M,s) (0)2675#endif /* MORECORE_CANNOT_TRIM */26762677/*2678TOP_FOOT_SIZE is padding at the end of a segment, including space2679that may be needed to place segment records and fenceposts when new2680noncontiguous segments are added.2681*/2682#define TOP_FOOT_SIZE\2683(align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)268426852686/* ------------------------------- Hooks -------------------------------- */26872688/*2689PREACTION should be defined to return 0 on success, and nonzero on2690failure. If you are not using locking, you can redefine these to do2691anything you like.2692*/26932694#if USE_LOCKS2695#define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)2696#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }2697#else /* USE_LOCKS */26982699#ifndef PREACTION2700#define PREACTION(M) (0)2701#endif /* PREACTION */27022703#ifndef POSTACTION2704#define POSTACTION(M)2705#endif /* POSTACTION */27062707#endif /* USE_LOCKS */27082709/*2710CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.2711USAGE_ERROR_ACTION is triggered on detected bad frees and2712reallocs. The argument p is an address that might have triggered the2713fault. It is ignored by the two predefined actions, but might be2714useful in custom actions that try to help diagnose errors.2715*/27162717#if PROCEED_ON_ERROR27182719/* A count of the number of corruption errors causing resets */2720int malloc_corruption_error_count;27212722/* default corruption action */2723static void reset_on_error(mstate m);27242725#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)2726#define USAGE_ERROR_ACTION(m, p)27272728#else /* PROCEED_ON_ERROR */27292730#ifndef CORRUPTION_ERROR_ACTION2731#define CORRUPTION_ERROR_ACTION(m) ABORT2732#endif /* CORRUPTION_ERROR_ACTION */27332734#ifndef USAGE_ERROR_ACTION2735#define USAGE_ERROR_ACTION(m,p) ABORT2736#endif /* USAGE_ERROR_ACTION */27372738#endif /* PROCEED_ON_ERROR */273927402741/* -------------------------- Debugging setup ---------------------------- */27422743#if ! DEBUG27442745#define check_free_chunk(M,P)2746#define check_inuse_chunk(M,P)2747#define check_malloced_chunk(M,P,N)2748#define check_mmapped_chunk(M,P)2749#define check_malloc_state(M)2750#define check_top_chunk(M,P)27512752#else /* DEBUG */2753#define check_free_chunk(M,P) do_check_free_chunk(M,P)2754#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)2755#define check_top_chunk(M,P) do_check_top_chunk(M,P)2756#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)2757#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)2758#define check_malloc_state(M) do_check_malloc_state(M)27592760static void do_check_any_chunk(mstate m, mchunkptr p);2761static void do_check_top_chunk(mstate m, mchunkptr p);2762static void do_check_mmapped_chunk(mstate m, mchunkptr p);2763static void do_check_inuse_chunk(mstate m, mchunkptr p);2764static void do_check_free_chunk(mstate m, mchunkptr p);2765static void do_check_malloced_chunk(mstate m, void* mem, size_t s);2766static void do_check_tree(mstate m, tchunkptr t);2767static void do_check_treebin(mstate m, bindex_t i);2768static void do_check_smallbin(mstate m, bindex_t i);2769static void do_check_malloc_state(mstate m);2770static int bin_find(mstate m, mchunkptr x);2771static size_t traverse_and_check(mstate m);2772#endif /* DEBUG */27732774/* ---------------------------- Indexing Bins ---------------------------- */27752776#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)2777#define small_index(s) (bindex_t)((s) >> SMALLBIN_SHIFT)2778#define small_index2size(i) ((i) << SMALLBIN_SHIFT)2779#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))27802781/* addressing by index. See above about smallbin repositioning */2782#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))2783#define treebin_at(M,i) (&((M)->treebins[i]))27842785/* assign tree index for size S to variable I. Use x86 asm if possible */2786#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))2787#define compute_tree_index(S, I)\2788{\2789unsigned int X = S >> TREEBIN_SHIFT;\2790if (X == 0)\2791I = 0;\2792else if (X > 0xFFFF)\2793I = NTREEBINS-1;\2794else {\2795unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \2796I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\2797}\2798}27992800#elif defined (__INTEL_COMPILER)2801#define compute_tree_index(S, I)\2802{\2803size_t X = S >> TREEBIN_SHIFT;\2804if (X == 0)\2805I = 0;\2806else if (X > 0xFFFF)\2807I = NTREEBINS-1;\2808else {\2809unsigned int K = _bit_scan_reverse (X); \2810I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\2811}\2812}28132814#elif defined(_MSC_VER) && _MSC_VER>=13002815#define compute_tree_index(S, I)\2816{\2817size_t X = S >> TREEBIN_SHIFT;\2818if (X == 0)\2819I = 0;\2820else if (X > 0xFFFF)\2821I = NTREEBINS-1;\2822else {\2823unsigned int K;\2824_BitScanReverse((DWORD *) &K, (DWORD) X);\2825I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\2826}\2827}28282829#else /* GNUC */2830#define compute_tree_index(S, I)\2831{\2832size_t X = S >> TREEBIN_SHIFT;\2833if (X == 0)\2834I = 0;\2835else if (X > 0xFFFF)\2836I = NTREEBINS-1;\2837else {\2838unsigned int Y = (unsigned int)X;\2839unsigned int N = ((Y - 0x100) >> 16) & 8;\2840unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\2841N += K;\2842N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\2843K = 14 - N + ((Y <<= K) >> 15);\2844I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\2845}\2846}2847#endif /* GNUC */28482849/* Bit representing maximum resolved size in a treebin at i */2850#define bit_for_tree_index(i) \2851(i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)28522853/* Shift placing maximum resolved bit in a treebin at i as sign bit */2854#define leftshift_for_tree_index(i) \2855((i == NTREEBINS-1)? 0 : \2856((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))28572858/* The size of the smallest chunk held in bin with index i */2859#define minsize_for_tree_index(i) \2860((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \2861(((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))286228632864/* ------------------------ Operations on bin maps ----------------------- */28652866/* bit corresponding to given index */2867#define idx2bit(i) ((binmap_t)(1) << (i))28682869/* Mark/Clear bits with given index */2870#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))2871#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))2872#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))28732874#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))2875#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))2876#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))28772878/* isolate the least set bit of a bitmap */2879#define least_bit(x) ((x) & -(x))28802881/* mask with all bits to left of least bit of x on */2882#define left_bits(x) ((x<<1) | -(x<<1))28832884/* mask with all bits to left of or equal to least bit of x on */2885#define same_or_left_bits(x) ((x) | -(x))28862887/* index corresponding to given bit. Use x86 asm if possible */28882889#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))2890#define compute_bit2idx(X, I)\2891{\2892unsigned int J;\2893J = __builtin_ctz(X); \2894I = (bindex_t)J;\2895}28962897#elif defined (__INTEL_COMPILER)2898#define compute_bit2idx(X, I)\2899{\2900unsigned int J;\2901J = _bit_scan_forward (X); \2902I = (bindex_t)J;\2903}29042905#elif defined(_MSC_VER) && _MSC_VER>=13002906#define compute_bit2idx(X, I)\2907{\2908unsigned int J;\2909_BitScanForward((DWORD *) &J, X);\2910I = (bindex_t)J;\2911}29122913#elif USE_BUILTIN_FFS2914#define compute_bit2idx(X, I) I = ffs(X)-129152916#else2917#define compute_bit2idx(X, I)\2918{\2919unsigned int Y = X - 1;\2920unsigned int K = Y >> (16-4) & 16;\2921unsigned int N = K; Y >>= K;\2922N += K = Y >> (8-3) & 8; Y >>= K;\2923N += K = Y >> (4-2) & 4; Y >>= K;\2924N += K = Y >> (2-1) & 2; Y >>= K;\2925N += K = Y >> (1-0) & 1; Y >>= K;\2926I = (bindex_t)(N + Y);\2927}2928#endif /* GNUC */292929302931/* ----------------------- Runtime Check Support ------------------------- */29322933/*2934For security, the main invariant is that malloc/free/etc never2935writes to a static address other than malloc_state, unless static2936malloc_state itself has been corrupted, which cannot occur via2937malloc (because of these checks). In essence this means that we2938believe all pointers, sizes, maps etc held in malloc_state, but2939check all of those linked or offsetted from other embedded data2940structures. These checks are interspersed with main code in a way2941that tends to minimize their run-time cost.29422943When FOOTERS is defined, in addition to range checking, we also2944verify footer fields of inuse chunks, which can be used guarantee2945that the mstate controlling malloc/free is intact. This is a2946streamlined version of the approach described by William Robertson2947et al in "Run-time Detection of Heap-based Overflows" LISA'032948http://www.usenix.org/events/lisa03/tech/robertson.html The footer2949of an inuse chunk holds the xor of its mstate and a random seed,2950that is checked upon calls to free() and realloc(). This is2951(probabalistically) unguessable from outside the program, but can be2952computed by any code successfully malloc'ing any chunk, so does not2953itself provide protection against code that has already broken2954security through some other means. Unlike Robertson et al, we2955always dynamically check addresses of all offset chunks (previous,2956next, etc). This turns out to be cheaper than relying on hashes.2957*/29582959#if !INSECURE2960/* Check if address a is at least as high as any from MORECORE or MMAP */2961#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)2962/* Check if address of next chunk n is higher than base chunk p */2963#define ok_next(p, n) ((char*)(p) < (char*)(n))2964/* Check if p has inuse status */2965#define ok_inuse(p) is_inuse(p)2966/* Check if p has its pinuse bit on */2967#define ok_pinuse(p) pinuse(p)29682969#else /* !INSECURE */2970#define ok_address(M, a) (1)2971#define ok_next(b, n) (1)2972#define ok_inuse(p) (1)2973#define ok_pinuse(p) (1)2974#endif /* !INSECURE */29752976#if (FOOTERS && !INSECURE)2977/* Check if (alleged) mstate m has expected magic field */2978#define ok_magic(M) ((M)->magic == mparams.magic)2979#else /* (FOOTERS && !INSECURE) */2980#define ok_magic(M) (1)2981#endif /* (FOOTERS && !INSECURE) */29822983/* In gcc, use __builtin_expect to minimize impact of checks */2984#if !INSECURE2985#if defined(__GNUC__) && __GNUC__ >= 32986#define RTCHECK(e) __builtin_expect(e, 1)2987#else /* GNUC */2988#define RTCHECK(e) (e)2989#endif /* GNUC */2990#else /* !INSECURE */2991#define RTCHECK(e) (1)2992#endif /* !INSECURE */29932994/* macros to set up inuse chunks with or without footers */29952996#if !FOOTERS29972998#define mark_inuse_foot(M,p,s)29993000/* Macros for setting head/foot of non-mmapped chunks */30013002/* Set cinuse bit and pinuse bit of next chunk */3003#define set_inuse(M,p,s)\3004((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\3005((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)30063007/* Set cinuse and pinuse of this chunk and pinuse of next chunk */3008#define set_inuse_and_pinuse(M,p,s)\3009((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\3010((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)30113012/* Set size, cinuse and pinuse bit of this chunk */3013#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\3014((p)->head = (s|PINUSE_BIT|CINUSE_BIT))30153016#else /* FOOTERS */30173018/* Set foot of inuse chunk to be xor of mstate and seed */3019#define mark_inuse_foot(M,p,s)\3020(((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))30213022#define get_mstate_for(p)\3023((mstate)(((mchunkptr)((char*)(p) +\3024(chunksize(p))))->prev_foot ^ mparams.magic))30253026#define set_inuse(M,p,s)\3027((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\3028(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \3029mark_inuse_foot(M,p,s))30303031#define set_inuse_and_pinuse(M,p,s)\3032((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\3033(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\3034mark_inuse_foot(M,p,s))30353036#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\3037((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\3038mark_inuse_foot(M, p, s))30393040#endif /* !FOOTERS */30413042/* ---------------------------- setting mparams -------------------------- */30433044/* Initialize mparams */3045static int init_mparams(void) {3046#ifdef NEED_GLOBAL_LOCK_INIT3047call_once(&malloc_global_mutex_init_once, init_malloc_global_mutex);3048#endif30493050ACQUIRE_MALLOC_GLOBAL_LOCK();3051if (mparams.magic == 0) {3052size_t magic;3053size_t psize;3054size_t gsize;30553056#ifndef WIN323057psize = malloc_getpagesize;3058gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize);3059#else /* WIN32 */3060{3061SYSTEM_INFO system_info;3062GetSystemInfo(&system_info);3063psize = system_info.dwPageSize;3064gsize = ((DEFAULT_GRANULARITY != 0)?3065DEFAULT_GRANULARITY : system_info.dwAllocationGranularity);3066}3067#endif /* WIN32 */30683069/* Sanity-check configuration:3070size_t must be unsigned and as wide as pointer type.3071ints must be at least 4 bytes.3072alignment must be at least 8.3073Alignment, min chunk size, and page size must all be powers of 2.3074*/3075if ((sizeof(size_t) != sizeof(char*)) ||3076(MAX_SIZE_T < MIN_CHUNK_SIZE) ||3077(sizeof(int) < 4) ||3078(MALLOC_ALIGNMENT < (size_t)8U) ||3079((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||3080((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||3081((gsize & (gsize-SIZE_T_ONE)) != 0) ||3082((psize & (psize-SIZE_T_ONE)) != 0))3083ABORT;30843085mparams.granularity = gsize;3086mparams.page_size = psize;3087mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;3088mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;3089#if MORECORE_CONTIGUOUS3090mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;3091#else /* MORECORE_CONTIGUOUS */3092mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;3093#endif /* MORECORE_CONTIGUOUS */30943095#if !ONLY_MSPACES3096/* Set up lock for main malloc area */3097gm->mflags = mparams.default_mflags;3098(void)INITIAL_LOCK(&gm->mutex);3099#endif31003101{3102#if USE_DEV_RANDOM3103int fd;3104unsigned char buf[sizeof(size_t)];3105/* Try to use /dev/urandom, else fall back on using time */3106if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&3107read(fd, buf, sizeof(buf)) == sizeof(buf)) {3108magic = *((size_t *) buf);3109close(fd);3110}3111else3112#endif /* USE_DEV_RANDOM */3113#ifdef WIN323114magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U);3115#elif defined(LACKS_TIME_H)3116magic = (size_t)&magic ^ (size_t)0x55555555U;3117#else3118magic = (size_t)(time(0) ^ (size_t)0x55555555U);3119#endif3120magic |= (size_t)8U; /* ensure nonzero */3121magic &= ~(size_t)7U; /* improve chances of fault for bad values */3122/* Until memory modes commonly available, use volatile-write */3123(*(volatile size_t *)(&(mparams.magic))) = magic;3124}3125}31263127RELEASE_MALLOC_GLOBAL_LOCK();3128return 1;3129}31303131/* support for mallopt */3132static int change_mparam(int param_number, int value) {3133size_t val;3134ensure_initialization();3135val = (value == -1)? MAX_SIZE_T : (size_t)value;3136switch(param_number) {3137case M_TRIM_THRESHOLD:3138mparams.trim_threshold = val;3139return 1;3140case M_GRANULARITY:3141if (val >= mparams.page_size && ((val & (val-1)) == 0)) {3142mparams.granularity = val;3143return 1;3144}3145else3146return 0;3147case M_MMAP_THRESHOLD:3148mparams.mmap_threshold = val;3149return 1;3150default:3151return 0;3152}3153}31543155#if DEBUG3156/* ------------------------- Debugging Support --------------------------- */31573158/* Check properties of any chunk, whether free, inuse, mmapped etc */3159static void do_check_any_chunk(mstate m, mchunkptr p) {3160assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));3161assert(ok_address(m, p));3162}31633164/* Check properties of top chunk */3165static void do_check_top_chunk(mstate m, mchunkptr p) {3166msegmentptr sp = segment_holding(m, (char*)p);3167size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */3168assert(sp != 0);3169assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));3170assert(ok_address(m, p));3171assert(sz == m->topsize);3172assert(sz > 0);3173assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);3174assert(pinuse(p));3175assert(!pinuse(chunk_plus_offset(p, sz)));3176}31773178/* Check properties of (inuse) mmapped chunks */3179static void do_check_mmapped_chunk(mstate m, mchunkptr p) {3180size_t sz = chunksize(p);3181size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD);3182assert(is_mmapped(p));3183assert(use_mmap(m));3184assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));3185assert(ok_address(m, p));3186assert(!is_small(sz));3187assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);3188assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);3189assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);3190}31913192/* Check properties of inuse chunks */3193static void do_check_inuse_chunk(mstate m, mchunkptr p) {3194do_check_any_chunk(m, p);3195assert(is_inuse(p));3196assert(next_pinuse(p));3197/* If not pinuse and not mmapped, previous chunk has OK offset */3198assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);3199if (is_mmapped(p))3200do_check_mmapped_chunk(m, p);3201}32023203/* Check properties of free chunks */3204static void do_check_free_chunk(mstate m, mchunkptr p) {3205size_t sz = chunksize(p);3206mchunkptr next = chunk_plus_offset(p, sz);3207do_check_any_chunk(m, p);3208assert(!is_inuse(p));3209assert(!next_pinuse(p));3210assert (!is_mmapped(p));3211if (p != m->dv && p != m->top) {3212if (sz >= MIN_CHUNK_SIZE) {3213assert((sz & CHUNK_ALIGN_MASK) == 0);3214assert(is_aligned(chunk2mem(p)));3215assert(next->prev_foot == sz);3216assert(pinuse(p));3217assert (next == m->top || is_inuse(next));3218assert(p->fd->bk == p);3219assert(p->bk->fd == p);3220}3221else /* markers are always of size SIZE_T_SIZE */3222assert(sz == SIZE_T_SIZE);3223}3224}32253226/* Check properties of malloced chunks at the point they are malloced */3227static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {3228if (mem != 0) {3229mchunkptr p = mem2chunk(mem);3230size_t sz = p->head & ~INUSE_BITS;3231do_check_inuse_chunk(m, p);3232assert((sz & CHUNK_ALIGN_MASK) == 0);3233assert(sz >= MIN_CHUNK_SIZE);3234assert(sz >= s);3235/* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */3236assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));3237}3238}32393240/* Check a tree and its subtrees. */3241static void do_check_tree(mstate m, tchunkptr t) {3242tchunkptr head = 0;3243tchunkptr u = t;3244bindex_t tindex = t->index;3245size_t tsize = chunksize(t);3246bindex_t idx;3247compute_tree_index(tsize, idx);3248assert(tindex == idx);3249assert(tsize >= MIN_LARGE_SIZE);3250assert(tsize >= minsize_for_tree_index(idx));3251assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));32523253do { /* traverse through chain of same-sized nodes */3254do_check_any_chunk(m, ((mchunkptr)u));3255assert(u->index == tindex);3256assert(chunksize(u) == tsize);3257assert(!is_inuse(u));3258assert(!next_pinuse(u));3259assert(u->fd->bk == u);3260assert(u->bk->fd == u);3261if (u->parent == 0) {3262assert(u->child[0] == 0);3263assert(u->child[1] == 0);3264}3265else {3266assert(head == 0); /* only one node on chain has parent */3267head = u;3268assert(u->parent != u);3269assert (u->parent->child[0] == u ||3270u->parent->child[1] == u ||3271*((tbinptr*)(u->parent)) == u);3272if (u->child[0] != 0) {3273assert(u->child[0]->parent == u);3274assert(u->child[0] != u);3275do_check_tree(m, u->child[0]);3276}3277if (u->child[1] != 0) {3278assert(u->child[1]->parent == u);3279assert(u->child[1] != u);3280do_check_tree(m, u->child[1]);3281}3282if (u->child[0] != 0 && u->child[1] != 0) {3283assert(chunksize(u->child[0]) < chunksize(u->child[1]));3284}3285}3286u = u->fd;3287} while (u != t);3288assert(head != 0);3289}32903291/* Check all the chunks in a treebin. */3292static void do_check_treebin(mstate m, bindex_t i) {3293tbinptr* tb = treebin_at(m, i);3294tchunkptr t = *tb;3295int empty = (m->treemap & (1U << i)) == 0;3296if (t == 0)3297assert(empty);3298if (!empty)3299do_check_tree(m, t);3300}33013302/* Check all the chunks in a smallbin. */3303static void do_check_smallbin(mstate m, bindex_t i) {3304sbinptr b = smallbin_at(m, i);3305mchunkptr p = b->bk;3306unsigned int empty = (m->smallmap & (1U << i)) == 0;3307if (p == b)3308assert(empty);3309if (!empty) {3310for (; p != b; p = p->bk) {3311size_t size = chunksize(p);3312mchunkptr q;3313/* each chunk claims to be free */3314do_check_free_chunk(m, p);3315/* chunk belongs in bin */3316assert(small_index(size) == i);3317assert(p->bk == b || chunksize(p->bk) == chunksize(p));3318/* chunk is followed by an inuse chunk */3319q = next_chunk(p);3320if (q->head != FENCEPOST_HEAD)3321do_check_inuse_chunk(m, q);3322}3323}3324}33253326/* Find x in a bin. Used in other check functions. */3327static int bin_find(mstate m, mchunkptr x) {3328size_t size = chunksize(x);3329if (is_small(size)) {3330bindex_t sidx = small_index(size);3331sbinptr b = smallbin_at(m, sidx);3332if (smallmap_is_marked(m, sidx)) {3333mchunkptr p = b;3334do {3335if (p == x)3336return 1;3337} while ((p = p->fd) != b);3338}3339}3340else {3341bindex_t tidx;3342compute_tree_index(size, tidx);3343if (treemap_is_marked(m, tidx)) {3344tchunkptr t = *treebin_at(m, tidx);3345size_t sizebits = size << leftshift_for_tree_index(tidx);3346while (t != 0 && chunksize(t) != size) {3347t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];3348sizebits <<= 1;3349}3350if (t != 0) {3351tchunkptr u = t;3352do {3353if (u == (tchunkptr)x)3354return 1;3355} while ((u = u->fd) != t);3356}3357}3358}3359return 0;3360}33613362/* Traverse each chunk and check it; return total */3363static size_t traverse_and_check(mstate m) {3364size_t sum = 0;3365if (is_initialized(m)) {3366msegmentptr s = &m->seg;3367sum += m->topsize + TOP_FOOT_SIZE;3368while (s != 0) {3369mchunkptr q = align_as_chunk(s->base);3370mchunkptr lastq = 0;3371assert(pinuse(q));3372while (segment_holds(s, q) &&3373q != m->top && q->head != FENCEPOST_HEAD) {3374sum += chunksize(q);3375if (is_inuse(q)) {3376assert(!bin_find(m, q));3377do_check_inuse_chunk(m, q);3378}3379else {3380assert(q == m->dv || bin_find(m, q));3381assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */3382do_check_free_chunk(m, q);3383}3384lastq = q;3385q = next_chunk(q);3386}3387s = s->next;3388}3389}3390return sum;3391}339233933394/* Check all properties of malloc_state. */3395static void do_check_malloc_state(mstate m) {3396bindex_t i;3397size_t total;3398/* check bins */3399for (i = 0; i < NSMALLBINS; ++i)3400do_check_smallbin(m, i);3401for (i = 0; i < NTREEBINS; ++i)3402do_check_treebin(m, i);34033404if (m->dvsize != 0) { /* check dv chunk */3405do_check_any_chunk(m, m->dv);3406assert(m->dvsize == chunksize(m->dv));3407assert(m->dvsize >= MIN_CHUNK_SIZE);3408assert(bin_find(m, m->dv) == 0);3409}34103411if (m->top != 0) { /* check top chunk */3412do_check_top_chunk(m, m->top);3413/*assert(m->topsize == chunksize(m->top)); redundant */3414assert(m->topsize > 0);3415assert(bin_find(m, m->top) == 0);3416}34173418total = traverse_and_check(m);3419assert(total <= m->footprint);3420assert(m->footprint <= m->max_footprint);3421}3422#endif /* DEBUG */34233424/* ----------------------------- statistics ------------------------------ */34253426#if !NO_MALLINFO3427static struct mallinfo internal_mallinfo(mstate m) {3428struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };3429ensure_initialization();3430if (!PREACTION(m)) {3431check_malloc_state(m);3432if (is_initialized(m)) {3433size_t nfree = SIZE_T_ONE; /* top always free */3434size_t mfree = m->topsize + TOP_FOOT_SIZE;3435size_t sum = mfree;3436msegmentptr s = &m->seg;3437while (s != 0) {3438mchunkptr q = align_as_chunk(s->base);3439while (segment_holds(s, q) &&3440q != m->top && q->head != FENCEPOST_HEAD) {3441size_t sz = chunksize(q);3442sum += sz;3443if (!is_inuse(q)) {3444mfree += sz;3445++nfree;3446}3447q = next_chunk(q);3448}3449s = s->next;3450}34513452nm.arena = sum;3453nm.ordblks = nfree;3454nm.hblkhd = m->footprint - sum;3455nm.usmblks = m->max_footprint;3456nm.uordblks = m->footprint - mfree;3457nm.fordblks = mfree;3458nm.keepcost = m->topsize;3459}34603461POSTACTION(m);3462}3463return nm;3464}3465#endif /* !NO_MALLINFO */34663467#if !NO_MALLOC_STATS3468static void internal_malloc_stats(mstate m) {3469ensure_initialization();3470if (!PREACTION(m)) {3471size_t maxfp = 0;3472size_t fp = 0;3473size_t used = 0;3474check_malloc_state(m);3475if (is_initialized(m)) {3476msegmentptr s = &m->seg;3477maxfp = m->max_footprint;3478fp = m->footprint;3479used = fp - (m->topsize + TOP_FOOT_SIZE);34803481while (s != 0) {3482mchunkptr q = align_as_chunk(s->base);3483while (segment_holds(s, q) &&3484q != m->top && q->head != FENCEPOST_HEAD) {3485if (!is_inuse(q))3486used -= chunksize(q);3487q = next_chunk(q);3488}3489s = s->next;3490}3491}3492POSTACTION(m); /* drop lock */3493fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));3494fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp));3495fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used));3496}3497}3498#endif /* NO_MALLOC_STATS */34993500/* ----------------------- Operations on smallbins ----------------------- */35013502/*3503Various forms of linking and unlinking are defined as macros. Even3504the ones for trees, which are very long but have very short typical3505paths. This is ugly but reduces reliance on inlining support of3506compilers.3507*/35083509/* Link a free chunk into a smallbin */3510#define insert_small_chunk(M, P, S) {\3511bindex_t I = small_index(S);\3512mchunkptr B = smallbin_at(M, I);\3513mchunkptr F = B;\3514assert(S >= MIN_CHUNK_SIZE);\3515if (!smallmap_is_marked(M, I))\3516mark_smallmap(M, I);\3517else if (RTCHECK(ok_address(M, B->fd)))\3518F = B->fd;\3519else {\3520CORRUPTION_ERROR_ACTION(M);\3521}\3522B->fd = P;\3523F->bk = P;\3524P->fd = F;\3525P->bk = B;\3526}35273528/* Unlink a chunk from a smallbin */3529#define unlink_small_chunk(M, P, S) {\3530mchunkptr F = P->fd;\3531mchunkptr B = P->bk;\3532bindex_t I = small_index(S);\3533assert(P != B);\3534assert(P != F);\3535assert(chunksize(P) == small_index2size(I));\3536if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { \3537if (B == F) {\3538clear_smallmap(M, I);\3539}\3540else if (RTCHECK(B == smallbin_at(M,I) ||\3541(ok_address(M, B) && B->fd == P))) {\3542F->bk = B;\3543B->fd = F;\3544}\3545else {\3546CORRUPTION_ERROR_ACTION(M);\3547}\3548}\3549else {\3550CORRUPTION_ERROR_ACTION(M);\3551}\3552}35533554/* Unlink the first chunk from a smallbin */3555#define unlink_first_small_chunk(M, B, P, I) {\3556mchunkptr F = P->fd;\3557assert(P != B);\3558assert(P != F);\3559assert(chunksize(P) == small_index2size(I));\3560if (B == F) {\3561clear_smallmap(M, I);\3562}\3563else if (RTCHECK(ok_address(M, F) && F->bk == P)) {\3564F->bk = B;\3565B->fd = F;\3566}\3567else {\3568CORRUPTION_ERROR_ACTION(M);\3569}\3570}35713572/* Replace dv node, binning the old one */3573/* Used only when dvsize known to be small */3574#define replace_dv(M, P, S) {\3575size_t DVS = M->dvsize;\3576assert(is_small(DVS));\3577if (DVS != 0) {\3578mchunkptr DV = M->dv;\3579insert_small_chunk(M, DV, DVS);\3580}\3581M->dvsize = S;\3582M->dv = P;\3583}35843585/* ------------------------- Operations on trees ------------------------- */35863587/* Insert chunk into tree */3588#define insert_large_chunk(M, X, S) {\3589tbinptr* H;\3590bindex_t I;\3591compute_tree_index(S, I);\3592H = treebin_at(M, I);\3593X->index = I;\3594X->child[0] = X->child[1] = 0;\3595if (!treemap_is_marked(M, I)) {\3596mark_treemap(M, I);\3597*H = X;\3598X->parent = (tchunkptr)H;\3599X->fd = X->bk = X;\3600}\3601else {\3602tchunkptr T = *H;\3603size_t K = S << leftshift_for_tree_index(I);\3604for (;;) {\3605if (chunksize(T) != S) {\3606tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\3607K <<= 1;\3608if (*C != 0)\3609T = *C;\3610else if (RTCHECK(ok_address(M, C))) {\3611*C = X;\3612X->parent = T;\3613X->fd = X->bk = X;\3614break;\3615}\3616else {\3617CORRUPTION_ERROR_ACTION(M);\3618break;\3619}\3620}\3621else {\3622tchunkptr F = T->fd;\3623if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\3624T->fd = F->bk = X;\3625X->fd = F;\3626X->bk = T;\3627X->parent = 0;\3628break;\3629}\3630else {\3631CORRUPTION_ERROR_ACTION(M);\3632break;\3633}\3634}\3635}\3636}\3637}36383639/*3640Unlink steps:364136421. If x is a chained node, unlink it from its same-sized fd/bk links3643and choose its bk node as its replacement.36442. If x was the last node of its size, but not a leaf node, it must3645be replaced with a leaf node (not merely one with an open left or3646right), to make sure that lefts and rights of descendents3647correspond properly to bit masks. We use the rightmost descendent3648of x. We could use any other leaf, but this is easy to locate and3649tends to counteract removal of leftmosts elsewhere, and so keeps3650paths shorter than minimally guaranteed. This doesn't loop much3651because on average a node in a tree is near the bottom.36523. If x is the base of a chain (i.e., has parent links) relink3653x's parent and children to x's replacement (or null if none).3654*/36553656#define unlink_large_chunk(M, X) {\3657tchunkptr XP = X->parent;\3658tchunkptr R;\3659if (X->bk != X) {\3660tchunkptr F = X->fd;\3661R = X->bk;\3662if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {\3663F->bk = R;\3664R->fd = F;\3665}\3666else {\3667CORRUPTION_ERROR_ACTION(M);\3668}\3669}\3670else {\3671tchunkptr* RP;\3672if (((R = *(RP = &(X->child[1]))) != 0) ||\3673((R = *(RP = &(X->child[0]))) != 0)) {\3674tchunkptr* CP;\3675while ((*(CP = &(R->child[1])) != 0) ||\3676(*(CP = &(R->child[0])) != 0)) {\3677R = *(RP = CP);\3678}\3679if (RTCHECK(ok_address(M, RP)))\3680*RP = 0;\3681else {\3682CORRUPTION_ERROR_ACTION(M);\3683}\3684}\3685}\3686if (XP != 0) {\3687tbinptr* H = treebin_at(M, X->index);\3688if (X == *H) {\3689if ((*H = R) == 0) \3690clear_treemap(M, X->index);\3691}\3692else if (RTCHECK(ok_address(M, XP))) {\3693if (XP->child[0] == X) \3694XP->child[0] = R;\3695else \3696XP->child[1] = R;\3697}\3698else\3699CORRUPTION_ERROR_ACTION(M);\3700if (R != 0) {\3701if (RTCHECK(ok_address(M, R))) {\3702tchunkptr C0, C1;\3703R->parent = XP;\3704if ((C0 = X->child[0]) != 0) {\3705if (RTCHECK(ok_address(M, C0))) {\3706R->child[0] = C0;\3707C0->parent = R;\3708}\3709else\3710CORRUPTION_ERROR_ACTION(M);\3711}\3712if ((C1 = X->child[1]) != 0) {\3713if (RTCHECK(ok_address(M, C1))) {\3714R->child[1] = C1;\3715C1->parent = R;\3716}\3717else\3718CORRUPTION_ERROR_ACTION(M);\3719}\3720}\3721else\3722CORRUPTION_ERROR_ACTION(M);\3723}\3724}\3725}37263727/* Relays to large vs small bin operations */37283729#define insert_chunk(M, P, S)\3730if (is_small(S)) insert_small_chunk(M, P, S)\3731else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }37323733#define unlink_chunk(M, P, S)\3734if (is_small(S)) unlink_small_chunk(M, P, S)\3735else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }373637373738/* Relays to internal calls to malloc/free from realloc, memalign etc */37393740#if ONLY_MSPACES3741#define internal_malloc(m, b) mspace_malloc(m, b)3742#define internal_free(m, mem) mspace_free(m,mem);3743#else /* ONLY_MSPACES */3744#if MSPACES3745#define internal_malloc(m, b)\3746((m == gm)? dlmalloc(b) : mspace_malloc(m, b))3747#define internal_free(m, mem)\3748if (m == gm) dlfree(mem); else mspace_free(m,mem);3749#else /* MSPACES */3750#define internal_malloc(m, b) dlmalloc(b)3751#define internal_free(m, mem) dlfree(mem)3752#endif /* MSPACES */3753#endif /* ONLY_MSPACES */37543755/* ----------------------- Direct-mmapping chunks ----------------------- */37563757/*3758Directly mmapped chunks are set up with an offset to the start of3759the mmapped region stored in the prev_foot field of the chunk. This3760allows reconstruction of the required argument to MUNMAP when freed,3761and also allows adjustment of the returned chunk to meet alignment3762requirements (especially in memalign).3763*/37643765/* Malloc using mmap */3766static void* mmap_alloc(mstate m, size_t nb) {3767size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);3768if (m->footprint_limit != 0) {3769size_t fp = m->footprint + mmsize;3770if (fp <= m->footprint || fp > m->footprint_limit)3771return 0;3772}3773if (mmsize > nb) { /* Check for wrap around 0 */3774char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));3775if (mm != CMFAIL) {3776size_t offset = align_offset(chunk2mem(mm));3777size_t psize = mmsize - offset - MMAP_FOOT_PAD;3778mchunkptr p = (mchunkptr)(mm + offset);3779p->prev_foot = offset;3780p->head = psize;3781mark_inuse_foot(m, p, psize);3782chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;3783chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;37843785if (m->least_addr == 0 || mm < m->least_addr)3786m->least_addr = mm;3787if ((m->footprint += mmsize) > m->max_footprint)3788m->max_footprint = m->footprint;3789assert(is_aligned(chunk2mem(p)));3790check_mmapped_chunk(m, p);3791return chunk2mem(p);3792}3793}3794return 0;3795}37963797/* Realloc using mmap */3798static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb, int flags) {3799size_t oldsize = chunksize(oldp);3800(void) flags;3801if (is_small(nb)) /* Can't shrink mmap regions below small size */3802return 0;3803/* Keep old chunk if big enough but not too big */3804if (oldsize >= nb + SIZE_T_SIZE &&3805(oldsize - nb) <= (mparams.granularity << 1))3806return oldp;3807else {3808size_t offset = oldp->prev_foot;3809size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;3810size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);3811char* cp = (char*)CALL_MREMAP((char*)oldp - offset,3812oldmmsize, newmmsize, flags);3813if (cp != CMFAIL) {3814mchunkptr newp = (mchunkptr)(cp + offset);3815size_t psize = newmmsize - offset - MMAP_FOOT_PAD;3816newp->head = psize;3817mark_inuse_foot(m, newp, psize);3818chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;3819chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;38203821if (cp < m->least_addr)3822m->least_addr = cp;3823if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)3824m->max_footprint = m->footprint;3825check_mmapped_chunk(m, newp);3826return newp;3827}3828}3829return 0;3830}383138323833/* -------------------------- mspace management -------------------------- */38343835/* Initialize top chunk and its size */3836static void init_top(mstate m, mchunkptr p, size_t psize) {3837/* Ensure alignment */3838size_t offset = align_offset(chunk2mem(p));3839p = (mchunkptr)((char*)p + offset);3840psize -= offset;38413842m->top = p;3843m->topsize = psize;3844p->head = psize | PINUSE_BIT;3845/* set size of fake trailing chunk holding overhead space only once */3846chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;3847m->trim_check = mparams.trim_threshold; /* reset on each update */3848}38493850/* Initialize bins for a new mstate that is otherwise zeroed out */3851static void init_bins(mstate m) {3852/* Establish circular links for smallbins */3853bindex_t i;3854for (i = 0; i < NSMALLBINS; ++i) {3855sbinptr bin = smallbin_at(m,i);3856bin->fd = bin->bk = bin;3857}3858}38593860#if PROCEED_ON_ERROR38613862/* default corruption action */3863static void reset_on_error(mstate m) {3864int i;3865++malloc_corruption_error_count;3866/* Reinitialize fields to forget about all memory */3867m->smallmap = m->treemap = 0;3868m->dvsize = m->topsize = 0;3869m->seg.base = 0;3870m->seg.size = 0;3871m->seg.next = 0;3872m->top = m->dv = 0;3873for (i = 0; i < NTREEBINS; ++i)3874*treebin_at(m, i) = 0;3875init_bins(m);3876}3877#endif /* PROCEED_ON_ERROR */38783879/* Allocate chunk and prepend remainder with chunk in successor base. */3880static void* prepend_alloc(mstate m, char* newbase, char* oldbase,3881size_t nb) {3882mchunkptr p = align_as_chunk(newbase);3883mchunkptr oldfirst = align_as_chunk(oldbase);3884size_t psize = (char*)oldfirst - (char*)p;3885mchunkptr q = chunk_plus_offset(p, nb);3886size_t qsize = psize - nb;3887set_size_and_pinuse_of_inuse_chunk(m, p, nb);38883889assert((char*)oldfirst > (char*)q);3890assert(pinuse(oldfirst));3891assert(qsize >= MIN_CHUNK_SIZE);38923893/* consolidate remainder with first chunk of old base */3894if (oldfirst == m->top) {3895size_t tsize = m->topsize += qsize;3896m->top = q;3897q->head = tsize | PINUSE_BIT;3898check_top_chunk(m, q);3899}3900else if (oldfirst == m->dv) {3901size_t dsize = m->dvsize += qsize;3902m->dv = q;3903set_size_and_pinuse_of_free_chunk(q, dsize);3904}3905else {3906if (!is_inuse(oldfirst)) {3907size_t nsize = chunksize(oldfirst);3908unlink_chunk(m, oldfirst, nsize);3909oldfirst = chunk_plus_offset(oldfirst, nsize);3910qsize += nsize;3911}3912set_free_with_pinuse(q, qsize, oldfirst);3913insert_chunk(m, q, qsize);3914check_free_chunk(m, q);3915}39163917check_malloced_chunk(m, chunk2mem(p), nb);3918return chunk2mem(p);3919}39203921/* Add a segment to hold a new noncontiguous region */3922static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {3923/* Determine locations and sizes of segment, fenceposts, old top */3924char* old_top = (char*)m->top;3925msegmentptr oldsp = segment_holding(m, old_top);3926char* old_end = oldsp->base + oldsp->size;3927size_t ssize = pad_request(sizeof(struct malloc_segment));3928char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);3929size_t offset = align_offset(chunk2mem(rawsp));3930char* asp = rawsp + offset;3931char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;3932mchunkptr sp = (mchunkptr)csp;3933msegmentptr ss = (msegmentptr)(chunk2mem(sp));3934mchunkptr tnext = chunk_plus_offset(sp, ssize);3935mchunkptr p = tnext;3936int nfences = 0;39373938/* reset top to new space */3939init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);39403941/* Set up segment record */3942assert(is_aligned(ss));3943set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);3944*ss = m->seg; /* Push current record */3945m->seg.base = tbase;3946m->seg.size = tsize;3947m->seg.sflags = mmapped;3948m->seg.next = ss;39493950/* Insert trailing fenceposts */3951for (;;) {3952mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);3953p->head = FENCEPOST_HEAD;3954++nfences;3955if ((char*)(&(nextp->head)) < old_end)3956p = nextp;3957else3958break;3959}3960assert(nfences >= 2);39613962/* Insert the rest of old top into a bin as an ordinary free chunk */3963if (csp != old_top) {3964mchunkptr q = (mchunkptr)old_top;3965size_t psize = csp - old_top;3966mchunkptr tn = chunk_plus_offset(q, psize);3967set_free_with_pinuse(q, psize, tn);3968insert_chunk(m, q, psize);3969}39703971check_top_chunk(m, m->top);3972}39733974/* -------------------------- System allocation -------------------------- */39753976/* Get memory from system using MORECORE or MMAP */3977static void* sys_alloc(mstate m, size_t nb) {3978char* tbase = CMFAIL;3979size_t tsize = 0;3980flag_t mmap_flag = 0;3981size_t asize; /* allocation size */39823983ensure_initialization();39843985/* Directly map large chunks, but only if already initialized */3986if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) {3987void* mem = mmap_alloc(m, nb);3988if (mem != 0)3989return mem;3990}39913992asize = granularity_align(nb + SYS_ALLOC_PADDING);3993if (asize <= nb)3994return 0; /* wraparound */3995if (m->footprint_limit != 0) {3996size_t fp = m->footprint + asize;3997if (fp <= m->footprint || fp > m->footprint_limit)3998return 0;3999}40004001/*4002Try getting memory in any of three ways (in most-preferred to4003least-preferred order):40041. A call to MORECORE that can normally contiguously extend memory.4005(disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or4006or main space is mmapped or a previous contiguous call failed)40072. A call to MMAP new space (disabled if not HAVE_MMAP).4008Note that under the default settings, if MORECORE is unable to4009fulfill a request, and HAVE_MMAP is true, then mmap is4010used as a noncontiguous system allocator. This is a useful backup4011strategy for systems with holes in address spaces -- in this case4012sbrk cannot contiguously expand the heap, but mmap may be able to4013find space.40143. A call to MORECORE that cannot usually contiguously extend memory.4015(disabled if not HAVE_MORECORE)40164017In all cases, we need to request enough bytes from system to ensure4018we can malloc nb bytes upon success, so pad with enough space for4019top_foot, plus alignment-pad to make sure we don't lose bytes if4020not on boundary, and round this up to a granularity unit.4021*/40224023if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {4024char* br = CMFAIL;4025msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);4026ACQUIRE_MALLOC_GLOBAL_LOCK();40274028if (ss == 0) { /* First time through or recovery */4029char* base = (char*)CALL_MORECORE(0);4030if (base != CMFAIL) {4031size_t fp;4032/* Adjust to end on a page boundary */4033if (!is_page_aligned(base))4034asize += (page_align((size_t)base) - (size_t)base);4035fp = m->footprint + asize; /* recheck limits */4036if (asize > nb && asize < HALF_MAX_SIZE_T &&4037(m->footprint_limit == 0 ||4038(fp > m->footprint && fp <= m->footprint_limit)) &&4039(br = (char*)(CALL_MORECORE(asize))) == base) {4040tbase = base;4041tsize = asize;4042}4043}4044}4045else {4046/* Subtract out existing available top space from MORECORE request. */4047asize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING);4048/* Use mem here only if it did continuously extend old space */4049if (asize < HALF_MAX_SIZE_T &&4050(br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) {4051tbase = br;4052tsize = asize;4053}4054}40554056if (tbase == CMFAIL) { /* Cope with partial failure */4057if (br != CMFAIL) { /* Try to use/extend the space we did get */4058if (asize < HALF_MAX_SIZE_T &&4059asize < nb + SYS_ALLOC_PADDING) {4060size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - asize);4061if (esize < HALF_MAX_SIZE_T) {4062char* end = (char*)CALL_MORECORE(esize);4063if (end != CMFAIL)4064asize += esize;4065else { /* Can't use; try to release */4066(void) CALL_MORECORE(-asize);4067br = CMFAIL;4068}4069}4070}4071}4072if (br != CMFAIL) { /* Use the space we did get */4073tbase = br;4074tsize = asize;4075}4076else4077disable_contiguous(m); /* Don't try contiguous path in the future */4078}40794080RELEASE_MALLOC_GLOBAL_LOCK();4081}40824083if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */4084char* mp = (char*)(CALL_MMAP(asize));4085if (mp != CMFAIL) {4086tbase = mp;4087tsize = asize;4088mmap_flag = USE_MMAP_BIT;4089}4090}40914092if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */4093if (asize < HALF_MAX_SIZE_T) {4094char* br = CMFAIL;4095char* end = CMFAIL;4096ACQUIRE_MALLOC_GLOBAL_LOCK();4097br = (char*)(CALL_MORECORE(asize));4098end = (char*)(CALL_MORECORE(0));4099RELEASE_MALLOC_GLOBAL_LOCK();4100if (br != CMFAIL && end != CMFAIL && br < end) {4101size_t ssize = end - br;4102if (ssize > nb + TOP_FOOT_SIZE) {4103tbase = br;4104tsize = ssize;4105}4106}4107}4108}41094110if (tbase != CMFAIL) {41114112if ((m->footprint += tsize) > m->max_footprint)4113m->max_footprint = m->footprint;41144115if (!is_initialized(m)) { /* first-time initialization */4116if (m->least_addr == 0 || tbase < m->least_addr)4117m->least_addr = tbase;4118m->seg.base = tbase;4119m->seg.size = tsize;4120m->seg.sflags = mmap_flag;4121m->magic = mparams.magic;4122m->release_checks = MAX_RELEASE_CHECK_RATE;4123init_bins(m);4124#if !ONLY_MSPACES4125if (is_global(m))4126init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);4127else4128#endif4129{4130/* Offset top by embedded malloc_state */4131mchunkptr mn = next_chunk(mem2chunk(m));4132init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);4133}4134}41354136else {4137/* Try to merge with an existing segment */4138msegmentptr sp = &m->seg;4139/* Only consider most recent segment if traversal suppressed */4140while (sp != 0 && tbase != sp->base + sp->size)4141sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;4142if (sp != 0 &&4143!is_extern_segment(sp) &&4144(sp->sflags & USE_MMAP_BIT) == mmap_flag &&4145segment_holds(sp, m->top)) { /* append */4146sp->size += tsize;4147init_top(m, m->top, m->topsize + tsize);4148}4149else {4150if (tbase < m->least_addr)4151m->least_addr = tbase;4152sp = &m->seg;4153while (sp != 0 && sp->base != tbase + tsize)4154sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;4155if (sp != 0 &&4156!is_extern_segment(sp) &&4157(sp->sflags & USE_MMAP_BIT) == mmap_flag) {4158char* oldbase = sp->base;4159sp->base = tbase;4160sp->size += tsize;4161return prepend_alloc(m, tbase, oldbase, nb);4162}4163else4164add_segment(m, tbase, tsize, mmap_flag);4165}4166}41674168if (nb < m->topsize) { /* Allocate from new or extended top space */4169size_t rsize = m->topsize -= nb;4170mchunkptr p = m->top;4171mchunkptr r = m->top = chunk_plus_offset(p, nb);4172r->head = rsize | PINUSE_BIT;4173set_size_and_pinuse_of_inuse_chunk(m, p, nb);4174check_top_chunk(m, m->top);4175check_malloced_chunk(m, chunk2mem(p), nb);4176return chunk2mem(p);4177}4178}41794180MALLOC_FAILURE_ACTION;4181return 0;4182}41834184/* ----------------------- system deallocation -------------------------- */41854186/* Unmap and unlink any mmapped segments that don't contain used chunks */4187static size_t release_unused_segments(mstate m) {4188size_t released = 0;4189int nsegs = 0;4190msegmentptr pred = &m->seg;4191msegmentptr sp = pred->next;4192while (sp != 0) {4193char* base = sp->base;4194size_t size = sp->size;4195msegmentptr next = sp->next;4196++nsegs;4197if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {4198mchunkptr p = align_as_chunk(base);4199size_t psize = chunksize(p);4200/* Can unmap if first chunk holds entire segment and not pinned */4201if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {4202tchunkptr tp = (tchunkptr)p;4203assert(segment_holds(sp, (char*)sp));4204if (p == m->dv) {4205m->dv = 0;4206m->dvsize = 0;4207}4208else {4209unlink_large_chunk(m, tp);4210}4211if (CALL_MUNMAP(base, size) == 0) {4212released += size;4213m->footprint -= size;4214/* unlink obsoleted record */4215sp = pred;4216sp->next = next;4217}4218else { /* back out if cannot unmap */4219insert_large_chunk(m, tp, psize);4220}4221}4222}4223if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */4224break;4225pred = sp;4226sp = next;4227}4228/* Reset check counter */4229m->release_checks = ((nsegs > MAX_RELEASE_CHECK_RATE)?4230nsegs : MAX_RELEASE_CHECK_RATE);4231return released;4232}42334234static int sys_trim(mstate m, size_t pad) {4235size_t released = 0;4236ensure_initialization();4237if (pad < MAX_REQUEST && is_initialized(m)) {4238pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */42394240if (m->topsize > pad) {4241/* Shrink top space in granularity-size units, keeping at least one */4242size_t unit = mparams.granularity;4243size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -4244SIZE_T_ONE) * unit;4245msegmentptr sp = segment_holding(m, (char*)m->top);42464247if (!is_extern_segment(sp)) {4248if (is_mmapped_segment(sp)) {4249if (HAVE_MMAP &&4250sp->size >= extra &&4251!has_segment_link(m, sp)) { /* can't shrink if pinned */4252size_t newsize = sp->size - extra;4253/* Prefer mremap, fall back to munmap */4254if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||4255(CALL_MUNMAP(sp->base + newsize, extra) == 0)) {4256released = extra;4257}4258}4259}4260else if (HAVE_MORECORE) {4261if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */4262extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;4263ACQUIRE_MALLOC_GLOBAL_LOCK();4264{4265/* Make sure end of memory is where we last set it. */4266char* old_br = (char*)(CALL_MORECORE(0));4267if (old_br == sp->base + sp->size) {4268char* rel_br = (char*)(CALL_MORECORE(-extra));4269char* new_br = (char*)(CALL_MORECORE(0));4270if (rel_br != CMFAIL && new_br < old_br)4271released = old_br - new_br;4272}4273}4274RELEASE_MALLOC_GLOBAL_LOCK();4275}4276}42774278if (released != 0) {4279sp->size -= released;4280m->footprint -= released;4281init_top(m, m->top, m->topsize - released);4282check_top_chunk(m, m->top);4283}4284}42854286/* Unmap any unused mmapped segments */4287if (HAVE_MMAP)4288released += release_unused_segments(m);42894290/* On failure, disable autotrim to avoid repeated failed future calls */4291if (released == 0 && m->topsize > m->trim_check)4292m->trim_check = MAX_SIZE_T;4293}42944295return (released != 0)? 1 : 0;4296}42974298/* Consolidate and bin a chunk. Differs from exported versions4299of free mainly in that the chunk need not be marked as inuse.4300*/4301static void dispose_chunk(mstate m, mchunkptr p, size_t psize) {4302mchunkptr next = chunk_plus_offset(p, psize);4303if (!pinuse(p)) {4304mchunkptr prev;4305size_t prevsize = p->prev_foot;4306if (is_mmapped(p)) {4307psize += prevsize + MMAP_FOOT_PAD;4308if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)4309m->footprint -= psize;4310return;4311}4312prev = chunk_minus_offset(p, prevsize);4313psize += prevsize;4314p = prev;4315if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */4316if (p != m->dv) {4317unlink_chunk(m, p, prevsize);4318}4319else if ((next->head & INUSE_BITS) == INUSE_BITS) {4320m->dvsize = psize;4321set_free_with_pinuse(p, psize, next);4322return;4323}4324}4325else {4326CORRUPTION_ERROR_ACTION(m);4327return;4328}4329}4330if (RTCHECK(ok_address(m, next))) {4331if (!cinuse(next)) { /* consolidate forward */4332if (next == m->top) {4333size_t tsize = m->topsize += psize;4334m->top = p;4335p->head = tsize | PINUSE_BIT;4336if (p == m->dv) {4337m->dv = 0;4338m->dvsize = 0;4339}4340return;4341}4342else if (next == m->dv) {4343size_t dsize = m->dvsize += psize;4344m->dv = p;4345set_size_and_pinuse_of_free_chunk(p, dsize);4346return;4347}4348else {4349size_t nsize = chunksize(next);4350psize += nsize;4351unlink_chunk(m, next, nsize);4352set_size_and_pinuse_of_free_chunk(p, psize);4353if (p == m->dv) {4354m->dvsize = psize;4355return;4356}4357}4358}4359else {4360set_free_with_pinuse(p, psize, next);4361}4362insert_chunk(m, p, psize);4363}4364else {4365CORRUPTION_ERROR_ACTION(m);4366}4367}43684369/* ---------------------------- malloc --------------------------- */43704371/* allocate a large request from the best fitting chunk in a treebin */4372static void* tmalloc_large(mstate m, size_t nb) {4373tchunkptr v = 0;4374size_t rsize = -nb; /* Unsigned negation */4375tchunkptr t;4376bindex_t idx;4377compute_tree_index(nb, idx);4378if ((t = *treebin_at(m, idx)) != 0) {4379/* Traverse tree for this bin looking for node with size == nb */4380size_t sizebits = nb << leftshift_for_tree_index(idx);4381tchunkptr rst = 0; /* The deepest untaken right subtree */4382for (;;) {4383tchunkptr rt;4384size_t trem = chunksize(t) - nb;4385if (trem < rsize) {4386v = t;4387if ((rsize = trem) == 0)4388break;4389}4390rt = t->child[1];4391t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];4392if (rt != 0 && rt != t)4393rst = rt;4394if (t == 0) {4395t = rst; /* set t to least subtree holding sizes > nb */4396break;4397}4398sizebits <<= 1;4399}4400}4401if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */4402binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;4403if (leftbits != 0) {4404bindex_t i;4405binmap_t leastbit = least_bit(leftbits);4406compute_bit2idx(leastbit, i);4407t = *treebin_at(m, i);4408}4409}44104411while (t != 0) { /* find smallest of tree or subtree */4412size_t trem = chunksize(t) - nb;4413if (trem < rsize) {4414rsize = trem;4415v = t;4416}4417t = leftmost_child(t);4418}44194420/* If dv is a better fit, return 0 so malloc will use it */4421if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {4422if (RTCHECK(ok_address(m, v))) { /* split */4423mchunkptr r = chunk_plus_offset(v, nb);4424assert(chunksize(v) == rsize + nb);4425if (RTCHECK(ok_next(v, r))) {4426unlink_large_chunk(m, v);4427if (rsize < MIN_CHUNK_SIZE)4428set_inuse_and_pinuse(m, v, (rsize + nb));4429else {4430set_size_and_pinuse_of_inuse_chunk(m, v, nb);4431set_size_and_pinuse_of_free_chunk(r, rsize);4432insert_chunk(m, r, rsize);4433}4434return chunk2mem(v);4435}4436}4437CORRUPTION_ERROR_ACTION(m);4438}4439return 0;4440}44414442/* allocate a small request from the best fitting chunk in a treebin */4443static void* tmalloc_small(mstate m, size_t nb) {4444tchunkptr t, v;4445size_t rsize;4446bindex_t i;4447binmap_t leastbit = least_bit(m->treemap);4448compute_bit2idx(leastbit, i);4449v = t = *treebin_at(m, i);4450rsize = chunksize(t) - nb;44514452while ((t = leftmost_child(t)) != 0) {4453size_t trem = chunksize(t) - nb;4454if (trem < rsize) {4455rsize = trem;4456v = t;4457}4458}44594460if (RTCHECK(ok_address(m, v))) {4461mchunkptr r = chunk_plus_offset(v, nb);4462assert(chunksize(v) == rsize + nb);4463if (RTCHECK(ok_next(v, r))) {4464unlink_large_chunk(m, v);4465if (rsize < MIN_CHUNK_SIZE)4466set_inuse_and_pinuse(m, v, (rsize + nb));4467else {4468set_size_and_pinuse_of_inuse_chunk(m, v, nb);4469set_size_and_pinuse_of_free_chunk(r, rsize);4470replace_dv(m, r, rsize);4471}4472return chunk2mem(v);4473}4474}44754476CORRUPTION_ERROR_ACTION(m);4477return 0;4478}44794480#if !ONLY_MSPACES44814482void* dlmalloc(size_t bytes) {4483/*4484Basic algorithm:4485If a small request (< 256 bytes minus per-chunk overhead):44861. If one exists, use a remainderless chunk in associated smallbin.4487(Remainderless means that there are too few excess bytes to4488represent as a chunk.)44892. If it is big enough, use the dv chunk, which is normally the4490chunk adjacent to the one used for the most recent small request.44913. If one exists, split the smallest available chunk in a bin,4492saving remainder in dv.44934. If it is big enough, use the top chunk.44945. If available, get memory from system and use it4495Otherwise, for a large request:44961. Find the smallest available binned chunk that fits, and use it4497if it is better fitting than dv chunk, splitting if necessary.44982. If better fitting than any binned chunk, use the dv chunk.44993. If it is big enough, use the top chunk.45004. If request size >= mmap threshold, try to directly mmap this chunk.45015. If available, get memory from system and use it45024503The ugly goto's here ensure that postaction occurs along all paths.4504*/45054506#if USE_LOCKS4507ensure_initialization(); /* initialize in sys_alloc if not using locks */4508#endif45094510if (!PREACTION(gm)) {4511void* mem;4512size_t nb;4513if (bytes <= MAX_SMALL_REQUEST) {4514bindex_t idx;4515binmap_t smallbits;4516nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);4517idx = small_index(nb);4518smallbits = gm->smallmap >> idx;45194520if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */4521mchunkptr b, p;4522idx += ~smallbits & 1; /* Uses next bin if idx empty */4523b = smallbin_at(gm, idx);4524p = b->fd;4525assert(chunksize(p) == small_index2size(idx));4526unlink_first_small_chunk(gm, b, p, idx);4527set_inuse_and_pinuse(gm, p, small_index2size(idx));4528mem = chunk2mem(p);4529check_malloced_chunk(gm, mem, nb);4530goto postaction;4531}45324533else if (nb > gm->dvsize) {4534if (smallbits != 0) { /* Use chunk in next nonempty smallbin */4535mchunkptr b, p, r;4536size_t rsize;4537bindex_t i;4538binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));4539binmap_t leastbit = least_bit(leftbits);4540compute_bit2idx(leastbit, i);4541b = smallbin_at(gm, i);4542p = b->fd;4543assert(chunksize(p) == small_index2size(i));4544unlink_first_small_chunk(gm, b, p, i);4545rsize = small_index2size(i) - nb;4546/* Fit here cannot be remainderless if 4byte sizes */4547if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)4548set_inuse_and_pinuse(gm, p, small_index2size(i));4549else {4550set_size_and_pinuse_of_inuse_chunk(gm, p, nb);4551r = chunk_plus_offset(p, nb);4552set_size_and_pinuse_of_free_chunk(r, rsize);4553replace_dv(gm, r, rsize);4554}4555mem = chunk2mem(p);4556check_malloced_chunk(gm, mem, nb);4557goto postaction;4558}45594560else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {4561check_malloced_chunk(gm, mem, nb);4562goto postaction;4563}4564}4565}4566else if (bytes >= MAX_REQUEST)4567nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */4568else {4569nb = pad_request(bytes);4570if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {4571check_malloced_chunk(gm, mem, nb);4572goto postaction;4573}4574}45754576if (nb <= gm->dvsize) {4577size_t rsize = gm->dvsize - nb;4578mchunkptr p = gm->dv;4579if (rsize >= MIN_CHUNK_SIZE) { /* split dv */4580mchunkptr r = gm->dv = chunk_plus_offset(p, nb);4581gm->dvsize = rsize;4582set_size_and_pinuse_of_free_chunk(r, rsize);4583set_size_and_pinuse_of_inuse_chunk(gm, p, nb);4584}4585else { /* exhaust dv */4586size_t dvs = gm->dvsize;4587gm->dvsize = 0;4588gm->dv = 0;4589set_inuse_and_pinuse(gm, p, dvs);4590}4591mem = chunk2mem(p);4592check_malloced_chunk(gm, mem, nb);4593goto postaction;4594}45954596else if (nb < gm->topsize) { /* Split top */4597size_t rsize = gm->topsize -= nb;4598mchunkptr p = gm->top;4599mchunkptr r = gm->top = chunk_plus_offset(p, nb);4600r->head = rsize | PINUSE_BIT;4601set_size_and_pinuse_of_inuse_chunk(gm, p, nb);4602mem = chunk2mem(p);4603check_top_chunk(gm, gm->top);4604check_malloced_chunk(gm, mem, nb);4605goto postaction;4606}46074608mem = sys_alloc(gm, nb);46094610postaction:4611POSTACTION(gm);4612return mem;4613}46144615return 0;4616}46174618/* ---------------------------- free --------------------------- */46194620void dlfree(void* mem) {4621/*4622Consolidate freed chunks with preceeding or succeeding bordering4623free chunks, if they exist, and then place in a bin. Intermixed4624with special cases for top, dv, mmapped chunks, and usage errors.4625*/46264627if (mem != 0) {4628mchunkptr p = mem2chunk(mem);4629#if FOOTERS4630mstate fm = get_mstate_for(p);4631if (!ok_magic(fm)) {4632USAGE_ERROR_ACTION(fm, p);4633return;4634}4635#else /* FOOTERS */4636#define fm gm4637#endif /* FOOTERS */4638if (!PREACTION(fm)) {4639check_inuse_chunk(fm, p);4640if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {4641size_t psize = chunksize(p);4642mchunkptr next = chunk_plus_offset(p, psize);4643if (!pinuse(p)) {4644size_t prevsize = p->prev_foot;4645if (is_mmapped(p)) {4646psize += prevsize + MMAP_FOOT_PAD;4647if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)4648fm->footprint -= psize;4649goto postaction;4650}4651else {4652mchunkptr prev = chunk_minus_offset(p, prevsize);4653psize += prevsize;4654p = prev;4655if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */4656if (p != fm->dv) {4657unlink_chunk(fm, p, prevsize);4658}4659else if ((next->head & INUSE_BITS) == INUSE_BITS) {4660fm->dvsize = psize;4661set_free_with_pinuse(p, psize, next);4662goto postaction;4663}4664}4665else4666goto erroraction;4667}4668}46694670if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {4671if (!cinuse(next)) { /* consolidate forward */4672if (next == fm->top) {4673size_t tsize = fm->topsize += psize;4674fm->top = p;4675p->head = tsize | PINUSE_BIT;4676if (p == fm->dv) {4677fm->dv = 0;4678fm->dvsize = 0;4679}4680if (should_trim(fm, tsize))4681sys_trim(fm, 0);4682goto postaction;4683}4684else if (next == fm->dv) {4685size_t dsize = fm->dvsize += psize;4686fm->dv = p;4687set_size_and_pinuse_of_free_chunk(p, dsize);4688goto postaction;4689}4690else {4691size_t nsize = chunksize(next);4692psize += nsize;4693unlink_chunk(fm, next, nsize);4694set_size_and_pinuse_of_free_chunk(p, psize);4695if (p == fm->dv) {4696fm->dvsize = psize;4697goto postaction;4698}4699}4700}4701else4702set_free_with_pinuse(p, psize, next);47034704if (is_small(psize)) {4705insert_small_chunk(fm, p, psize);4706check_free_chunk(fm, p);4707}4708else {4709tchunkptr tp = (tchunkptr)p;4710insert_large_chunk(fm, tp, psize);4711check_free_chunk(fm, p);4712if (--fm->release_checks == 0)4713release_unused_segments(fm);4714}4715goto postaction;4716}4717}4718erroraction:4719USAGE_ERROR_ACTION(fm, p);4720postaction:4721POSTACTION(fm);4722}4723}4724#if !FOOTERS4725#undef fm4726#endif /* FOOTERS */4727}47284729void* dlcalloc(size_t n_elements, size_t elem_size) {4730void* mem;4731size_t req = 0;4732if (n_elements != 0) {4733req = n_elements * elem_size;4734if (((n_elements | elem_size) & ~(size_t)0xffff) &&4735(req / n_elements != elem_size))4736req = MAX_SIZE_T; /* force downstream failure on overflow */4737}4738mem = dlmalloc(req);4739if (mem != 0 && calloc_must_clear(mem2chunk(mem)))4740memset(mem, 0, req);4741return mem;4742}47434744#endif /* !ONLY_MSPACES */47454746/* ------------ Internal support for realloc, memalign, etc -------------- */47474748/* Try to realloc; only in-place unless can_move true */4749static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb,4750int can_move) {4751mchunkptr newp = 0;4752size_t oldsize = chunksize(p);4753mchunkptr next = chunk_plus_offset(p, oldsize);4754if (RTCHECK(ok_address(m, p) && ok_inuse(p) &&4755ok_next(p, next) && ok_pinuse(next))) {4756if (is_mmapped(p)) {4757newp = mmap_resize(m, p, nb, can_move);4758}4759else if (oldsize >= nb) { /* already big enough */4760size_t rsize = oldsize - nb;4761if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */4762mchunkptr r = chunk_plus_offset(p, nb);4763set_inuse(m, p, nb);4764set_inuse(m, r, rsize);4765dispose_chunk(m, r, rsize);4766}4767newp = p;4768}4769else if (next == m->top) { /* extend into top */4770if (oldsize + m->topsize > nb) {4771size_t newsize = oldsize + m->topsize;4772size_t newtopsize = newsize - nb;4773mchunkptr newtop = chunk_plus_offset(p, nb);4774set_inuse(m, p, nb);4775newtop->head = newtopsize |PINUSE_BIT;4776m->top = newtop;4777m->topsize = newtopsize;4778newp = p;4779}4780}4781else if (next == m->dv) { /* extend into dv */4782size_t dvs = m->dvsize;4783if (oldsize + dvs >= nb) {4784size_t dsize = oldsize + dvs - nb;4785if (dsize >= MIN_CHUNK_SIZE) {4786mchunkptr r = chunk_plus_offset(p, nb);4787mchunkptr n = chunk_plus_offset(r, dsize);4788set_inuse(m, p, nb);4789set_size_and_pinuse_of_free_chunk(r, dsize);4790clear_pinuse(n);4791m->dvsize = dsize;4792m->dv = r;4793}4794else { /* exhaust dv */4795size_t newsize = oldsize + dvs;4796set_inuse(m, p, newsize);4797m->dvsize = 0;4798m->dv = 0;4799}4800newp = p;4801}4802}4803else if (!cinuse(next)) { /* extend into next free chunk */4804size_t nextsize = chunksize(next);4805if (oldsize + nextsize >= nb) {4806size_t rsize = oldsize + nextsize - nb;4807unlink_chunk(m, next, nextsize);4808if (rsize < MIN_CHUNK_SIZE) {4809size_t newsize = oldsize + nextsize;4810set_inuse(m, p, newsize);4811}4812else {4813mchunkptr r = chunk_plus_offset(p, nb);4814set_inuse(m, p, nb);4815set_inuse(m, r, rsize);4816dispose_chunk(m, r, rsize);4817}4818newp = p;4819}4820}4821}4822else {4823USAGE_ERROR_ACTION(m, oldmem);4824}4825return newp;4826}48274828static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {4829void* mem = 0;4830if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */4831alignment = MIN_CHUNK_SIZE;4832if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */4833size_t a = MALLOC_ALIGNMENT << 1;4834while (a < alignment) a <<= 1;4835alignment = a;4836}4837if (bytes >= MAX_REQUEST - alignment) {4838if (m != 0) { /* Test isn't needed but avoids compiler warning */4839MALLOC_FAILURE_ACTION;4840}4841}4842else {4843size_t nb = request2size(bytes);4844size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;4845mem = internal_malloc(m, req);4846if (mem != 0) {4847mchunkptr p = mem2chunk(mem);4848if (PREACTION(m))4849return 0;4850if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */4851/*4852Find an aligned spot inside chunk. Since we need to give4853back leading space in a chunk of at least MIN_CHUNK_SIZE, if4854the first calculation places us at a spot with less than4855MIN_CHUNK_SIZE leader, we can move to the next aligned spot.4856We've allocated enough total room so that this is always4857possible.4858*/4859char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment -4860SIZE_T_ONE)) &4861-alignment));4862char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?4863br : br+alignment;4864mchunkptr newp = (mchunkptr)pos;4865size_t leadsize = pos - (char*)(p);4866size_t newsize = chunksize(p) - leadsize;48674868if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */4869newp->prev_foot = p->prev_foot + leadsize;4870newp->head = newsize;4871}4872else { /* Otherwise, give back leader, use the rest */4873set_inuse(m, newp, newsize);4874set_inuse(m, p, leadsize);4875dispose_chunk(m, p, leadsize);4876}4877p = newp;4878}48794880/* Give back spare room at the end */4881if (!is_mmapped(p)) {4882size_t size = chunksize(p);4883if (size > nb + MIN_CHUNK_SIZE) {4884size_t remainder_size = size - nb;4885mchunkptr remainder = chunk_plus_offset(p, nb);4886set_inuse(m, p, nb);4887set_inuse(m, remainder, remainder_size);4888dispose_chunk(m, remainder, remainder_size);4889}4890}48914892mem = chunk2mem(p);4893assert (chunksize(p) >= nb);4894assert(((size_t)mem & (alignment - 1)) == 0);4895check_inuse_chunk(m, p);4896POSTACTION(m);4897}4898}4899return mem;4900}49014902/*4903Common support for independent_X routines, handling4904all of the combinations that can result.4905The opts arg has:4906bit 0 set if all elements are same size (using sizes[0])4907bit 1 set if elements should be zeroed4908*/4909static void** ialloc(mstate m,4910size_t n_elements,4911size_t* sizes,4912int opts,4913void* chunks[]) {49144915size_t element_size; /* chunksize of each element, if all same */4916size_t contents_size; /* total size of elements */4917size_t array_size; /* request size of pointer array */4918void* mem; /* malloced aggregate space */4919mchunkptr p; /* corresponding chunk */4920size_t remainder_size; /* remaining bytes while splitting */4921void** marray; /* either "chunks" or malloced ptr array */4922mchunkptr array_chunk; /* chunk for malloced ptr array */4923flag_t was_enabled; /* to disable mmap */4924size_t size;4925size_t i;49264927ensure_initialization();4928/* compute array length, if needed */4929if (chunks != 0) {4930if (n_elements == 0)4931return chunks; /* nothing to do */4932marray = chunks;4933array_size = 0;4934}4935else {4936/* if empty req, must still return chunk representing empty array */4937if (n_elements == 0)4938return (void**)internal_malloc(m, 0);4939marray = 0;4940array_size = request2size(n_elements * (sizeof(void*)));4941}49424943/* compute total element size */4944if (opts & 0x1) { /* all-same-size */4945element_size = request2size(*sizes);4946contents_size = n_elements * element_size;4947}4948else { /* add up all the sizes */4949element_size = 0;4950contents_size = 0;4951for (i = 0; i != n_elements; ++i)4952contents_size += request2size(sizes[i]);4953}49544955size = contents_size + array_size;49564957/*4958Allocate the aggregate chunk. First disable direct-mmapping so4959malloc won't use it, since we would not be able to later4960free/realloc space internal to a segregated mmap region.4961*/4962was_enabled = use_mmap(m);4963disable_mmap(m);4964mem = internal_malloc(m, size - CHUNK_OVERHEAD);4965if (was_enabled)4966enable_mmap(m);4967if (mem == 0)4968return 0;49694970if (PREACTION(m)) return 0;4971p = mem2chunk(mem);4972remainder_size = chunksize(p);49734974assert(!is_mmapped(p));49754976if (opts & 0x2) { /* optionally clear the elements */4977memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);4978}49794980/* If not provided, allocate the pointer array as final part of chunk */4981if (marray == 0) {4982size_t array_chunk_size;4983array_chunk = chunk_plus_offset(p, contents_size);4984array_chunk_size = remainder_size - contents_size;4985marray = (void**) (chunk2mem(array_chunk));4986set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);4987remainder_size = contents_size;4988}49894990/* split out elements */4991for (i = 0; ; ++i) {4992marray[i] = chunk2mem(p);4993if (i != n_elements-1) {4994if (element_size != 0)4995size = element_size;4996else4997size = request2size(sizes[i]);4998remainder_size -= size;4999set_size_and_pinuse_of_inuse_chunk(m, p, size);5000p = chunk_plus_offset(p, size);5001}5002else { /* the final element absorbs any overallocation slop */5003set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);5004break;5005}5006}50075008#if DEBUG5009if (marray != chunks) {5010/* final element must have exactly exhausted chunk */5011if (element_size != 0) {5012assert(remainder_size == element_size);5013}5014else {5015assert(remainder_size == request2size(sizes[i]));5016}5017check_inuse_chunk(m, mem2chunk(marray));5018}5019for (i = 0; i != n_elements; ++i)5020check_inuse_chunk(m, mem2chunk(marray[i]));50215022#endif /* DEBUG */50235024POSTACTION(m);5025return marray;5026}50275028/* Try to free all pointers in the given array.5029Note: this could be made faster, by delaying consolidation,5030at the price of disabling some user integrity checks, We5031still optimize some consolidations by combining adjacent5032chunks before freeing, which will occur often if allocated5033with ialloc or the array is sorted.5034*/5035static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) {5036size_t unfreed = 0;5037if (!PREACTION(m)) {5038void** a;5039void** fence = &(array[nelem]);5040for (a = array; a != fence; ++a) {5041void* mem = *a;5042if (mem != 0) {5043mchunkptr p = mem2chunk(mem);5044size_t psize = chunksize(p);5045#if FOOTERS5046if (get_mstate_for(p) != m) {5047++unfreed;5048continue;5049}5050#endif5051check_inuse_chunk(m, p);5052*a = 0;5053if (RTCHECK(ok_address(m, p) && ok_inuse(p))) {5054void ** b = a + 1; /* try to merge with next chunk */5055mchunkptr next = next_chunk(p);5056if (b != fence && *b == chunk2mem(next)) {5057size_t newsize = chunksize(next) + psize;5058set_inuse(m, p, newsize);5059*b = chunk2mem(p);5060}5061else5062dispose_chunk(m, p, psize);5063}5064else {5065CORRUPTION_ERROR_ACTION(m);5066break;5067}5068}5069}5070if (should_trim(m, m->topsize))5071sys_trim(m, 0);5072POSTACTION(m);5073}5074return unfreed;5075}50765077/* Traversal */5078#if MALLOC_INSPECT_ALL5079static void internal_inspect_all(mstate m,5080void(*handler)(void *start,5081void *end,5082size_t used_bytes,5083void* callback_arg),5084void* arg) {5085if (is_initialized(m)) {5086mchunkptr top = m->top;5087msegmentptr s;5088for (s = &m->seg; s != 0; s = s->next) {5089mchunkptr q = align_as_chunk(s->base);5090while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) {5091mchunkptr next = next_chunk(q);5092size_t sz = chunksize(q);5093size_t used;5094void* start;5095if (is_inuse(q)) {5096used = sz - CHUNK_OVERHEAD; /* must not be mmapped */5097start = chunk2mem(q);5098}5099else {5100used = 0;5101if (is_small(sz)) { /* offset by possible bookkeeping */5102start = (void*)((char*)q + sizeof(malloc_chunk));5103}5104else {5105start = (void*)((char*)q + sizeof(malloc_tree_chunk));5106}5107}5108if (start < (void*)next) /* skip if all space is bookkeeping */5109handler(start, next, used, arg);5110if (q == top)5111break;5112q = next;5113}5114}5115}5116}5117#endif /* MALLOC_INSPECT_ALL */51185119/* ------------------ Exported realloc, memalign, etc -------------------- */51205121#if !ONLY_MSPACES51225123void* dlrealloc(void* oldmem, size_t bytes) {5124void* mem = 0;5125if (oldmem == 0) {5126mem = dlmalloc(bytes);5127}5128else if (bytes >= MAX_REQUEST) {5129MALLOC_FAILURE_ACTION;5130}5131#ifdef REALLOC_ZERO_BYTES_FREES5132else if (bytes == 0) {5133dlfree(oldmem);5134}5135#endif /* REALLOC_ZERO_BYTES_FREES */5136else {5137size_t nb = request2size(bytes);5138mchunkptr oldp = mem2chunk(oldmem);5139#if ! FOOTERS5140mstate m = gm;5141#else /* FOOTERS */5142mstate m = get_mstate_for(oldp);5143if (!ok_magic(m)) {5144USAGE_ERROR_ACTION(m, oldmem);5145return 0;5146}5147#endif /* FOOTERS */5148if (!PREACTION(m)) {5149mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1);5150POSTACTION(m);5151if (newp != 0) {5152check_inuse_chunk(m, newp);5153mem = chunk2mem(newp);5154}5155else {5156mem = internal_malloc(m, bytes);5157if (mem != 0) {5158size_t oc = chunksize(oldp) - overhead_for(oldp);5159memcpy(mem, oldmem, (oc < bytes)? oc : bytes);5160internal_free(m, oldmem);5161}5162}5163}5164}5165return mem;5166}51675168void* dlrealloc_in_place(void* oldmem, size_t bytes) {5169void* mem = 0;5170if (oldmem != 0) {5171if (bytes >= MAX_REQUEST) {5172MALLOC_FAILURE_ACTION;5173}5174else {5175size_t nb = request2size(bytes);5176mchunkptr oldp = mem2chunk(oldmem);5177#if ! FOOTERS5178mstate m = gm;5179#else /* FOOTERS */5180mstate m = get_mstate_for(oldp);5181if (!ok_magic(m)) {5182USAGE_ERROR_ACTION(m, oldmem);5183return 0;5184}5185#endif /* FOOTERS */5186if (!PREACTION(m)) {5187mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0);5188POSTACTION(m);5189if (newp == oldp) {5190check_inuse_chunk(m, newp);5191mem = oldmem;5192}5193}5194}5195}5196return mem;5197}51985199void* dlmemalign(size_t alignment, size_t bytes) {5200if (alignment <= MALLOC_ALIGNMENT) {5201return dlmalloc(bytes);5202}5203return internal_memalign(gm, alignment, bytes);5204}52055206int dlposix_memalign(void** pp, size_t alignment, size_t bytes) {5207void* mem = 0;5208if (alignment == MALLOC_ALIGNMENT)5209mem = dlmalloc(bytes);5210else {5211size_t d = alignment / sizeof(void*);5212size_t r = alignment % sizeof(void*);5213if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0)5214return EINVAL;5215else if (bytes >= MAX_REQUEST - alignment) {5216if (alignment < MIN_CHUNK_SIZE)5217alignment = MIN_CHUNK_SIZE;5218mem = internal_memalign(gm, alignment, bytes);5219}5220}5221if (mem == 0)5222return ENOMEM;5223else {5224*pp = mem;5225return 0;5226}5227}52285229void* dlvalloc(size_t bytes) {5230size_t pagesz;5231ensure_initialization();5232pagesz = mparams.page_size;5233return dlmemalign(pagesz, bytes);5234}52355236void* dlpvalloc(size_t bytes) {5237size_t pagesz;5238ensure_initialization();5239pagesz = mparams.page_size;5240return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));5241}52425243void** dlindependent_calloc(size_t n_elements, size_t elem_size,5244void* chunks[]) {5245size_t sz = elem_size; /* serves as 1-element array */5246return ialloc(gm, n_elements, &sz, 3, chunks);5247}52485249void** dlindependent_comalloc(size_t n_elements, size_t sizes[],5250void* chunks[]) {5251return ialloc(gm, n_elements, sizes, 0, chunks);5252}52535254size_t dlbulk_free(void* array[], size_t nelem) {5255return internal_bulk_free(gm, array, nelem);5256}52575258#if MALLOC_INSPECT_ALL5259void dlmalloc_inspect_all(void(*handler)(void *start,5260void *end,5261size_t used_bytes,5262void* callback_arg),5263void* arg) {5264ensure_initialization();5265if (!PREACTION(gm)) {5266internal_inspect_all(gm, handler, arg);5267POSTACTION(gm);5268}5269}5270#endif /* MALLOC_INSPECT_ALL */52715272int dlmalloc_trim(size_t pad) {5273int result = 0;5274ensure_initialization();5275if (!PREACTION(gm)) {5276result = sys_trim(gm, pad);5277POSTACTION(gm);5278}5279return result;5280}52815282size_t dlmalloc_footprint(void) {5283return gm->footprint;5284}52855286size_t dlmalloc_max_footprint(void) {5287return gm->max_footprint;5288}52895290size_t dlmalloc_footprint_limit(void) {5291size_t maf = gm->footprint_limit;5292return maf == 0 ? MAX_SIZE_T : maf;5293}52945295size_t dlmalloc_set_footprint_limit(size_t bytes) {5296size_t result; /* invert sense of 0 */5297if (bytes == 0)5298result = granularity_align(1); /* Use minimal size */5299if (bytes == MAX_SIZE_T)5300result = 0; /* disable */5301else5302result = granularity_align(bytes);5303return gm->footprint_limit = result;5304}53055306#if !NO_MALLINFO5307struct mallinfo dlmallinfo(void) {5308return internal_mallinfo(gm);5309}5310#endif /* NO_MALLINFO */53115312#if !NO_MALLOC_STATS5313void dlmalloc_stats() {5314internal_malloc_stats(gm);5315}5316#endif /* NO_MALLOC_STATS */53175318int dlmallopt(int param_number, int value) {5319return change_mparam(param_number, value);5320}53215322size_t dlmalloc_usable_size(void* mem) {5323if (mem != 0) {5324mchunkptr p = mem2chunk(mem);5325if (is_inuse(p))5326return chunksize(p) - overhead_for(p);5327}5328return 0;5329}53305331#endif /* !ONLY_MSPACES */53325333/* ----------------------------- user mspaces ---------------------------- */53345335#if MSPACES53365337static mstate init_user_mstate(char* tbase, size_t tsize) {5338size_t msize = pad_request(sizeof(struct malloc_state));5339mchunkptr mn;5340mchunkptr msp = align_as_chunk(tbase);5341mstate m = (mstate)(chunk2mem(msp));5342memset(m, 0, msize);5343(void)INITIAL_LOCK(&m->mutex);5344msp->head = (msize|INUSE_BITS);5345m->seg.base = m->least_addr = tbase;5346m->seg.size = m->footprint = m->max_footprint = tsize;5347m->magic = mparams.magic;5348m->release_checks = MAX_RELEASE_CHECK_RATE;5349m->mflags = mparams.default_mflags;5350m->extp = 0;5351m->exts = 0;5352disable_contiguous(m);5353init_bins(m);5354mn = next_chunk(mem2chunk(m));5355init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);5356check_top_chunk(m, m->top);5357return m;5358}53595360mspace create_mspace(size_t capacity, int locked) {5361mstate m = 0;5362size_t msize;5363ensure_initialization();5364msize = pad_request(sizeof(struct malloc_state));5365if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {5366size_t rs = ((capacity == 0)? mparams.granularity :5367(capacity + TOP_FOOT_SIZE + msize));5368size_t tsize = granularity_align(rs);5369char* tbase = (char*)(CALL_MMAP(tsize));5370if (tbase != CMFAIL) {5371m = init_user_mstate(tbase, tsize);5372m->seg.sflags = USE_MMAP_BIT;5373set_lock(m, locked);5374}5375}5376return (mspace)m;5377}53785379mspace create_mspace_with_base(void* base, size_t capacity, int locked) {5380mstate m = 0;5381size_t msize;5382ensure_initialization();5383msize = pad_request(sizeof(struct malloc_state));5384if (capacity > msize + TOP_FOOT_SIZE &&5385capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {5386m = init_user_mstate((char*)base, capacity);5387m->seg.sflags = EXTERN_BIT;5388set_lock(m, locked);5389}5390return (mspace)m;5391}53925393int mspace_track_large_chunks(mspace msp, int enable) {5394int ret = 0;5395mstate ms = (mstate)msp;5396if (!PREACTION(ms)) {5397if (!use_mmap(ms))5398ret = 1;5399if (!enable)5400enable_mmap(ms);5401else5402disable_mmap(ms);5403POSTACTION(ms);5404}5405return ret;5406}54075408size_t destroy_mspace(mspace msp) {5409size_t freed = 0;5410mstate ms = (mstate)msp;5411if (ok_magic(ms)) {5412msegmentptr sp = &ms->seg;5413(void)DESTROY_LOCK(&ms->mutex); /* destroy before unmapped */5414while (sp != 0) {5415char* base = sp->base;5416size_t size = sp->size;5417flag_t flag = sp->sflags;5418sp = sp->next;5419if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) &&5420CALL_MUNMAP(base, size) == 0)5421freed += size;5422}5423}5424else {5425USAGE_ERROR_ACTION(ms,ms);5426}5427return freed;5428}54295430/*5431mspace versions of routines are near-clones of the global5432versions. This is not so nice but better than the alternatives.5433*/54345435void* mspace_malloc(mspace msp, size_t bytes) {5436mstate ms = (mstate)msp;5437if (!ok_magic(ms)) {5438USAGE_ERROR_ACTION(ms,ms);5439return 0;5440}5441if (!PREACTION(ms)) {5442void* mem;5443size_t nb;5444if (bytes <= MAX_SMALL_REQUEST) {5445bindex_t idx;5446binmap_t smallbits;5447nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);5448idx = small_index(nb);5449smallbits = ms->smallmap >> idx;54505451if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */5452mchunkptr b, p;5453idx += ~smallbits & 1; /* Uses next bin if idx empty */5454b = smallbin_at(ms, idx);5455p = b->fd;5456assert(chunksize(p) == small_index2size(idx));5457unlink_first_small_chunk(ms, b, p, idx);5458set_inuse_and_pinuse(ms, p, small_index2size(idx));5459mem = chunk2mem(p);5460check_malloced_chunk(ms, mem, nb);5461goto postaction;5462}54635464else if (nb > ms->dvsize) {5465if (smallbits != 0) { /* Use chunk in next nonempty smallbin */5466mchunkptr b, p, r;5467size_t rsize;5468bindex_t i;5469binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));5470binmap_t leastbit = least_bit(leftbits);5471compute_bit2idx(leastbit, i);5472b = smallbin_at(ms, i);5473p = b->fd;5474assert(chunksize(p) == small_index2size(i));5475unlink_first_small_chunk(ms, b, p, i);5476rsize = small_index2size(i) - nb;5477/* Fit here cannot be remainderless if 4byte sizes */5478if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)5479set_inuse_and_pinuse(ms, p, small_index2size(i));5480else {5481set_size_and_pinuse_of_inuse_chunk(ms, p, nb);5482r = chunk_plus_offset(p, nb);5483set_size_and_pinuse_of_free_chunk(r, rsize);5484replace_dv(ms, r, rsize);5485}5486mem = chunk2mem(p);5487check_malloced_chunk(ms, mem, nb);5488goto postaction;5489}54905491else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {5492check_malloced_chunk(ms, mem, nb);5493goto postaction;5494}5495}5496}5497else if (bytes >= MAX_REQUEST)5498nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */5499else {5500nb = pad_request(bytes);5501if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {5502check_malloced_chunk(ms, mem, nb);5503goto postaction;5504}5505}55065507if (nb <= ms->dvsize) {5508size_t rsize = ms->dvsize - nb;5509mchunkptr p = ms->dv;5510if (rsize >= MIN_CHUNK_SIZE) { /* split dv */5511mchunkptr r = ms->dv = chunk_plus_offset(p, nb);5512ms->dvsize = rsize;5513set_size_and_pinuse_of_free_chunk(r, rsize);5514set_size_and_pinuse_of_inuse_chunk(ms, p, nb);5515}5516else { /* exhaust dv */5517size_t dvs = ms->dvsize;5518ms->dvsize = 0;5519ms->dv = 0;5520set_inuse_and_pinuse(ms, p, dvs);5521}5522mem = chunk2mem(p);5523check_malloced_chunk(ms, mem, nb);5524goto postaction;5525}55265527else if (nb < ms->topsize) { /* Split top */5528size_t rsize = ms->topsize -= nb;5529mchunkptr p = ms->top;5530mchunkptr r = ms->top = chunk_plus_offset(p, nb);5531r->head = rsize | PINUSE_BIT;5532set_size_and_pinuse_of_inuse_chunk(ms, p, nb);5533mem = chunk2mem(p);5534check_top_chunk(ms, ms->top);5535check_malloced_chunk(ms, mem, nb);5536goto postaction;5537}55385539mem = sys_alloc(ms, nb);55405541postaction:5542POSTACTION(ms);5543return mem;5544}55455546return 0;5547}55485549void mspace_free(mspace msp, void* mem) {5550if (mem != 0) {5551mchunkptr p = mem2chunk(mem);5552#if FOOTERS5553mstate fm = get_mstate_for(p);5554msp = msp; /* placate people compiling -Wunused */5555#else /* FOOTERS */5556mstate fm = (mstate)msp;5557#endif /* FOOTERS */5558if (!ok_magic(fm)) {5559USAGE_ERROR_ACTION(fm, p);5560return;5561}5562if (!PREACTION(fm)) {5563check_inuse_chunk(fm, p);5564if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {5565size_t psize = chunksize(p);5566mchunkptr next = chunk_plus_offset(p, psize);5567if (!pinuse(p)) {5568size_t prevsize = p->prev_foot;5569if (is_mmapped(p)) {5570psize += prevsize + MMAP_FOOT_PAD;5571if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)5572fm->footprint -= psize;5573goto postaction;5574}5575else {5576mchunkptr prev = chunk_minus_offset(p, prevsize);5577psize += prevsize;5578p = prev;5579if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */5580if (p != fm->dv) {5581unlink_chunk(fm, p, prevsize);5582}5583else if ((next->head & INUSE_BITS) == INUSE_BITS) {5584fm->dvsize = psize;5585set_free_with_pinuse(p, psize, next);5586goto postaction;5587}5588}5589else5590goto erroraction;5591}5592}55935594if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {5595if (!cinuse(next)) { /* consolidate forward */5596if (next == fm->top) {5597size_t tsize = fm->topsize += psize;5598fm->top = p;5599p->head = tsize | PINUSE_BIT;5600if (p == fm->dv) {5601fm->dv = 0;5602fm->dvsize = 0;5603}5604if (should_trim(fm, tsize))5605sys_trim(fm, 0);5606goto postaction;5607}5608else if (next == fm->dv) {5609size_t dsize = fm->dvsize += psize;5610fm->dv = p;5611set_size_and_pinuse_of_free_chunk(p, dsize);5612goto postaction;5613}5614else {5615size_t nsize = chunksize(next);5616psize += nsize;5617unlink_chunk(fm, next, nsize);5618set_size_and_pinuse_of_free_chunk(p, psize);5619if (p == fm->dv) {5620fm->dvsize = psize;5621goto postaction;5622}5623}5624}5625else5626set_free_with_pinuse(p, psize, next);56275628if (is_small(psize)) {5629insert_small_chunk(fm, p, psize);5630check_free_chunk(fm, p);5631}5632else {5633tchunkptr tp = (tchunkptr)p;5634insert_large_chunk(fm, tp, psize);5635check_free_chunk(fm, p);5636if (--fm->release_checks == 0)5637release_unused_segments(fm);5638}5639goto postaction;5640}5641}5642erroraction:5643USAGE_ERROR_ACTION(fm, p);5644postaction:5645POSTACTION(fm);5646}5647}5648}56495650void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {5651void* mem;5652size_t req = 0;5653mstate ms = (mstate)msp;5654if (!ok_magic(ms)) {5655USAGE_ERROR_ACTION(ms,ms);5656return 0;5657}5658if (n_elements != 0) {5659req = n_elements * elem_size;5660if (((n_elements | elem_size) & ~(size_t)0xffff) &&5661(req / n_elements != elem_size))5662req = MAX_SIZE_T; /* force downstream failure on overflow */5663}5664mem = internal_malloc(ms, req);5665if (mem != 0 && calloc_must_clear(mem2chunk(mem)))5666memset(mem, 0, req);5667return mem;5668}56695670void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {5671void* mem = 0;5672if (oldmem == 0) {5673mem = mspace_malloc(msp, bytes);5674}5675else if (bytes >= MAX_REQUEST) {5676MALLOC_FAILURE_ACTION;5677}5678#ifdef REALLOC_ZERO_BYTES_FREES5679else if (bytes == 0) {5680mspace_free(msp, oldmem);5681}5682#endif /* REALLOC_ZERO_BYTES_FREES */5683else {5684size_t nb = request2size(bytes);5685mchunkptr oldp = mem2chunk(oldmem);5686#if ! FOOTERS5687mstate m = (mstate)msp;5688#else /* FOOTERS */5689mstate m = get_mstate_for(oldp);5690if (!ok_magic(m)) {5691USAGE_ERROR_ACTION(m, oldmem);5692return 0;5693}5694#endif /* FOOTERS */5695if (!PREACTION(m)) {5696mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1);5697POSTACTION(m);5698if (newp != 0) {5699check_inuse_chunk(m, newp);5700mem = chunk2mem(newp);5701}5702else {5703mem = mspace_malloc(m, bytes);5704if (mem != 0) {5705size_t oc = chunksize(oldp) - overhead_for(oldp);5706memcpy(mem, oldmem, (oc < bytes)? oc : bytes);5707mspace_free(m, oldmem);5708}5709}5710}5711}5712return mem;5713}57145715void* mspace_realloc_in_place(mspace msp, void* oldmem, size_t bytes) {5716void* mem = 0;5717if (oldmem != 0) {5718if (bytes >= MAX_REQUEST) {5719MALLOC_FAILURE_ACTION;5720}5721else {5722size_t nb = request2size(bytes);5723mchunkptr oldp = mem2chunk(oldmem);5724#if ! FOOTERS5725mstate m = (mstate)msp;5726#else /* FOOTERS */5727mstate m = get_mstate_for(oldp);5728msp = msp; /* placate people compiling -Wunused */5729if (!ok_magic(m)) {5730USAGE_ERROR_ACTION(m, oldmem);5731return 0;5732}5733#endif /* FOOTERS */5734if (!PREACTION(m)) {5735mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0);5736POSTACTION(m);5737if (newp == oldp) {5738check_inuse_chunk(m, newp);5739mem = oldmem;5740}5741}5742}5743}5744return mem;5745}57465747void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {5748mstate ms = (mstate)msp;5749if (!ok_magic(ms)) {5750USAGE_ERROR_ACTION(ms,ms);5751return 0;5752}5753if (alignment <= MALLOC_ALIGNMENT)5754return mspace_malloc(msp, bytes);5755return internal_memalign(ms, alignment, bytes);5756}57575758void** mspace_independent_calloc(mspace msp, size_t n_elements,5759size_t elem_size, void* chunks[]) {5760size_t sz = elem_size; /* serves as 1-element array */5761mstate ms = (mstate)msp;5762if (!ok_magic(ms)) {5763USAGE_ERROR_ACTION(ms,ms);5764return 0;5765}5766return ialloc(ms, n_elements, &sz, 3, chunks);5767}57685769void** mspace_independent_comalloc(mspace msp, size_t n_elements,5770size_t sizes[], void* chunks[]) {5771mstate ms = (mstate)msp;5772if (!ok_magic(ms)) {5773USAGE_ERROR_ACTION(ms,ms);5774return 0;5775}5776return ialloc(ms, n_elements, sizes, 0, chunks);5777}57785779size_t mspace_bulk_free(mspace msp, void* array[], size_t nelem) {5780return internal_bulk_free((mstate)msp, array, nelem);5781}57825783#if MALLOC_INSPECT_ALL5784void mspace_inspect_all(mspace msp,5785void(*handler)(void *start,5786void *end,5787size_t used_bytes,5788void* callback_arg),5789void* arg) {5790mstate ms = (mstate)msp;5791if (ok_magic(ms)) {5792if (!PREACTION(ms)) {5793internal_inspect_all(ms, handler, arg);5794POSTACTION(ms);5795}5796}5797else {5798USAGE_ERROR_ACTION(ms,ms);5799}5800}5801#endif /* MALLOC_INSPECT_ALL */58025803int mspace_trim(mspace msp, size_t pad) {5804int result = 0;5805mstate ms = (mstate)msp;5806if (ok_magic(ms)) {5807if (!PREACTION(ms)) {5808result = sys_trim(ms, pad);5809POSTACTION(ms);5810}5811}5812else {5813USAGE_ERROR_ACTION(ms,ms);5814}5815return result;5816}58175818#if !NO_MALLOC_STATS5819void mspace_malloc_stats(mspace msp) {5820mstate ms = (mstate)msp;5821if (ok_magic(ms)) {5822internal_malloc_stats(ms);5823}5824else {5825USAGE_ERROR_ACTION(ms,ms);5826}5827}5828#endif /* NO_MALLOC_STATS */58295830size_t mspace_footprint(mspace msp) {5831size_t result = 0;5832mstate ms = (mstate)msp;5833if (ok_magic(ms)) {5834result = ms->footprint;5835}5836else {5837USAGE_ERROR_ACTION(ms,ms);5838}5839return result;5840}58415842size_t mspace_max_footprint(mspace msp) {5843size_t result = 0;5844mstate ms = (mstate)msp;5845if (ok_magic(ms)) {5846result = ms->max_footprint;5847}5848else {5849USAGE_ERROR_ACTION(ms,ms);5850}5851return result;5852}58535854size_t mspace_footprint_limit(mspace msp) {5855size_t result = 0;5856mstate ms = (mstate)msp;5857if (ok_magic(ms)) {5858size_t maf = ms->footprint_limit;5859result = (maf == 0) ? MAX_SIZE_T : maf;5860}5861else {5862USAGE_ERROR_ACTION(ms,ms);5863}5864return result;5865}58665867size_t mspace_set_footprint_limit(mspace msp, size_t bytes) {5868size_t result = 0;5869mstate ms = (mstate)msp;5870if (ok_magic(ms)) {5871if (bytes == 0)5872result = granularity_align(1); /* Use minimal size */5873if (bytes == MAX_SIZE_T)5874result = 0; /* disable */5875else5876result = granularity_align(bytes);5877ms->footprint_limit = result;5878}5879else {5880USAGE_ERROR_ACTION(ms,ms);5881}5882return result;5883}58845885#if !NO_MALLINFO5886struct mallinfo mspace_mallinfo(mspace msp) {5887mstate ms = (mstate)msp;5888if (!ok_magic(ms)) {5889USAGE_ERROR_ACTION(ms,ms);5890}5891return internal_mallinfo(ms);5892}5893#endif /* NO_MALLINFO */58945895size_t mspace_usable_size(void* mem) {5896if (mem != 0) {5897mchunkptr p = mem2chunk(mem);5898if (is_inuse(p))5899return chunksize(p) - overhead_for(p);5900}5901return 0;5902}59035904int mspace_mallopt(int param_number, int value) {5905return change_mparam(param_number, value);5906}59075908#endif /* MSPACES */590959105911/* -------------------- Alternative MORECORE functions ------------------- */59125913/*5914Guidelines for creating a custom version of MORECORE:59155916* For best performance, MORECORE should allocate in multiples of pagesize.5917* MORECORE may allocate more memory than requested. (Or even less,5918but this will usually result in a malloc failure.)5919* MORECORE must not allocate memory when given argument zero, but5920instead return one past the end address of memory from previous5921nonzero call.5922* For best performance, consecutive calls to MORECORE with positive5923arguments should return increasing addresses, indicating that5924space has been contiguously extended.5925* Even though consecutive calls to MORECORE need not return contiguous5926addresses, it must be OK for malloc'ed chunks to span multiple5927regions in those cases where they do happen to be contiguous.5928* MORECORE need not handle negative arguments -- it may instead5929just return MFAIL when given negative arguments.5930Negative arguments are always multiples of pagesize. MORECORE5931must not misinterpret negative args as large positive unsigned5932args. You can suppress all such calls from even occurring by defining5933MORECORE_CANNOT_TRIM,59345935As an example alternative MORECORE, here is a custom allocator5936kindly contributed for pre-OSX macOS. It uses virtually but not5937necessarily physically contiguous non-paged memory (locked in,5938present and won't get swapped out). You can use it by uncommenting5939this section, adding some #includes, and setting up the appropriate5940defines above:59415942#define MORECORE osMoreCore59435944There is also a shutdown routine that should somehow be called for5945cleanup upon program exit.59465947#define MAX_POOL_ENTRIES 1005948#define MINIMUM_MORECORE_SIZE (64 * 1024U)5949static int next_os_pool;5950void *our_os_pools[MAX_POOL_ENTRIES];59515952void *osMoreCore(int size)5953{5954void *ptr = 0;5955static void *sbrk_top = 0;59565957if (size > 0)5958{5959if (size < MINIMUM_MORECORE_SIZE)5960size = MINIMUM_MORECORE_SIZE;5961if (CurrentExecutionLevel() == kTaskLevel)5962ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);5963if (ptr == 0)5964{5965return (void *) MFAIL;5966}5967// save ptrs so they can be freed during cleanup5968our_os_pools[next_os_pool] = ptr;5969next_os_pool++;5970ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);5971sbrk_top = (char *) ptr + size;5972return ptr;5973}5974else if (size < 0)5975{5976// we don't currently support shrink behavior5977return (void *) MFAIL;5978}5979else5980{5981return sbrk_top;5982}5983}59845985// cleanup any allocated memory pools5986// called as last thing before shutting down driver59875988void osCleanupMem(void)5989{5990void **ptr;59915992for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)5993if (*ptr)5994{5995PoolDeallocate(*ptr);5996*ptr = 0;5997}5998}59996000*/600160026003/* -----------------------------------------------------------------------6004History:6005v2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee)6006* Always perform unlink checks unless INSECURE6007* Add posix_memalign.6008* Improve realloc to expand in more cases; expose realloc_in_place.6009Thanks to Peter Buhr for the suggestion.6010* Add footprint_limit, inspect_all, bulk_free. Thanks6011to Barry Hayes and others for the suggestions.6012* Internal refactorings to avoid calls while holding locks6013* Use non-reentrant locks by default. Thanks to Roland McGrath6014for the suggestion.6015* Small fixes to mspace_destroy, reset_on_error.6016* Various configuration extensions/changes. Thanks6017to all who contributed these.60186019V2.8.4a Thu Apr 28 14:39:43 2011 (dl at gee.cs.oswego.edu)6020* Update Creative Commons URL60216022V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee)6023* Use zeros instead of prev foot for is_mmapped6024* Add mspace_track_large_chunks; thanks to Jean Brouwers6025* Fix set_inuse in internal_realloc; thanks to Jean Brouwers6026* Fix insufficient sys_alloc padding when using 16byte alignment6027* Fix bad error check in mspace_footprint6028* Adaptations for ptmalloc; thanks to Wolfram Gloger.6029* Reentrant spin locks; thanks to Earl Chew and others6030* Win32 improvements; thanks to Niall Douglas and Earl Chew6031* Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options6032* Extension hook in malloc_state6033* Various small adjustments to reduce warnings on some compilers6034* Various configuration extensions/changes for more platforms. Thanks6035to all who contributed these.60366037V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)6038* Add max_footprint functions6039* Ensure all appropriate literals are size_t6040* Fix conditional compilation problem for some #define settings6041* Avoid concatenating segments with the one provided6042in create_mspace_with_base6043* Rename some variables to avoid compiler shadowing warnings6044* Use explicit lock initialization.6045* Better handling of sbrk interference.6046* Simplify and fix segment insertion, trimming and mspace_destroy6047* Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x6048* Thanks especially to Dennis Flanagan for help on these.60496050V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)6051* Fix memalign brace error.60526053V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)6054* Fix improper #endif nesting in C++6055* Add explicit casts needed for C++60566057V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)6058* Use trees for large bins6059* Support mspaces6060* Use segments to unify sbrk-based and mmap-based system allocation,6061removing need for emulation on most platforms without sbrk.6062* Default safety checks6063* Optional footer checks. Thanks to William Robertson for the idea.6064* Internal code refactoring6065* Incorporate suggestions and platform-specific changes.6066Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,6067Aaron Bachmann, Emery Berger, and others.6068* Speed up non-fastbin processing enough to remove fastbins.6069* Remove useless cfree() to avoid conflicts with other apps.6070* Remove internal memcpy, memset. Compilers handle builtins better.6071* Remove some options that no one ever used and rename others.60726073V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)6074* Fix malloc_state bitmap array misdeclaration60756076V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)6077* Allow tuning of FIRST_SORTED_BIN_SIZE6078* Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.6079* Better detection and support for non-contiguousness of MORECORE.6080Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger6081* Bypass most of malloc if no frees. Thanks To Emery Berger.6082* Fix freeing of old top non-contiguous chunk im sysmalloc.6083* Raised default trim and map thresholds to 256K.6084* Fix mmap-related #defines. Thanks to Lubos Lunak.6085* Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.6086* Branch-free bin calculation6087* Default trim and mmap thresholds now 256K.60886089V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)6090* Introduce independent_comalloc and independent_calloc.6091Thanks to Michael Pachos for motivation and help.6092* Make optional .h file available6093* Allow > 2GB requests on 32bit systems.6094* new WIN32 sbrk, mmap, munmap, lock code from <[email protected]>.6095Thanks also to Andreas Mueller <a.mueller at paradatec.de>,6096and Anonymous.6097* Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for6098helping test this.)6099* memalign: check alignment arg6100* realloc: don't try to shift chunks backwards, since this6101leads to more fragmentation in some programs and doesn't6102seem to help in any others.6103* Collect all cases in malloc requiring system memory into sysmalloc6104* Use mmap as backup to sbrk6105* Place all internal state in malloc_state6106* Introduce fastbins (although similar to 2.5.1)6107* Many minor tunings and cosmetic improvements6108* Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK6109* Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS6110Thanks to Tony E. Bennett <[email protected]> and others.6111* Include errno.h to support default failure action.61126113V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)6114* return null for negative arguments6115* Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>6116* Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'6117(e.g. WIN32 platforms)6118* Cleanup header file inclusion for WIN32 platforms6119* Cleanup code to avoid Microsoft Visual C++ compiler complaints6120* Add 'USE_DL_PREFIX' to quickly allow co-existence with existing6121memory allocation routines6122* Set 'malloc_getpagesize' for WIN32 platforms (needs more work)6123* Use 'assert' rather than 'ASSERT' in WIN32 code to conform to6124usage of 'assert' in non-WIN32 code6125* Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to6126avoid infinite loop6127* Always call 'fREe()' rather than 'free()'61286129V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)6130* Fixed ordering problem with boundary-stamping61316132V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)6133* Added pvalloc, as recommended by H.J. Liu6134* Added 64bit pointer support mainly from Wolfram Gloger6135* Added anonymously donated WIN32 sbrk emulation6136* Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen6137* malloc_extend_top: fix mask error that caused wastage after6138foreign sbrks6139* Add linux mremap support code from HJ Liu61406141V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)6142* Integrated most documentation with the code.6143* Add support for mmap, with help from6144Wolfram Gloger ([email protected]).6145* Use last_remainder in more cases.6146* Pack bins using idea from [email protected]6147* Use ordered bins instead of best-fit threshhold6148* Eliminate block-local decls to simplify tracing and debugging.6149* Support another case of realloc via move into top6150* Fix error occuring when initial sbrk_base not word-aligned.6151* Rely on page size for units instead of SBRK_UNIT to6152avoid surprises about sbrk alignment conventions.6153* Add mallinfo, mallopt. Thanks to Raymond Nijssen6154([email protected]) for the suggestion.6155* Add `pad' argument to malloc_trim and top_pad mallopt parameter.6156* More precautions for cases where other routines call sbrk,6157courtesy of Wolfram Gloger ([email protected]).6158* Added macros etc., allowing use in linux libc from6159H.J. Lu ([email protected])6160* Inverted this history list61616162V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)6163* Re-tuned and fixed to behave more nicely with V2.6.0 changes.6164* Removed all preallocation code since under current scheme6165the work required to undo bad preallocations exceeds6166the work saved in good cases for most test programs.6167* No longer use return list or unconsolidated bins since6168no scheme using them consistently outperforms those that don't6169given above changes.6170* Use best fit for very large chunks to prevent some worst-cases.6171* Added some support for debugging61726173V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)6174* Removed footers when chunks are in use. Thanks to6175Paul Wilson ([email protected]) for the suggestion.61766177V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)6178* Added malloc_trim, with help from Wolfram Gloger6179([email protected]).61806181V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)61826183V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)6184* realloc: try to expand in both directions6185* malloc: swap order of clean-bin strategy;6186* realloc: only conditionally expand backwards6187* Try not to scavenge used bins6188* Use bin counts as a guide to preallocation6189* Occasionally bin return list chunks in first scan6190* Add a few optimizations from [email protected]61916192V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)6193* faster bin computation & slightly different binning6194* merged all consolidations to one part of malloc proper6195(eliminating old malloc_find_space & malloc_clean_bin)6196* Scan 2 returns chunks (not just 1)6197* Propagate failure in realloc if malloc returns 06198* Add stuff to allow compilation on non-ANSI compilers6199from [email protected]62006201V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)6202* removed potential for odd address access in prev_chunk6203* removed dependency on getpagesize.h6204* misc cosmetics and a bit more internal documentation6205* anticosmetics: mangled names in macros to evade debugger strangeness6206* tested on sparc, hp-700, dec-mips, rs60006207with gcc & native cc (hp, dec only) allowing6208Detlefs & Zorn comparison study (in SIGPLAN Notices.)62096210Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)6211* Based loosely on libg++-1.2X malloc. (It retains some of the overall6212structure of old version, but most details differ.)62136214*/6215#endif62166217#ifdef TEST6218#include "_PDCLIB_test.h"62196220/* TODO: TEST ME */6221int main( void )6222{6223return TEST_RESULTS;6224}62256226#endif622762286229