// Windows has terrible malloc/free performance, so use dlmalloc1// instead. This makes malloc/free time per frame go from order of2// milliseconds to tens of microseconds.3#ifdef _WIN324#include <errno.h>5#define FORCEINLINE // define this to nothing to make gcc happy6#define USE_LOCKS 178/*9This is a version (aka dlmalloc) of malloc/free/realloc written by10Doug Lea and released to the public domain, as explained at11http://creativecommons.org/publicdomain/zero/1.0/ Send questions,12comments, complaints, performance data, etc to [email protected]1314* Version 2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea15Note: There may be an updated version of this malloc obtainable at16ftp://gee.cs.oswego.edu/pub/misc/malloc.c17Check before installing!1819* Quickstart2021This library is all in one file to simplify the most common usage:22ftp it, compile it (-O3), and link it into another program. All of23the compile-time options default to reasonable values for use on24most platforms. You might later want to step through various25compile-time and dynamic tuning options.2627For convenience, an include file for code using this malloc is at:28ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.6.h29You don't really need this .h file unless you call functions not30defined in your system include files. The .h file contains only the31excerpts from this file needed for using this malloc on ANSI C/C++32systems, so long as you haven't changed compile-time options about33naming and tuning parameters. If you do, then you can create your34own malloc.h that does include all settings by cutting at the point35indicated below. Note that you may already by default be using a C36library containing a malloc that is based on some version of this37malloc (for example in linux). You might still want to use the one38in this file to customize settings or to avoid overheads associated39with library versions.4041* Vital statistics:4243Supported pointer/size_t representation: 4 or 8 bytes44size_t MUST be an unsigned type of the same width as45pointers. (If you are using an ancient system that declares46size_t as a signed type, or need it to be a different width47than pointers, you can use a previous release of this malloc48(e.g. 2.7.2) supporting these.)4950Alignment: 8 bytes (minimum)51This suffices for nearly all current machines and C compilers.52However, you can define MALLOC_ALIGNMENT to be wider than this53if necessary (up to 128bytes), at the expense of using more space.5455Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)568 or 16 bytes (if 8byte sizes)57Each malloced chunk has a hidden word of overhead holding size58and status information, and additional cross-check word59if FOOTERS is defined.6061Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)628-byte ptrs: 32 bytes (including overhead)6364Even a request for zero bytes (i.e., malloc(0)) returns a65pointer to something of the minimum allocatable size.66The maximum overhead wastage (i.e., number of extra bytes67allocated than were requested in malloc) is less than or equal68to the minimum size, except for requests >= mmap_threshold that69are serviced via mmap(), where the worst case wastage is about7032 bytes plus the remainder from a system page (the minimal71mmap unit); typically 4096 or 8192 bytes.7273Security: static-safe; optionally more or less74The "security" of malloc refers to the ability of malicious75code to accentuate the effects of errors (for example, freeing76space that is not currently malloc'ed or overwriting past the77ends of chunks) in code that calls malloc. This malloc78guarantees not to modify any memory locations below the base of79heap, i.e., static variables, even in the presence of usage80errors. The routines additionally detect most improper frees81and reallocs. All this holds as long as the static bookkeeping82for malloc itself is not corrupted by some other means. This83is only one aspect of security -- these checks do not, and84cannot, detect all possible programming errors.8586If FOOTERS is defined nonzero, then each allocated chunk87carries an additional check word to verify that it was malloced88from its space. These check words are the same within each89execution of a program using malloc, but differ across90executions, so externally crafted fake chunks cannot be91freed. This improves security by rejecting frees/reallocs that92could corrupt heap memory, in addition to the checks preventing93writes to statics that are always on. This may further improve94security at the expense of time and space overhead. (Note that95FOOTERS may also be worth using with MSPACES.)9697By default detected errors cause the program to abort (calling98"abort()"). You can override this to instead proceed past99errors by defining PROCEED_ON_ERROR. In this case, a bad free100has no effect, and a malloc that encounters a bad address101caused by user overwrites will ignore the bad address by102dropping pointers and indices to all known memory. This may103be appropriate for programs that should continue if at all104possible in the face of programming errors, although they may105run out of memory because dropped memory is never reclaimed.106107If you don't like either of these options, you can define108CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything109else. And if if you are sure that your program using malloc has110no errors or vulnerabilities, you can define INSECURE to 1,111which might (or might not) provide a small performance improvement.112113It is also possible to limit the maximum total allocatable114space, using malloc_set_footprint_limit. This is not115designed as a security feature in itself (calls to set limits116are not screened or privileged), but may be useful as one117aspect of a secure implementation.118119Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero120When USE_LOCKS is defined, each public call to malloc, free,121etc is surrounded with a lock. By default, this uses a plain122pthread mutex, win32 critical section, or a spin-lock if if123available for the platform and not disabled by setting124USE_SPIN_LOCKS=0. However, if USE_RECURSIVE_LOCKS is defined,125recursive versions are used instead (which are not required for126base functionality but may be needed in layered extensions).127Using a global lock is not especially fast, and can be a major128bottleneck. It is designed only to provide minimal protection129in concurrent environments, and to provide a basis for130extensions. If you are using malloc in a concurrent program,131consider instead using nedmalloc132(http://www.nedprod.com/programs/portable/nedmalloc/) or133ptmalloc (See http://www.malloc.de), which are derived from134versions of this malloc.135136System requirements: Any combination of MORECORE and/or MMAP/MUNMAP137This malloc can use unix sbrk or any emulation (invoked using138the CALL_MORECORE macro) and/or mmap/munmap or any emulation139(invoked using CALL_MMAP/CALL_MUNMAP) to get and release system140memory. On most unix systems, it tends to work best if both141MORECORE and MMAP are enabled. On Win32, it uses emulations142based on VirtualAlloc. It also uses common C library functions143like memset.144145Compliance: I believe it is compliant with the Single Unix Specification146(See http://www.unix.org). Also SVID/XPG, ANSI C, and probably147others as well.148149* Overview of algorithms150151This is not the fastest, most space-conserving, most portable, or152most tunable malloc ever written. However it is among the fastest153while also being among the most space-conserving, portable and154tunable. Consistent balance across these factors results in a good155general-purpose allocator for malloc-intensive programs.156157In most ways, this malloc is a best-fit allocator. Generally, it158chooses the best-fitting existing chunk for a request, with ties159broken in approximately least-recently-used order. (This strategy160normally maintains low fragmentation.) However, for requests less161than 256bytes, it deviates from best-fit when there is not an162exactly fitting available chunk by preferring to use space adjacent163to that used for the previous small request, as well as by breaking164ties in approximately most-recently-used order. (These enhance165locality of series of small allocations.) And for very large requests166(>= 256Kb by default), it relies on system memory mapping167facilities, if supported. (This helps avoid carrying around and168possibly fragmenting memory used only for large chunks.)169170All operations (except malloc_stats and mallinfo) have execution171times that are bounded by a constant factor of the number of bits in172a size_t, not counting any clearing in calloc or copying in realloc,173or actions surrounding MORECORE and MMAP that have times174proportional to the number of non-contiguous regions returned by175system allocation routines, which is often just 1. In real-time176applications, you can optionally suppress segment traversals using177NO_SEGMENT_TRAVERSAL, which assures bounded execution even when178system allocators return non-contiguous spaces, at the typical179expense of carrying around more memory and increased fragmentation.180181The implementation is not very modular and seriously overuses182macros. Perhaps someday all C compilers will do as good a job183inlining modular code as can now be done by brute-force expansion,184but now, enough of them seem not to.185186Some compilers issue a lot of warnings about code that is187dead/unreachable only on some platforms, and also about intentional188uses of negation on unsigned types. All known cases of each can be189ignored.190191For a longer but out of date high-level description, see192http://gee.cs.oswego.edu/dl/html/malloc.html193194* MSPACES195If MSPACES is defined, then in addition to malloc, free, etc.,196this file also defines mspace_malloc, mspace_free, etc. These197are versions of malloc routines that take an "mspace" argument198obtained using create_mspace, to control all internal bookkeeping.199If ONLY_MSPACES is defined, only these versions are compiled.200So if you would like to use this allocator for only some allocations,201and your system malloc for others, you can compile with202ONLY_MSPACES and then do something like...203static mspace mymspace = create_mspace(0,0); // for example204#define mymalloc(bytes) mspace_malloc(mymspace, bytes)205206(Note: If you only need one instance of an mspace, you can instead207use "USE_DL_PREFIX" to relabel the global malloc.)208209You can similarly create thread-local allocators by storing210mspaces as thread-locals. For example:211static __thread mspace tlms = 0;212void* tlmalloc(size_t bytes) {213if (tlms == 0) tlms = create_mspace(0, 0);214return mspace_malloc(tlms, bytes);215}216void tlfree(void* mem) { mspace_free(tlms, mem); }217218Unless FOOTERS is defined, each mspace is completely independent.219You cannot allocate from one and free to another (although220conformance is only weakly checked, so usage errors are not always221caught). If FOOTERS is defined, then each chunk carries around a tag222indicating its originating mspace, and frees are directed to their223originating spaces. Normally, this requires use of locks.224225------------------------- Compile-time options ---------------------------226227Be careful in setting #define values for numerical constants of type228size_t. On some systems, literal values are not automatically extended229to size_t precision unless they are explicitly casted. You can also230use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.231232WIN32 default: defined if _WIN32 defined233Defining WIN32 sets up defaults for MS environment and compilers.234Otherwise defaults are for unix. Beware that there seem to be some235cases where this malloc might not be a pure drop-in replacement for236Win32 malloc: Random-looking failures from Win32 GDI API's (eg;237SetDIBits()) may be due to bugs in some video driver implementations238when pixel buffers are malloc()ed, and the region spans more than239one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb)240default granularity, pixel buffers may straddle virtual allocation241regions more often than when using the Microsoft allocator. You can242avoid this by using VirtualAlloc() and VirtualFree() for all pixel243buffers rather than using malloc(). If this is not possible,244recompile this malloc with a larger DEFAULT_GRANULARITY. Note:245in cases where MSC and gcc (cygwin) are known to differ on WIN32,246conditions use _MSC_VER to distinguish them.247248DLMALLOC_EXPORT default: extern249Defines how public APIs are declared. If you want to export via a250Windows DLL, you might define this as251#define DLMALLOC_EXPORT extern __declspec(dllexport)252If you want a POSIX ELF shared object, you might use253#define DLMALLOC_EXPORT extern __attribute__((visibility("default")))254255MALLOC_ALIGNMENT default: (size_t)(2 * sizeof(void *))256Controls the minimum alignment for malloc'ed chunks. It must be a257power of two and at least 8, even on machines for which smaller258alignments would suffice. It may be defined as larger than this259though. Note however that code and data structures are optimized for260the case of 8-byte alignment.261262MSPACES default: 0 (false)263If true, compile in support for independent allocation spaces.264This is only supported if HAVE_MMAP is true.265266ONLY_MSPACES default: 0 (false)267If true, only compile in mspace versions, not regular versions.268269USE_LOCKS default: 0 (false)270Causes each call to each public routine to be surrounded with271pthread or WIN32 mutex lock/unlock. (If set true, this can be272overridden on a per-mspace basis for mspace versions.) If set to a273non-zero value other than 1, locks are used, but their274implementation is left out, so lock functions must be supplied manually,275as described below.276277USE_SPIN_LOCKS default: 1 iff USE_LOCKS and spin locks available278If true, uses custom spin locks for locking. This is currently279supported only gcc >= 4.1, older gccs on x86 platforms, and recent280MS compilers. Otherwise, posix locks or win32 critical sections are281used.282283USE_RECURSIVE_LOCKS default: not defined284If defined nonzero, uses recursive (aka reentrant) locks, otherwise285uses plain mutexes. This is not required for malloc proper, but may286be needed for layered allocators such as nedmalloc.287288LOCK_AT_FORK default: not defined289If defined nonzero, performs pthread_atfork upon initialization290to initialize child lock while holding parent lock. The implementation291assumes that pthread locks (not custom locks) are being used. In other292cases, you may need to customize the implementation.293294FOOTERS default: 0295If true, provide extra checking and dispatching by placing296information in the footers of allocated chunks. This adds297space and time overhead.298299INSECURE default: 0300If true, omit checks for usage errors and heap space overwrites.301302USE_DL_PREFIX default: NOT defined303Causes compiler to prefix all public routines with the string 'dl'.304This can be useful when you only want to use this malloc in one part305of a program, using your regular system malloc elsewhere.306307MALLOC_INSPECT_ALL default: NOT defined308If defined, compiles malloc_inspect_all and mspace_inspect_all, that309perform traversal of all heap space. Unless access to these310functions is otherwise restricted, you probably do not want to311include them in secure implementations.312313ABORT default: defined as abort()314Defines how to abort on failed checks. On most systems, a failed315check cannot die with an "assert" or even print an informative316message, because the underlying print routines in turn call malloc,317which will fail again. Generally, the best policy is to simply call318abort(). It's not very useful to do more than this because many319errors due to overwriting will show up as address faults (null, odd320addresses etc) rather than malloc-triggered checks, so will also321abort. Also, most compilers know that abort() does not return, so322can better optimize code conditionally calling it.323324PROCEED_ON_ERROR default: defined as 0 (false)325Controls whether detected bad addresses cause them to bypassed326rather than aborting. If set, detected bad arguments to free and327realloc are ignored. And all bookkeeping information is zeroed out328upon a detected overwrite of freed heap space, thus losing the329ability to ever return it from malloc again, but enabling the330application to proceed. If PROCEED_ON_ERROR is defined, the331static variable malloc_corruption_error_count is compiled in332and can be examined to see if errors have occurred. This option333generates slower code than the default abort policy.334335DEBUG default: NOT defined336The DEBUG setting is mainly intended for people trying to modify337this code or diagnose problems when porting to new platforms.338However, it may also be able to better isolate user errors than just339using runtime checks. The assertions in the check routines spell340out in more detail the assumptions and invariants underlying the341algorithms. The checking is fairly extensive, and will slow down342execution noticeably. Calling malloc_stats or mallinfo with DEBUG343set will attempt to check every non-mmapped allocated and free chunk344in the course of computing the summaries.345346ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)347Debugging assertion failures can be nearly impossible if your348version of the assert macro causes malloc to be called, which will349lead to a cascade of further failures, blowing the runtime stack.350ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),351which will usually make debugging easier.352353MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32354The action to take before "return 0" when malloc fails to be able to355return memory because there is none available.356357HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES358True if this system supports sbrk or an emulation of it.359360MORECORE default: sbrk361The name of the sbrk-style system routine to call to obtain more362memory. See below for guidance on writing custom MORECORE363functions. The type of the argument to sbrk/MORECORE varies across364systems. It cannot be size_t, because it supports negative365arguments, so it is normally the signed type of the same width as366size_t (sometimes declared as "intptr_t"). It doesn't much matter367though. Internally, we only call it with arguments less than half368the max value of a size_t, which should work across all reasonable369possibilities, although sometimes generating compiler warnings.370371MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE372If true, take advantage of fact that consecutive calls to MORECORE373with positive arguments always return contiguous increasing374addresses. This is true of unix sbrk. It does not hurt too much to375set it true anyway, since malloc copes with non-contiguities.376Setting it false when definitely non-contiguous saves time377and possibly wasted space it would take to discover this though.378379MORECORE_CANNOT_TRIM default: NOT defined380True if MORECORE cannot release space back to the system when given381negative arguments. This is generally necessary only if you are382using a hand-crafted MORECORE function that cannot handle negative383arguments.384385NO_SEGMENT_TRAVERSAL default: 0386If non-zero, suppresses traversals of memory segments387returned by either MORECORE or CALL_MMAP. This disables388merging of segments that are contiguous, and selectively389releasing them to the OS if unused, but bounds execution times.390391HAVE_MMAP default: 1 (true)392True if this system supports mmap or an emulation of it. If so, and393HAVE_MORECORE is not true, MMAP is used for all system394allocation. If set and HAVE_MORECORE is true as well, MMAP is395primarily used to directly allocate very large blocks. It is also396used as a backup strategy in cases where MORECORE fails to provide397space from system. Note: A single call to MUNMAP is assumed to be398able to unmap memory that may have be allocated using multiple calls399to MMAP, so long as they are adjacent.400401HAVE_MREMAP default: 1 on linux, else 0402If true realloc() uses mremap() to re-allocate large blocks and403extend or shrink allocation spaces.404405MMAP_CLEARS default: 1 except on WINCE.406True if mmap clears memory so calloc doesn't need to. This is true407for standard unix mmap using /dev/zero and on WIN32 except for WINCE.408409USE_BUILTIN_FFS default: 0 (i.e., not used)410Causes malloc to use the builtin ffs() function to compute indices.411Some compilers may recognize and intrinsify ffs to be faster than the412supplied C version. Also, the case of x86 using gcc is special-cased413to an asm instruction, so is already as fast as it can be, and so414this setting has no effect. Similarly for Win32 under recent MS compilers.415(On most x86s, the asm version is only slightly faster than the C version.)416417malloc_getpagesize default: derive from system includes, or 4096.418The system page size. To the extent possible, this malloc manages419memory from the system in page-size units. This may be (and420usually is) a function rather than a constant. This is ignored421if WIN32, where page size is determined using getSystemInfo during422initialization.423424USE_DEV_RANDOM default: 0 (i.e., not used)425Causes malloc to use /dev/random to initialize secure magic seed for426stamping footers. Otherwise, the current time is used.427428NO_MALLINFO default: 0429If defined, don't compile "mallinfo". This can be a simple way430of dealing with mismatches between system declarations and431those in this file.432433MALLINFO_FIELD_TYPE default: size_t434The type of the fields in the mallinfo struct. This was originally435defined as "int" in SVID etc, but is more usefully defined as436size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set437438NO_MALLOC_STATS default: 0439If defined, don't compile "malloc_stats". This avoids calls to440fprintf and bringing in stdio dependencies you might not want.441442REALLOC_ZERO_BYTES_FREES default: not defined443This should be set if a call to realloc with zero bytes should444be the same as a call to free. Some people think it should. Otherwise,445since this malloc returns a unique pointer for malloc(0), so does446realloc(p, 0).447448LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H449LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H450LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H default: NOT defined unless on WIN32451Define these if your system does not have these header files.452You might need to manually insert some of the declarations they provide.453454DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,455system_info.dwAllocationGranularity in WIN32,456otherwise 64K.457Also settable using mallopt(M_GRANULARITY, x)458The unit for allocating and deallocating memory from the system. On459most systems with contiguous MORECORE, there is no reason to460make this more than a page. However, systems with MMAP tend to461either require or encourage larger granularities. You can increase462this value to prevent system allocation functions to be called so463often, especially if they are slow. The value must be at least one464page and must be a power of two. Setting to 0 causes initialization465to either page size or win32 region size. (Note: In previous466versions of malloc, the equivalent of this option was called467"TOP_PAD")468469DEFAULT_TRIM_THRESHOLD default: 2MB470Also settable using mallopt(M_TRIM_THRESHOLD, x)471The maximum amount of unused top-most memory to keep before472releasing via malloc_trim in free(). Automatic trimming is mainly473useful in long-lived programs using contiguous MORECORE. Because474trimming via sbrk can be slow on some systems, and can sometimes be475wasteful (in cases where programs immediately afterward allocate476more large chunks) the value should be high enough so that your477overall system performance would improve by releasing this much478memory. As a rough guide, you might set to a value close to the479average size of a process (program) running on your system.480Releasing this much memory would allow such a process to run in481memory. Generally, it is worth tuning trim thresholds when a482program undergoes phases where several large chunks are allocated483and released in ways that can reuse each other's storage, perhaps484mixed with phases where there are no such chunks at all. The trim485value must be greater than page size to have any useful effect. To486disable trimming completely, you can set to MAX_SIZE_T. Note that the trick487some people use of mallocing a huge space and then freeing it at488program startup, in an attempt to reserve system memory, doesn't489have the intended effect under automatic trimming, since that memory490will immediately be returned to the system.491492DEFAULT_MMAP_THRESHOLD default: 256K493Also settable using mallopt(M_MMAP_THRESHOLD, x)494The request size threshold for using MMAP to directly service a495request. Requests of at least this size that cannot be allocated496using already-existing space will be serviced via mmap. (If enough497normal freed space already exists it is used instead.) Using mmap498segregates relatively large chunks of memory so that they can be499individually obtained and released from the host system. A request500serviced through mmap is never reused by any other request (at least501not directly; the system may just so happen to remap successive502requests to the same locations). Segregating space in this way has503the benefits that: Mmapped space can always be individually released504back to the system, which helps keep the system level memory demands505of a long-lived program low. Also, mapped memory doesn't become506`locked' between other chunks, as can happen with normally allocated507chunks, which means that even trimming via malloc_trim would not508release them. However, it has the disadvantage that the space509cannot be reclaimed, consolidated, and then used to service later510requests, as happens with normal chunks. The advantages of mmap511nearly always outweigh disadvantages for "large" chunks, but the512value of "large" may vary across systems. The default is an513empirically derived value that works well in most systems. You can514disable mmap by setting to MAX_SIZE_T.515516MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP517The number of consolidated frees between checks to release518unused segments when freeing. When using non-contiguous segments,519especially with multiple mspaces, checking only for topmost space520doesn't always suffice to trigger trimming. To compensate for this,521free() will, with a period of MAX_RELEASE_CHECK_RATE (or the522current number of segments, if greater) try to release unused523segments to the OS when freeing chunks that result in524consolidation. The best value for this parameter is a compromise525between slowing down frees with relatively costly checks that526rarely trigger versus holding on to unused memory. To effectively527disable, set to MAX_SIZE_T. This may lead to a very slight speed528improvement at the expense of carrying around more memory.529*/530531/* Version identifier to allow people to support multiple versions */532#ifndef DLMALLOC_VERSION533#define DLMALLOC_VERSION 20806534#endif /* DLMALLOC_VERSION */535536#ifndef DLMALLOC_EXPORT537#define DLMALLOC_EXPORT extern538#endif539540#ifndef WIN32541#ifdef _WIN32542#define WIN32 1543#endif /* _WIN32 */544#ifdef _WIN32_WCE545#define LACKS_FCNTL_H546#define WIN32 1547#endif /* _WIN32_WCE */548#endif /* WIN32 */549#ifdef WIN32550#define WIN32_LEAN_AND_MEAN551#include <windows.h>552#include <tchar.h>553#define HAVE_MMAP 1554#define HAVE_MORECORE 0555#define LACKS_UNISTD_H556#define LACKS_SYS_PARAM_H557#define LACKS_SYS_MMAN_H558#define LACKS_STRING_H559#define LACKS_STRINGS_H560#define LACKS_SYS_TYPES_H561#define LACKS_ERRNO_H562#define LACKS_SCHED_H563#ifndef MALLOC_FAILURE_ACTION564#define MALLOC_FAILURE_ACTION565#endif /* MALLOC_FAILURE_ACTION */566#ifndef MMAP_CLEARS567#ifdef _WIN32_WCE /* WINCE reportedly does not clear */568#define MMAP_CLEARS 0569#else570#define MMAP_CLEARS 1571#endif /* _WIN32_WCE */572#endif /*MMAP_CLEARS */573#endif /* WIN32 */574575#if defined(DARWIN) || defined(_DARWIN)576/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */577#ifndef HAVE_MORECORE578#define HAVE_MORECORE 0579#define HAVE_MMAP 1580/* OSX allocators provide 16 byte alignment */581#ifndef MALLOC_ALIGNMENT582#define MALLOC_ALIGNMENT ((size_t)16U)583#endif584#endif /* HAVE_MORECORE */585#endif /* DARWIN */586587#ifndef LACKS_SYS_TYPES_H588#include <sys/types.h> /* For size_t */589#endif /* LACKS_SYS_TYPES_H */590591/* The maximum possible size_t value has all bits set */592#define MAX_SIZE_T (~(size_t)0)593594#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */595#define USE_LOCKS ((defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \596(defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0))597#endif /* USE_LOCKS */598599#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86, MSC >= 1310 */600#if ((defined(__GNUC__) && \601((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \602defined(__i386__) || defined(__x86_64__))) || \603(defined(_MSC_VER) && _MSC_VER>=1310))604#ifndef USE_SPIN_LOCKS605#define USE_SPIN_LOCKS 1606#endif /* USE_SPIN_LOCKS */607#elif USE_SPIN_LOCKS608#error "USE_SPIN_LOCKS defined without implementation"609#endif /* ... locks available... */610#elif !defined(USE_SPIN_LOCKS)611#define USE_SPIN_LOCKS 0612#endif /* USE_LOCKS */613614#ifndef ONLY_MSPACES615#define ONLY_MSPACES 0616#endif /* ONLY_MSPACES */617#ifndef MSPACES618#if ONLY_MSPACES619#define MSPACES 1620#else /* ONLY_MSPACES */621#define MSPACES 0622#endif /* ONLY_MSPACES */623#endif /* MSPACES */624#ifndef MALLOC_ALIGNMENT625#define MALLOC_ALIGNMENT ((size_t)(2 * sizeof(void *)))626#endif /* MALLOC_ALIGNMENT */627#ifndef FOOTERS628#define FOOTERS 0629#endif /* FOOTERS */630#ifndef ABORT631#define ABORT abort()632#endif /* ABORT */633#ifndef ABORT_ON_ASSERT_FAILURE634#define ABORT_ON_ASSERT_FAILURE 1635#endif /* ABORT_ON_ASSERT_FAILURE */636#ifndef PROCEED_ON_ERROR637#define PROCEED_ON_ERROR 0638#endif /* PROCEED_ON_ERROR */639640#ifndef INSECURE641#define INSECURE 0642#endif /* INSECURE */643#ifndef MALLOC_INSPECT_ALL644#define MALLOC_INSPECT_ALL 0645#endif /* MALLOC_INSPECT_ALL */646#ifndef HAVE_MMAP647#define HAVE_MMAP 1648#endif /* HAVE_MMAP */649#ifndef MMAP_CLEARS650#define MMAP_CLEARS 1651#endif /* MMAP_CLEARS */652#ifndef HAVE_MREMAP653#ifdef linux654#define HAVE_MREMAP 1655#define _GNU_SOURCE /* Turns on mremap() definition */656#else /* linux */657#define HAVE_MREMAP 0658#endif /* linux */659#endif /* HAVE_MREMAP */660#ifndef MALLOC_FAILURE_ACTION661#define MALLOC_FAILURE_ACTION errno = ENOMEM;662#endif /* MALLOC_FAILURE_ACTION */663#ifndef HAVE_MORECORE664#if ONLY_MSPACES665#define HAVE_MORECORE 0666#else /* ONLY_MSPACES */667#define HAVE_MORECORE 1668#endif /* ONLY_MSPACES */669#endif /* HAVE_MORECORE */670#if !HAVE_MORECORE671#define MORECORE_CONTIGUOUS 0672#else /* !HAVE_MORECORE */673#define MORECORE_DEFAULT sbrk674#ifndef MORECORE_CONTIGUOUS675#define MORECORE_CONTIGUOUS 1676#endif /* MORECORE_CONTIGUOUS */677#endif /* HAVE_MORECORE */678#ifndef DEFAULT_GRANULARITY679#if (MORECORE_CONTIGUOUS || defined(WIN32))680#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */681#else /* MORECORE_CONTIGUOUS */682#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)683#endif /* MORECORE_CONTIGUOUS */684#endif /* DEFAULT_GRANULARITY */685#ifndef DEFAULT_TRIM_THRESHOLD686#ifndef MORECORE_CANNOT_TRIM687#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)688#else /* MORECORE_CANNOT_TRIM */689#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T690#endif /* MORECORE_CANNOT_TRIM */691#endif /* DEFAULT_TRIM_THRESHOLD */692#ifndef DEFAULT_MMAP_THRESHOLD693#if HAVE_MMAP694#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)695#else /* HAVE_MMAP */696#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T697#endif /* HAVE_MMAP */698#endif /* DEFAULT_MMAP_THRESHOLD */699#ifndef MAX_RELEASE_CHECK_RATE700#if HAVE_MMAP701#define MAX_RELEASE_CHECK_RATE 4095702#else703#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T704#endif /* HAVE_MMAP */705#endif /* MAX_RELEASE_CHECK_RATE */706#ifndef USE_BUILTIN_FFS707#define USE_BUILTIN_FFS 0708#endif /* USE_BUILTIN_FFS */709#ifndef USE_DEV_RANDOM710#define USE_DEV_RANDOM 0711#endif /* USE_DEV_RANDOM */712#ifndef NO_MALLINFO713#define NO_MALLINFO 0714#endif /* NO_MALLINFO */715#ifndef MALLINFO_FIELD_TYPE716#define MALLINFO_FIELD_TYPE size_t717#endif /* MALLINFO_FIELD_TYPE */718#ifndef NO_MALLOC_STATS719#define NO_MALLOC_STATS 0720#endif /* NO_MALLOC_STATS */721#ifndef NO_SEGMENT_TRAVERSAL722#define NO_SEGMENT_TRAVERSAL 0723#endif /* NO_SEGMENT_TRAVERSAL */724725/*726mallopt tuning options. SVID/XPG defines four standard parameter727numbers for mallopt, normally defined in malloc.h. None of these728are used in this malloc, so setting them has no effect. But this729malloc does support the following options.730*/731732#define M_TRIM_THRESHOLD (-1)733#define M_GRANULARITY (-2)734#define M_MMAP_THRESHOLD (-3)735736/* ------------------------ Mallinfo declarations ------------------------ */737738#if !NO_MALLINFO739/*740This version of malloc supports the standard SVID/XPG mallinfo741routine that returns a struct containing usage properties and742statistics. It should work on any system that has a743/usr/include/malloc.h defining struct mallinfo. The main744declaration needed is the mallinfo struct that is returned (by-copy)745by mallinfo(). The malloinfo struct contains a bunch of fields that746are not even meaningful in this version of malloc. These fields are747are instead filled by mallinfo() with other numbers that might be of748interest.749750HAVE_USR_INCLUDE_MALLOC_H should be set if you have a751/usr/include/malloc.h file that includes a declaration of struct752mallinfo. If so, it is included; else a compliant version is753declared below. These must be precisely the same for mallinfo() to754work. The original SVID version of this struct, defined on most755systems with mallinfo, declares all fields as ints. But some others756define as unsigned long. If your system defines the fields using a757type of different width than listed here, you MUST #include your758system version and #define HAVE_USR_INCLUDE_MALLOC_H.759*/760761/* #define HAVE_USR_INCLUDE_MALLOC_H */762763#ifdef HAVE_USR_INCLUDE_MALLOC_H764#include "/usr/include/malloc.h"765#else /* HAVE_USR_INCLUDE_MALLOC_H */766#ifndef STRUCT_MALLINFO_DECLARED767/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */768#define _STRUCT_MALLINFO769#define STRUCT_MALLINFO_DECLARED 1770struct mallinfo {771MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */772MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */773MALLINFO_FIELD_TYPE smblks; /* always 0 */774MALLINFO_FIELD_TYPE hblks; /* always 0 */775MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */776MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */777MALLINFO_FIELD_TYPE fsmblks; /* always 0 */778MALLINFO_FIELD_TYPE uordblks; /* total allocated space */779MALLINFO_FIELD_TYPE fordblks; /* total free space */780MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */781};782#endif /* STRUCT_MALLINFO_DECLARED */783#endif /* HAVE_USR_INCLUDE_MALLOC_H */784#endif /* NO_MALLINFO */785786/*787Try to persuade compilers to inline. The most critical functions for788inlining are defined as macros, so these aren't used for them.789*/790791#ifndef FORCEINLINE792#if defined(__GNUC__)793#define FORCEINLINE __inline __attribute__ ((always_inline))794#elif defined(_MSC_VER)795#define FORCEINLINE __forceinline796#endif797#endif798#ifndef NOINLINE799#if defined(__GNUC__)800#define NOINLINE __attribute__ ((noinline))801#elif defined(_MSC_VER)802#define NOINLINE __declspec(noinline)803#else804#define NOINLINE805#endif806#endif807808#ifdef __cplusplus809extern "C" {810#ifndef FORCEINLINE811#define FORCEINLINE inline812#endif813#endif /* __cplusplus */814#ifndef FORCEINLINE815#define FORCEINLINE816#endif817818#if !ONLY_MSPACES819820/* ------------------- Declarations of public routines ------------------- */821822#ifndef USE_DL_PREFIX823#define dlcalloc calloc824#define dlfree free825#define dlmalloc malloc826#define dlmemalign memalign827#define dlposix_memalign posix_memalign828#define dlrealloc realloc829#define dlrealloc_in_place realloc_in_place830#define dlvalloc valloc831#define dlpvalloc pvalloc832#define dlmallinfo mallinfo833#define dlmallopt mallopt834#define dlmalloc_trim malloc_trim835#define dlmalloc_stats malloc_stats836#define dlmalloc_usable_size malloc_usable_size837#define dlmalloc_footprint malloc_footprint838#define dlmalloc_max_footprint malloc_max_footprint839#define dlmalloc_footprint_limit malloc_footprint_limit840#define dlmalloc_set_footprint_limit malloc_set_footprint_limit841#define dlmalloc_inspect_all malloc_inspect_all842#define dlindependent_calloc independent_calloc843#define dlindependent_comalloc independent_comalloc844#define dlbulk_free bulk_free845#endif /* USE_DL_PREFIX */846847/*848malloc(size_t n)849Returns a pointer to a newly allocated chunk of at least n bytes, or850null if no space is available, in which case errno is set to ENOMEM851on ANSI C systems.852853If n is zero, malloc returns a minimum-sized chunk. (The minimum854size is 16 bytes on most 32bit systems, and 32 bytes on 64bit855systems.) Note that size_t is an unsigned type, so calls with856arguments that would be negative if signed are interpreted as857requests for huge amounts of space, which will often fail. The858maximum supported value of n differs across systems, but is in all859cases less than the maximum representable value of a size_t.860*/861DLMALLOC_EXPORT void* dlmalloc(size_t);862863/*864free(void* p)865Releases the chunk of memory pointed to by p, that had been previously866allocated using malloc or a related routine such as realloc.867It has no effect if p is null. If p was not malloced or already868freed, free(p) will by default cause the current program to abort.869*/870DLMALLOC_EXPORT void dlfree(void*);871872/*873calloc(size_t n_elements, size_t element_size);874Returns a pointer to n_elements * element_size bytes, with all locations875set to zero.876*/877DLMALLOC_EXPORT void* dlcalloc(size_t, size_t);878879/*880realloc(void* p, size_t n)881Returns a pointer to a chunk of size n that contains the same data882as does chunk p up to the minimum of (n, p's size) bytes, or null883if no space is available.884885The returned pointer may or may not be the same as p. The algorithm886prefers extending p in most cases when possible, otherwise it887employs the equivalent of a malloc-copy-free sequence.888889If p is null, realloc is equivalent to malloc.890891If space is not available, realloc returns null, errno is set (if on892ANSI) and p is NOT freed.893894if n is for fewer bytes than already held by p, the newly unused895space is lopped off and freed if possible. realloc with a size896argument of zero (re)allocates a minimum-sized chunk.897898The old unix realloc convention of allowing the last-free'd chunk899to be used as an argument to realloc is not supported.900*/901DLMALLOC_EXPORT void* dlrealloc(void*, size_t);902903/*904realloc_in_place(void* p, size_t n)905Resizes the space allocated for p to size n, only if this can be906done without moving p (i.e., only if there is adjacent space907available if n is greater than p's current allocated size, or n is908less than or equal to p's size). This may be used instead of plain909realloc if an alternative allocation strategy is needed upon failure910to expand space; for example, reallocation of a buffer that must be911memory-aligned or cleared. You can use realloc_in_place to trigger912these alternatives only when needed.913914Returns p if successful; otherwise null.915*/916DLMALLOC_EXPORT void* dlrealloc_in_place(void*, size_t);917918/*919memalign(size_t alignment, size_t n);920Returns a pointer to a newly allocated chunk of n bytes, aligned921in accord with the alignment argument.922923The alignment argument should be a power of two. If the argument is924not a power of two, the nearest greater power is used.9258-byte alignment is guaranteed by normal malloc calls, so don't926bother calling memalign with an argument of 8 or less.927928Overreliance on memalign is a sure way to fragment space.929*/930DLMALLOC_EXPORT void* dlmemalign(size_t, size_t);931932/*933int posix_memalign(void** pp, size_t alignment, size_t n);934Allocates a chunk of n bytes, aligned in accord with the alignment935argument. Differs from memalign only in that it (1) assigns the936allocated memory to *pp rather than returning it, (2) fails and937returns EINVAL if the alignment is not a power of two (3) fails and938returns ENOMEM if memory cannot be allocated.939*/940DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t);941942/*943valloc(size_t n);944Equivalent to memalign(pagesize, n), where pagesize is the page945size of the system. If the pagesize is unknown, 4096 is used.946*/947DLMALLOC_EXPORT void* dlvalloc(size_t);948949/*950mallopt(int parameter_number, int parameter_value)951Sets tunable parameters The format is to provide a952(parameter-number, parameter-value) pair. mallopt then sets the953corresponding parameter to the argument value if it can (i.e., so954long as the value is meaningful), and returns 1 if successful else9550. To workaround the fact that mallopt is specified to use int,956not size_t parameters, the value -1 is specially treated as the957maximum unsigned size_t value.958959SVID/XPG/ANSI defines four standard param numbers for mallopt,960normally defined in malloc.h. None of these are use in this malloc,961so setting them has no effect. But this malloc also supports other962options in mallopt. See below for details. Briefly, supported963parameters are as follows (listed defaults are for "typical"964configurations).965966Symbol param # default allowed param values967M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables)968M_GRANULARITY -2 page size any power of 2 >= page size969M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)970*/971DLMALLOC_EXPORT int dlmallopt(int, int);972973/*974malloc_footprint();975Returns the number of bytes obtained from the system. The total976number of bytes allocated by malloc, realloc etc., is less than this977value. Unlike mallinfo, this function returns only a precomputed978result, so can be called frequently to monitor memory consumption.979Even if locks are otherwise defined, this function does not use them,980so results might not be up to date.981*/982DLMALLOC_EXPORT size_t dlmalloc_footprint(void);983984/*985malloc_max_footprint();986Returns the maximum number of bytes obtained from the system. This987value will be greater than current footprint if deallocated space988has been reclaimed by the system. The peak number of bytes allocated989by malloc, realloc etc., is less than this value. Unlike mallinfo,990this function returns only a precomputed result, so can be called991frequently to monitor memory consumption. Even if locks are992otherwise defined, this function does not use them, so results might993not be up to date.994*/995DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void);996997/*998malloc_footprint_limit();999Returns the number of bytes that the heap is allowed to obtain from1000the system, returning the last value returned by1001malloc_set_footprint_limit, or the maximum size_t value if1002never set. The returned value reflects a permission. There is no1003guarantee that this number of bytes can actually be obtained from1004the system.1005*/1006DLMALLOC_EXPORT size_t dlmalloc_footprint_limit();10071008/*1009malloc_set_footprint_limit();1010Sets the maximum number of bytes to obtain from the system, causing1011failure returns from malloc and related functions upon attempts to1012exceed this value. The argument value may be subject to page1013rounding to an enforceable limit; this actual value is returned.1014Using an argument of the maximum possible size_t effectively1015disables checks. If the argument is less than or equal to the1016current malloc_footprint, then all future allocations that require1017additional system memory will fail. However, invocation cannot1018retroactively deallocate existing used memory.1019*/1020DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes);10211022#if MALLOC_INSPECT_ALL1023/*1024malloc_inspect_all(void(*handler)(void *start,1025void *end,1026size_t used_bytes,1027void* callback_arg),1028void* arg);1029Traverses the heap and calls the given handler for each managed1030region, skipping all bytes that are (or may be) used for bookkeeping1031purposes. Traversal does not include include chunks that have been1032directly memory mapped. Each reported region begins at the start1033address, and continues up to but not including the end address. The1034first used_bytes of the region contain allocated data. If1035used_bytes is zero, the region is unallocated. The handler is1036invoked with the given callback argument. If locks are defined, they1037are held during the entire traversal. It is a bad idea to invoke1038other malloc functions from within the handler.10391040For example, to count the number of in-use chunks with size greater1041than 1000, you could write:1042static int count = 0;1043void count_chunks(void* start, void* end, size_t used, void* arg) {1044if (used >= 1000) ++count;1045}1046then:1047malloc_inspect_all(count_chunks, NULL);10481049malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined.1050*/1051DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*),1052void* arg);10531054#endif /* MALLOC_INSPECT_ALL */10551056#if !NO_MALLINFO1057/*1058mallinfo()1059Returns (by copy) a struct containing various summary statistics:10601061arena: current total non-mmapped bytes allocated from system1062ordblks: the number of free chunks1063smblks: always zero.1064hblks: current number of mmapped regions1065hblkhd: total bytes held in mmapped regions1066usmblks: the maximum total allocated space. This will be greater1067than current total if trimming has occurred.1068fsmblks: always zero1069uordblks: current total allocated space (normal or mmapped)1070fordblks: total free space1071keepcost: the maximum number of bytes that could ideally be released1072back to system via malloc_trim. ("ideally" means that1073it ignores page restrictions etc.)10741075Because these fields are ints, but internal bookkeeping may1076be kept as longs, the reported values may wrap around zero and1077thus be inaccurate.1078*/1079DLMALLOC_EXPORT struct mallinfo dlmallinfo(void);1080#endif /* NO_MALLINFO */10811082/*1083independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);10841085independent_calloc is similar to calloc, but instead of returning a1086single cleared space, it returns an array of pointers to n_elements1087independent elements that can hold contents of size elem_size, each1088of which starts out cleared, and can be independently freed,1089realloc'ed etc. The elements are guaranteed to be adjacently1090allocated (this is not guaranteed to occur with multiple callocs or1091mallocs), which may also improve cache locality in some1092applications.10931094The "chunks" argument is optional (i.e., may be null, which is1095probably the most typical usage). If it is null, the returned array1096is itself dynamically allocated and should also be freed when it is1097no longer needed. Otherwise, the chunks array must be of at least1098n_elements in length. It is filled in with the pointers to the1099chunks.11001101In either case, independent_calloc returns this pointer array, or1102null if the allocation failed. If n_elements is zero and "chunks"1103is null, it returns a chunk representing an array with zero elements1104(which should be freed if not wanted).11051106Each element must be freed when it is no longer needed. This can be1107done all at once using bulk_free.11081109independent_calloc simplifies and speeds up implementations of many1110kinds of pools. It may also be useful when constructing large data1111structures that initially have a fixed number of fixed-sized nodes,1112but the number is not known at compile time, and some of the nodes1113may later need to be freed. For example:11141115struct Node { int item; struct Node* next; };11161117struct Node* build_list() {1118struct Node** pool;1119int n = read_number_of_nodes_needed();1120if (n <= 0) return 0;1121pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);1122if (pool == 0) die();1123// organize into a linked list...1124struct Node* first = pool[0];1125for (i = 0; i < n-1; ++i)1126pool[i]->next = pool[i+1];1127free(pool); // Can now free the array (or not, if it is needed later)1128return first;1129}1130*/1131DLMALLOC_EXPORT void** dlindependent_calloc(size_t, size_t, void**);11321133/*1134independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);11351136independent_comalloc allocates, all at once, a set of n_elements1137chunks with sizes indicated in the "sizes" array. It returns1138an array of pointers to these elements, each of which can be1139independently freed, realloc'ed etc. The elements are guaranteed to1140be adjacently allocated (this is not guaranteed to occur with1141multiple callocs or mallocs), which may also improve cache locality1142in some applications.11431144The "chunks" argument is optional (i.e., may be null). If it is null1145the returned array is itself dynamically allocated and should also1146be freed when it is no longer needed. Otherwise, the chunks array1147must be of at least n_elements in length. It is filled in with the1148pointers to the chunks.11491150In either case, independent_comalloc returns this pointer array, or1151null if the allocation failed. If n_elements is zero and chunks is1152null, it returns a chunk representing an array with zero elements1153(which should be freed if not wanted).11541155Each element must be freed when it is no longer needed. This can be1156done all at once using bulk_free.11571158independent_comallac differs from independent_calloc in that each1159element may have a different size, and also that it does not1160automatically clear elements.11611162independent_comalloc can be used to speed up allocation in cases1163where several structs or objects must always be allocated at the1164same time. For example:11651166struct Head { ... }1167struct Foot { ... }11681169void send_message(char* msg) {1170int msglen = strlen(msg);1171size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };1172void* chunks[3];1173if (independent_comalloc(3, sizes, chunks) == 0)1174die();1175struct Head* head = (struct Head*)(chunks[0]);1176char* body = (char*)(chunks[1]);1177struct Foot* foot = (struct Foot*)(chunks[2]);1178// ...1179}11801181In general though, independent_comalloc is worth using only for1182larger values of n_elements. For small values, you probably won't1183detect enough difference from series of malloc calls to bother.11841185Overuse of independent_comalloc can increase overall memory usage,1186since it cannot reuse existing noncontiguous small chunks that1187might be available for some of the elements.1188*/1189DLMALLOC_EXPORT void** dlindependent_comalloc(size_t, size_t*, void**);11901191/*1192bulk_free(void* array[], size_t n_elements)1193Frees and clears (sets to null) each non-null pointer in the given1194array. This is likely to be faster than freeing them one-by-one.1195If footers are used, pointers that have been allocated in different1196mspaces are not freed or cleared, and the count of all such pointers1197is returned. For large arrays of pointers with poor locality, it1198may be worthwhile to sort this array before calling bulk_free.1199*/1200DLMALLOC_EXPORT size_t dlbulk_free(void**, size_t n_elements);12011202/*1203pvalloc(size_t n);1204Equivalent to valloc(minimum-page-that-holds(n)), that is,1205round up n to nearest pagesize.1206*/1207DLMALLOC_EXPORT void* dlpvalloc(size_t);12081209/*1210malloc_trim(size_t pad);12111212If possible, gives memory back to the system (via negative arguments1213to sbrk) if there is unused memory at the `high' end of the malloc1214pool or in unused MMAP segments. You can call this after freeing1215large blocks of memory to potentially reduce the system-level memory1216requirements of a program. However, it cannot guarantee to reduce1217memory. Under some allocation patterns, some large free blocks of1218memory will be locked between two used chunks, so they cannot be1219given back to the system.12201221The `pad' argument to malloc_trim represents the amount of free1222trailing space to leave untrimmed. If this argument is zero, only1223the minimum amount of memory to maintain internal data structures1224will be left. Non-zero arguments can be supplied to maintain enough1225trailing space to service future expected allocations without having1226to re-obtain memory from the system.12271228Malloc_trim returns 1 if it actually released any memory, else 0.1229*/1230DLMALLOC_EXPORT int dlmalloc_trim(size_t);12311232/*1233malloc_stats();1234Prints on stderr the amount of space obtained from the system (both1235via sbrk and mmap), the maximum amount (which may be more than1236current if malloc_trim and/or munmap got called), and the current1237number of bytes allocated via malloc (or realloc, etc) but not yet1238freed. Note that this is the number of bytes allocated, not the1239number requested. It will be larger than the number requested1240because of alignment and bookkeeping overhead. Because it includes1241alignment wastage as being in use, this figure may be greater than1242zero even when no user-level chunks are allocated.12431244The reported current and maximum system memory can be inaccurate if1245a program makes other calls to system memory allocation functions1246(normally sbrk) outside of malloc.12471248malloc_stats prints only the most commonly interesting statistics.1249More information can be obtained by calling mallinfo.1250*/1251DLMALLOC_EXPORT void dlmalloc_stats(void);12521253/*1254malloc_usable_size(void* p);12551256Returns the number of bytes you can actually use in1257an allocated chunk, which may be more than you requested (although1258often not) due to alignment and minimum size constraints.1259You can use this many bytes without worrying about1260overwriting other allocated objects. This is not a particularly great1261programming practice. malloc_usable_size can be more useful in1262debugging and assertions, for example:12631264p = malloc(n);1265assert(malloc_usable_size(p) >= 256);1266*/1267size_t dlmalloc_usable_size(void*);12681269#endif /* ONLY_MSPACES */12701271#if MSPACES12721273/*1274mspace is an opaque type representing an independent1275region of space that supports mspace_malloc, etc.1276*/1277typedef void* mspace;12781279/*1280create_mspace creates and returns a new independent space with the1281given initial capacity, or, if 0, the default granularity size. It1282returns null if there is no system memory available to create the1283space. If argument locked is non-zero, the space uses a separate1284lock to control access. The capacity of the space will grow1285dynamically as needed to service mspace_malloc requests. You can1286control the sizes of incremental increases of this space by1287compiling with a different DEFAULT_GRANULARITY or dynamically1288setting with mallopt(M_GRANULARITY, value).1289*/1290DLMALLOC_EXPORT mspace create_mspace(size_t capacity, int locked);12911292/*1293destroy_mspace destroys the given space, and attempts to return all1294of its memory back to the system, returning the total number of1295bytes freed. After destruction, the results of access to all memory1296used by the space become undefined.1297*/1298DLMALLOC_EXPORT size_t destroy_mspace(mspace msp);12991300/*1301create_mspace_with_base uses the memory supplied as the initial base1302of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this1303space is used for bookkeeping, so the capacity must be at least this1304large. (Otherwise 0 is returned.) When this initial space is1305exhausted, additional memory will be obtained from the system.1306Destroying this space will deallocate all additionally allocated1307space (if possible) but not the initial base.1308*/1309DLMALLOC_EXPORT mspace create_mspace_with_base(void* base, size_t capacity, int locked);13101311/*1312mspace_track_large_chunks controls whether requests for large chunks1313are allocated in their own untracked mmapped regions, separate from1314others in this mspace. By default large chunks are not tracked,1315which reduces fragmentation. However, such chunks are not1316necessarily released to the system upon destroy_mspace. Enabling1317tracking by setting to true may increase fragmentation, but avoids1318leakage when relying on destroy_mspace to release all memory1319allocated using this space. The function returns the previous1320setting.1321*/1322DLMALLOC_EXPORT int mspace_track_large_chunks(mspace msp, int enable);132313241325/*1326mspace_malloc behaves as malloc, but operates within1327the given space.1328*/1329DLMALLOC_EXPORT void* mspace_malloc(mspace msp, size_t bytes);13301331/*1332mspace_free behaves as free, but operates within1333the given space.13341335If compiled with FOOTERS==1, mspace_free is not actually needed.1336free may be called instead of mspace_free because freed chunks from1337any space are handled by their originating spaces.1338*/1339DLMALLOC_EXPORT void mspace_free(mspace msp, void* mem);13401341/*1342mspace_realloc behaves as realloc, but operates within1343the given space.13441345If compiled with FOOTERS==1, mspace_realloc is not actually1346needed. realloc may be called instead of mspace_realloc because1347realloced chunks from any space are handled by their originating1348spaces.1349*/1350DLMALLOC_EXPORT void* mspace_realloc(mspace msp, void* mem, size_t newsize);13511352/*1353mspace_calloc behaves as calloc, but operates within1354the given space.1355*/1356DLMALLOC_EXPORT void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);13571358/*1359mspace_memalign behaves as memalign, but operates within1360the given space.1361*/1362DLMALLOC_EXPORT void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);13631364/*1365mspace_independent_calloc behaves as independent_calloc, but1366operates within the given space.1367*/1368DLMALLOC_EXPORT void** mspace_independent_calloc(mspace msp, size_t n_elements,1369size_t elem_size, void* chunks[]);13701371/*1372mspace_independent_comalloc behaves as independent_comalloc, but1373operates within the given space.1374*/1375DLMALLOC_EXPORT void** mspace_independent_comalloc(mspace msp, size_t n_elements,1376size_t sizes[], void* chunks[]);13771378/*1379mspace_footprint() returns the number of bytes obtained from the1380system for this space.1381*/1382DLMALLOC_EXPORT size_t mspace_footprint(mspace msp);13831384/*1385mspace_max_footprint() returns the peak number of bytes obtained from the1386system for this space.1387*/1388DLMALLOC_EXPORT size_t mspace_max_footprint(mspace msp);138913901391#if !NO_MALLINFO1392/*1393mspace_mallinfo behaves as mallinfo, but reports properties of1394the given space.1395*/1396DLMALLOC_EXPORT struct mallinfo mspace_mallinfo(mspace msp);1397#endif /* NO_MALLINFO */13981399/*1400malloc_usable_size(void* p) behaves the same as malloc_usable_size;1401*/1402DLMALLOC_EXPORT size_t mspace_usable_size(const void* mem);14031404/*1405mspace_malloc_stats behaves as malloc_stats, but reports1406properties of the given space.1407*/1408DLMALLOC_EXPORT void mspace_malloc_stats(mspace msp);14091410/*1411mspace_trim behaves as malloc_trim, but1412operates within the given space.1413*/1414DLMALLOC_EXPORT int mspace_trim(mspace msp, size_t pad);14151416/*1417An alias for mallopt.1418*/1419DLMALLOC_EXPORT int mspace_mallopt(int, int);14201421#endif /* MSPACES */14221423#ifdef __cplusplus1424} /* end of extern "C" */1425#endif /* __cplusplus */14261427/*1428========================================================================1429To make a fully customizable malloc.h header file, cut everything1430above this line, put into file malloc.h, edit to suit, and #include it1431on the next line, as well as in programs that use this malloc.1432========================================================================1433*/14341435/* #include "malloc.h" */14361437/*------------------------------ internal #includes ---------------------- */14381439#ifdef _MSC_VER1440#pragma warning( disable : 4146 ) /* no "unsigned" warnings */1441#endif /* _MSC_VER */1442#if !NO_MALLOC_STATS1443#include <stdio.h> /* for printing in malloc_stats */1444#endif /* NO_MALLOC_STATS */1445#ifndef LACKS_ERRNO_H1446#include <errno.h> /* for MALLOC_FAILURE_ACTION */1447#endif /* LACKS_ERRNO_H */1448#ifdef DEBUG1449#if ABORT_ON_ASSERT_FAILURE1450#undef assert1451#define assert(x) if(!(x)) ABORT1452#else /* ABORT_ON_ASSERT_FAILURE */1453#include <assert.h>1454#endif /* ABORT_ON_ASSERT_FAILURE */1455#else /* DEBUG */1456#ifndef assert1457#define assert(x)1458#endif1459#define DEBUG 01460#endif /* DEBUG */1461#if !defined(WIN32) && !defined(LACKS_TIME_H)1462#include <time.h> /* for magic initialization */1463#endif /* WIN32 */1464#ifndef LACKS_STDLIB_H1465#include <stdlib.h> /* for abort() */1466#endif /* LACKS_STDLIB_H */1467#ifndef LACKS_STRING_H1468#include <string.h> /* for memset etc */1469#endif /* LACKS_STRING_H */1470#if USE_BUILTIN_FFS1471#ifndef LACKS_STRINGS_H1472#include <strings.h> /* for ffs */1473#endif /* LACKS_STRINGS_H */1474#endif /* USE_BUILTIN_FFS */1475#if HAVE_MMAP1476#ifndef LACKS_SYS_MMAN_H1477/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */1478#if (defined(linux) && !defined(__USE_GNU))1479#define __USE_GNU 11480#include <sys/mman.h> /* for mmap */1481#undef __USE_GNU1482#else1483#include <sys/mman.h> /* for mmap */1484#endif /* linux */1485#endif /* LACKS_SYS_MMAN_H */1486#ifndef LACKS_FCNTL_H1487#include <fcntl.h>1488#endif /* LACKS_FCNTL_H */1489#endif /* HAVE_MMAP */1490#ifndef LACKS_UNISTD_H1491#include <unistd.h> /* for sbrk, sysconf */1492#else /* LACKS_UNISTD_H */1493#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)1494extern void* sbrk(ptrdiff_t);1495#endif /* FreeBSD etc */1496#endif /* LACKS_UNISTD_H */14971498/* Declarations for locking */1499#if USE_LOCKS1500#ifndef WIN321501#if defined (__SVR4) && defined (__sun) /* solaris */1502#include <thread.h>1503#elif !defined(LACKS_SCHED_H)1504#include <sched.h>1505#endif /* solaris or LACKS_SCHED_H */1506#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS1507#include <pthread.h>1508#endif /* USE_RECURSIVE_LOCKS ... */1509#elif defined(_MSC_VER)1510#ifndef _M_AMD641511/* These are already defined on AMD64 builds */1512#ifdef __cplusplus1513extern "C" {1514#endif /* __cplusplus */1515LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp);1516LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value);1517#ifdef __cplusplus1518}1519#endif /* __cplusplus */1520#endif /* _M_AMD64 */1521#pragma intrinsic (_InterlockedCompareExchange)1522#pragma intrinsic (_InterlockedExchange)1523#define interlockedcompareexchange _InterlockedCompareExchange1524#define interlockedexchange _InterlockedExchange1525#elif defined(WIN32) && defined(__GNUC__)1526#define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b)1527#define interlockedexchange __sync_lock_test_and_set1528#endif /* Win32 */1529#else /* USE_LOCKS */1530#endif /* USE_LOCKS */15311532#ifndef LOCK_AT_FORK1533#define LOCK_AT_FORK 01534#endif15351536/* Declarations for bit scanning on win32 */1537#if defined(_MSC_VER) && _MSC_VER>=13001538#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */1539#ifdef __cplusplus1540extern "C" {1541#endif /* __cplusplus */1542unsigned char _BitScanForward(unsigned long *index, unsigned long mask);1543unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);1544#ifdef __cplusplus1545}1546#endif /* __cplusplus */15471548#define BitScanForward _BitScanForward1549#define BitScanReverse _BitScanReverse1550#pragma intrinsic(_BitScanForward)1551#pragma intrinsic(_BitScanReverse)1552#endif /* BitScanForward */1553#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */15541555#ifndef WIN321556#ifndef malloc_getpagesize1557# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */1558# ifndef _SC_PAGE_SIZE1559# define _SC_PAGE_SIZE _SC_PAGESIZE1560# endif1561# endif1562# ifdef _SC_PAGE_SIZE1563# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)1564# else1565# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)1566extern size_t getpagesize();1567# define malloc_getpagesize getpagesize()1568# else1569# ifdef WIN32 /* use supplied emulation of getpagesize */1570# define malloc_getpagesize getpagesize()1571# else1572# ifndef LACKS_SYS_PARAM_H1573# include <sys/param.h>1574# endif1575# ifdef EXEC_PAGESIZE1576# define malloc_getpagesize EXEC_PAGESIZE1577# else1578# ifdef NBPG1579# ifndef CLSIZE1580# define malloc_getpagesize NBPG1581# else1582# define malloc_getpagesize (NBPG * CLSIZE)1583# endif1584# else1585# ifdef NBPC1586# define malloc_getpagesize NBPC1587# else1588# ifdef PAGESIZE1589# define malloc_getpagesize PAGESIZE1590# else /* just guess */1591# define malloc_getpagesize ((size_t)4096U)1592# endif1593# endif1594# endif1595# endif1596# endif1597# endif1598# endif1599#endif1600#endif16011602/* ------------------- size_t and alignment properties -------------------- */16031604/* The byte and bit size of a size_t */1605#define SIZE_T_SIZE (sizeof(size_t))1606#define SIZE_T_BITSIZE (sizeof(size_t) << 3)16071608/* Some constants coerced to size_t */1609/* Annoying but necessary to avoid errors on some platforms */1610#define SIZE_T_ZERO ((size_t)0)1611#define SIZE_T_ONE ((size_t)1)1612#define SIZE_T_TWO ((size_t)2)1613#define SIZE_T_FOUR ((size_t)4)1614#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)1615#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)1616#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)1617#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)16181619/* The bit mask value corresponding to MALLOC_ALIGNMENT */1620#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)16211622/* True if address a has acceptable alignment */1623#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)16241625/* the number of bytes to offset an address to align it */1626#define align_offset(A)\1627((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\1628((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))16291630/* -------------------------- MMAP preliminaries ------------------------- */16311632/*1633If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and1634checks to fail so compiler optimizer can delete code rather than1635using so many "#if"s.1636*/163716381639/* MORECORE and MMAP must return MFAIL on failure */1640#define MFAIL ((void*)(MAX_SIZE_T))1641#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */16421643#if HAVE_MMAP16441645#ifndef WIN321646#define MUNMAP_DEFAULT(a, s) munmap((a), (s))1647#define MMAP_PROT (PROT_READ|PROT_WRITE)1648#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)1649#define MAP_ANONYMOUS MAP_ANON1650#endif /* MAP_ANON */1651#ifdef MAP_ANONYMOUS1652#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)1653#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)1654#else /* MAP_ANONYMOUS */1655/*1656Nearly all versions of mmap support MAP_ANONYMOUS, so the following1657is unlikely to be needed, but is supplied just in case.1658*/1659#define MMAP_FLAGS (MAP_PRIVATE)1660static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */1661#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \1662(dev_zero_fd = open("/dev/zero", O_RDWR), \1663mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \1664mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))1665#endif /* MAP_ANONYMOUS */16661667#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s)16681669#else /* WIN32 */16701671/* Win32 MMAP via VirtualAlloc */1672static FORCEINLINE void* win32mmap(size_t size) {1673void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);1674return (ptr != 0)? ptr: MFAIL;1675}16761677/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */1678static FORCEINLINE void* win32direct_mmap(size_t size) {1679void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,1680PAGE_READWRITE);1681return (ptr != 0)? ptr: MFAIL;1682}16831684/* This function supports releasing coalesed segments */1685static FORCEINLINE int win32munmap(void* ptr, size_t size) {1686MEMORY_BASIC_INFORMATION minfo;1687char* cptr = (char*)ptr;1688while (size) {1689if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)1690return -1;1691if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||1692minfo.State != MEM_COMMIT || minfo.RegionSize > size)1693return -1;1694if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)1695return -1;1696cptr += minfo.RegionSize;1697size -= minfo.RegionSize;1698}1699return 0;1700}17011702#define MMAP_DEFAULT(s) win32mmap(s)1703#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s))1704#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s)1705#endif /* WIN32 */1706#endif /* HAVE_MMAP */17071708#if HAVE_MREMAP1709#ifndef WIN321710#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))1711#endif /* WIN32 */1712#endif /* HAVE_MREMAP */17131714/**1715* Define CALL_MORECORE1716*/1717#if HAVE_MORECORE1718#ifdef MORECORE1719#define CALL_MORECORE(S) MORECORE(S)1720#else /* MORECORE */1721#define CALL_MORECORE(S) MORECORE_DEFAULT(S)1722#endif /* MORECORE */1723#else /* HAVE_MORECORE */1724#define CALL_MORECORE(S) MFAIL1725#endif /* HAVE_MORECORE */17261727/**1728* Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP1729*/1730#if HAVE_MMAP1731#define USE_MMAP_BIT (SIZE_T_ONE)17321733#ifdef MMAP1734#define CALL_MMAP(s) MMAP(s)1735#else /* MMAP */1736#define CALL_MMAP(s) MMAP_DEFAULT(s)1737#endif /* MMAP */1738#ifdef MUNMAP1739#define CALL_MUNMAP(a, s) MUNMAP((a), (s))1740#else /* MUNMAP */1741#define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s))1742#endif /* MUNMAP */1743#ifdef DIRECT_MMAP1744#define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)1745#else /* DIRECT_MMAP */1746#define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s)1747#endif /* DIRECT_MMAP */1748#else /* HAVE_MMAP */1749#define USE_MMAP_BIT (SIZE_T_ZERO)17501751#define MMAP(s) MFAIL1752#define MUNMAP(a, s) (-1)1753#define DIRECT_MMAP(s) MFAIL1754#define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)1755#define CALL_MMAP(s) MMAP(s)1756#define CALL_MUNMAP(a, s) MUNMAP((a), (s))1757#endif /* HAVE_MMAP */17581759/**1760* Define CALL_MREMAP1761*/1762#if HAVE_MMAP && HAVE_MREMAP1763#ifdef MREMAP1764#define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv))1765#else /* MREMAP */1766#define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv))1767#endif /* MREMAP */1768#else /* HAVE_MMAP && HAVE_MREMAP */1769#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL1770#endif /* HAVE_MMAP && HAVE_MREMAP */17711772/* mstate bit set if continguous morecore disabled or failed */1773#define USE_NONCONTIGUOUS_BIT (4U)17741775/* segment bit set in create_mspace_with_base */1776#define EXTERN_BIT (8U)177717781779/* --------------------------- Lock preliminaries ------------------------ */17801781/*1782When locks are defined, there is one global lock, plus1783one per-mspace lock.17841785The global lock_ensures that mparams.magic and other unique1786mparams values are initialized only once. It also protects1787sequences of calls to MORECORE. In many cases sys_alloc requires1788two calls, that should not be interleaved with calls by other1789threads. This does not protect against direct calls to MORECORE1790by other threads not using this lock, so there is still code to1791cope the best we can on interference.17921793Per-mspace locks surround calls to malloc, free, etc.1794By default, locks are simple non-reentrant mutexes.17951796Because lock-protected regions generally have bounded times, it is1797OK to use the supplied simple spinlocks. Spinlocks are likely to1798improve performance for lightly contended applications, but worsen1799performance under heavy contention.18001801If USE_LOCKS is > 1, the definitions of lock routines here are1802bypassed, in which case you will need to define the type MLOCK_T,1803and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK1804and TRY_LOCK. You must also declare a1805static MLOCK_T malloc_global_mutex = { initialization values };.18061807*/18081809#if !USE_LOCKS1810#define USE_LOCK_BIT (0U)1811#define INITIAL_LOCK(l) (0)1812#define DESTROY_LOCK(l) (0)1813#define ACQUIRE_MALLOC_GLOBAL_LOCK()1814#define RELEASE_MALLOC_GLOBAL_LOCK()18151816#else1817#if USE_LOCKS > 11818/* ----------------------- User-defined locks ------------------------ */1819/* Define your own lock implementation here */1820/* #define INITIAL_LOCK(lk) ... */1821/* #define DESTROY_LOCK(lk) ... */1822/* #define ACQUIRE_LOCK(lk) ... */1823/* #define RELEASE_LOCK(lk) ... */1824/* #define TRY_LOCK(lk) ... */1825/* static MLOCK_T malloc_global_mutex = ... */18261827#elif USE_SPIN_LOCKS18281829/* First, define CAS_LOCK and CLEAR_LOCK on ints */1830/* Note CAS_LOCK defined to return 0 on success */18311832#if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1))1833#define CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1)1834#define CLEAR_LOCK(sl) __sync_lock_release(sl)18351836#elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))1837/* Custom spin locks for older gcc on x86 */1838static FORCEINLINE int x86_cas_lock(int *sl) {1839int ret;1840int val = 1;1841int cmp = 0;1842__asm__ __volatile__ ("lock; cmpxchgl %1, %2"1843: "=a" (ret)1844: "r" (val), "m" (*(sl)), "0"(cmp)1845: "memory", "cc");1846return ret;1847}18481849static FORCEINLINE void x86_clear_lock(int* sl) {1850assert(*sl != 0);1851int prev = 0;1852int ret;1853__asm__ __volatile__ ("lock; xchgl %0, %1"1854: "=r" (ret)1855: "m" (*(sl)), "0"(prev)1856: "memory");1857}18581859#define CAS_LOCK(sl) x86_cas_lock(sl)1860#define CLEAR_LOCK(sl) x86_clear_lock(sl)18611862#else /* Win32 MSC */1863#define CAS_LOCK(sl) interlockedexchange(sl, (LONG)1)1864#define CLEAR_LOCK(sl) interlockedexchange (sl, (LONG)0)18651866#endif /* ... gcc spins locks ... */18671868/* How to yield for a spin lock */1869#define SPINS_PER_YIELD 631870#if defined(_MSC_VER)1871#define SLEEP_EX_DURATION 50 /* delay for yield/sleep */1872#define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE)1873#elif defined (__SVR4) && defined (__sun) /* solaris */1874#define SPIN_LOCK_YIELD thr_yield();1875#elif !defined(LACKS_SCHED_H)1876#define SPIN_LOCK_YIELD sched_yield();1877#else1878#define SPIN_LOCK_YIELD1879#endif /* ... yield ... */18801881#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 01882/* Plain spin locks use single word (embedded in malloc_states) */1883static int spin_acquire_lock(int *sl) {1884int spins = 0;1885while (*(volatile int *)sl != 0 || CAS_LOCK(sl)) {1886if ((++spins & SPINS_PER_YIELD) == 0) {1887SPIN_LOCK_YIELD;1888}1889}1890return 0;1891}18921893#define MLOCK_T int1894#define TRY_LOCK(sl) !CAS_LOCK(sl)1895#define RELEASE_LOCK(sl) CLEAR_LOCK(sl)1896#define ACQUIRE_LOCK(sl) (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0)1897#define INITIAL_LOCK(sl) (*sl = 0)1898#define DESTROY_LOCK(sl) (0)1899static MLOCK_T malloc_global_mutex = 0;19001901#else /* USE_RECURSIVE_LOCKS */1902/* types for lock owners */1903#ifdef WIN321904#define THREAD_ID_T DWORD1905#define CURRENT_THREAD GetCurrentThreadId()1906#define EQ_OWNER(X,Y) ((X) == (Y))1907#else1908/*1909Note: the following assume that pthread_t is a type that can be1910initialized to (casted) zero. If this is not the case, you will need to1911somehow redefine these or not use spin locks.1912*/1913#define THREAD_ID_T pthread_t1914#define CURRENT_THREAD pthread_self()1915#define EQ_OWNER(X,Y) pthread_equal(X, Y)1916#endif19171918struct malloc_recursive_lock {1919int sl;1920unsigned int c;1921THREAD_ID_T threadid;1922};19231924#define MLOCK_T struct malloc_recursive_lock1925static MLOCK_T malloc_global_mutex = { 0, 0, (THREAD_ID_T)0};19261927static FORCEINLINE void recursive_release_lock(MLOCK_T *lk) {1928assert(lk->sl != 0);1929if (--lk->c == 0) {1930CLEAR_LOCK(&lk->sl);1931}1932}19331934static FORCEINLINE int recursive_acquire_lock(MLOCK_T *lk) {1935THREAD_ID_T mythreadid = CURRENT_THREAD;1936int spins = 0;1937for (;;) {1938if (*((volatile int *)(&lk->sl)) == 0) {1939if (!CAS_LOCK(&lk->sl)) {1940lk->threadid = mythreadid;1941lk->c = 1;1942return 0;1943}1944}1945else if (EQ_OWNER(lk->threadid, mythreadid)) {1946++lk->c;1947return 0;1948}1949if ((++spins & SPINS_PER_YIELD) == 0) {1950SPIN_LOCK_YIELD;1951}1952}1953}19541955static FORCEINLINE int recursive_try_lock(MLOCK_T *lk) {1956THREAD_ID_T mythreadid = CURRENT_THREAD;1957if (*((volatile int *)(&lk->sl)) == 0) {1958if (!CAS_LOCK(&lk->sl)) {1959lk->threadid = mythreadid;1960lk->c = 1;1961return 1;1962}1963}1964else if (EQ_OWNER(lk->threadid, mythreadid)) {1965++lk->c;1966return 1;1967}1968return 0;1969}19701971#define RELEASE_LOCK(lk) recursive_release_lock(lk)1972#define TRY_LOCK(lk) recursive_try_lock(lk)1973#define ACQUIRE_LOCK(lk) recursive_acquire_lock(lk)1974#define INITIAL_LOCK(lk) ((lk)->threadid = (THREAD_ID_T)0, (lk)->sl = 0, (lk)->c = 0)1975#define DESTROY_LOCK(lk) (0)1976#endif /* USE_RECURSIVE_LOCKS */19771978#elif defined(WIN32) /* Win32 critical sections */1979#define MLOCK_T CRITICAL_SECTION1980#define ACQUIRE_LOCK(lk) (EnterCriticalSection(lk), 0)1981#define RELEASE_LOCK(lk) LeaveCriticalSection(lk)1982#define TRY_LOCK(lk) TryEnterCriticalSection(lk)1983#define INITIAL_LOCK(lk) (!InitializeCriticalSectionAndSpinCount((lk), 0x80000000|4000))1984#define DESTROY_LOCK(lk) (DeleteCriticalSection(lk), 0)1985#define NEED_GLOBAL_LOCK_INIT19861987static MLOCK_T malloc_global_mutex;1988static volatile LONG malloc_global_mutex_status;19891990/* Use spin loop to initialize global lock */1991static void init_malloc_global_mutex() {1992for (;;) {1993long stat = malloc_global_mutex_status;1994if (stat > 0)1995return;1996/* transition to < 0 while initializing, then to > 0) */1997if (stat == 0 &&1998interlockedcompareexchange(&malloc_global_mutex_status, (LONG)-1, (LONG)0) == 0) {1999InitializeCriticalSection(&malloc_global_mutex);2000interlockedexchange(&malloc_global_mutex_status, (LONG)1);2001return;2002}2003SleepEx(0, FALSE);2004}2005}20062007#else /* pthreads-based locks */2008#define MLOCK_T pthread_mutex_t2009#define ACQUIRE_LOCK(lk) pthread_mutex_lock(lk)2010#define RELEASE_LOCK(lk) pthread_mutex_unlock(lk)2011#define TRY_LOCK(lk) (!pthread_mutex_trylock(lk))2012#define INITIAL_LOCK(lk) pthread_init_lock(lk)2013#define DESTROY_LOCK(lk) pthread_mutex_destroy(lk)20142015#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 && defined(linux) && !defined(PTHREAD_MUTEX_RECURSIVE)2016/* Cope with old-style linux recursive lock initialization by adding */2017/* skipped internal declaration from pthread.h */2018extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr,2019int __kind));2020#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP2021#define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y)2022#endif /* USE_RECURSIVE_LOCKS ... */20232024static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER;20252026static int pthread_init_lock (MLOCK_T *lk) {2027pthread_mutexattr_t attr;2028if (pthread_mutexattr_init(&attr)) return 1;2029#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 02030if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1;2031#endif2032if (pthread_mutex_init(lk, &attr)) return 1;2033if (pthread_mutexattr_destroy(&attr)) return 1;2034return 0;2035}20362037#endif /* ... lock types ... */20382039/* Common code for all lock types */2040#define USE_LOCK_BIT (2U)20412042#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK2043#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex);2044#endif20452046#ifndef RELEASE_MALLOC_GLOBAL_LOCK2047#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex);2048#endif20492050#endif /* USE_LOCKS */20512052/* ----------------------- Chunk representations ------------------------ */20532054/*2055(The following includes lightly edited explanations by Colin Plumb.)20562057The malloc_chunk declaration below is misleading (but accurate and2058necessary). It declares a "view" into memory allowing access to2059necessary fields at known offsets from a given base.20602061Chunks of memory are maintained using a `boundary tag' method as2062originally described by Knuth. (See the paper by Paul Wilson2063ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such2064techniques.) Sizes of free chunks are stored both in the front of2065each chunk and at the end. This makes consolidating fragmented2066chunks into bigger chunks fast. The head fields also hold bits2067representing whether chunks are free or in use.20682069Here are some pictures to make it clearer. They are "exploded" to2070show that the state of a chunk can be thought of as extending from2071the high 31 bits of the head field of its header through the2072prev_foot and PINUSE_BIT bit of the following chunk header.20732074A chunk that's in use looks like:20752076chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2077| Size of previous chunk (if P = 0) |2078+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2079+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|2080| Size of this chunk 1| +-+2081mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2082| |2083+- -+2084| |2085+- -+2086| :2087+- size - sizeof(size_t) available payload bytes -+2088: |2089chunk-> +- -+2090| |2091+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2092+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|2093| Size of next chunk (may or may not be in use) | +-+2094mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+20952096And if it's free, it looks like this:20972098chunk-> +- -+2099| User payload (must be in use, or we would have merged!) |2100+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2101+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|2102| Size of this chunk 0| +-+2103mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2104| Next pointer |2105+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2106| Prev pointer |2107+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2108| :2109+- size - sizeof(struct chunk) unused bytes -+2110: |2111chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2112| Size of this chunk |2113+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2114+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|2115| Size of next chunk (must be in use, or we would have merged)| +-+2116mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2117| :2118+- User payload -+2119: |2120+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2121|0|2122+-+2123Note that since we always merge adjacent free chunks, the chunks2124adjacent to a free chunk must be in use.21252126Given a pointer to a chunk (which can be derived trivially from the2127payload pointer) we can, in O(1) time, find out whether the adjacent2128chunks are free, and if so, unlink them from the lists that they2129are on and merge them with the current chunk.21302131Chunks always begin on even word boundaries, so the mem portion2132(which is returned to the user) is also on an even word boundary, and2133thus at least double-word aligned.21342135The P (PINUSE_BIT) bit, stored in the unused low-order bit of the2136chunk size (which is always a multiple of two words), is an in-use2137bit for the *previous* chunk. If that bit is *clear*, then the2138word before the current chunk size contains the previous chunk2139size, and can be used to find the front of the previous chunk.2140The very first chunk allocated always has this bit set, preventing2141access to non-existent (or non-owned) memory. If pinuse is set for2142any given chunk, then you CANNOT determine the size of the2143previous chunk, and might even get a memory addressing fault when2144trying to do so.21452146The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of2147the chunk size redundantly records whether the current chunk is2148inuse (unless the chunk is mmapped). This redundancy enables usage2149checks within free and realloc, and reduces indirection when freeing2150and consolidating chunks.21512152Each freshly allocated chunk must have both cinuse and pinuse set.2153That is, each allocated chunk borders either a previously allocated2154and still in-use chunk, or the base of its memory arena. This is2155ensured by making all allocations from the `lowest' part of any2156found chunk. Further, no free chunk physically borders another one,2157so each free chunk is known to be preceded and followed by either2158inuse chunks or the ends of memory.21592160Note that the `foot' of the current chunk is actually represented2161as the prev_foot of the NEXT chunk. This makes it easier to2162deal with alignments etc but can be very confusing when trying2163to extend or adapt this code.21642165The exceptions to all this are216621671. The special chunk `top' is the top-most available chunk (i.e.,2168the one bordering the end of available memory). It is treated2169specially. Top is never included in any bin, is used only if2170no other chunk is available, and is released back to the2171system if it is very large (see M_TRIM_THRESHOLD). In effect,2172the top chunk is treated as larger (and thus less well2173fitting) than any other available chunk. The top chunk2174doesn't update its trailing size field since there is no next2175contiguous chunk that would have to index off it. However,2176space is still allocated for it (TOP_FOOT_SIZE) to enable2177separation or merging when space is extended.217821793. Chunks allocated via mmap, have both cinuse and pinuse bits2180cleared in their head fields. Because they are allocated2181one-by-one, each must carry its own prev_foot field, which is2182also used to hold the offset this chunk has within its mmapped2183region, which is needed to preserve alignment. Each mmapped2184chunk is trailed by the first two fields of a fake next-chunk2185for sake of usage checks.21862187*/21882189struct malloc_chunk {2190size_t prev_foot; /* Size of previous chunk (if free). */2191size_t head; /* Size and inuse bits. */2192struct malloc_chunk* fd; /* double links -- used only if free. */2193struct malloc_chunk* bk;2194};21952196typedef struct malloc_chunk mchunk;2197typedef struct malloc_chunk* mchunkptr;2198typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */2199typedef unsigned int bindex_t; /* Described below */2200typedef unsigned int binmap_t; /* Described below */2201typedef unsigned int flag_t; /* The type of various bit flag sets */22022203/* ------------------- Chunks sizes and alignments ----------------------- */22042205#define MCHUNK_SIZE (sizeof(mchunk))22062207#if FOOTERS2208#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)2209#else /* FOOTERS */2210#define CHUNK_OVERHEAD (SIZE_T_SIZE)2211#endif /* FOOTERS */22122213/* MMapped chunks need a second word of overhead ... */2214#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)2215/* ... and additional padding for fake next-chunk at foot */2216#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)22172218/* The smallest size we can malloc is an aligned minimal chunk */2219#define MIN_CHUNK_SIZE\2220((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)22212222/* conversion from malloc headers to user pointers, and back */2223#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))2224#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))2225/* chunk associated with aligned address A */2226#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))22272228/* Bounds on request (not chunk) sizes. */2229#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)2230#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)22312232/* pad request bytes into a usable size */2233#define pad_request(req) \2234(((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)22352236/* pad request, checking for minimum (but not maximum) */2237#define request2size(req) \2238(((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))223922402241/* ------------------ Operations on head and foot fields ----------------- */22422243/*2244The head field of a chunk is or'ed with PINUSE_BIT when previous2245adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in2246use, unless mmapped, in which case both bits are cleared.22472248FLAG4_BIT is not used by this malloc, but might be useful in extensions.2249*/22502251#define PINUSE_BIT (SIZE_T_ONE)2252#define CINUSE_BIT (SIZE_T_TWO)2253#define FLAG4_BIT (SIZE_T_FOUR)2254#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)2255#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT)22562257/* Head value for fenceposts */2258#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)22592260/* extraction of fields from head words */2261#define cinuse(p) ((p)->head & CINUSE_BIT)2262#define pinuse(p) ((p)->head & PINUSE_BIT)2263#define flag4inuse(p) ((p)->head & FLAG4_BIT)2264#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT)2265#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0)22662267#define chunksize(p) ((p)->head & ~(FLAG_BITS))22682269#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)2270#define set_flag4(p) ((p)->head |= FLAG4_BIT)2271#define clear_flag4(p) ((p)->head &= ~FLAG4_BIT)22722273/* Treat space at ptr +/- offset as a chunk */2274#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))2275#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))22762277/* Ptr to next or previous physical malloc_chunk. */2278#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS)))2279#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))22802281/* extract next chunk's pinuse bit */2282#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)22832284/* Get/set size at footer */2285#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)2286#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))22872288/* Set size, pinuse bit, and foot */2289#define set_size_and_pinuse_of_free_chunk(p, s)\2290((p)->head = (s|PINUSE_BIT), set_foot(p, s))22912292/* Set size, pinuse bit, foot, and clear next pinuse */2293#define set_free_with_pinuse(p, s, n)\2294(clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))22952296/* Get the internal overhead associated with chunk p */2297#define overhead_for(p)\2298(is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)22992300/* Return true if malloced space is not necessarily cleared */2301#if MMAP_CLEARS2302#define calloc_must_clear(p) (!is_mmapped(p))2303#else /* MMAP_CLEARS */2304#define calloc_must_clear(p) (1)2305#endif /* MMAP_CLEARS */23062307/* ---------------------- Overlaid data structures ----------------------- */23082309/*2310When chunks are not in use, they are treated as nodes of either2311lists or trees.23122313"Small" chunks are stored in circular doubly-linked lists, and look2314like this:23152316chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2317| Size of previous chunk |2318+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2319`head:' | Size of chunk, in bytes |P|2320mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2321| Forward pointer to next chunk in list |2322+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2323| Back pointer to previous chunk in list |2324+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2325| Unused space (may be 0 bytes long) .2326. .2327. |2328nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2329`foot:' | Size of chunk, in bytes |2330+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+23312332Larger chunks are kept in a form of bitwise digital trees (aka2333tries) keyed on chunksizes. Because malloc_tree_chunks are only for2334free chunks greater than 256 bytes, their size doesn't impose any2335constraints on user chunk sizes. Each node looks like:23362337chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2338| Size of previous chunk |2339+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2340`head:' | Size of chunk, in bytes |P|2341mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2342| Forward pointer to next chunk of same size |2343+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2344| Back pointer to previous chunk of same size |2345+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2346| Pointer to left child (child[0]) |2347+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2348| Pointer to right child (child[1]) |2349+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2350| Pointer to parent |2351+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2352| bin index of this chunk |2353+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2354| Unused space .2355. |2356nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+2357`foot:' | Size of chunk, in bytes |2358+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+23592360Each tree holding treenodes is a tree of unique chunk sizes. Chunks2361of the same size are arranged in a circularly-linked list, with only2362the oldest chunk (the next to be used, in our FIFO ordering)2363actually in the tree. (Tree members are distinguished by a non-null2364parent pointer.) If a chunk with the same size an an existing node2365is inserted, it is linked off the existing node using pointers that2366work in the same way as fd/bk pointers of small chunks.23672368Each tree contains a power of 2 sized range of chunk sizes (the2369smallest is 0x100 <= x < 0x180), which is is divided in half at each2370tree level, with the chunks in the smaller half of the range (0x1002371<= x < 0x140 for the top nose) in the left subtree and the larger2372half (0x140 <= x < 0x180) in the right subtree. This is, of course,2373done by inspecting individual bits.23742375Using these rules, each node's left subtree contains all smaller2376sizes than its right subtree. However, the node at the root of each2377subtree has no particular ordering relationship to either. (The2378dividing line between the subtree sizes is based on trie relation.)2379If we remove the last chunk of a given size from the interior of the2380tree, we need to replace it with a leaf node. The tree ordering2381rules permit a node to be replaced by any leaf below it.23822383The smallest chunk in a tree (a common operation in a best-fit2384allocator) can be found by walking a path to the leftmost leaf in2385the tree. Unlike a usual binary tree, where we follow left child2386pointers until we reach a null, here we follow the right child2387pointer any time the left one is null, until we reach a leaf with2388both child pointers null. The smallest chunk in the tree will be2389somewhere along that path.23902391The worst case number of steps to add, find, or remove a node is2392bounded by the number of bits differentiating chunks within2393bins. Under current bin calculations, this ranges from 6 up to 212394(for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case2395is of course much better.2396*/23972398struct malloc_tree_chunk {2399/* The first four fields must be compatible with malloc_chunk */2400size_t prev_foot;2401size_t head;2402struct malloc_tree_chunk* fd;2403struct malloc_tree_chunk* bk;24042405struct malloc_tree_chunk* child[2];2406struct malloc_tree_chunk* parent;2407bindex_t index;2408};24092410typedef struct malloc_tree_chunk tchunk;2411typedef struct malloc_tree_chunk* tchunkptr;2412typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */24132414/* A little helper macro for trees */2415#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])24162417/* ----------------------------- Segments -------------------------------- */24182419/*2420Each malloc space may include non-contiguous segments, held in a2421list headed by an embedded malloc_segment record representing the2422top-most space. Segments also include flags holding properties of2423the space. Large chunks that are directly allocated by mmap are not2424included in this list. They are instead independently created and2425destroyed without otherwise keeping track of them.24262427Segment management mainly comes into play for spaces allocated by2428MMAP. Any call to MMAP might or might not return memory that is2429adjacent to an existing segment. MORECORE normally contiguously2430extends the current space, so this space is almost always adjacent,2431which is simpler and faster to deal with. (This is why MORECORE is2432used preferentially to MMAP when both are available -- see2433sys_alloc.) When allocating using MMAP, we don't use any of the2434hinting mechanisms (inconsistently) supported in various2435implementations of unix mmap, or distinguish reserving from2436committing memory. Instead, we just ask for space, and exploit2437contiguity when we get it. It is probably possible to do2438better than this on some systems, but no general scheme seems2439to be significantly better.24402441Management entails a simpler variant of the consolidation scheme2442used for chunks to reduce fragmentation -- new adjacent memory is2443normally prepended or appended to an existing segment. However,2444there are limitations compared to chunk consolidation that mostly2445reflect the fact that segment processing is relatively infrequent2446(occurring only when getting memory from system) and that we2447don't expect to have huge numbers of segments:24482449* Segments are not indexed, so traversal requires linear scans. (It2450would be possible to index these, but is not worth the extra2451overhead and complexity for most programs on most platforms.)2452* New segments are only appended to old ones when holding top-most2453memory; if they cannot be prepended to others, they are held in2454different segments.24552456Except for the top-most segment of an mstate, each segment record2457is kept at the tail of its segment. Segments are added by pushing2458segment records onto the list headed by &mstate.seg for the2459containing mstate.24602461Segment flags control allocation/merge/deallocation policies:2462* If EXTERN_BIT set, then we did not allocate this segment,2463and so should not try to deallocate or merge with others.2464(This currently holds only for the initial segment passed2465into create_mspace_with_base.)2466* If USE_MMAP_BIT set, the segment may be merged with2467other surrounding mmapped segments and trimmed/de-allocated2468using munmap.2469* If neither bit is set, then the segment was obtained using2470MORECORE so can be merged with surrounding MORECORE'd segments2471and deallocated/trimmed using MORECORE with negative arguments.2472*/24732474struct malloc_segment {2475char* base; /* base address */2476size_t size; /* allocated size */2477struct malloc_segment* next; /* ptr to next segment */2478flag_t sflags; /* mmap and extern flag */2479};24802481#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT)2482#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)24832484typedef struct malloc_segment msegment;2485typedef struct malloc_segment* msegmentptr;24862487/* ---------------------------- malloc_state ----------------------------- */24882489/*2490A malloc_state holds all of the bookkeeping for a space.2491The main fields are:24922493Top2494The topmost chunk of the currently active segment. Its size is2495cached in topsize. The actual size of topmost space is2496topsize+TOP_FOOT_SIZE, which includes space reserved for adding2497fenceposts and segment records if necessary when getting more2498space from the system. The size at which to autotrim top is2499cached from mparams in trim_check, except that it is disabled if2500an autotrim fails.25012502Designated victim (dv)2503This is the preferred chunk for servicing small requests that2504don't have exact fits. It is normally the chunk split off most2505recently to service another small request. Its size is cached in2506dvsize. The link fields of this chunk are not maintained since it2507is not kept in a bin.25082509SmallBins2510An array of bin headers for free chunks. These bins hold chunks2511with sizes less than MIN_LARGE_SIZE bytes. Each bin contains2512chunks of all the same size, spaced 8 bytes apart. To simplify2513use in double-linked lists, each bin header acts as a malloc_chunk2514pointing to the real first node, if it exists (else pointing to2515itself). This avoids special-casing for headers. But to avoid2516waste, we allocate only the fd/bk pointers of bins, and then use2517repositioning tricks to treat these as the fields of a chunk.25182519TreeBins2520Treebins are pointers to the roots of trees holding a range of2521sizes. There are 2 equally spaced treebins for each power of two2522from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything2523larger.25242525Bin maps2526There is one bit map for small bins ("smallmap") and one for2527treebins ("treemap). Each bin sets its bit when non-empty, and2528clears the bit when empty. Bit operations are then used to avoid2529bin-by-bin searching -- nearly all "search" is done without ever2530looking at bins that won't be selected. The bit maps2531conservatively use 32 bits per map word, even if on 64bit system.2532For a good description of some of the bit-based techniques used2533here, see Henry S. Warren Jr's book "Hacker's Delight" (and2534supplement at http://hackersdelight.org/). Many of these are2535intended to reduce the branchiness of paths through malloc etc, as2536well as to reduce the number of memory locations read or written.25372538Segments2539A list of segments headed by an embedded malloc_segment record2540representing the initial space.25412542Address check support2543The least_addr field is the least address ever obtained from2544MORECORE or MMAP. Attempted frees and reallocs of any address less2545than this are trapped (unless INSECURE is defined).25462547Magic tag2548A cross-check field that should always hold same value as mparams.magic.25492550Max allowed footprint2551The maximum allowed bytes to allocate from system (zero means no limit)25522553Flags2554Bits recording whether to use MMAP, locks, or contiguous MORECORE25552556Statistics2557Each space keeps track of current and maximum system memory2558obtained via MORECORE or MMAP.25592560Trim support2561Fields holding the amount of unused topmost memory that should trigger2562trimming, and a counter to force periodic scanning to release unused2563non-topmost segments.25642565Locking2566If USE_LOCKS is defined, the "mutex" lock is acquired and released2567around every public call using this mspace.25682569Extension support2570A void* pointer and a size_t field that can be used to help implement2571extensions to this malloc.2572*/25732574/* Bin types, widths and sizes */2575#define NSMALLBINS (32U)2576#define NTREEBINS (32U)2577#define SMALLBIN_SHIFT (3U)2578#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)2579#define TREEBIN_SHIFT (8U)2580#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)2581#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)2582#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)25832584struct malloc_state {2585binmap_t smallmap;2586binmap_t treemap;2587size_t dvsize;2588size_t topsize;2589char* least_addr;2590mchunkptr dv;2591mchunkptr top;2592size_t trim_check;2593size_t release_checks;2594size_t magic;2595mchunkptr smallbins[(NSMALLBINS+1)*2];2596tbinptr treebins[NTREEBINS];2597size_t footprint;2598size_t max_footprint;2599size_t footprint_limit; /* zero means no limit */2600flag_t mflags;2601#if USE_LOCKS2602MLOCK_T mutex; /* locate lock among fields that rarely change */2603#endif /* USE_LOCKS */2604msegment seg;2605void* extp; /* Unused but available for extensions */2606size_t exts;2607};26082609typedef struct malloc_state* mstate;26102611/* ------------- Global malloc_state and malloc_params ------------------- */26122613/*2614malloc_params holds global properties, including those that can be2615dynamically set using mallopt. There is a single instance, mparams,2616initialized in init_mparams. Note that the non-zeroness of "magic"2617also serves as an initialization flag.2618*/26192620struct malloc_params {2621size_t magic;2622size_t page_size;2623size_t granularity;2624size_t mmap_threshold;2625size_t trim_threshold;2626flag_t default_mflags;2627};26282629static struct malloc_params mparams;26302631/* Ensure mparams initialized */2632#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams())26332634#if !ONLY_MSPACES26352636/* The global malloc_state used for all non-"mspace" calls */2637static struct malloc_state _gm_;2638#define gm (&_gm_)2639#define is_global(M) ((M) == &_gm_)26402641#endif /* !ONLY_MSPACES */26422643#define is_initialized(M) ((M)->top != 0)26442645/* -------------------------- system alloc setup ------------------------- */26462647/* Operations on mflags */26482649#define use_lock(M) ((M)->mflags & USE_LOCK_BIT)2650#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)2651#if USE_LOCKS2652#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)2653#else2654#define disable_lock(M)2655#endif26562657#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)2658#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)2659#if HAVE_MMAP2660#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)2661#else2662#define disable_mmap(M)2663#endif26642665#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)2666#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)26672668#define set_lock(M,L)\2669((M)->mflags = (L)?\2670((M)->mflags | USE_LOCK_BIT) :\2671((M)->mflags & ~USE_LOCK_BIT))26722673/* page-align a size */2674#define page_align(S)\2675(((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE))26762677/* granularity-align a size */2678#define granularity_align(S)\2679(((S) + (mparams.granularity - SIZE_T_ONE))\2680& ~(mparams.granularity - SIZE_T_ONE))268126822683/* For mmap, use granularity alignment on windows, else page-align */2684#ifdef WIN322685#define mmap_align(S) granularity_align(S)2686#else2687#define mmap_align(S) page_align(S)2688#endif26892690/* For sys_alloc, enough padding to ensure can malloc request on success */2691#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT)26922693#define is_page_aligned(S)\2694(((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)2695#define is_granularity_aligned(S)\2696(((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)26972698/* True if segment S holds address A */2699#define segment_holds(S, A)\2700((char*)(A) >= S->base && (char*)(A) < S->base + S->size)27012702/* Return segment holding given address */2703static msegmentptr segment_holding(mstate m, char* addr) {2704msegmentptr sp = &m->seg;2705for (;;) {2706if (addr >= sp->base && addr < sp->base + sp->size)2707return sp;2708if ((sp = sp->next) == 0)2709return 0;2710}2711}27122713/* Return true if segment contains a segment link */2714static int has_segment_link(mstate m, msegmentptr ss) {2715msegmentptr sp = &m->seg;2716for (;;) {2717if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)2718return 1;2719if ((sp = sp->next) == 0)2720return 0;2721}2722}27232724#ifndef MORECORE_CANNOT_TRIM2725#define should_trim(M,s) ((s) > (M)->trim_check)2726#else /* MORECORE_CANNOT_TRIM */2727#define should_trim(M,s) (0)2728#endif /* MORECORE_CANNOT_TRIM */27292730/*2731TOP_FOOT_SIZE is padding at the end of a segment, including space2732that may be needed to place segment records and fenceposts when new2733noncontiguous segments are added.2734*/2735#define TOP_FOOT_SIZE\2736(align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)273727382739/* ------------------------------- Hooks -------------------------------- */27402741/*2742PREACTION should be defined to return 0 on success, and nonzero on2743failure. If you are not using locking, you can redefine these to do2744anything you like.2745*/27462747#if USE_LOCKS2748#define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)2749#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }2750#else /* USE_LOCKS */27512752#ifndef PREACTION2753#define PREACTION(M) (0)2754#endif /* PREACTION */27552756#ifndef POSTACTION2757#define POSTACTION(M)2758#endif /* POSTACTION */27592760#endif /* USE_LOCKS */27612762/*2763CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.2764USAGE_ERROR_ACTION is triggered on detected bad frees and2765reallocs. The argument p is an address that might have triggered the2766fault. It is ignored by the two predefined actions, but might be2767useful in custom actions that try to help diagnose errors.2768*/27692770#if PROCEED_ON_ERROR27712772/* A count of the number of corruption errors causing resets */2773int malloc_corruption_error_count;27742775/* default corruption action */2776static void reset_on_error(mstate m);27772778#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)2779#define USAGE_ERROR_ACTION(m, p)27802781#else /* PROCEED_ON_ERROR */27822783#ifndef CORRUPTION_ERROR_ACTION2784#define CORRUPTION_ERROR_ACTION(m) ABORT2785#endif /* CORRUPTION_ERROR_ACTION */27862787#ifndef USAGE_ERROR_ACTION2788#define USAGE_ERROR_ACTION(m,p) ABORT2789#endif /* USAGE_ERROR_ACTION */27902791#endif /* PROCEED_ON_ERROR */279227932794/* -------------------------- Debugging setup ---------------------------- */27952796#if ! DEBUG27972798#define check_free_chunk(M,P)2799#define check_inuse_chunk(M,P)2800#define check_malloced_chunk(M,P,N)2801#define check_mmapped_chunk(M,P)2802#define check_malloc_state(M)2803#define check_top_chunk(M,P)28042805#else /* DEBUG */2806#define check_free_chunk(M,P) do_check_free_chunk(M,P)2807#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)2808#define check_top_chunk(M,P) do_check_top_chunk(M,P)2809#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)2810#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)2811#define check_malloc_state(M) do_check_malloc_state(M)28122813static void do_check_any_chunk(mstate m, mchunkptr p);2814static void do_check_top_chunk(mstate m, mchunkptr p);2815static void do_check_mmapped_chunk(mstate m, mchunkptr p);2816static void do_check_inuse_chunk(mstate m, mchunkptr p);2817static void do_check_free_chunk(mstate m, mchunkptr p);2818static void do_check_malloced_chunk(mstate m, void* mem, size_t s);2819static void do_check_tree(mstate m, tchunkptr t);2820static void do_check_treebin(mstate m, bindex_t i);2821static void do_check_smallbin(mstate m, bindex_t i);2822static void do_check_malloc_state(mstate m);2823static int bin_find(mstate m, mchunkptr x);2824static size_t traverse_and_check(mstate m);2825#endif /* DEBUG */28262827/* ---------------------------- Indexing Bins ---------------------------- */28282829#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)2830#define small_index(s) (bindex_t)((s) >> SMALLBIN_SHIFT)2831#define small_index2size(i) ((i) << SMALLBIN_SHIFT)2832#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))28332834/* addressing by index. See above about smallbin repositioning */2835#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))2836#define treebin_at(M,i) (&((M)->treebins[i]))28372838/* assign tree index for size S to variable I. Use x86 asm if possible */2839#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))2840#define compute_tree_index(S, I)\2841{\2842unsigned int X = S >> TREEBIN_SHIFT;\2843if (X == 0)\2844I = 0;\2845else if (X > 0xFFFF)\2846I = NTREEBINS-1;\2847else {\2848unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \2849I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\2850}\2851}28522853#elif defined (__INTEL_COMPILER)2854#define compute_tree_index(S, I)\2855{\2856size_t X = S >> TREEBIN_SHIFT;\2857if (X == 0)\2858I = 0;\2859else if (X > 0xFFFF)\2860I = NTREEBINS-1;\2861else {\2862unsigned int K = _bit_scan_reverse (X); \2863I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\2864}\2865}28662867#elif defined(_MSC_VER) && _MSC_VER>=13002868#define compute_tree_index(S, I)\2869{\2870size_t X = S >> TREEBIN_SHIFT;\2871if (X == 0)\2872I = 0;\2873else if (X > 0xFFFF)\2874I = NTREEBINS-1;\2875else {\2876unsigned int K;\2877_BitScanReverse((DWORD *) &K, (DWORD) X);\2878I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\2879}\2880}28812882#else /* GNUC */2883#define compute_tree_index(S, I)\2884{\2885size_t X = S >> TREEBIN_SHIFT;\2886if (X == 0)\2887I = 0;\2888else if (X > 0xFFFF)\2889I = NTREEBINS-1;\2890else {\2891unsigned int Y = (unsigned int)X;\2892unsigned int N = ((Y - 0x100) >> 16) & 8;\2893unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\2894N += K;\2895N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\2896K = 14 - N + ((Y <<= K) >> 15);\2897I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\2898}\2899}2900#endif /* GNUC */29012902/* Bit representing maximum resolved size in a treebin at i */2903#define bit_for_tree_index(i) \2904(i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)29052906/* Shift placing maximum resolved bit in a treebin at i as sign bit */2907#define leftshift_for_tree_index(i) \2908((i == NTREEBINS-1)? 0 : \2909((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))29102911/* The size of the smallest chunk held in bin with index i */2912#define minsize_for_tree_index(i) \2913((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \2914(((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))291529162917/* ------------------------ Operations on bin maps ----------------------- */29182919/* bit corresponding to given index */2920#define idx2bit(i) ((binmap_t)(1) << (i))29212922/* Mark/Clear bits with given index */2923#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))2924#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))2925#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))29262927#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))2928#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))2929#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))29302931/* isolate the least set bit of a bitmap */2932#define least_bit(x) ((x) & -(x))29332934/* mask with all bits to left of least bit of x on */2935#define left_bits(x) ((x<<1) | -(x<<1))29362937/* mask with all bits to left of or equal to least bit of x on */2938#define same_or_left_bits(x) ((x) | -(x))29392940/* index corresponding to given bit. Use x86 asm if possible */29412942#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))2943#define compute_bit2idx(X, I)\2944{\2945unsigned int J;\2946J = __builtin_ctz(X); \2947I = (bindex_t)J;\2948}29492950#elif defined (__INTEL_COMPILER)2951#define compute_bit2idx(X, I)\2952{\2953unsigned int J;\2954J = _bit_scan_forward (X); \2955I = (bindex_t)J;\2956}29572958#elif defined(_MSC_VER) && _MSC_VER>=13002959#define compute_bit2idx(X, I)\2960{\2961unsigned int J;\2962_BitScanForward((DWORD *) &J, X);\2963I = (bindex_t)J;\2964}29652966#elif USE_BUILTIN_FFS2967#define compute_bit2idx(X, I) I = ffs(X)-129682969#else2970#define compute_bit2idx(X, I)\2971{\2972unsigned int Y = X - 1;\2973unsigned int K = Y >> (16-4) & 16;\2974unsigned int N = K; Y >>= K;\2975N += K = Y >> (8-3) & 8; Y >>= K;\2976N += K = Y >> (4-2) & 4; Y >>= K;\2977N += K = Y >> (2-1) & 2; Y >>= K;\2978N += K = Y >> (1-0) & 1; Y >>= K;\2979I = (bindex_t)(N + Y);\2980}2981#endif /* GNUC */298229832984/* ----------------------- Runtime Check Support ------------------------- */29852986/*2987For security, the main invariant is that malloc/free/etc never2988writes to a static address other than malloc_state, unless static2989malloc_state itself has been corrupted, which cannot occur via2990malloc (because of these checks). In essence this means that we2991believe all pointers, sizes, maps etc held in malloc_state, but2992check all of those linked or offsetted from other embedded data2993structures. These checks are interspersed with main code in a way2994that tends to minimize their run-time cost.29952996When FOOTERS is defined, in addition to range checking, we also2997verify footer fields of inuse chunks, which can be used guarantee2998that the mstate controlling malloc/free is intact. This is a2999streamlined version of the approach described by William Robertson3000et al in "Run-time Detection of Heap-based Overflows" LISA'033001http://www.usenix.org/events/lisa03/tech/robertson.html The footer3002of an inuse chunk holds the xor of its mstate and a random seed,3003that is checked upon calls to free() and realloc(). This is3004(probabalistically) unguessable from outside the program, but can be3005computed by any code successfully malloc'ing any chunk, so does not3006itself provide protection against code that has already broken3007security through some other means. Unlike Robertson et al, we3008always dynamically check addresses of all offset chunks (previous,3009next, etc). This turns out to be cheaper than relying on hashes.3010*/30113012#if !INSECURE3013/* Check if address a is at least as high as any from MORECORE or MMAP */3014#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)3015/* Check if address of next chunk n is higher than base chunk p */3016#define ok_next(p, n) ((char*)(p) < (char*)(n))3017/* Check if p has inuse status */3018#define ok_inuse(p) is_inuse(p)3019/* Check if p has its pinuse bit on */3020#define ok_pinuse(p) pinuse(p)30213022#else /* !INSECURE */3023#define ok_address(M, a) (1)3024#define ok_next(b, n) (1)3025#define ok_inuse(p) (1)3026#define ok_pinuse(p) (1)3027#endif /* !INSECURE */30283029#if (FOOTERS && !INSECURE)3030/* Check if (alleged) mstate m has expected magic field */3031#define ok_magic(M) ((M)->magic == mparams.magic)3032#else /* (FOOTERS && !INSECURE) */3033#define ok_magic(M) (1)3034#endif /* (FOOTERS && !INSECURE) */30353036/* In gcc, use __builtin_expect to minimize impact of checks */3037#if !INSECURE3038#if defined(__GNUC__) && __GNUC__ >= 33039#define RTCHECK(e) __builtin_expect(e, 1)3040#else /* GNUC */3041#define RTCHECK(e) (e)3042#endif /* GNUC */3043#else /* !INSECURE */3044#define RTCHECK(e) (1)3045#endif /* !INSECURE */30463047/* macros to set up inuse chunks with or without footers */30483049#if !FOOTERS30503051#define mark_inuse_foot(M,p,s)30523053/* Macros for setting head/foot of non-mmapped chunks */30543055/* Set cinuse bit and pinuse bit of next chunk */3056#define set_inuse(M,p,s)\3057((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\3058((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)30593060/* Set cinuse and pinuse of this chunk and pinuse of next chunk */3061#define set_inuse_and_pinuse(M,p,s)\3062((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\3063((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)30643065/* Set size, cinuse and pinuse bit of this chunk */3066#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\3067((p)->head = (s|PINUSE_BIT|CINUSE_BIT))30683069#else /* FOOTERS */30703071/* Set foot of inuse chunk to be xor of mstate and seed */3072#define mark_inuse_foot(M,p,s)\3073(((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))30743075#define get_mstate_for(p)\3076((mstate)(((mchunkptr)((char*)(p) +\3077(chunksize(p))))->prev_foot ^ mparams.magic))30783079#define set_inuse(M,p,s)\3080((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\3081(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \3082mark_inuse_foot(M,p,s))30833084#define set_inuse_and_pinuse(M,p,s)\3085((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\3086(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\3087mark_inuse_foot(M,p,s))30883089#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\3090((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\3091mark_inuse_foot(M, p, s))30923093#endif /* !FOOTERS */30943095/* ---------------------------- setting mparams -------------------------- */30963097#if LOCK_AT_FORK3098static void pre_fork(void) { ACQUIRE_LOCK(&(gm)->mutex); }3099static void post_fork_parent(void) { RELEASE_LOCK(&(gm)->mutex); }3100static void post_fork_child(void) { INITIAL_LOCK(&(gm)->mutex); }3101#endif /* LOCK_AT_FORK */31023103/* Initialize mparams */3104static int init_mparams(void) {3105#ifdef NEED_GLOBAL_LOCK_INIT3106if (malloc_global_mutex_status <= 0)3107init_malloc_global_mutex();3108#endif31093110ACQUIRE_MALLOC_GLOBAL_LOCK();3111if (mparams.magic == 0) {3112size_t magic;3113size_t psize;3114size_t gsize;31153116#ifndef WIN323117psize = malloc_getpagesize;3118gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize);3119#else /* WIN32 */3120{3121SYSTEM_INFO system_info;3122GetSystemInfo(&system_info);3123psize = system_info.dwPageSize;3124gsize = ((DEFAULT_GRANULARITY != 0)?3125DEFAULT_GRANULARITY : system_info.dwAllocationGranularity);3126}3127#endif /* WIN32 */31283129/* Sanity-check configuration:3130size_t must be unsigned and as wide as pointer type.3131ints must be at least 4 bytes.3132alignment must be at least 8.3133Alignment, min chunk size, and page size must all be powers of 2.3134*/3135if ((sizeof(size_t) != sizeof(char*)) ||3136(MAX_SIZE_T < MIN_CHUNK_SIZE) ||3137(sizeof(int) < 4) ||3138(MALLOC_ALIGNMENT < (size_t)8U) ||3139((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||3140((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||3141((gsize & (gsize-SIZE_T_ONE)) != 0) ||3142((psize & (psize-SIZE_T_ONE)) != 0))3143ABORT;3144mparams.granularity = gsize;3145mparams.page_size = psize;3146mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;3147mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;3148#if MORECORE_CONTIGUOUS3149mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;3150#else /* MORECORE_CONTIGUOUS */3151mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;3152#endif /* MORECORE_CONTIGUOUS */31533154#if !ONLY_MSPACES3155/* Set up lock for main malloc area */3156gm->mflags = mparams.default_mflags;3157(void)INITIAL_LOCK(&gm->mutex);3158#endif3159#if LOCK_AT_FORK3160pthread_atfork(&pre_fork, &post_fork_parent, &post_fork_child);3161#endif31623163{3164#if USE_DEV_RANDOM3165int fd;3166unsigned char buf[sizeof(size_t)];3167/* Try to use /dev/urandom, else fall back on using time */3168if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&3169read(fd, buf, sizeof(buf)) == sizeof(buf)) {3170magic = *((size_t *) buf);3171close(fd);3172}3173else3174#endif /* USE_DEV_RANDOM */3175#ifdef WIN323176magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U);3177#elif defined(LACKS_TIME_H)3178magic = (size_t)&magic ^ (size_t)0x55555555U;3179#else3180magic = (size_t)(time(0) ^ (size_t)0x55555555U);3181#endif3182magic |= (size_t)8U; /* ensure nonzero */3183magic &= ~(size_t)7U; /* improve chances of fault for bad values */3184/* Until memory modes commonly available, use volatile-write */3185(*(volatile size_t *)(&(mparams.magic))) = magic;3186}3187}31883189RELEASE_MALLOC_GLOBAL_LOCK();3190return 1;3191}31923193/* support for mallopt */3194static int change_mparam(int param_number, int value) {3195size_t val;3196ensure_initialization();3197val = (value == -1)? MAX_SIZE_T : (size_t)value;3198switch(param_number) {3199case M_TRIM_THRESHOLD:3200mparams.trim_threshold = val;3201return 1;3202case M_GRANULARITY:3203if (val >= mparams.page_size && ((val & (val-1)) == 0)) {3204mparams.granularity = val;3205return 1;3206}3207else3208return 0;3209case M_MMAP_THRESHOLD:3210mparams.mmap_threshold = val;3211return 1;3212default:3213return 0;3214}3215}32163217#if DEBUG3218/* ------------------------- Debugging Support --------------------------- */32193220/* Check properties of any chunk, whether free, inuse, mmapped etc */3221static void do_check_any_chunk(mstate m, mchunkptr p) {3222assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));3223assert(ok_address(m, p));3224}32253226/* Check properties of top chunk */3227static void do_check_top_chunk(mstate m, mchunkptr p) {3228msegmentptr sp = segment_holding(m, (char*)p);3229size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */3230assert(sp != 0);3231assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));3232assert(ok_address(m, p));3233assert(sz == m->topsize);3234assert(sz > 0);3235assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);3236assert(pinuse(p));3237assert(!pinuse(chunk_plus_offset(p, sz)));3238}32393240/* Check properties of (inuse) mmapped chunks */3241static void do_check_mmapped_chunk(mstate m, mchunkptr p) {3242size_t sz = chunksize(p);3243size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD);3244assert(is_mmapped(p));3245assert(use_mmap(m));3246assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));3247assert(ok_address(m, p));3248assert(!is_small(sz));3249assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);3250assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);3251assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);3252}32533254/* Check properties of inuse chunks */3255static void do_check_inuse_chunk(mstate m, mchunkptr p) {3256do_check_any_chunk(m, p);3257assert(is_inuse(p));3258assert(next_pinuse(p));3259/* If not pinuse and not mmapped, previous chunk has OK offset */3260assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);3261if (is_mmapped(p))3262do_check_mmapped_chunk(m, p);3263}32643265/* Check properties of free chunks */3266static void do_check_free_chunk(mstate m, mchunkptr p) {3267size_t sz = chunksize(p);3268mchunkptr next = chunk_plus_offset(p, sz);3269do_check_any_chunk(m, p);3270assert(!is_inuse(p));3271assert(!next_pinuse(p));3272assert (!is_mmapped(p));3273if (p != m->dv && p != m->top) {3274if (sz >= MIN_CHUNK_SIZE) {3275assert((sz & CHUNK_ALIGN_MASK) == 0);3276assert(is_aligned(chunk2mem(p)));3277assert(next->prev_foot == sz);3278assert(pinuse(p));3279assert (next == m->top || is_inuse(next));3280assert(p->fd->bk == p);3281assert(p->bk->fd == p);3282}3283else /* markers are always of size SIZE_T_SIZE */3284assert(sz == SIZE_T_SIZE);3285}3286}32873288/* Check properties of malloced chunks at the point they are malloced */3289static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {3290if (mem != 0) {3291mchunkptr p = mem2chunk(mem);3292size_t sz = p->head & ~INUSE_BITS;3293do_check_inuse_chunk(m, p);3294assert((sz & CHUNK_ALIGN_MASK) == 0);3295assert(sz >= MIN_CHUNK_SIZE);3296assert(sz >= s);3297/* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */3298assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));3299}3300}33013302/* Check a tree and its subtrees. */3303static void do_check_tree(mstate m, tchunkptr t) {3304tchunkptr head = 0;3305tchunkptr u = t;3306bindex_t tindex = t->index;3307size_t tsize = chunksize(t);3308bindex_t idx;3309compute_tree_index(tsize, idx);3310assert(tindex == idx);3311assert(tsize >= MIN_LARGE_SIZE);3312assert(tsize >= minsize_for_tree_index(idx));3313assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));33143315do { /* traverse through chain of same-sized nodes */3316do_check_any_chunk(m, ((mchunkptr)u));3317assert(u->index == tindex);3318assert(chunksize(u) == tsize);3319assert(!is_inuse(u));3320assert(!next_pinuse(u));3321assert(u->fd->bk == u);3322assert(u->bk->fd == u);3323if (u->parent == 0) {3324assert(u->child[0] == 0);3325assert(u->child[1] == 0);3326}3327else {3328assert(head == 0); /* only one node on chain has parent */3329head = u;3330assert(u->parent != u);3331assert (u->parent->child[0] == u ||3332u->parent->child[1] == u ||3333*((tbinptr*)(u->parent)) == u);3334if (u->child[0] != 0) {3335assert(u->child[0]->parent == u);3336assert(u->child[0] != u);3337do_check_tree(m, u->child[0]);3338}3339if (u->child[1] != 0) {3340assert(u->child[1]->parent == u);3341assert(u->child[1] != u);3342do_check_tree(m, u->child[1]);3343}3344if (u->child[0] != 0 && u->child[1] != 0) {3345assert(chunksize(u->child[0]) < chunksize(u->child[1]));3346}3347}3348u = u->fd;3349} while (u != t);3350assert(head != 0);3351}33523353/* Check all the chunks in a treebin. */3354static void do_check_treebin(mstate m, bindex_t i) {3355tbinptr* tb = treebin_at(m, i);3356tchunkptr t = *tb;3357int empty = (m->treemap & (1U << i)) == 0;3358if (t == 0)3359assert(empty);3360if (!empty)3361do_check_tree(m, t);3362}33633364/* Check all the chunks in a smallbin. */3365static void do_check_smallbin(mstate m, bindex_t i) {3366sbinptr b = smallbin_at(m, i);3367mchunkptr p = b->bk;3368unsigned int empty = (m->smallmap & (1U << i)) == 0;3369if (p == b)3370assert(empty);3371if (!empty) {3372for (; p != b; p = p->bk) {3373size_t size = chunksize(p);3374mchunkptr q;3375/* each chunk claims to be free */3376do_check_free_chunk(m, p);3377/* chunk belongs in bin */3378assert(small_index(size) == i);3379assert(p->bk == b || chunksize(p->bk) == chunksize(p));3380/* chunk is followed by an inuse chunk */3381q = next_chunk(p);3382if (q->head != FENCEPOST_HEAD)3383do_check_inuse_chunk(m, q);3384}3385}3386}33873388/* Find x in a bin. Used in other check functions. */3389static int bin_find(mstate m, mchunkptr x) {3390size_t size = chunksize(x);3391if (is_small(size)) {3392bindex_t sidx = small_index(size);3393sbinptr b = smallbin_at(m, sidx);3394if (smallmap_is_marked(m, sidx)) {3395mchunkptr p = b;3396do {3397if (p == x)3398return 1;3399} while ((p = p->fd) != b);3400}3401}3402else {3403bindex_t tidx;3404compute_tree_index(size, tidx);3405if (treemap_is_marked(m, tidx)) {3406tchunkptr t = *treebin_at(m, tidx);3407size_t sizebits = size << leftshift_for_tree_index(tidx);3408while (t != 0 && chunksize(t) != size) {3409t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];3410sizebits <<= 1;3411}3412if (t != 0) {3413tchunkptr u = t;3414do {3415if (u == (tchunkptr)x)3416return 1;3417} while ((u = u->fd) != t);3418}3419}3420}3421return 0;3422}34233424/* Traverse each chunk and check it; return total */3425static size_t traverse_and_check(mstate m) {3426size_t sum = 0;3427if (is_initialized(m)) {3428msegmentptr s = &m->seg;3429sum += m->topsize + TOP_FOOT_SIZE;3430while (s != 0) {3431mchunkptr q = align_as_chunk(s->base);3432mchunkptr lastq = 0;3433assert(pinuse(q));3434while (segment_holds(s, q) &&3435q != m->top && q->head != FENCEPOST_HEAD) {3436sum += chunksize(q);3437if (is_inuse(q)) {3438assert(!bin_find(m, q));3439do_check_inuse_chunk(m, q);3440}3441else {3442assert(q == m->dv || bin_find(m, q));3443assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */3444do_check_free_chunk(m, q);3445}3446lastq = q;3447q = next_chunk(q);3448}3449s = s->next;3450}3451}3452return sum;3453}345434553456/* Check all properties of malloc_state. */3457static void do_check_malloc_state(mstate m) {3458bindex_t i;3459size_t total;3460/* check bins */3461for (i = 0; i < NSMALLBINS; ++i)3462do_check_smallbin(m, i);3463for (i = 0; i < NTREEBINS; ++i)3464do_check_treebin(m, i);34653466if (m->dvsize != 0) { /* check dv chunk */3467do_check_any_chunk(m, m->dv);3468assert(m->dvsize == chunksize(m->dv));3469assert(m->dvsize >= MIN_CHUNK_SIZE);3470assert(bin_find(m, m->dv) == 0);3471}34723473if (m->top != 0) { /* check top chunk */3474do_check_top_chunk(m, m->top);3475/*assert(m->topsize == chunksize(m->top)); redundant */3476assert(m->topsize > 0);3477assert(bin_find(m, m->top) == 0);3478}34793480total = traverse_and_check(m);3481assert(total <= m->footprint);3482assert(m->footprint <= m->max_footprint);3483}3484#endif /* DEBUG */34853486/* ----------------------------- statistics ------------------------------ */34873488#if !NO_MALLINFO3489static struct mallinfo internal_mallinfo(mstate m) {3490struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };3491ensure_initialization();3492if (!PREACTION(m)) {3493check_malloc_state(m);3494if (is_initialized(m)) {3495size_t nfree = SIZE_T_ONE; /* top always free */3496size_t mfree = m->topsize + TOP_FOOT_SIZE;3497size_t sum = mfree;3498msegmentptr s = &m->seg;3499while (s != 0) {3500mchunkptr q = align_as_chunk(s->base);3501while (segment_holds(s, q) &&3502q != m->top && q->head != FENCEPOST_HEAD) {3503size_t sz = chunksize(q);3504sum += sz;3505if (!is_inuse(q)) {3506mfree += sz;3507++nfree;3508}3509q = next_chunk(q);3510}3511s = s->next;3512}35133514nm.arena = sum;3515nm.ordblks = nfree;3516nm.hblkhd = m->footprint - sum;3517nm.usmblks = m->max_footprint;3518nm.uordblks = m->footprint - mfree;3519nm.fordblks = mfree;3520nm.keepcost = m->topsize;3521}35223523POSTACTION(m);3524}3525return nm;3526}3527#endif /* !NO_MALLINFO */35283529#if !NO_MALLOC_STATS3530static void internal_malloc_stats(mstate m) {3531ensure_initialization();3532if (!PREACTION(m)) {3533size_t maxfp = 0;3534size_t fp = 0;3535size_t used = 0;3536check_malloc_state(m);3537if (is_initialized(m)) {3538msegmentptr s = &m->seg;3539maxfp = m->max_footprint;3540fp = m->footprint;3541used = fp - (m->topsize + TOP_FOOT_SIZE);35423543while (s != 0) {3544mchunkptr q = align_as_chunk(s->base);3545while (segment_holds(s, q) &&3546q != m->top && q->head != FENCEPOST_HEAD) {3547if (!is_inuse(q))3548used -= chunksize(q);3549q = next_chunk(q);3550}3551s = s->next;3552}3553}3554POSTACTION(m); /* drop lock */3555fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));3556fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp));3557fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used));3558}3559}3560#endif /* NO_MALLOC_STATS */35613562/* ----------------------- Operations on smallbins ----------------------- */35633564/*3565Various forms of linking and unlinking are defined as macros. Even3566the ones for trees, which are very long but have very short typical3567paths. This is ugly but reduces reliance on inlining support of3568compilers.3569*/35703571/* Link a free chunk into a smallbin */3572#define insert_small_chunk(M, P, S) {\3573bindex_t I = small_index(S);\3574mchunkptr B = smallbin_at(M, I);\3575mchunkptr F = B;\3576assert(S >= MIN_CHUNK_SIZE);\3577if (!smallmap_is_marked(M, I))\3578mark_smallmap(M, I);\3579else if (RTCHECK(ok_address(M, B->fd)))\3580F = B->fd;\3581else {\3582CORRUPTION_ERROR_ACTION(M);\3583}\3584B->fd = P;\3585F->bk = P;\3586P->fd = F;\3587P->bk = B;\3588}35893590/* Unlink a chunk from a smallbin */3591#define unlink_small_chunk(M, P, S) {\3592mchunkptr F = P->fd;\3593mchunkptr B = P->bk;\3594bindex_t I = small_index(S);\3595assert(P != B);\3596assert(P != F);\3597assert(chunksize(P) == small_index2size(I));\3598if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { \3599if (B == F) {\3600clear_smallmap(M, I);\3601}\3602else if (RTCHECK(B == smallbin_at(M,I) ||\3603(ok_address(M, B) && B->fd == P))) {\3604F->bk = B;\3605B->fd = F;\3606}\3607else {\3608CORRUPTION_ERROR_ACTION(M);\3609}\3610}\3611else {\3612CORRUPTION_ERROR_ACTION(M);\3613}\3614}36153616/* Unlink the first chunk from a smallbin */3617#define unlink_first_small_chunk(M, B, P, I) {\3618mchunkptr F = P->fd;\3619assert(P != B);\3620assert(P != F);\3621assert(chunksize(P) == small_index2size(I));\3622if (B == F) {\3623clear_smallmap(M, I);\3624}\3625else if (RTCHECK(ok_address(M, F) && F->bk == P)) {\3626F->bk = B;\3627B->fd = F;\3628}\3629else {\3630CORRUPTION_ERROR_ACTION(M);\3631}\3632}36333634/* Replace dv node, binning the old one */3635/* Used only when dvsize known to be small */3636#define replace_dv(M, P, S) {\3637size_t DVS = M->dvsize;\3638assert(is_small(DVS));\3639if (DVS != 0) {\3640mchunkptr DV = M->dv;\3641insert_small_chunk(M, DV, DVS);\3642}\3643M->dvsize = S;\3644M->dv = P;\3645}36463647/* ------------------------- Operations on trees ------------------------- */36483649/* Insert chunk into tree */3650#define insert_large_chunk(M, X, S) {\3651tbinptr* H;\3652bindex_t I;\3653compute_tree_index(S, I);\3654H = treebin_at(M, I);\3655X->index = I;\3656X->child[0] = X->child[1] = 0;\3657if (!treemap_is_marked(M, I)) {\3658mark_treemap(M, I);\3659*H = X;\3660X->parent = (tchunkptr)H;\3661X->fd = X->bk = X;\3662}\3663else {\3664tchunkptr T = *H;\3665size_t K = S << leftshift_for_tree_index(I);\3666for (;;) {\3667if (chunksize(T) != S) {\3668tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\3669K <<= 1;\3670if (*C != 0)\3671T = *C;\3672else if (RTCHECK(ok_address(M, C))) {\3673*C = X;\3674X->parent = T;\3675X->fd = X->bk = X;\3676break;\3677}\3678else {\3679CORRUPTION_ERROR_ACTION(M);\3680break;\3681}\3682}\3683else {\3684tchunkptr F = T->fd;\3685if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\3686T->fd = F->bk = X;\3687X->fd = F;\3688X->bk = T;\3689X->parent = 0;\3690break;\3691}\3692else {\3693CORRUPTION_ERROR_ACTION(M);\3694break;\3695}\3696}\3697}\3698}\3699}37003701/*3702Unlink steps:370337041. If x is a chained node, unlink it from its same-sized fd/bk links3705and choose its bk node as its replacement.37062. If x was the last node of its size, but not a leaf node, it must3707be replaced with a leaf node (not merely one with an open left or3708right), to make sure that lefts and rights of descendents3709correspond properly to bit masks. We use the rightmost descendent3710of x. We could use any other leaf, but this is easy to locate and3711tends to counteract removal of leftmosts elsewhere, and so keeps3712paths shorter than minimally guaranteed. This doesn't loop much3713because on average a node in a tree is near the bottom.37143. If x is the base of a chain (i.e., has parent links) relink3715x's parent and children to x's replacement (or null if none).3716*/37173718#define unlink_large_chunk(M, X) {\3719tchunkptr XP = X->parent;\3720tchunkptr R;\3721if (X->bk != X) {\3722tchunkptr F = X->fd;\3723R = X->bk;\3724if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {\3725F->bk = R;\3726R->fd = F;\3727}\3728else {\3729CORRUPTION_ERROR_ACTION(M);\3730}\3731}\3732else {\3733tchunkptr* RP;\3734if (((R = *(RP = &(X->child[1]))) != 0) ||\3735((R = *(RP = &(X->child[0]))) != 0)) {\3736tchunkptr* CP;\3737while ((*(CP = &(R->child[1])) != 0) ||\3738(*(CP = &(R->child[0])) != 0)) {\3739R = *(RP = CP);\3740}\3741if (RTCHECK(ok_address(M, RP)))\3742*RP = 0;\3743else {\3744CORRUPTION_ERROR_ACTION(M);\3745}\3746}\3747}\3748if (XP != 0) {\3749tbinptr* H = treebin_at(M, X->index);\3750if (X == *H) {\3751if ((*H = R) == 0) \3752clear_treemap(M, X->index);\3753}\3754else if (RTCHECK(ok_address(M, XP))) {\3755if (XP->child[0] == X) \3756XP->child[0] = R;\3757else \3758XP->child[1] = R;\3759}\3760else\3761CORRUPTION_ERROR_ACTION(M);\3762if (R != 0) {\3763if (RTCHECK(ok_address(M, R))) {\3764tchunkptr C0, C1;\3765R->parent = XP;\3766if ((C0 = X->child[0]) != 0) {\3767if (RTCHECK(ok_address(M, C0))) {\3768R->child[0] = C0;\3769C0->parent = R;\3770}\3771else\3772CORRUPTION_ERROR_ACTION(M);\3773}\3774if ((C1 = X->child[1]) != 0) {\3775if (RTCHECK(ok_address(M, C1))) {\3776R->child[1] = C1;\3777C1->parent = R;\3778}\3779else\3780CORRUPTION_ERROR_ACTION(M);\3781}\3782}\3783else\3784CORRUPTION_ERROR_ACTION(M);\3785}\3786}\3787}37883789/* Relays to large vs small bin operations */37903791#define insert_chunk(M, P, S)\3792if (is_small(S)) insert_small_chunk(M, P, S)\3793else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }37943795#define unlink_chunk(M, P, S)\3796if (is_small(S)) unlink_small_chunk(M, P, S)\3797else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }379837993800/* Relays to internal calls to malloc/free from realloc, memalign etc */38013802#if ONLY_MSPACES3803#define internal_malloc(m, b) mspace_malloc(m, b)3804#define internal_free(m, mem) mspace_free(m,mem);3805#else /* ONLY_MSPACES */3806#if MSPACES3807#define internal_malloc(m, b)\3808((m == gm)? dlmalloc(b) : mspace_malloc(m, b))3809#define internal_free(m, mem)\3810if (m == gm) dlfree(mem); else mspace_free(m,mem);3811#else /* MSPACES */3812#define internal_malloc(m, b) dlmalloc(b)3813#define internal_free(m, mem) dlfree(mem)3814#endif /* MSPACES */3815#endif /* ONLY_MSPACES */38163817/* ----------------------- Direct-mmapping chunks ----------------------- */38183819/*3820Directly mmapped chunks are set up with an offset to the start of3821the mmapped region stored in the prev_foot field of the chunk. This3822allows reconstruction of the required argument to MUNMAP when freed,3823and also allows adjustment of the returned chunk to meet alignment3824requirements (especially in memalign).3825*/38263827/* Malloc using mmap */3828static void* mmap_alloc(mstate m, size_t nb) {3829size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);3830if (m->footprint_limit != 0) {3831size_t fp = m->footprint + mmsize;3832if (fp <= m->footprint || fp > m->footprint_limit)3833return 0;3834}3835if (mmsize > nb) { /* Check for wrap around 0 */3836char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));3837if (mm != CMFAIL) {3838size_t offset = align_offset(chunk2mem(mm));3839size_t psize = mmsize - offset - MMAP_FOOT_PAD;3840mchunkptr p = (mchunkptr)(mm + offset);3841p->prev_foot = offset;3842p->head = psize;3843mark_inuse_foot(m, p, psize);3844chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;3845chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;38463847if (m->least_addr == 0 || mm < m->least_addr)3848m->least_addr = mm;3849if ((m->footprint += mmsize) > m->max_footprint)3850m->max_footprint = m->footprint;3851assert(is_aligned(chunk2mem(p)));3852check_mmapped_chunk(m, p);3853return chunk2mem(p);3854}3855}3856return 0;3857}38583859/* Realloc using mmap */3860static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb, int flags) {3861size_t oldsize = chunksize(oldp);3862(void)flags; /* placate people compiling -Wunused */3863if (is_small(nb)) /* Can't shrink mmap regions below small size */3864return 0;3865/* Keep old chunk if big enough but not too big */3866if (oldsize >= nb + SIZE_T_SIZE &&3867(oldsize - nb) <= (mparams.granularity << 1))3868return oldp;3869else {3870size_t offset = oldp->prev_foot;3871size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;3872size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);3873char* cp = (char*)CALL_MREMAP((char*)oldp - offset,3874oldmmsize, newmmsize, flags);3875if (cp != CMFAIL) {3876mchunkptr newp = (mchunkptr)(cp + offset);3877size_t psize = newmmsize - offset - MMAP_FOOT_PAD;3878newp->head = psize;3879mark_inuse_foot(m, newp, psize);3880chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;3881chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;38823883if (cp < m->least_addr)3884m->least_addr = cp;3885if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)3886m->max_footprint = m->footprint;3887check_mmapped_chunk(m, newp);3888return newp;3889}3890}3891return 0;3892}389338943895/* -------------------------- mspace management -------------------------- */38963897/* Initialize top chunk and its size */3898static void init_top(mstate m, mchunkptr p, size_t psize) {3899/* Ensure alignment */3900size_t offset = align_offset(chunk2mem(p));3901p = (mchunkptr)((char*)p + offset);3902psize -= offset;39033904m->top = p;3905m->topsize = psize;3906p->head = psize | PINUSE_BIT;3907/* set size of fake trailing chunk holding overhead space only once */3908chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;3909m->trim_check = mparams.trim_threshold; /* reset on each update */3910}39113912/* Initialize bins for a new mstate that is otherwise zeroed out */3913static void init_bins(mstate m) {3914/* Establish circular links for smallbins */3915bindex_t i;3916for (i = 0; i < NSMALLBINS; ++i) {3917sbinptr bin = smallbin_at(m,i);3918bin->fd = bin->bk = bin;3919}3920}39213922#if PROCEED_ON_ERROR39233924/* default corruption action */3925static void reset_on_error(mstate m) {3926int i;3927++malloc_corruption_error_count;3928/* Reinitialize fields to forget about all memory */3929m->smallmap = m->treemap = 0;3930m->dvsize = m->topsize = 0;3931m->seg.base = 0;3932m->seg.size = 0;3933m->seg.next = 0;3934m->top = m->dv = 0;3935for (i = 0; i < NTREEBINS; ++i)3936*treebin_at(m, i) = 0;3937init_bins(m);3938}3939#endif /* PROCEED_ON_ERROR */39403941/* Allocate chunk and prepend remainder with chunk in successor base. */3942static void* prepend_alloc(mstate m, char* newbase, char* oldbase,3943size_t nb) {3944mchunkptr p = align_as_chunk(newbase);3945mchunkptr oldfirst = align_as_chunk(oldbase);3946size_t psize = (char*)oldfirst - (char*)p;3947mchunkptr q = chunk_plus_offset(p, nb);3948size_t qsize = psize - nb;3949set_size_and_pinuse_of_inuse_chunk(m, p, nb);39503951assert((char*)oldfirst > (char*)q);3952assert(pinuse(oldfirst));3953assert(qsize >= MIN_CHUNK_SIZE);39543955/* consolidate remainder with first chunk of old base */3956if (oldfirst == m->top) {3957size_t tsize = m->topsize += qsize;3958m->top = q;3959q->head = tsize | PINUSE_BIT;3960check_top_chunk(m, q);3961}3962else if (oldfirst == m->dv) {3963size_t dsize = m->dvsize += qsize;3964m->dv = q;3965set_size_and_pinuse_of_free_chunk(q, dsize);3966}3967else {3968if (!is_inuse(oldfirst)) {3969size_t nsize = chunksize(oldfirst);3970unlink_chunk(m, oldfirst, nsize);3971oldfirst = chunk_plus_offset(oldfirst, nsize);3972qsize += nsize;3973}3974set_free_with_pinuse(q, qsize, oldfirst);3975insert_chunk(m, q, qsize);3976check_free_chunk(m, q);3977}39783979check_malloced_chunk(m, chunk2mem(p), nb);3980return chunk2mem(p);3981}39823983/* Add a segment to hold a new noncontiguous region */3984static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {3985/* Determine locations and sizes of segment, fenceposts, old top */3986char* old_top = (char*)m->top;3987msegmentptr oldsp = segment_holding(m, old_top);3988char* old_end = oldsp->base + oldsp->size;3989size_t ssize = pad_request(sizeof(struct malloc_segment));3990char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);3991size_t offset = align_offset(chunk2mem(rawsp));3992char* asp = rawsp + offset;3993char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;3994mchunkptr sp = (mchunkptr)csp;3995msegmentptr ss = (msegmentptr)(chunk2mem(sp));3996mchunkptr tnext = chunk_plus_offset(sp, ssize);3997mchunkptr p = tnext;3998int nfences = 0;39994000/* reset top to new space */4001init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);40024003/* Set up segment record */4004assert(is_aligned(ss));4005set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);4006*ss = m->seg; /* Push current record */4007m->seg.base = tbase;4008m->seg.size = tsize;4009m->seg.sflags = mmapped;4010m->seg.next = ss;40114012/* Insert trailing fenceposts */4013for (;;) {4014mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);4015p->head = FENCEPOST_HEAD;4016++nfences;4017if ((char*)(&(nextp->head)) < old_end)4018p = nextp;4019else4020break;4021}4022assert(nfences >= 2);40234024/* Insert the rest of old top into a bin as an ordinary free chunk */4025if (csp != old_top) {4026mchunkptr q = (mchunkptr)old_top;4027size_t psize = csp - old_top;4028mchunkptr tn = chunk_plus_offset(q, psize);4029set_free_with_pinuse(q, psize, tn);4030insert_chunk(m, q, psize);4031}40324033check_top_chunk(m, m->top);4034}40354036/* -------------------------- System allocation -------------------------- */40374038/* Get memory from system using MORECORE or MMAP */4039static void* sys_alloc(mstate m, size_t nb) {4040char* tbase = CMFAIL;4041size_t tsize = 0;4042flag_t mmap_flag = 0;4043size_t asize; /* allocation size */40444045ensure_initialization();40464047/* Directly map large chunks, but only if already initialized */4048if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) {4049void* mem = mmap_alloc(m, nb);4050if (mem != 0)4051return mem;4052}40534054asize = granularity_align(nb + SYS_ALLOC_PADDING);4055if (asize <= nb)4056return 0; /* wraparound */4057if (m->footprint_limit != 0) {4058size_t fp = m->footprint + asize;4059if (fp <= m->footprint || fp > m->footprint_limit)4060return 0;4061}40624063/*4064Try getting memory in any of three ways (in most-preferred to4065least-preferred order):40661. A call to MORECORE that can normally contiguously extend memory.4067(disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or4068or main space is mmapped or a previous contiguous call failed)40692. A call to MMAP new space (disabled if not HAVE_MMAP).4070Note that under the default settings, if MORECORE is unable to4071fulfill a request, and HAVE_MMAP is true, then mmap is4072used as a noncontiguous system allocator. This is a useful backup4073strategy for systems with holes in address spaces -- in this case4074sbrk cannot contiguously expand the heap, but mmap may be able to4075find space.40763. A call to MORECORE that cannot usually contiguously extend memory.4077(disabled if not HAVE_MORECORE)40784079In all cases, we need to request enough bytes from system to ensure4080we can malloc nb bytes upon success, so pad with enough space for4081top_foot, plus alignment-pad to make sure we don't lose bytes if4082not on boundary, and round this up to a granularity unit.4083*/40844085if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {4086char* br = CMFAIL;4087size_t ssize = asize; /* sbrk call size */4088msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);4089ACQUIRE_MALLOC_GLOBAL_LOCK();40904091if (ss == 0) { /* First time through or recovery */4092char* base = (char*)CALL_MORECORE(0);4093if (base != CMFAIL) {4094size_t fp;4095/* Adjust to end on a page boundary */4096if (!is_page_aligned(base))4097ssize += (page_align((size_t)base) - (size_t)base);4098fp = m->footprint + ssize; /* recheck limits */4099if (ssize > nb && ssize < HALF_MAX_SIZE_T &&4100(m->footprint_limit == 0 ||4101(fp > m->footprint && fp <= m->footprint_limit)) &&4102(br = (char*)(CALL_MORECORE(ssize))) == base) {4103tbase = base;4104tsize = ssize;4105}4106}4107}4108else {4109/* Subtract out existing available top space from MORECORE request. */4110ssize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING);4111/* Use mem here only if it did continuously extend old space */4112if (ssize < HALF_MAX_SIZE_T &&4113(br = (char*)(CALL_MORECORE(ssize))) == ss->base+ss->size) {4114tbase = br;4115tsize = ssize;4116}4117}41184119if (tbase == CMFAIL) { /* Cope with partial failure */4120if (br != CMFAIL) { /* Try to use/extend the space we did get */4121if (ssize < HALF_MAX_SIZE_T &&4122ssize < nb + SYS_ALLOC_PADDING) {4123size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - ssize);4124if (esize < HALF_MAX_SIZE_T) {4125char* end = (char*)CALL_MORECORE(esize);4126if (end != CMFAIL)4127ssize += esize;4128else { /* Can't use; try to release */4129(void) CALL_MORECORE(-ssize);4130br = CMFAIL;4131}4132}4133}4134}4135if (br != CMFAIL) { /* Use the space we did get */4136tbase = br;4137tsize = ssize;4138}4139else4140disable_contiguous(m); /* Don't try contiguous path in the future */4141}41424143RELEASE_MALLOC_GLOBAL_LOCK();4144}41454146if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */4147char* mp = (char*)(CALL_MMAP(asize));4148if (mp != CMFAIL) {4149tbase = mp;4150tsize = asize;4151mmap_flag = USE_MMAP_BIT;4152}4153}41544155if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */4156if (asize < HALF_MAX_SIZE_T) {4157char* br = CMFAIL;4158char* end = CMFAIL;4159ACQUIRE_MALLOC_GLOBAL_LOCK();4160br = (char*)(CALL_MORECORE(asize));4161end = (char*)(CALL_MORECORE(0));4162RELEASE_MALLOC_GLOBAL_LOCK();4163if (br != CMFAIL && end != CMFAIL && br < end) {4164size_t ssize = end - br;4165if (ssize > nb + TOP_FOOT_SIZE) {4166tbase = br;4167tsize = ssize;4168}4169}4170}4171}41724173if (tbase != CMFAIL) {41744175if ((m->footprint += tsize) > m->max_footprint)4176m->max_footprint = m->footprint;41774178if (!is_initialized(m)) { /* first-time initialization */4179if (m->least_addr == 0 || tbase < m->least_addr)4180m->least_addr = tbase;4181m->seg.base = tbase;4182m->seg.size = tsize;4183m->seg.sflags = mmap_flag;4184m->magic = mparams.magic;4185m->release_checks = MAX_RELEASE_CHECK_RATE;4186init_bins(m);4187#if !ONLY_MSPACES4188if (is_global(m))4189init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);4190else4191#endif4192{4193/* Offset top by embedded malloc_state */4194mchunkptr mn = next_chunk(mem2chunk(m));4195init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);4196}4197}41984199else {4200/* Try to merge with an existing segment */4201msegmentptr sp = &m->seg;4202/* Only consider most recent segment if traversal suppressed */4203while (sp != 0 && tbase != sp->base + sp->size)4204sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;4205if (sp != 0 &&4206!is_extern_segment(sp) &&4207(sp->sflags & USE_MMAP_BIT) == mmap_flag &&4208segment_holds(sp, m->top)) { /* append */4209sp->size += tsize;4210init_top(m, m->top, m->topsize + tsize);4211}4212else {4213if (tbase < m->least_addr)4214m->least_addr = tbase;4215sp = &m->seg;4216while (sp != 0 && sp->base != tbase + tsize)4217sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;4218if (sp != 0 &&4219!is_extern_segment(sp) &&4220(sp->sflags & USE_MMAP_BIT) == mmap_flag) {4221char* oldbase = sp->base;4222sp->base = tbase;4223sp->size += tsize;4224return prepend_alloc(m, tbase, oldbase, nb);4225}4226else4227add_segment(m, tbase, tsize, mmap_flag);4228}4229}42304231if (nb < m->topsize) { /* Allocate from new or extended top space */4232size_t rsize = m->topsize -= nb;4233mchunkptr p = m->top;4234mchunkptr r = m->top = chunk_plus_offset(p, nb);4235r->head = rsize | PINUSE_BIT;4236set_size_and_pinuse_of_inuse_chunk(m, p, nb);4237check_top_chunk(m, m->top);4238check_malloced_chunk(m, chunk2mem(p), nb);4239return chunk2mem(p);4240}4241}42424243MALLOC_FAILURE_ACTION;4244return 0;4245}42464247/* ----------------------- system deallocation -------------------------- */42484249/* Unmap and unlink any mmapped segments that don't contain used chunks */4250static size_t release_unused_segments(mstate m) {4251size_t released = 0;4252int nsegs = 0;4253msegmentptr pred = &m->seg;4254msegmentptr sp = pred->next;4255while (sp != 0) {4256char* base = sp->base;4257size_t size = sp->size;4258msegmentptr next = sp->next;4259++nsegs;4260if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {4261mchunkptr p = align_as_chunk(base);4262size_t psize = chunksize(p);4263/* Can unmap if first chunk holds entire segment and not pinned */4264if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {4265tchunkptr tp = (tchunkptr)p;4266assert(segment_holds(sp, (char*)sp));4267if (p == m->dv) {4268m->dv = 0;4269m->dvsize = 0;4270}4271else {4272unlink_large_chunk(m, tp);4273}4274if (CALL_MUNMAP(base, size) == 0) {4275released += size;4276m->footprint -= size;4277/* unlink obsoleted record */4278sp = pred;4279sp->next = next;4280}4281else { /* back out if cannot unmap */4282insert_large_chunk(m, tp, psize);4283}4284}4285}4286if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */4287break;4288pred = sp;4289sp = next;4290}4291/* Reset check counter */4292m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)?4293(size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE);4294return released;4295}42964297static int sys_trim(mstate m, size_t pad) {4298size_t released = 0;4299ensure_initialization();4300if (pad < MAX_REQUEST && is_initialized(m)) {4301pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */43024303if (m->topsize > pad) {4304/* Shrink top space in granularity-size units, keeping at least one */4305size_t unit = mparams.granularity;4306size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -4307SIZE_T_ONE) * unit;4308msegmentptr sp = segment_holding(m, (char*)m->top);43094310if (!is_extern_segment(sp)) {4311if (is_mmapped_segment(sp)) {4312if (HAVE_MMAP &&4313sp->size >= extra &&4314!has_segment_link(m, sp)) { /* can't shrink if pinned */4315size_t newsize = sp->size - extra;4316(void)newsize; /* placate people compiling -Wunused-variable */4317/* Prefer mremap, fall back to munmap */4318if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||4319(CALL_MUNMAP(sp->base + newsize, extra) == 0)) {4320released = extra;4321}4322}4323}4324else if (HAVE_MORECORE) {4325if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */4326extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;4327ACQUIRE_MALLOC_GLOBAL_LOCK();4328{4329/* Make sure end of memory is where we last set it. */4330char* old_br = (char*)(CALL_MORECORE(0));4331if (old_br == sp->base + sp->size) {4332char* rel_br = (char*)(CALL_MORECORE(-extra));4333char* new_br = (char*)(CALL_MORECORE(0));4334if (rel_br != CMFAIL && new_br < old_br)4335released = old_br - new_br;4336}4337}4338RELEASE_MALLOC_GLOBAL_LOCK();4339}4340}43414342if (released != 0) {4343sp->size -= released;4344m->footprint -= released;4345init_top(m, m->top, m->topsize - released);4346check_top_chunk(m, m->top);4347}4348}43494350/* Unmap any unused mmapped segments */4351if (HAVE_MMAP)4352released += release_unused_segments(m);43534354/* On failure, disable autotrim to avoid repeated failed future calls */4355if (released == 0 && m->topsize > m->trim_check)4356m->trim_check = MAX_SIZE_T;4357}43584359return (released != 0)? 1 : 0;4360}43614362/* Consolidate and bin a chunk. Differs from exported versions4363of free mainly in that the chunk need not be marked as inuse.4364*/4365static void dispose_chunk(mstate m, mchunkptr p, size_t psize) {4366mchunkptr next = chunk_plus_offset(p, psize);4367if (!pinuse(p)) {4368mchunkptr prev;4369size_t prevsize = p->prev_foot;4370if (is_mmapped(p)) {4371psize += prevsize + MMAP_FOOT_PAD;4372if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)4373m->footprint -= psize;4374return;4375}4376prev = chunk_minus_offset(p, prevsize);4377psize += prevsize;4378p = prev;4379if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */4380if (p != m->dv) {4381unlink_chunk(m, p, prevsize);4382}4383else if ((next->head & INUSE_BITS) == INUSE_BITS) {4384m->dvsize = psize;4385set_free_with_pinuse(p, psize, next);4386return;4387}4388}4389else {4390CORRUPTION_ERROR_ACTION(m);4391return;4392}4393}4394if (RTCHECK(ok_address(m, next))) {4395if (!cinuse(next)) { /* consolidate forward */4396if (next == m->top) {4397size_t tsize = m->topsize += psize;4398m->top = p;4399p->head = tsize | PINUSE_BIT;4400if (p == m->dv) {4401m->dv = 0;4402m->dvsize = 0;4403}4404return;4405}4406else if (next == m->dv) {4407size_t dsize = m->dvsize += psize;4408m->dv = p;4409set_size_and_pinuse_of_free_chunk(p, dsize);4410return;4411}4412else {4413size_t nsize = chunksize(next);4414psize += nsize;4415unlink_chunk(m, next, nsize);4416set_size_and_pinuse_of_free_chunk(p, psize);4417if (p == m->dv) {4418m->dvsize = psize;4419return;4420}4421}4422}4423else {4424set_free_with_pinuse(p, psize, next);4425}4426insert_chunk(m, p, psize);4427}4428else {4429CORRUPTION_ERROR_ACTION(m);4430}4431}44324433/* ---------------------------- malloc --------------------------- */44344435/* allocate a large request from the best fitting chunk in a treebin */4436static void* tmalloc_large(mstate m, size_t nb) {4437tchunkptr v = 0;4438size_t rsize = -nb; /* Unsigned negation */4439tchunkptr t;4440bindex_t idx;4441compute_tree_index(nb, idx);4442if ((t = *treebin_at(m, idx)) != 0) {4443/* Traverse tree for this bin looking for node with size == nb */4444size_t sizebits = nb << leftshift_for_tree_index(idx);4445tchunkptr rst = 0; /* The deepest untaken right subtree */4446for (;;) {4447tchunkptr rt;4448size_t trem = chunksize(t) - nb;4449if (trem < rsize) {4450v = t;4451if ((rsize = trem) == 0)4452break;4453}4454rt = t->child[1];4455t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];4456if (rt != 0 && rt != t)4457rst = rt;4458if (t == 0) {4459t = rst; /* set t to least subtree holding sizes > nb */4460break;4461}4462sizebits <<= 1;4463}4464}4465if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */4466binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;4467if (leftbits != 0) {4468bindex_t i;4469binmap_t leastbit = least_bit(leftbits);4470compute_bit2idx(leastbit, i);4471t = *treebin_at(m, i);4472}4473}44744475while (t != 0) { /* find smallest of tree or subtree */4476size_t trem = chunksize(t) - nb;4477if (trem < rsize) {4478rsize = trem;4479v = t;4480}4481t = leftmost_child(t);4482}44834484/* If dv is a better fit, return 0 so malloc will use it */4485if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {4486if (RTCHECK(ok_address(m, v))) { /* split */4487mchunkptr r = chunk_plus_offset(v, nb);4488assert(chunksize(v) == rsize + nb);4489if (RTCHECK(ok_next(v, r))) {4490unlink_large_chunk(m, v);4491if (rsize < MIN_CHUNK_SIZE)4492set_inuse_and_pinuse(m, v, (rsize + nb));4493else {4494set_size_and_pinuse_of_inuse_chunk(m, v, nb);4495set_size_and_pinuse_of_free_chunk(r, rsize);4496insert_chunk(m, r, rsize);4497}4498return chunk2mem(v);4499}4500}4501CORRUPTION_ERROR_ACTION(m);4502}4503return 0;4504}45054506/* allocate a small request from the best fitting chunk in a treebin */4507static void* tmalloc_small(mstate m, size_t nb) {4508tchunkptr t, v;4509size_t rsize;4510bindex_t i;4511binmap_t leastbit = least_bit(m->treemap);4512compute_bit2idx(leastbit, i);4513v = t = *treebin_at(m, i);4514rsize = chunksize(t) - nb;45154516while ((t = leftmost_child(t)) != 0) {4517size_t trem = chunksize(t) - nb;4518if (trem < rsize) {4519rsize = trem;4520v = t;4521}4522}45234524if (RTCHECK(ok_address(m, v))) {4525mchunkptr r = chunk_plus_offset(v, nb);4526assert(chunksize(v) == rsize + nb);4527if (RTCHECK(ok_next(v, r))) {4528unlink_large_chunk(m, v);4529if (rsize < MIN_CHUNK_SIZE)4530set_inuse_and_pinuse(m, v, (rsize + nb));4531else {4532set_size_and_pinuse_of_inuse_chunk(m, v, nb);4533set_size_and_pinuse_of_free_chunk(r, rsize);4534replace_dv(m, r, rsize);4535}4536return chunk2mem(v);4537}4538}45394540CORRUPTION_ERROR_ACTION(m);4541return 0;4542}45434544#if !ONLY_MSPACES45454546void* dlmalloc(size_t bytes) {4547/*4548Basic algorithm:4549If a small request (< 256 bytes minus per-chunk overhead):45501. If one exists, use a remainderless chunk in associated smallbin.4551(Remainderless means that there are too few excess bytes to4552represent as a chunk.)45532. If it is big enough, use the dv chunk, which is normally the4554chunk adjacent to the one used for the most recent small request.45553. If one exists, split the smallest available chunk in a bin,4556saving remainder in dv.45574. If it is big enough, use the top chunk.45585. If available, get memory from system and use it4559Otherwise, for a large request:45601. Find the smallest available binned chunk that fits, and use it4561if it is better fitting than dv chunk, splitting if necessary.45622. If better fitting than any binned chunk, use the dv chunk.45633. If it is big enough, use the top chunk.45644. If request size >= mmap threshold, try to directly mmap this chunk.45655. If available, get memory from system and use it45664567The ugly goto's here ensure that postaction occurs along all paths.4568*/45694570#if USE_LOCKS4571ensure_initialization(); /* initialize in sys_alloc if not using locks */4572#endif45734574if (!PREACTION(gm)) {4575void* mem;4576size_t nb;4577if (bytes <= MAX_SMALL_REQUEST) {4578bindex_t idx;4579binmap_t smallbits;4580nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);4581idx = small_index(nb);4582smallbits = gm->smallmap >> idx;45834584if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */4585mchunkptr b, p;4586idx += ~smallbits & 1; /* Uses next bin if idx empty */4587b = smallbin_at(gm, idx);4588p = b->fd;4589assert(chunksize(p) == small_index2size(idx));4590unlink_first_small_chunk(gm, b, p, idx);4591set_inuse_and_pinuse(gm, p, small_index2size(idx));4592mem = chunk2mem(p);4593check_malloced_chunk(gm, mem, nb);4594goto postaction;4595}45964597else if (nb > gm->dvsize) {4598if (smallbits != 0) { /* Use chunk in next nonempty smallbin */4599mchunkptr b, p, r;4600size_t rsize;4601bindex_t i;4602binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));4603binmap_t leastbit = least_bit(leftbits);4604compute_bit2idx(leastbit, i);4605b = smallbin_at(gm, i);4606p = b->fd;4607assert(chunksize(p) == small_index2size(i));4608unlink_first_small_chunk(gm, b, p, i);4609rsize = small_index2size(i) - nb;4610/* Fit here cannot be remainderless if 4byte sizes */4611if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)4612set_inuse_and_pinuse(gm, p, small_index2size(i));4613else {4614set_size_and_pinuse_of_inuse_chunk(gm, p, nb);4615r = chunk_plus_offset(p, nb);4616set_size_and_pinuse_of_free_chunk(r, rsize);4617replace_dv(gm, r, rsize);4618}4619mem = chunk2mem(p);4620check_malloced_chunk(gm, mem, nb);4621goto postaction;4622}46234624else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {4625check_malloced_chunk(gm, mem, nb);4626goto postaction;4627}4628}4629}4630else if (bytes >= MAX_REQUEST)4631nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */4632else {4633nb = pad_request(bytes);4634if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {4635check_malloced_chunk(gm, mem, nb);4636goto postaction;4637}4638}46394640if (nb <= gm->dvsize) {4641size_t rsize = gm->dvsize - nb;4642mchunkptr p = gm->dv;4643if (rsize >= MIN_CHUNK_SIZE) { /* split dv */4644mchunkptr r = gm->dv = chunk_plus_offset(p, nb);4645gm->dvsize = rsize;4646set_size_and_pinuse_of_free_chunk(r, rsize);4647set_size_and_pinuse_of_inuse_chunk(gm, p, nb);4648}4649else { /* exhaust dv */4650size_t dvs = gm->dvsize;4651gm->dvsize = 0;4652gm->dv = 0;4653set_inuse_and_pinuse(gm, p, dvs);4654}4655mem = chunk2mem(p);4656check_malloced_chunk(gm, mem, nb);4657goto postaction;4658}46594660else if (nb < gm->topsize) { /* Split top */4661size_t rsize = gm->topsize -= nb;4662mchunkptr p = gm->top;4663mchunkptr r = gm->top = chunk_plus_offset(p, nb);4664r->head = rsize | PINUSE_BIT;4665set_size_and_pinuse_of_inuse_chunk(gm, p, nb);4666mem = chunk2mem(p);4667check_top_chunk(gm, gm->top);4668check_malloced_chunk(gm, mem, nb);4669goto postaction;4670}46714672mem = sys_alloc(gm, nb);46734674postaction:4675POSTACTION(gm);4676return mem;4677}46784679return 0;4680}46814682/* ---------------------------- free --------------------------- */46834684void dlfree(void* mem) {4685/*4686Consolidate freed chunks with preceeding or succeeding bordering4687free chunks, if they exist, and then place in a bin. Intermixed4688with special cases for top, dv, mmapped chunks, and usage errors.4689*/46904691if (mem != 0) {4692mchunkptr p = mem2chunk(mem);4693#if FOOTERS4694mstate fm = get_mstate_for(p);4695if (!ok_magic(fm)) {4696USAGE_ERROR_ACTION(fm, p);4697return;4698}4699#else /* FOOTERS */4700#define fm gm4701#endif /* FOOTERS */4702if (!PREACTION(fm)) {4703check_inuse_chunk(fm, p);4704if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {4705size_t psize = chunksize(p);4706mchunkptr next = chunk_plus_offset(p, psize);4707if (!pinuse(p)) {4708size_t prevsize = p->prev_foot;4709if (is_mmapped(p)) {4710psize += prevsize + MMAP_FOOT_PAD;4711if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)4712fm->footprint -= psize;4713goto postaction;4714}4715else {4716mchunkptr prev = chunk_minus_offset(p, prevsize);4717psize += prevsize;4718p = prev;4719if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */4720if (p != fm->dv) {4721unlink_chunk(fm, p, prevsize);4722}4723else if ((next->head & INUSE_BITS) == INUSE_BITS) {4724fm->dvsize = psize;4725set_free_with_pinuse(p, psize, next);4726goto postaction;4727}4728}4729else4730goto erroraction;4731}4732}47334734if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {4735if (!cinuse(next)) { /* consolidate forward */4736if (next == fm->top) {4737size_t tsize = fm->topsize += psize;4738fm->top = p;4739p->head = tsize | PINUSE_BIT;4740if (p == fm->dv) {4741fm->dv = 0;4742fm->dvsize = 0;4743}4744if (should_trim(fm, tsize))4745sys_trim(fm, 0);4746goto postaction;4747}4748else if (next == fm->dv) {4749size_t dsize = fm->dvsize += psize;4750fm->dv = p;4751set_size_and_pinuse_of_free_chunk(p, dsize);4752goto postaction;4753}4754else {4755size_t nsize = chunksize(next);4756psize += nsize;4757unlink_chunk(fm, next, nsize);4758set_size_and_pinuse_of_free_chunk(p, psize);4759if (p == fm->dv) {4760fm->dvsize = psize;4761goto postaction;4762}4763}4764}4765else4766set_free_with_pinuse(p, psize, next);47674768if (is_small(psize)) {4769insert_small_chunk(fm, p, psize);4770check_free_chunk(fm, p);4771}4772else {4773tchunkptr tp = (tchunkptr)p;4774insert_large_chunk(fm, tp, psize);4775check_free_chunk(fm, p);4776if (--fm->release_checks == 0)4777release_unused_segments(fm);4778}4779goto postaction;4780}4781}4782erroraction:4783USAGE_ERROR_ACTION(fm, p);4784postaction:4785POSTACTION(fm);4786}4787}4788#if !FOOTERS4789#undef fm4790#endif /* FOOTERS */4791}47924793void* dlcalloc(size_t n_elements, size_t elem_size) {4794void* mem;4795size_t req = 0;4796if (n_elements != 0) {4797req = n_elements * elem_size;4798if (((n_elements | elem_size) & ~(size_t)0xffff) &&4799(req / n_elements != elem_size))4800req = MAX_SIZE_T; /* force downstream failure on overflow */4801}4802mem = dlmalloc(req);4803if (mem != 0 && calloc_must_clear(mem2chunk(mem)))4804memset(mem, 0, req);4805return mem;4806}48074808#endif /* !ONLY_MSPACES */48094810/* ------------ Internal support for realloc, memalign, etc -------------- */48114812/* Try to realloc; only in-place unless can_move true */4813static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb,4814int can_move) {4815mchunkptr newp = 0;4816size_t oldsize = chunksize(p);4817mchunkptr next = chunk_plus_offset(p, oldsize);4818if (RTCHECK(ok_address(m, p) && ok_inuse(p) &&4819ok_next(p, next) && ok_pinuse(next))) {4820if (is_mmapped(p)) {4821newp = mmap_resize(m, p, nb, can_move);4822}4823else if (oldsize >= nb) { /* already big enough */4824size_t rsize = oldsize - nb;4825if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */4826mchunkptr r = chunk_plus_offset(p, nb);4827set_inuse(m, p, nb);4828set_inuse(m, r, rsize);4829dispose_chunk(m, r, rsize);4830}4831newp = p;4832}4833else if (next == m->top) { /* extend into top */4834if (oldsize + m->topsize > nb) {4835size_t newsize = oldsize + m->topsize;4836size_t newtopsize = newsize - nb;4837mchunkptr newtop = chunk_plus_offset(p, nb);4838set_inuse(m, p, nb);4839newtop->head = newtopsize |PINUSE_BIT;4840m->top = newtop;4841m->topsize = newtopsize;4842newp = p;4843}4844}4845else if (next == m->dv) { /* extend into dv */4846size_t dvs = m->dvsize;4847if (oldsize + dvs >= nb) {4848size_t dsize = oldsize + dvs - nb;4849if (dsize >= MIN_CHUNK_SIZE) {4850mchunkptr r = chunk_plus_offset(p, nb);4851mchunkptr n = chunk_plus_offset(r, dsize);4852set_inuse(m, p, nb);4853set_size_and_pinuse_of_free_chunk(r, dsize);4854clear_pinuse(n);4855m->dvsize = dsize;4856m->dv = r;4857}4858else { /* exhaust dv */4859size_t newsize = oldsize + dvs;4860set_inuse(m, p, newsize);4861m->dvsize = 0;4862m->dv = 0;4863}4864newp = p;4865}4866}4867else if (!cinuse(next)) { /* extend into next free chunk */4868size_t nextsize = chunksize(next);4869if (oldsize + nextsize >= nb) {4870size_t rsize = oldsize + nextsize - nb;4871unlink_chunk(m, next, nextsize);4872if (rsize < MIN_CHUNK_SIZE) {4873size_t newsize = oldsize + nextsize;4874set_inuse(m, p, newsize);4875}4876else {4877mchunkptr r = chunk_plus_offset(p, nb);4878set_inuse(m, p, nb);4879set_inuse(m, r, rsize);4880dispose_chunk(m, r, rsize);4881}4882newp = p;4883}4884}4885}4886else {4887USAGE_ERROR_ACTION(m, chunk2mem(p));4888}4889return newp;4890}48914892static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {4893void* mem = 0;4894if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */4895alignment = MIN_CHUNK_SIZE;4896if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */4897size_t a = MALLOC_ALIGNMENT << 1;4898while (a < alignment) a <<= 1;4899alignment = a;4900}4901if (bytes >= MAX_REQUEST - alignment) {4902if (m != 0) { /* Test isn't needed but avoids compiler warning */4903MALLOC_FAILURE_ACTION;4904}4905}4906else {4907size_t nb = request2size(bytes);4908size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;4909mem = internal_malloc(m, req);4910if (mem != 0) {4911mchunkptr p = mem2chunk(mem);4912if (PREACTION(m))4913return 0;4914if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */4915/*4916Find an aligned spot inside chunk. Since we need to give4917back leading space in a chunk of at least MIN_CHUNK_SIZE, if4918the first calculation places us at a spot with less than4919MIN_CHUNK_SIZE leader, we can move to the next aligned spot.4920We've allocated enough total room so that this is always4921possible.4922*/4923char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment -4924SIZE_T_ONE)) &4925-alignment));4926char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?4927br : br+alignment;4928mchunkptr newp = (mchunkptr)pos;4929size_t leadsize = pos - (char*)(p);4930size_t newsize = chunksize(p) - leadsize;49314932if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */4933newp->prev_foot = p->prev_foot + leadsize;4934newp->head = newsize;4935}4936else { /* Otherwise, give back leader, use the rest */4937set_inuse(m, newp, newsize);4938set_inuse(m, p, leadsize);4939dispose_chunk(m, p, leadsize);4940}4941p = newp;4942}49434944/* Give back spare room at the end */4945if (!is_mmapped(p)) {4946size_t size = chunksize(p);4947if (size > nb + MIN_CHUNK_SIZE) {4948size_t remainder_size = size - nb;4949mchunkptr remainder = chunk_plus_offset(p, nb);4950set_inuse(m, p, nb);4951set_inuse(m, remainder, remainder_size);4952dispose_chunk(m, remainder, remainder_size);4953}4954}49554956mem = chunk2mem(p);4957assert (chunksize(p) >= nb);4958assert(((size_t)mem & (alignment - 1)) == 0);4959check_inuse_chunk(m, p);4960POSTACTION(m);4961}4962}4963return mem;4964}49654966/*4967Common support for independent_X routines, handling4968all of the combinations that can result.4969The opts arg has:4970bit 0 set if all elements are same size (using sizes[0])4971bit 1 set if elements should be zeroed4972*/4973static void** ialloc(mstate m,4974size_t n_elements,4975size_t* sizes,4976int opts,4977void* chunks[]) {49784979size_t element_size; /* chunksize of each element, if all same */4980size_t contents_size; /* total size of elements */4981size_t array_size; /* request size of pointer array */4982void* mem; /* malloced aggregate space */4983mchunkptr p; /* corresponding chunk */4984size_t remainder_size; /* remaining bytes while splitting */4985void** marray; /* either "chunks" or malloced ptr array */4986mchunkptr array_chunk; /* chunk for malloced ptr array */4987flag_t was_enabled; /* to disable mmap */4988size_t size;4989size_t i;49904991ensure_initialization();4992/* compute array length, if needed */4993if (chunks != 0) {4994if (n_elements == 0)4995return chunks; /* nothing to do */4996marray = chunks;4997array_size = 0;4998}4999else {5000/* if empty req, must still return chunk representing empty array */5001if (n_elements == 0)5002return (void**)internal_malloc(m, 0);5003marray = 0;5004array_size = request2size(n_elements * (sizeof(void*)));5005}50065007/* compute total element size */5008if (opts & 0x1) { /* all-same-size */5009element_size = request2size(*sizes);5010contents_size = n_elements * element_size;5011}5012else { /* add up all the sizes */5013element_size = 0;5014contents_size = 0;5015for (i = 0; i != n_elements; ++i)5016contents_size += request2size(sizes[i]);5017}50185019size = contents_size + array_size;50205021/*5022Allocate the aggregate chunk. First disable direct-mmapping so5023malloc won't use it, since we would not be able to later5024free/realloc space internal to a segregated mmap region.5025*/5026was_enabled = use_mmap(m);5027disable_mmap(m);5028mem = internal_malloc(m, size - CHUNK_OVERHEAD);5029if (was_enabled)5030enable_mmap(m);5031if (mem == 0)5032return 0;50335034if (PREACTION(m)) return 0;5035p = mem2chunk(mem);5036remainder_size = chunksize(p);50375038assert(!is_mmapped(p));50395040if (opts & 0x2) { /* optionally clear the elements */5041memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);5042}50435044/* If not provided, allocate the pointer array as final part of chunk */5045if (marray == 0) {5046size_t array_chunk_size;5047array_chunk = chunk_plus_offset(p, contents_size);5048array_chunk_size = remainder_size - contents_size;5049marray = (void**) (chunk2mem(array_chunk));5050set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);5051remainder_size = contents_size;5052}50535054/* split out elements */5055for (i = 0; ; ++i) {5056marray[i] = chunk2mem(p);5057if (i != n_elements-1) {5058if (element_size != 0)5059size = element_size;5060else5061size = request2size(sizes[i]);5062remainder_size -= size;5063set_size_and_pinuse_of_inuse_chunk(m, p, size);5064p = chunk_plus_offset(p, size);5065}5066else { /* the final element absorbs any overallocation slop */5067set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);5068break;5069}5070}50715072#if DEBUG5073if (marray != chunks) {5074/* final element must have exactly exhausted chunk */5075if (element_size != 0) {5076assert(remainder_size == element_size);5077}5078else {5079assert(remainder_size == request2size(sizes[i]));5080}5081check_inuse_chunk(m, mem2chunk(marray));5082}5083for (i = 0; i != n_elements; ++i)5084check_inuse_chunk(m, mem2chunk(marray[i]));50855086#endif /* DEBUG */50875088POSTACTION(m);5089return marray;5090}50915092/* Try to free all pointers in the given array.5093Note: this could be made faster, by delaying consolidation,5094at the price of disabling some user integrity checks, We5095still optimize some consolidations by combining adjacent5096chunks before freeing, which will occur often if allocated5097with ialloc or the array is sorted.5098*/5099static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) {5100size_t unfreed = 0;5101if (!PREACTION(m)) {5102void** a;5103void** fence = &(array[nelem]);5104for (a = array; a != fence; ++a) {5105void* mem = *a;5106if (mem != 0) {5107mchunkptr p = mem2chunk(mem);5108size_t psize = chunksize(p);5109#if FOOTERS5110if (get_mstate_for(p) != m) {5111++unfreed;5112continue;5113}5114#endif5115check_inuse_chunk(m, p);5116*a = 0;5117if (RTCHECK(ok_address(m, p) && ok_inuse(p))) {5118void ** b = a + 1; /* try to merge with next chunk */5119mchunkptr next = next_chunk(p);5120if (b != fence && *b == chunk2mem(next)) {5121size_t newsize = chunksize(next) + psize;5122set_inuse(m, p, newsize);5123*b = chunk2mem(p);5124}5125else5126dispose_chunk(m, p, psize);5127}5128else {5129CORRUPTION_ERROR_ACTION(m);5130break;5131}5132}5133}5134if (should_trim(m, m->topsize))5135sys_trim(m, 0);5136POSTACTION(m);5137}5138return unfreed;5139}51405141/* Traversal */5142#if MALLOC_INSPECT_ALL5143static void internal_inspect_all(mstate m,5144void(*handler)(void *start,5145void *end,5146size_t used_bytes,5147void* callback_arg),5148void* arg) {5149if (is_initialized(m)) {5150mchunkptr top = m->top;5151msegmentptr s;5152for (s = &m->seg; s != 0; s = s->next) {5153mchunkptr q = align_as_chunk(s->base);5154while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) {5155mchunkptr next = next_chunk(q);5156size_t sz = chunksize(q);5157size_t used;5158void* start;5159if (is_inuse(q)) {5160used = sz - CHUNK_OVERHEAD; /* must not be mmapped */5161start = chunk2mem(q);5162}5163else {5164used = 0;5165if (is_small(sz)) { /* offset by possible bookkeeping */5166start = (void*)((char*)q + sizeof(struct malloc_chunk));5167}5168else {5169start = (void*)((char*)q + sizeof(struct malloc_tree_chunk));5170}5171}5172if (start < (void*)next) /* skip if all space is bookkeeping */5173handler(start, next, used, arg);5174if (q == top)5175break;5176q = next;5177}5178}5179}5180}5181#endif /* MALLOC_INSPECT_ALL */51825183/* ------------------ Exported realloc, memalign, etc -------------------- */51845185#if !ONLY_MSPACES51865187void* dlrealloc(void* oldmem, size_t bytes) {5188void* mem = 0;5189if (oldmem == 0) {5190mem = dlmalloc(bytes);5191}5192else if (bytes >= MAX_REQUEST) {5193MALLOC_FAILURE_ACTION;5194}5195#ifdef REALLOC_ZERO_BYTES_FREES5196else if (bytes == 0) {5197dlfree(oldmem);5198}5199#endif /* REALLOC_ZERO_BYTES_FREES */5200else {5201size_t nb = request2size(bytes);5202mchunkptr oldp = mem2chunk(oldmem);5203#if ! FOOTERS5204mstate m = gm;5205#else /* FOOTERS */5206mstate m = get_mstate_for(oldp);5207if (!ok_magic(m)) {5208USAGE_ERROR_ACTION(m, oldmem);5209return 0;5210}5211#endif /* FOOTERS */5212if (!PREACTION(m)) {5213mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1);5214POSTACTION(m);5215if (newp != 0) {5216check_inuse_chunk(m, newp);5217mem = chunk2mem(newp);5218}5219else {5220mem = internal_malloc(m, bytes);5221if (mem != 0) {5222size_t oc = chunksize(oldp) - overhead_for(oldp);5223memcpy(mem, oldmem, (oc < bytes)? oc : bytes);5224internal_free(m, oldmem);5225}5226}5227}5228}5229return mem;5230}52315232void* dlrealloc_in_place(void* oldmem, size_t bytes) {5233void* mem = 0;5234if (oldmem != 0) {5235if (bytes >= MAX_REQUEST) {5236MALLOC_FAILURE_ACTION;5237}5238else {5239size_t nb = request2size(bytes);5240mchunkptr oldp = mem2chunk(oldmem);5241#if ! FOOTERS5242mstate m = gm;5243#else /* FOOTERS */5244mstate m = get_mstate_for(oldp);5245if (!ok_magic(m)) {5246USAGE_ERROR_ACTION(m, oldmem);5247return 0;5248}5249#endif /* FOOTERS */5250if (!PREACTION(m)) {5251mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0);5252POSTACTION(m);5253if (newp == oldp) {5254check_inuse_chunk(m, newp);5255mem = oldmem;5256}5257}5258}5259}5260return mem;5261}52625263void* dlmemalign(size_t alignment, size_t bytes) {5264if (alignment <= MALLOC_ALIGNMENT) {5265return dlmalloc(bytes);5266}5267return internal_memalign(gm, alignment, bytes);5268}52695270int dlposix_memalign(void** pp, size_t alignment, size_t bytes) {5271void* mem = 0;5272if (alignment == MALLOC_ALIGNMENT)5273mem = dlmalloc(bytes);5274else {5275size_t d = alignment / sizeof(void*);5276size_t r = alignment % sizeof(void*);5277if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0)5278return EINVAL;5279else if (bytes <= MAX_REQUEST - alignment) {5280if (alignment < MIN_CHUNK_SIZE)5281alignment = MIN_CHUNK_SIZE;5282mem = internal_memalign(gm, alignment, bytes);5283}5284}5285if (mem == 0)5286return ENOMEM;5287else {5288*pp = mem;5289return 0;5290}5291}52925293void* dlvalloc(size_t bytes) {5294size_t pagesz;5295ensure_initialization();5296pagesz = mparams.page_size;5297return dlmemalign(pagesz, bytes);5298}52995300void* dlpvalloc(size_t bytes) {5301size_t pagesz;5302ensure_initialization();5303pagesz = mparams.page_size;5304return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));5305}53065307void** dlindependent_calloc(size_t n_elements, size_t elem_size,5308void* chunks[]) {5309size_t sz = elem_size; /* serves as 1-element array */5310return ialloc(gm, n_elements, &sz, 3, chunks);5311}53125313void** dlindependent_comalloc(size_t n_elements, size_t sizes[],5314void* chunks[]) {5315return ialloc(gm, n_elements, sizes, 0, chunks);5316}53175318size_t dlbulk_free(void* array[], size_t nelem) {5319return internal_bulk_free(gm, array, nelem);5320}53215322#if MALLOC_INSPECT_ALL5323void dlmalloc_inspect_all(void(*handler)(void *start,5324void *end,5325size_t used_bytes,5326void* callback_arg),5327void* arg) {5328ensure_initialization();5329if (!PREACTION(gm)) {5330internal_inspect_all(gm, handler, arg);5331POSTACTION(gm);5332}5333}5334#endif /* MALLOC_INSPECT_ALL */53355336int dlmalloc_trim(size_t pad) {5337int result = 0;5338ensure_initialization();5339if (!PREACTION(gm)) {5340result = sys_trim(gm, pad);5341POSTACTION(gm);5342}5343return result;5344}53455346size_t dlmalloc_footprint(void) {5347return gm->footprint;5348}53495350size_t dlmalloc_max_footprint(void) {5351return gm->max_footprint;5352}53535354size_t dlmalloc_footprint_limit(void) {5355size_t maf = gm->footprint_limit;5356return maf == 0 ? MAX_SIZE_T : maf;5357}53585359size_t dlmalloc_set_footprint_limit(size_t bytes) {5360size_t result; /* invert sense of 0 */5361if (bytes == 0)5362result = granularity_align(1); /* Use minimal size */5363if (bytes == MAX_SIZE_T)5364result = 0; /* disable */5365else5366result = granularity_align(bytes);5367return gm->footprint_limit = result;5368}53695370#if !NO_MALLINFO5371struct mallinfo dlmallinfo(void) {5372return internal_mallinfo(gm);5373}5374#endif /* NO_MALLINFO */53755376#if !NO_MALLOC_STATS5377void dlmalloc_stats() {5378internal_malloc_stats(gm);5379}5380#endif /* NO_MALLOC_STATS */53815382int dlmallopt(int param_number, int value) {5383return change_mparam(param_number, value);5384}53855386size_t dlmalloc_usable_size(void* mem) {5387if (mem != 0) {5388mchunkptr p = mem2chunk(mem);5389if (is_inuse(p))5390return chunksize(p) - overhead_for(p);5391}5392return 0;5393}53945395#endif /* !ONLY_MSPACES */53965397/* ----------------------------- user mspaces ---------------------------- */53985399#if MSPACES54005401static mstate init_user_mstate(char* tbase, size_t tsize) {5402size_t msize = pad_request(sizeof(struct malloc_state));5403mchunkptr mn;5404mchunkptr msp = align_as_chunk(tbase);5405mstate m = (mstate)(chunk2mem(msp));5406memset(m, 0, msize);5407(void)INITIAL_LOCK(&m->mutex);5408msp->head = (msize|INUSE_BITS);5409m->seg.base = m->least_addr = tbase;5410m->seg.size = m->footprint = m->max_footprint = tsize;5411m->magic = mparams.magic;5412m->release_checks = MAX_RELEASE_CHECK_RATE;5413m->mflags = mparams.default_mflags;5414m->extp = 0;5415m->exts = 0;5416disable_contiguous(m);5417init_bins(m);5418mn = next_chunk(mem2chunk(m));5419init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);5420check_top_chunk(m, m->top);5421return m;5422}54235424mspace create_mspace(size_t capacity, int locked) {5425mstate m = 0;5426size_t msize;5427ensure_initialization();5428msize = pad_request(sizeof(struct malloc_state));5429if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {5430size_t rs = ((capacity == 0)? mparams.granularity :5431(capacity + TOP_FOOT_SIZE + msize));5432size_t tsize = granularity_align(rs);5433char* tbase = (char*)(CALL_MMAP(tsize));5434if (tbase != CMFAIL) {5435m = init_user_mstate(tbase, tsize);5436m->seg.sflags = USE_MMAP_BIT;5437set_lock(m, locked);5438}5439}5440return (mspace)m;5441}54425443mspace create_mspace_with_base(void* base, size_t capacity, int locked) {5444mstate m = 0;5445size_t msize;5446ensure_initialization();5447msize = pad_request(sizeof(struct malloc_state));5448if (capacity > msize + TOP_FOOT_SIZE &&5449capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {5450m = init_user_mstate((char*)base, capacity);5451m->seg.sflags = EXTERN_BIT;5452set_lock(m, locked);5453}5454return (mspace)m;5455}54565457int mspace_track_large_chunks(mspace msp, int enable) {5458int ret = 0;5459mstate ms = (mstate)msp;5460if (!PREACTION(ms)) {5461if (!use_mmap(ms)) {5462ret = 1;5463}5464if (!enable) {5465enable_mmap(ms);5466} else {5467disable_mmap(ms);5468}5469POSTACTION(ms);5470}5471return ret;5472}54735474size_t destroy_mspace(mspace msp) {5475size_t freed = 0;5476mstate ms = (mstate)msp;5477if (ok_magic(ms)) {5478msegmentptr sp = &ms->seg;5479(void)DESTROY_LOCK(&ms->mutex); /* destroy before unmapped */5480while (sp != 0) {5481char* base = sp->base;5482size_t size = sp->size;5483flag_t flag = sp->sflags;5484(void)base; /* placate people compiling -Wunused-variable */5485sp = sp->next;5486if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) &&5487CALL_MUNMAP(base, size) == 0)5488freed += size;5489}5490}5491else {5492USAGE_ERROR_ACTION(ms,ms);5493}5494return freed;5495}54965497/*5498mspace versions of routines are near-clones of the global5499versions. This is not so nice but better than the alternatives.5500*/55015502void* mspace_malloc(mspace msp, size_t bytes) {5503mstate ms = (mstate)msp;5504if (!ok_magic(ms)) {5505USAGE_ERROR_ACTION(ms,ms);5506return 0;5507}5508if (!PREACTION(ms)) {5509void* mem;5510size_t nb;5511if (bytes <= MAX_SMALL_REQUEST) {5512bindex_t idx;5513binmap_t smallbits;5514nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);5515idx = small_index(nb);5516smallbits = ms->smallmap >> idx;55175518if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */5519mchunkptr b, p;5520idx += ~smallbits & 1; /* Uses next bin if idx empty */5521b = smallbin_at(ms, idx);5522p = b->fd;5523assert(chunksize(p) == small_index2size(idx));5524unlink_first_small_chunk(ms, b, p, idx);5525set_inuse_and_pinuse(ms, p, small_index2size(idx));5526mem = chunk2mem(p);5527check_malloced_chunk(ms, mem, nb);5528goto postaction;5529}55305531else if (nb > ms->dvsize) {5532if (smallbits != 0) { /* Use chunk in next nonempty smallbin */5533mchunkptr b, p, r;5534size_t rsize;5535bindex_t i;5536binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));5537binmap_t leastbit = least_bit(leftbits);5538compute_bit2idx(leastbit, i);5539b = smallbin_at(ms, i);5540p = b->fd;5541assert(chunksize(p) == small_index2size(i));5542unlink_first_small_chunk(ms, b, p, i);5543rsize = small_index2size(i) - nb;5544/* Fit here cannot be remainderless if 4byte sizes */5545if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)5546set_inuse_and_pinuse(ms, p, small_index2size(i));5547else {5548set_size_and_pinuse_of_inuse_chunk(ms, p, nb);5549r = chunk_plus_offset(p, nb);5550set_size_and_pinuse_of_free_chunk(r, rsize);5551replace_dv(ms, r, rsize);5552}5553mem = chunk2mem(p);5554check_malloced_chunk(ms, mem, nb);5555goto postaction;5556}55575558else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {5559check_malloced_chunk(ms, mem, nb);5560goto postaction;5561}5562}5563}5564else if (bytes >= MAX_REQUEST)5565nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */5566else {5567nb = pad_request(bytes);5568if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {5569check_malloced_chunk(ms, mem, nb);5570goto postaction;5571}5572}55735574if (nb <= ms->dvsize) {5575size_t rsize = ms->dvsize - nb;5576mchunkptr p = ms->dv;5577if (rsize >= MIN_CHUNK_SIZE) { /* split dv */5578mchunkptr r = ms->dv = chunk_plus_offset(p, nb);5579ms->dvsize = rsize;5580set_size_and_pinuse_of_free_chunk(r, rsize);5581set_size_and_pinuse_of_inuse_chunk(ms, p, nb);5582}5583else { /* exhaust dv */5584size_t dvs = ms->dvsize;5585ms->dvsize = 0;5586ms->dv = 0;5587set_inuse_and_pinuse(ms, p, dvs);5588}5589mem = chunk2mem(p);5590check_malloced_chunk(ms, mem, nb);5591goto postaction;5592}55935594else if (nb < ms->topsize) { /* Split top */5595size_t rsize = ms->topsize -= nb;5596mchunkptr p = ms->top;5597mchunkptr r = ms->top = chunk_plus_offset(p, nb);5598r->head = rsize | PINUSE_BIT;5599set_size_and_pinuse_of_inuse_chunk(ms, p, nb);5600mem = chunk2mem(p);5601check_top_chunk(ms, ms->top);5602check_malloced_chunk(ms, mem, nb);5603goto postaction;5604}56055606mem = sys_alloc(ms, nb);56075608postaction:5609POSTACTION(ms);5610return mem;5611}56125613return 0;5614}56155616void mspace_free(mspace msp, void* mem) {5617if (mem != 0) {5618mchunkptr p = mem2chunk(mem);5619#if FOOTERS5620mstate fm = get_mstate_for(p);5621(void)msp; /* placate people compiling -Wunused */5622#else /* FOOTERS */5623mstate fm = (mstate)msp;5624#endif /* FOOTERS */5625if (!ok_magic(fm)) {5626USAGE_ERROR_ACTION(fm, p);5627return;5628}5629if (!PREACTION(fm)) {5630check_inuse_chunk(fm, p);5631if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {5632size_t psize = chunksize(p);5633mchunkptr next = chunk_plus_offset(p, psize);5634if (!pinuse(p)) {5635size_t prevsize = p->prev_foot;5636if (is_mmapped(p)) {5637psize += prevsize + MMAP_FOOT_PAD;5638if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)5639fm->footprint -= psize;5640goto postaction;5641}5642else {5643mchunkptr prev = chunk_minus_offset(p, prevsize);5644psize += prevsize;5645p = prev;5646if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */5647if (p != fm->dv) {5648unlink_chunk(fm, p, prevsize);5649}5650else if ((next->head & INUSE_BITS) == INUSE_BITS) {5651fm->dvsize = psize;5652set_free_with_pinuse(p, psize, next);5653goto postaction;5654}5655}5656else5657goto erroraction;5658}5659}56605661if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {5662if (!cinuse(next)) { /* consolidate forward */5663if (next == fm->top) {5664size_t tsize = fm->topsize += psize;5665fm->top = p;5666p->head = tsize | PINUSE_BIT;5667if (p == fm->dv) {5668fm->dv = 0;5669fm->dvsize = 0;5670}5671if (should_trim(fm, tsize))5672sys_trim(fm, 0);5673goto postaction;5674}5675else if (next == fm->dv) {5676size_t dsize = fm->dvsize += psize;5677fm->dv = p;5678set_size_and_pinuse_of_free_chunk(p, dsize);5679goto postaction;5680}5681else {5682size_t nsize = chunksize(next);5683psize += nsize;5684unlink_chunk(fm, next, nsize);5685set_size_and_pinuse_of_free_chunk(p, psize);5686if (p == fm->dv) {5687fm->dvsize = psize;5688goto postaction;5689}5690}5691}5692else5693set_free_with_pinuse(p, psize, next);56945695if (is_small(psize)) {5696insert_small_chunk(fm, p, psize);5697check_free_chunk(fm, p);5698}5699else {5700tchunkptr tp = (tchunkptr)p;5701insert_large_chunk(fm, tp, psize);5702check_free_chunk(fm, p);5703if (--fm->release_checks == 0)5704release_unused_segments(fm);5705}5706goto postaction;5707}5708}5709erroraction:5710USAGE_ERROR_ACTION(fm, p);5711postaction:5712POSTACTION(fm);5713}5714}5715}57165717void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {5718void* mem;5719size_t req = 0;5720mstate ms = (mstate)msp;5721if (!ok_magic(ms)) {5722USAGE_ERROR_ACTION(ms,ms);5723return 0;5724}5725if (n_elements != 0) {5726req = n_elements * elem_size;5727if (((n_elements | elem_size) & ~(size_t)0xffff) &&5728(req / n_elements != elem_size))5729req = MAX_SIZE_T; /* force downstream failure on overflow */5730}5731mem = internal_malloc(ms, req);5732if (mem != 0 && calloc_must_clear(mem2chunk(mem)))5733memset(mem, 0, req);5734return mem;5735}57365737void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {5738void* mem = 0;5739if (oldmem == 0) {5740mem = mspace_malloc(msp, bytes);5741}5742else if (bytes >= MAX_REQUEST) {5743MALLOC_FAILURE_ACTION;5744}5745#ifdef REALLOC_ZERO_BYTES_FREES5746else if (bytes == 0) {5747mspace_free(msp, oldmem);5748}5749#endif /* REALLOC_ZERO_BYTES_FREES */5750else {5751size_t nb = request2size(bytes);5752mchunkptr oldp = mem2chunk(oldmem);5753#if ! FOOTERS5754mstate m = (mstate)msp;5755#else /* FOOTERS */5756mstate m = get_mstate_for(oldp);5757if (!ok_magic(m)) {5758USAGE_ERROR_ACTION(m, oldmem);5759return 0;5760}5761#endif /* FOOTERS */5762if (!PREACTION(m)) {5763mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1);5764POSTACTION(m);5765if (newp != 0) {5766check_inuse_chunk(m, newp);5767mem = chunk2mem(newp);5768}5769else {5770mem = mspace_malloc(m, bytes);5771if (mem != 0) {5772size_t oc = chunksize(oldp) - overhead_for(oldp);5773memcpy(mem, oldmem, (oc < bytes)? oc : bytes);5774mspace_free(m, oldmem);5775}5776}5777}5778}5779return mem;5780}57815782void* mspace_realloc_in_place(mspace msp, void* oldmem, size_t bytes) {5783void* mem = 0;5784if (oldmem != 0) {5785if (bytes >= MAX_REQUEST) {5786MALLOC_FAILURE_ACTION;5787}5788else {5789size_t nb = request2size(bytes);5790mchunkptr oldp = mem2chunk(oldmem);5791#if ! FOOTERS5792mstate m = (mstate)msp;5793#else /* FOOTERS */5794mstate m = get_mstate_for(oldp);5795(void)msp; /* placate people compiling -Wunused */5796if (!ok_magic(m)) {5797USAGE_ERROR_ACTION(m, oldmem);5798return 0;5799}5800#endif /* FOOTERS */5801if (!PREACTION(m)) {5802mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0);5803POSTACTION(m);5804if (newp == oldp) {5805check_inuse_chunk(m, newp);5806mem = oldmem;5807}5808}5809}5810}5811return mem;5812}58135814void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {5815mstate ms = (mstate)msp;5816if (!ok_magic(ms)) {5817USAGE_ERROR_ACTION(ms,ms);5818return 0;5819}5820if (alignment <= MALLOC_ALIGNMENT)5821return mspace_malloc(msp, bytes);5822return internal_memalign(ms, alignment, bytes);5823}58245825void** mspace_independent_calloc(mspace msp, size_t n_elements,5826size_t elem_size, void* chunks[]) {5827size_t sz = elem_size; /* serves as 1-element array */5828mstate ms = (mstate)msp;5829if (!ok_magic(ms)) {5830USAGE_ERROR_ACTION(ms,ms);5831return 0;5832}5833return ialloc(ms, n_elements, &sz, 3, chunks);5834}58355836void** mspace_independent_comalloc(mspace msp, size_t n_elements,5837size_t sizes[], void* chunks[]) {5838mstate ms = (mstate)msp;5839if (!ok_magic(ms)) {5840USAGE_ERROR_ACTION(ms,ms);5841return 0;5842}5843return ialloc(ms, n_elements, sizes, 0, chunks);5844}58455846size_t mspace_bulk_free(mspace msp, void* array[], size_t nelem) {5847return internal_bulk_free((mstate)msp, array, nelem);5848}58495850#if MALLOC_INSPECT_ALL5851void mspace_inspect_all(mspace msp,5852void(*handler)(void *start,5853void *end,5854size_t used_bytes,5855void* callback_arg),5856void* arg) {5857mstate ms = (mstate)msp;5858if (ok_magic(ms)) {5859if (!PREACTION(ms)) {5860internal_inspect_all(ms, handler, arg);5861POSTACTION(ms);5862}5863}5864else {5865USAGE_ERROR_ACTION(ms,ms);5866}5867}5868#endif /* MALLOC_INSPECT_ALL */58695870int mspace_trim(mspace msp, size_t pad) {5871int result = 0;5872mstate ms = (mstate)msp;5873if (ok_magic(ms)) {5874if (!PREACTION(ms)) {5875result = sys_trim(ms, pad);5876POSTACTION(ms);5877}5878}5879else {5880USAGE_ERROR_ACTION(ms,ms);5881}5882return result;5883}58845885#if !NO_MALLOC_STATS5886void mspace_malloc_stats(mspace msp) {5887mstate ms = (mstate)msp;5888if (ok_magic(ms)) {5889internal_malloc_stats(ms);5890}5891else {5892USAGE_ERROR_ACTION(ms,ms);5893}5894}5895#endif /* NO_MALLOC_STATS */58965897size_t mspace_footprint(mspace msp) {5898size_t result = 0;5899mstate ms = (mstate)msp;5900if (ok_magic(ms)) {5901result = ms->footprint;5902}5903else {5904USAGE_ERROR_ACTION(ms,ms);5905}5906return result;5907}59085909size_t mspace_max_footprint(mspace msp) {5910size_t result = 0;5911mstate ms = (mstate)msp;5912if (ok_magic(ms)) {5913result = ms->max_footprint;5914}5915else {5916USAGE_ERROR_ACTION(ms,ms);5917}5918return result;5919}59205921size_t mspace_footprint_limit(mspace msp) {5922size_t result = 0;5923mstate ms = (mstate)msp;5924if (ok_magic(ms)) {5925size_t maf = ms->footprint_limit;5926result = (maf == 0) ? MAX_SIZE_T : maf;5927}5928else {5929USAGE_ERROR_ACTION(ms,ms);5930}5931return result;5932}59335934size_t mspace_set_footprint_limit(mspace msp, size_t bytes) {5935size_t result = 0;5936mstate ms = (mstate)msp;5937if (ok_magic(ms)) {5938if (bytes == 0)5939result = granularity_align(1); /* Use minimal size */5940if (bytes == MAX_SIZE_T)5941result = 0; /* disable */5942else5943result = granularity_align(bytes);5944ms->footprint_limit = result;5945}5946else {5947USAGE_ERROR_ACTION(ms,ms);5948}5949return result;5950}59515952#if !NO_MALLINFO5953struct mallinfo mspace_mallinfo(mspace msp) {5954mstate ms = (mstate)msp;5955if (!ok_magic(ms)) {5956USAGE_ERROR_ACTION(ms,ms);5957}5958return internal_mallinfo(ms);5959}5960#endif /* NO_MALLINFO */59615962size_t mspace_usable_size(const void* mem) {5963if (mem != 0) {5964mchunkptr p = mem2chunk(mem);5965if (is_inuse(p))5966return chunksize(p) - overhead_for(p);5967}5968return 0;5969}59705971int mspace_mallopt(int param_number, int value) {5972return change_mparam(param_number, value);5973}59745975#endif /* MSPACES */597659775978/* -------------------- Alternative MORECORE functions ------------------- */59795980/*5981Guidelines for creating a custom version of MORECORE:59825983* For best performance, MORECORE should allocate in multiples of pagesize.5984* MORECORE may allocate more memory than requested. (Or even less,5985but this will usually result in a malloc failure.)5986* MORECORE must not allocate memory when given argument zero, but5987instead return one past the end address of memory from previous5988nonzero call.5989* For best performance, consecutive calls to MORECORE with positive5990arguments should return increasing addresses, indicating that5991space has been contiguously extended.5992* Even though consecutive calls to MORECORE need not return contiguous5993addresses, it must be OK for malloc'ed chunks to span multiple5994regions in those cases where they do happen to be contiguous.5995* MORECORE need not handle negative arguments -- it may instead5996just return MFAIL when given negative arguments.5997Negative arguments are always multiples of pagesize. MORECORE5998must not misinterpret negative args as large positive unsigned5999args. You can suppress all such calls from even occurring by defining6000MORECORE_CANNOT_TRIM,60016002As an example alternative MORECORE, here is a custom allocator6003kindly contributed for pre-OSX macOS. It uses virtually but not6004necessarily physically contiguous non-paged memory (locked in,6005present and won't get swapped out). You can use it by uncommenting6006this section, adding some #includes, and setting up the appropriate6007defines above:60086009#define MORECORE osMoreCore60106011There is also a shutdown routine that should somehow be called for6012cleanup upon program exit.60136014#define MAX_POOL_ENTRIES 1006015#define MINIMUM_MORECORE_SIZE (64 * 1024U)6016static int next_os_pool;6017void *our_os_pools[MAX_POOL_ENTRIES];60186019void *osMoreCore(int size)6020{6021void *ptr = 0;6022static void *sbrk_top = 0;60236024if (size > 0)6025{6026if (size < MINIMUM_MORECORE_SIZE)6027size = MINIMUM_MORECORE_SIZE;6028if (CurrentExecutionLevel() == kTaskLevel)6029ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);6030if (ptr == 0)6031{6032return (void *) MFAIL;6033}6034// save ptrs so they can be freed during cleanup6035our_os_pools[next_os_pool] = ptr;6036next_os_pool++;6037ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);6038sbrk_top = (char *) ptr + size;6039return ptr;6040}6041else if (size < 0)6042{6043// we don't currently support shrink behavior6044return (void *) MFAIL;6045}6046else6047{6048return sbrk_top;6049}6050}60516052// cleanup any allocated memory pools6053// called as last thing before shutting down driver60546055void osCleanupMem(void)6056{6057void **ptr;60586059for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)6060if (*ptr)6061{6062PoolDeallocate(*ptr);6063*ptr = 0;6064}6065}60666067*/606860696070/* -----------------------------------------------------------------------6071History:6072v2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea6073* fix bad comparison in dlposix_memalign6074* don't reuse adjusted asize in sys_alloc6075* add LOCK_AT_FORK -- thanks to Kirill Artamonov for the suggestion6076* reduce compiler warnings -- thanks to all who reported/suggested these60776078v2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee)6079* Always perform unlink checks unless INSECURE6080* Add posix_memalign.6081* Improve realloc to expand in more cases; expose realloc_in_place.6082Thanks to Peter Buhr for the suggestion.6083* Add footprint_limit, inspect_all, bulk_free. Thanks6084to Barry Hayes and others for the suggestions.6085* Internal refactorings to avoid calls while holding locks6086* Use non-reentrant locks by default. Thanks to Roland McGrath6087for the suggestion.6088* Small fixes to mspace_destroy, reset_on_error.6089* Various configuration extensions/changes. Thanks6090to all who contributed these.60916092V2.8.4a Thu Apr 28 14:39:43 2011 (dl at gee.cs.oswego.edu)6093* Update Creative Commons URL60946095V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee)6096* Use zeros instead of prev foot for is_mmapped6097* Add mspace_track_large_chunks; thanks to Jean Brouwers6098* Fix set_inuse in internal_realloc; thanks to Jean Brouwers6099* Fix insufficient sys_alloc padding when using 16byte alignment6100* Fix bad error check in mspace_footprint6101* Adaptations for ptmalloc; thanks to Wolfram Gloger.6102* Reentrant spin locks; thanks to Earl Chew and others6103* Win32 improvements; thanks to Niall Douglas and Earl Chew6104* Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options6105* Extension hook in malloc_state6106* Various small adjustments to reduce warnings on some compilers6107* Various configuration extensions/changes for more platforms. Thanks6108to all who contributed these.61096110V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)6111* Add max_footprint functions6112* Ensure all appropriate literals are size_t6113* Fix conditional compilation problem for some #define settings6114* Avoid concatenating segments with the one provided6115in create_mspace_with_base6116* Rename some variables to avoid compiler shadowing warnings6117* Use explicit lock initialization.6118* Better handling of sbrk interference.6119* Simplify and fix segment insertion, trimming and mspace_destroy6120* Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x6121* Thanks especially to Dennis Flanagan for help on these.61226123V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)6124* Fix memalign brace error.61256126V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)6127* Fix improper #endif nesting in C++6128* Add explicit casts needed for C++61296130V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)6131* Use trees for large bins6132* Support mspaces6133* Use segments to unify sbrk-based and mmap-based system allocation,6134removing need for emulation on most platforms without sbrk.6135* Default safety checks6136* Optional footer checks. Thanks to William Robertson for the idea.6137* Internal code refactoring6138* Incorporate suggestions and platform-specific changes.6139Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,6140Aaron Bachmann, Emery Berger, and others.6141* Speed up non-fastbin processing enough to remove fastbins.6142* Remove useless cfree() to avoid conflicts with other apps.6143* Remove internal memcpy, memset. Compilers handle builtins better.6144* Remove some options that no one ever used and rename others.61456146V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)6147* Fix malloc_state bitmap array misdeclaration61486149V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)6150* Allow tuning of FIRST_SORTED_BIN_SIZE6151* Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.6152* Better detection and support for non-contiguousness of MORECORE.6153Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger6154* Bypass most of malloc if no frees. Thanks To Emery Berger.6155* Fix freeing of old top non-contiguous chunk im sysmalloc.6156* Raised default trim and map thresholds to 256K.6157* Fix mmap-related #defines. Thanks to Lubos Lunak.6158* Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.6159* Branch-free bin calculation6160* Default trim and mmap thresholds now 256K.61616162V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)6163* Introduce independent_comalloc and independent_calloc.6164Thanks to Michael Pachos for motivation and help.6165* Make optional .h file available6166* Allow > 2GB requests on 32bit systems.6167* new WIN32 sbrk, mmap, munmap, lock code from <[email protected]>.6168Thanks also to Andreas Mueller <a.mueller at paradatec.de>,6169and Anonymous.6170* Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for6171helping test this.)6172* memalign: check alignment arg6173* realloc: don't try to shift chunks backwards, since this6174leads to more fragmentation in some programs and doesn't6175seem to help in any others.6176* Collect all cases in malloc requiring system memory into sysmalloc6177* Use mmap as backup to sbrk6178* Place all internal state in malloc_state6179* Introduce fastbins (although similar to 2.5.1)6180* Many minor tunings and cosmetic improvements6181* Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK6182* Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS6183Thanks to Tony E. Bennett <[email protected]> and others.6184* Include errno.h to support default failure action.61856186V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)6187* return null for negative arguments6188* Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>6189* Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'6190(e.g. WIN32 platforms)6191* Cleanup header file inclusion for WIN32 platforms6192* Cleanup code to avoid Microsoft Visual C++ compiler complaints6193* Add 'USE_DL_PREFIX' to quickly allow co-existence with existing6194memory allocation routines6195* Set 'malloc_getpagesize' for WIN32 platforms (needs more work)6196* Use 'assert' rather than 'ASSERT' in WIN32 code to conform to6197usage of 'assert' in non-WIN32 code6198* Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to6199avoid infinite loop6200* Always call 'fREe()' rather than 'free()'62016202V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)6203* Fixed ordering problem with boundary-stamping62046205V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)6206* Added pvalloc, as recommended by H.J. Liu6207* Added 64bit pointer support mainly from Wolfram Gloger6208* Added anonymously donated WIN32 sbrk emulation6209* Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen6210* malloc_extend_top: fix mask error that caused wastage after6211foreign sbrks6212* Add linux mremap support code from HJ Liu62136214V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)6215* Integrated most documentation with the code.6216* Add support for mmap, with help from6217Wolfram Gloger ([email protected]).6218* Use last_remainder in more cases.6219* Pack bins using idea from [email protected]6220* Use ordered bins instead of best-fit threshhold6221* Eliminate block-local decls to simplify tracing and debugging.6222* Support another case of realloc via move into top6223* Fix error occuring when initial sbrk_base not word-aligned.6224* Rely on page size for units instead of SBRK_UNIT to6225avoid surprises about sbrk alignment conventions.6226* Add mallinfo, mallopt. Thanks to Raymond Nijssen6227([email protected]) for the suggestion.6228* Add `pad' argument to malloc_trim and top_pad mallopt parameter.6229* More precautions for cases where other routines call sbrk,6230courtesy of Wolfram Gloger ([email protected]).6231* Added macros etc., allowing use in linux libc from6232H.J. Lu ([email protected])6233* Inverted this history list62346235V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)6236* Re-tuned and fixed to behave more nicely with V2.6.0 changes.6237* Removed all preallocation code since under current scheme6238the work required to undo bad preallocations exceeds6239the work saved in good cases for most test programs.6240* No longer use return list or unconsolidated bins since6241no scheme using them consistently outperforms those that don't6242given above changes.6243* Use best fit for very large chunks to prevent some worst-cases.6244* Added some support for debugging62456246V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)6247* Removed footers when chunks are in use. Thanks to6248Paul Wilson ([email protected]) for the suggestion.62496250V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)6251* Added malloc_trim, with help from Wolfram Gloger6252([email protected]).62536254V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)62556256V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)6257* realloc: try to expand in both directions6258* malloc: swap order of clean-bin strategy;6259* realloc: only conditionally expand backwards6260* Try not to scavenge used bins6261* Use bin counts as a guide to preallocation6262* Occasionally bin return list chunks in first scan6263* Add a few optimizations from [email protected]62646265V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)6266* faster bin computation & slightly different binning6267* merged all consolidations to one part of malloc proper6268(eliminating old malloc_find_space & malloc_clean_bin)6269* Scan 2 returns chunks (not just 1)6270* Propagate failure in realloc if malloc returns 06271* Add stuff to allow compilation on non-ANSI compilers6272from [email protected]62736274V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)6275* removed potential for odd address access in prev_chunk6276* removed dependency on getpagesize.h6277* misc cosmetics and a bit more internal documentation6278* anticosmetics: mangled names in macros to evade debugger strangeness6279* tested on sparc, hp-700, dec-mips, rs60006280with gcc & native cc (hp, dec only) allowing6281Detlefs & Zorn comparison study (in SIGPLAN Notices.)62826283Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)6284* Based loosely on libg++-1.2X malloc. (It retains some of the overall6285structure of old version, but most details differ.)62866287*/6288#endif628962906291