HACK
[asbestos.git] / stage2 / malloc.c
blob61884ea1fdc88734a4ea8c97b160b80996b6325c
1 /*
2 This is a version (aka dlmalloc) of malloc/free/realloc written by
3 Doug Lea and released to the public domain, as explained at
4 http://creativecommons.org/licenses/publicdomain. Send questions,
5 comments, complaints, performance data, etc to dl@cs.oswego.edu
7 * Version 2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee)
9 Note: There may be an updated version of this malloc obtainable at
10 ftp://gee.cs.oswego.edu/pub/misc/malloc.c
11 Check before installing!
13 * Quickstart
15 This library is all in one file to simplify the most common usage:
16 ftp it, compile it (-O3), and link it into another program. All of
17 the compile-time options default to reasonable values for use on
18 most platforms. You might later want to step through various
19 compile-time and dynamic tuning options.
21 For convenience, an include file for code using this malloc is at:
22 ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.4.h
23 You don't really need this .h file unless you call functions not
24 defined in your system include files. The .h file contains only the
25 excerpts from this file needed for using this malloc on ANSI C/C++
26 systems, so long as you haven't changed compile-time options about
27 naming and tuning parameters. If you do, then you can create your
28 own malloc.h that does include all settings by cutting at the point
29 indicated below. Note that you may already by default be using a C
30 library containing a malloc that is based on some version of this
31 malloc (for example in linux). You might still want to use the one
32 in this file to customize settings or to avoid overheads associated
33 with library versions.
35 * Vital statistics:
37 Supported pointer/size_t representation: 4 or 8 bytes
38 size_t MUST be an unsigned type of the same width as
39 pointers. (If you are using an ancient system that declares
40 size_t as a signed type, or need it to be a different width
41 than pointers, you can use a previous release of this malloc
42 (e.g. 2.7.2) supporting these.)
44 Alignment: 8 bytes (default)
45 This suffices for nearly all current machines and C compilers.
46 However, you can define MALLOC_ALIGNMENT to be wider than this
47 if necessary (up to 128bytes), at the expense of using more space.
49 Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
50 8 or 16 bytes (if 8byte sizes)
51 Each malloced chunk has a hidden word of overhead holding size
52 and status information, and additional cross-check word
53 if FOOTERS is defined.
55 Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
56 8-byte ptrs: 32 bytes (including overhead)
58 Even a request for zero bytes (i.e., malloc(0)) returns a
59 pointer to something of the minimum allocatable size.
60 The maximum overhead wastage (i.e., number of extra bytes
61 allocated than were requested in malloc) is less than or equal
62 to the minimum size, except for requests >= mmap_threshold that
63 are serviced via mmap(), where the worst case wastage is about
64 32 bytes plus the remainder from a system page (the minimal
65 mmap unit); typically 4096 or 8192 bytes.
67 Security: static-safe; optionally more or less
68 The "security" of malloc refers to the ability of malicious
69 code to accentuate the effects of errors (for example, freeing
70 space that is not currently malloc'ed or overwriting past the
71 ends of chunks) in code that calls malloc. This malloc
72 guarantees not to modify any memory locations below the base of
73 heap, i.e., static variables, even in the presence of usage
74 errors. The routines additionally detect most improper frees
75 and reallocs. All this holds as long as the static bookkeeping
76 for malloc itself is not corrupted by some other means. This
77 is only one aspect of security -- these checks do not, and
78 cannot, detect all possible programming errors.
80 If FOOTERS is defined nonzero, then each allocated chunk
81 carries an additional check word to verify that it was malloced
82 from its space. These check words are the same within each
83 execution of a program using malloc, but differ across
84 executions, so externally crafted fake chunks cannot be
85 freed. This improves security by rejecting frees/reallocs that
86 could corrupt heap memory, in addition to the checks preventing
87 writes to statics that are always on. This may further improve
88 security at the expense of time and space overhead. (Note that
89 FOOTERS may also be worth using with MSPACES.)
91 By default detected errors cause the program to abort (calling
92 "abort()"). You can override this to instead proceed past
93 errors by defining PROCEED_ON_ERROR. In this case, a bad free
94 has no effect, and a malloc that encounters a bad address
95 caused by user overwrites will ignore the bad address by
96 dropping pointers and indices to all known memory. This may
97 be appropriate for programs that should continue if at all
98 possible in the face of programming errors, although they may
99 run out of memory because dropped memory is never reclaimed.
101 If you don't like either of these options, you can define
102 CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
103 else. And if if you are sure that your program using malloc has
104 no errors or vulnerabilities, you can define INSECURE to 1,
105 which might (or might not) provide a small performance improvement.
107 Thread-safety: NOT thread-safe unless USE_LOCKS defined
108 When USE_LOCKS is defined, each public call to malloc, free,
109 etc is surrounded with either a pthread mutex or a win32
110 spinlock (depending on WIN32). This is not especially fast, and
111 can be a major bottleneck. It is designed only to provide
112 minimal protection in concurrent environments, and to provide a
113 basis for extensions. If you are using malloc in a concurrent
114 program, consider instead using nedmalloc
115 (http://www.nedprod.com/programs/portable/nedmalloc/) or
116 ptmalloc (See http://www.malloc.de), which are derived
117 from versions of this malloc.
119 System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
120 This malloc can use unix sbrk or any emulation (invoked using
121 the CALL_MORECORE macro) and/or mmap/munmap or any emulation
122 (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
123 memory. On most unix systems, it tends to work best if both
124 MORECORE and MMAP are enabled. On Win32, it uses emulations
125 based on VirtualAlloc. It also uses common C library functions
126 like memset.
128 Compliance: I believe it is compliant with the Single Unix Specification
129 (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
130 others as well.
132 * Overview of algorithms
134 This is not the fastest, most space-conserving, most portable, or
135 most tunable malloc ever written. However it is among the fastest
136 while also being among the most space-conserving, portable and
137 tunable. Consistent balance across these factors results in a good
138 general-purpose allocator for malloc-intensive programs.
140 In most ways, this malloc is a best-fit allocator. Generally, it
141 chooses the best-fitting existing chunk for a request, with ties
142 broken in approximately least-recently-used order. (This strategy
143 normally maintains low fragmentation.) However, for requests less
144 than 256bytes, it deviates from best-fit when there is not an
145 exactly fitting available chunk by preferring to use space adjacent
146 to that used for the previous small request, as well as by breaking
147 ties in approximately most-recently-used order. (These enhance
148 locality of series of small allocations.) And for very large requests
149 (>= 256Kb by default), it relies on system memory mapping
150 facilities, if supported. (This helps avoid carrying around and
151 possibly fragmenting memory used only for large chunks.)
153 All operations (except malloc_stats and mallinfo) have execution
154 times that are bounded by a constant factor of the number of bits in
155 a size_t, not counting any clearing in calloc or copying in realloc,
156 or actions surrounding MORECORE and MMAP that have times
157 proportional to the number of non-contiguous regions returned by
158 system allocation routines, which is often just 1. In real-time
159 applications, you can optionally suppress segment traversals using
160 NO_SEGMENT_TRAVERSAL, which assures bounded execution even when
161 system allocators return non-contiguous spaces, at the typical
162 expense of carrying around more memory and increased fragmentation.
164 The implementation is not very modular and seriously overuses
165 macros. Perhaps someday all C compilers will do as good a job
166 inlining modular code as can now be done by brute-force expansion,
167 but now, enough of them seem not to.
169 Some compilers issue a lot of warnings about code that is
170 dead/unreachable only on some platforms, and also about intentional
171 uses of negation on unsigned types. All known cases of each can be
172 ignored.
174 For a longer but out of date high-level description, see
175 http://gee.cs.oswego.edu/dl/html/malloc.html
177 * MSPACES
178 If MSPACES is defined, then in addition to malloc, free, etc.,
179 this file also defines mspace_malloc, mspace_free, etc. These
180 are versions of malloc routines that take an "mspace" argument
181 obtained using create_mspace, to control all internal bookkeeping.
182 If ONLY_MSPACES is defined, only these versions are compiled.
183 So if you would like to use this allocator for only some allocations,
184 and your system malloc for others, you can compile with
185 ONLY_MSPACES and then do something like...
186 static mspace mymspace = create_mspace(0,0); // for example
187 #define mymalloc(bytes) mspace_malloc(mymspace, bytes)
189 (Note: If you only need one instance of an mspace, you can instead
190 use "USE_DL_PREFIX" to relabel the global malloc.)
192 You can similarly create thread-local allocators by storing
193 mspaces as thread-locals. For example:
194 static __thread mspace tlms = 0;
195 void* tlmalloc(size_t bytes) {
196 if (tlms == 0) tlms = create_mspace(0, 0);
197 return mspace_malloc(tlms, bytes);
199 void tlfree(void* mem) { mspace_free(tlms, mem); }
201 Unless FOOTERS is defined, each mspace is completely independent.
202 You cannot allocate from one and free to another (although
203 conformance is only weakly checked, so usage errors are not always
204 caught). If FOOTERS is defined, then each chunk carries around a tag
205 indicating its originating mspace, and frees are directed to their
206 originating spaces.
208 ------------------------- Compile-time options ---------------------------
210 Be careful in setting #define values for numerical constants of type
211 size_t. On some systems, literal values are not automatically extended
212 to size_t precision unless they are explicitly casted. You can also
213 use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.
215 WIN32 default: defined if _WIN32 defined
216 Defining WIN32 sets up defaults for MS environment and compilers.
217 Otherwise defaults are for unix. Beware that there seem to be some
218 cases where this malloc might not be a pure drop-in replacement for
219 Win32 malloc: Random-looking failures from Win32 GDI API's (eg;
220 SetDIBits()) may be due to bugs in some video driver implementations
221 when pixel buffers are malloc()ed, and the region spans more than
222 one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb)
223 default granularity, pixel buffers may straddle virtual allocation
224 regions more often than when using the Microsoft allocator. You can
225 avoid this by using VirtualAlloc() and VirtualFree() for all pixel
226 buffers rather than using malloc(). If this is not possible,
227 recompile this malloc with a larger DEFAULT_GRANULARITY.
229 MALLOC_ALIGNMENT default: (size_t)8
230 Controls the minimum alignment for malloc'ed chunks. It must be a
231 power of two and at least 8, even on machines for which smaller
232 alignments would suffice. It may be defined as larger than this
233 though. Note however that code and data structures are optimized for
234 the case of 8-byte alignment.
236 MSPACES default: 0 (false)
237 If true, compile in support for independent allocation spaces.
238 This is only supported if HAVE_MMAP is true.
240 ONLY_MSPACES default: 0 (false)
241 If true, only compile in mspace versions, not regular versions.
243 USE_LOCKS default: 0 (false)
244 Causes each call to each public routine to be surrounded with
245 pthread or WIN32 mutex lock/unlock. (If set true, this can be
246 overridden on a per-mspace basis for mspace versions.) If set to a
247 non-zero value other than 1, locks are used, but their
248 implementation is left out, so lock functions must be supplied manually,
249 as described below.
251 USE_SPIN_LOCKS default: 1 iff USE_LOCKS and on x86 using gcc or MSC
252 If true, uses custom spin locks for locking. This is currently
253 supported only for x86 platforms using gcc or recent MS compilers.
254 Otherwise, posix locks or win32 critical sections are used.
256 FOOTERS default: 0
257 If true, provide extra checking and dispatching by placing
258 information in the footers of allocated chunks. This adds
259 space and time overhead.
261 INSECURE default: 0
262 If true, omit checks for usage errors and heap space overwrites.
264 USE_DL_PREFIX default: NOT defined
265 Causes compiler to prefix all public routines with the string 'dl'.
266 This can be useful when you only want to use this malloc in one part
267 of a program, using your regular system malloc elsewhere.
269 ABORT default: defined as abort()
270 Defines how to abort on failed checks. On most systems, a failed
271 check cannot die with an "assert" or even print an informative
272 message, because the underlying print routines in turn call malloc,
273 which will fail again. Generally, the best policy is to simply call
274 abort(). It's not very useful to do more than this because many
275 errors due to overwriting will show up as address faults (null, odd
276 addresses etc) rather than malloc-triggered checks, so will also
277 abort. Also, most compilers know that abort() does not return, so
278 can better optimize code conditionally calling it.
280 PROCEED_ON_ERROR default: defined as 0 (false)
281 Controls whether detected bad addresses cause them to bypassed
282 rather than aborting. If set, detected bad arguments to free and
283 realloc are ignored. And all bookkeeping information is zeroed out
284 upon a detected overwrite of freed heap space, thus losing the
285 ability to ever return it from malloc again, but enabling the
286 application to proceed. If PROCEED_ON_ERROR is defined, the
287 static variable malloc_corruption_error_count is compiled in
288 and can be examined to see if errors have occurred. This option
289 generates slower code than the default abort policy.
291 DEBUG default: NOT defined
292 The DEBUG setting is mainly intended for people trying to modify
293 this code or diagnose problems when porting to new platforms.
294 However, it may also be able to better isolate user errors than just
295 using runtime checks. The assertions in the check routines spell
296 out in more detail the assumptions and invariants underlying the
297 algorithms. The checking is fairly extensive, and will slow down
298 execution noticeably. Calling malloc_stats or mallinfo with DEBUG
299 set will attempt to check every non-mmapped allocated and free chunk
300 in the course of computing the summaries.
302 ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
303 Debugging assertion failures can be nearly impossible if your
304 version of the assert macro causes malloc to be called, which will
305 lead to a cascade of further failures, blowing the runtime stack.
306 ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
307 which will usually make debugging easier.
309 MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
310 The action to take before "return 0" when malloc fails to be able to
311 return memory because there is none available.
313 HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
314 True if this system supports sbrk or an emulation of it.
316 MORECORE default: sbrk
317 The name of the sbrk-style system routine to call to obtain more
318 memory. See below for guidance on writing custom MORECORE
319 functions. The type of the argument to sbrk/MORECORE varies across
320 systems. It cannot be size_t, because it supports negative
321 arguments, so it is normally the signed type of the same width as
322 size_t (sometimes declared as "intptr_t"). It doesn't much matter
323 though. Internally, we only call it with arguments less than half
324 the max value of a size_t, which should work across all reasonable
325 possibilities, although sometimes generating compiler warnings.
327 MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE
328 If true, take advantage of fact that consecutive calls to MORECORE
329 with positive arguments always return contiguous increasing
330 addresses. This is true of unix sbrk. It does not hurt too much to
331 set it true anyway, since malloc copes with non-contiguities.
332 Setting it false when definitely non-contiguous saves time
333 and possibly wasted space it would take to discover this though.
335 MORECORE_CANNOT_TRIM default: NOT defined
336 True if MORECORE cannot release space back to the system when given
337 negative arguments. This is generally necessary only if you are
338 using a hand-crafted MORECORE function that cannot handle negative
339 arguments.
341 NO_SEGMENT_TRAVERSAL default: 0
342 If non-zero, suppresses traversals of memory segments
343 returned by either MORECORE or CALL_MMAP. This disables
344 merging of segments that are contiguous, and selectively
345 releasing them to the OS if unused, but bounds execution times.
347 HAVE_MMAP default: 1 (true)
348 True if this system supports mmap or an emulation of it. If so, and
349 HAVE_MORECORE is not true, MMAP is used for all system
350 allocation. If set and HAVE_MORECORE is true as well, MMAP is
351 primarily used to directly allocate very large blocks. It is also
352 used as a backup strategy in cases where MORECORE fails to provide
353 space from system. Note: A single call to MUNMAP is assumed to be
354 able to unmap memory that may have be allocated using multiple calls
355 to MMAP, so long as they are adjacent.
357 HAVE_MREMAP default: 1 on linux, else 0
358 If true realloc() uses mremap() to re-allocate large blocks and
359 extend or shrink allocation spaces.
361 MMAP_CLEARS default: 1 except on WINCE.
362 True if mmap clears memory so calloc doesn't need to. This is true
363 for standard unix mmap using /dev/zero and on WIN32 except for WINCE.
365 USE_BUILTIN_FFS default: 0 (i.e., not used)
366 Causes malloc to use the builtin ffs() function to compute indices.
367 Some compilers may recognize and intrinsify ffs to be faster than the
368 supplied C version. Also, the case of x86 using gcc is special-cased
369 to an asm instruction, so is already as fast as it can be, and so
370 this setting has no effect. Similarly for Win32 under recent MS compilers.
371 (On most x86s, the asm version is only slightly faster than the C version.)
373 malloc_getpagesize default: derive from system includes, or 4096.
374 The system page size. To the extent possible, this malloc manages
375 memory from the system in page-size units. This may be (and
376 usually is) a function rather than a constant. This is ignored
377 if WIN32, where page size is determined using getSystemInfo during
378 initialization.
380 USE_DEV_RANDOM default: 0 (i.e., not used)
381 Causes malloc to use /dev/random to initialize secure magic seed for
382 stamping footers. Otherwise, the current time is used.
384 NO_MALLINFO default: 0
385 If defined, don't compile "mallinfo". This can be a simple way
386 of dealing with mismatches between system declarations and
387 those in this file.
389 MALLINFO_FIELD_TYPE default: size_t
390 The type of the fields in the mallinfo struct. This was originally
391 defined as "int" in SVID etc, but is more usefully defined as
392 size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
394 REALLOC_ZERO_BYTES_FREES default: not defined
395 This should be set if a call to realloc with zero bytes should
396 be the same as a call to free. Some people think it should. Otherwise,
397 since this malloc returns a unique pointer for malloc(0), so does
398 realloc(p, 0).
400 LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
401 LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
402 LACKS_STDLIB_H default: NOT defined unless on WIN32
403 Define these if your system does not have these header files.
404 You might need to manually insert some of the declarations they provide.
406 DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
407 system_info.dwAllocationGranularity in WIN32,
408 otherwise 64K.
409 Also settable using mallopt(M_GRANULARITY, x)
410 The unit for allocating and deallocating memory from the system. On
411 most systems with contiguous MORECORE, there is no reason to
412 make this more than a page. However, systems with MMAP tend to
413 either require or encourage larger granularities. You can increase
414 this value to prevent system allocation functions to be called so
415 often, especially if they are slow. The value must be at least one
416 page and must be a power of two. Setting to 0 causes initialization
417 to either page size or win32 region size. (Note: In previous
418 versions of malloc, the equivalent of this option was called
419 "TOP_PAD")
421 DEFAULT_TRIM_THRESHOLD default: 2MB
422 Also settable using mallopt(M_TRIM_THRESHOLD, x)
423 The maximum amount of unused top-most memory to keep before
424 releasing via malloc_trim in free(). Automatic trimming is mainly
425 useful in long-lived programs using contiguous MORECORE. Because
426 trimming via sbrk can be slow on some systems, and can sometimes be
427 wasteful (in cases where programs immediately afterward allocate
428 more large chunks) the value should be high enough so that your
429 overall system performance would improve by releasing this much
430 memory. As a rough guide, you might set to a value close to the
431 average size of a process (program) running on your system.
432 Releasing this much memory would allow such a process to run in
433 memory. Generally, it is worth tuning trim thresholds when a
434 program undergoes phases where several large chunks are allocated
435 and released in ways that can reuse each other's storage, perhaps
436 mixed with phases where there are no such chunks at all. The trim
437 value must be greater than page size to have any useful effect. To
438 disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
439 some people use of mallocing a huge space and then freeing it at
440 program startup, in an attempt to reserve system memory, doesn't
441 have the intended effect under automatic trimming, since that memory
442 will immediately be returned to the system.
444 DEFAULT_MMAP_THRESHOLD default: 256K
445 Also settable using mallopt(M_MMAP_THRESHOLD, x)
446 The request size threshold for using MMAP to directly service a
447 request. Requests of at least this size that cannot be allocated
448 using already-existing space will be serviced via mmap. (If enough
449 normal freed space already exists it is used instead.) Using mmap
450 segregates relatively large chunks of memory so that they can be
451 individually obtained and released from the host system. A request
452 serviced through mmap is never reused by any other request (at least
453 not directly; the system may just so happen to remap successive
454 requests to the same locations). Segregating space in this way has
455 the benefits that: Mmapped space can always be individually released
456 back to the system, which helps keep the system level memory demands
457 of a long-lived program low. Also, mapped memory doesn't become
458 `locked' between other chunks, as can happen with normally allocated
459 chunks, which means that even trimming via malloc_trim would not
460 release them. However, it has the disadvantage that the space
461 cannot be reclaimed, consolidated, and then used to service later
462 requests, as happens with normal chunks. The advantages of mmap
463 nearly always outweigh disadvantages for "large" chunks, but the
464 value of "large" may vary across systems. The default is an
465 empirically derived value that works well in most systems. You can
466 disable mmap by setting to MAX_SIZE_T.
468 MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP
469 The number of consolidated frees between checks to release
470 unused segments when freeing. When using non-contiguous segments,
471 especially with multiple mspaces, checking only for topmost space
472 doesn't always suffice to trigger trimming. To compensate for this,
473 free() will, with a period of MAX_RELEASE_CHECK_RATE (or the
474 current number of segments, if greater) try to release unused
475 segments to the OS when freeing chunks that result in
476 consolidation. The best value for this parameter is a compromise
477 between slowing down frees with relatively costly checks that
478 rarely trigger versus holding on to unused memory. To effectively
479 disable, set to MAX_SIZE_T. This may lead to a very slight speed
480 improvement at the expense of carrying around more memory.
483 #include <stddef.h>
484 #include "debug.h"
485 #include "string.h"
487 #define HAVE_MMAP 0
488 #define MORECORE sbrk
489 #define MORECORE_CANNOT_TRIM 1
490 #define LACKS_ERRNO_H 1
491 #define LACKS_STDLIB_H 1
492 #define LACKS_STRING_H 1
493 #define LACKS_STRINGS_H 1
494 #define LACKS_UNISTD_H 1
495 #define LACKS_SYS_TYPES_H 1
496 #define LACKS_SYS_PARAM_H 1
497 #define MALLOC_FAILURE_ACTION
498 #define NO_MALLINFO 1
500 #define time(x) 0
502 extern char __freemem[];
503 static char *current_break = __freemem;
505 static void *sbrk(long increment)
507 void *ret = current_break;
508 current_break += increment;
509 return ret;
512 /* Version identifier to allow people to support multiple versions */
513 #ifndef DLMALLOC_VERSION
514 #define DLMALLOC_VERSION 20804
515 #endif /* DLMALLOC_VERSION */
517 #ifndef WIN32
518 #ifdef _WIN32
519 #define WIN32 1
520 #endif /* _WIN32 */
521 #ifdef _WIN32_WCE
522 #define LACKS_FCNTL_H
523 #define WIN32 1
524 #endif /* _WIN32_WCE */
525 #endif /* WIN32 */
526 #ifdef WIN32
527 #define WIN32_LEAN_AND_MEAN
528 #include <windows.h>
529 #define HAVE_MMAP 1
530 #define HAVE_MORECORE 0
531 #define LACKS_UNISTD_H
532 #define LACKS_SYS_PARAM_H
533 #define LACKS_SYS_MMAN_H
534 #define LACKS_STRING_H
535 #define LACKS_STRINGS_H
536 #define LACKS_SYS_TYPES_H
537 #define LACKS_ERRNO_H
538 #ifndef MALLOC_FAILURE_ACTION
539 #define MALLOC_FAILURE_ACTION
540 #endif /* MALLOC_FAILURE_ACTION */
541 #ifdef _WIN32_WCE /* WINCE reportedly does not clear */
542 #define MMAP_CLEARS 0
543 #else
544 #define MMAP_CLEARS 1
545 #endif /* _WIN32_WCE */
546 #endif /* WIN32 */
548 #if defined(DARWIN) || defined(_DARWIN)
549 /* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
550 #ifndef HAVE_MORECORE
551 #define HAVE_MORECORE 0
552 #define HAVE_MMAP 1
553 /* OSX allocators provide 16 byte alignment */
554 #ifndef MALLOC_ALIGNMENT
555 #define MALLOC_ALIGNMENT ((size_t)16U)
556 #endif
557 #endif /* HAVE_MORECORE */
558 #endif /* DARWIN */
560 #ifndef LACKS_SYS_TYPES_H
561 #include <sys/types.h> /* For size_t */
562 #endif /* LACKS_SYS_TYPES_H */
564 #if (defined(__GNUC__) && ((defined(__i386__) || defined(__x86_64__)))) || (defined(_MSC_VER) && _MSC_VER>=1310)
565 #define SPIN_LOCKS_AVAILABLE 1
566 #else
567 #define SPIN_LOCKS_AVAILABLE 0
568 #endif
570 /* The maximum possible size_t value has all bits set */
571 #define MAX_SIZE_T (~(size_t)0)
573 #ifndef ONLY_MSPACES
574 #define ONLY_MSPACES 0 /* define to a value */
575 #else
576 #define ONLY_MSPACES 1
577 #endif /* ONLY_MSPACES */
578 #ifndef MSPACES
579 #if ONLY_MSPACES
580 #define MSPACES 1
581 #else /* ONLY_MSPACES */
582 #define MSPACES 0
583 #endif /* ONLY_MSPACES */
584 #endif /* MSPACES */
585 #ifndef MALLOC_ALIGNMENT
586 #define MALLOC_ALIGNMENT ((size_t)8U)
587 #endif /* MALLOC_ALIGNMENT */
588 #ifndef FOOTERS
589 #define FOOTERS 0
590 #endif /* FOOTERS */
591 #ifndef ABORT
592 #define ABORT abort()
593 #endif /* ABORT */
594 #ifndef ABORT_ON_ASSERT_FAILURE
595 #define ABORT_ON_ASSERT_FAILURE 1
596 #endif /* ABORT_ON_ASSERT_FAILURE */
597 #ifndef PROCEED_ON_ERROR
598 #define PROCEED_ON_ERROR 0
599 #endif /* PROCEED_ON_ERROR */
600 #ifndef USE_LOCKS
601 #define USE_LOCKS 0
602 #endif /* USE_LOCKS */
603 #ifndef USE_SPIN_LOCKS
604 #if USE_LOCKS && SPIN_LOCKS_AVAILABLE
605 #define USE_SPIN_LOCKS 1
606 #else
607 #define USE_SPIN_LOCKS 0
608 #endif /* USE_LOCKS && SPIN_LOCKS_AVAILABLE. */
609 #endif /* USE_SPIN_LOCKS */
610 #ifndef INSECURE
611 #define INSECURE 0
612 #endif /* INSECURE */
613 #ifndef HAVE_MMAP
614 #define HAVE_MMAP 1
615 #endif /* HAVE_MMAP */
616 #ifndef MMAP_CLEARS
617 #define MMAP_CLEARS 1
618 #endif /* MMAP_CLEARS */
619 #ifndef HAVE_MREMAP
620 #ifdef linux
621 #define HAVE_MREMAP 1
622 #else /* linux */
623 #define HAVE_MREMAP 0
624 #endif /* linux */
625 #endif /* HAVE_MREMAP */
626 #ifndef MALLOC_FAILURE_ACTION
627 #define MALLOC_FAILURE_ACTION errno = ENOMEM;
628 #endif /* MALLOC_FAILURE_ACTION */
629 #ifndef HAVE_MORECORE
630 #if ONLY_MSPACES
631 #define HAVE_MORECORE 0
632 #else /* ONLY_MSPACES */
633 #define HAVE_MORECORE 1
634 #endif /* ONLY_MSPACES */
635 #endif /* HAVE_MORECORE */
636 #if !HAVE_MORECORE
637 #define MORECORE_CONTIGUOUS 0
638 #else /* !HAVE_MORECORE */
639 #define MORECORE_DEFAULT sbrk
640 #ifndef MORECORE_CONTIGUOUS
641 #define MORECORE_CONTIGUOUS 1
642 #endif /* MORECORE_CONTIGUOUS */
643 #endif /* HAVE_MORECORE */
644 #ifndef DEFAULT_GRANULARITY
645 #if (MORECORE_CONTIGUOUS || defined(WIN32))
646 #define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
647 #else /* MORECORE_CONTIGUOUS */
648 #define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
649 #endif /* MORECORE_CONTIGUOUS */
650 #endif /* DEFAULT_GRANULARITY */
651 #ifndef DEFAULT_TRIM_THRESHOLD
652 #ifndef MORECORE_CANNOT_TRIM
653 #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
654 #else /* MORECORE_CANNOT_TRIM */
655 #define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
656 #endif /* MORECORE_CANNOT_TRIM */
657 #endif /* DEFAULT_TRIM_THRESHOLD */
658 #ifndef DEFAULT_MMAP_THRESHOLD
659 #if HAVE_MMAP
660 #define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
661 #else /* HAVE_MMAP */
662 #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
663 #endif /* HAVE_MMAP */
664 #endif /* DEFAULT_MMAP_THRESHOLD */
665 #ifndef MAX_RELEASE_CHECK_RATE
666 #if HAVE_MMAP
667 #define MAX_RELEASE_CHECK_RATE 4095
668 #else
669 #define MAX_RELEASE_CHECK_RATE MAX_SIZE_T
670 #endif /* HAVE_MMAP */
671 #endif /* MAX_RELEASE_CHECK_RATE */
672 #ifndef USE_BUILTIN_FFS
673 #define USE_BUILTIN_FFS 0
674 #endif /* USE_BUILTIN_FFS */
675 #ifndef USE_DEV_RANDOM
676 #define USE_DEV_RANDOM 0
677 #endif /* USE_DEV_RANDOM */
678 #ifndef NO_MALLINFO
679 #define NO_MALLINFO 0
680 #endif /* NO_MALLINFO */
681 #ifndef MALLINFO_FIELD_TYPE
682 #define MALLINFO_FIELD_TYPE size_t
683 #endif /* MALLINFO_FIELD_TYPE */
684 #ifndef NO_SEGMENT_TRAVERSAL
685 #define NO_SEGMENT_TRAVERSAL 0
686 #endif /* NO_SEGMENT_TRAVERSAL */
689 mallopt tuning options. SVID/XPG defines four standard parameter
690 numbers for mallopt, normally defined in malloc.h. None of these
691 are used in this malloc, so setting them has no effect. But this
692 malloc does support the following options.
695 #define M_TRIM_THRESHOLD (-1)
696 #define M_GRANULARITY (-2)
697 #define M_MMAP_THRESHOLD (-3)
699 /* ------------------------ Mallinfo declarations ------------------------ */
701 #if !NO_MALLINFO
703 This version of malloc supports the standard SVID/XPG mallinfo
704 routine that returns a struct containing usage properties and
705 statistics. It should work on any system that has a
706 /usr/include/malloc.h defining struct mallinfo. The main
707 declaration needed is the mallinfo struct that is returned (by-copy)
708 by mallinfo(). The malloinfo struct contains a bunch of fields that
709 are not even meaningful in this version of malloc. These fields are
710 are instead filled by mallinfo() with other numbers that might be of
711 interest.
713 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
714 /usr/include/malloc.h file that includes a declaration of struct
715 mallinfo. If so, it is included; else a compliant version is
716 declared below. These must be precisely the same for mallinfo() to
717 work. The original SVID version of this struct, defined on most
718 systems with mallinfo, declares all fields as ints. But some others
719 define as unsigned long. If your system defines the fields using a
720 type of different width than listed here, you MUST #include your
721 system version and #define HAVE_USR_INCLUDE_MALLOC_H.
724 /* #define HAVE_USR_INCLUDE_MALLOC_H */
726 #ifdef HAVE_USR_INCLUDE_MALLOC_H
727 #include "/usr/include/malloc.h"
728 #else /* HAVE_USR_INCLUDE_MALLOC_H */
729 #ifndef STRUCT_MALLINFO_DECLARED
730 #define STRUCT_MALLINFO_DECLARED 1
731 struct mallinfo {
732 MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
733 MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
734 MALLINFO_FIELD_TYPE smblks; /* always 0 */
735 MALLINFO_FIELD_TYPE hblks; /* always 0 */
736 MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
737 MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
738 MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
739 MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
740 MALLINFO_FIELD_TYPE fordblks; /* total free space */
741 MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
743 #endif /* STRUCT_MALLINFO_DECLARED */
744 #endif /* HAVE_USR_INCLUDE_MALLOC_H */
745 #endif /* NO_MALLINFO */
748 Try to persuade compilers to inline. The most critical functions for
749 inlining are defined as macros, so these aren't used for them.
752 #ifndef FORCEINLINE
753 #if defined(__GNUC__)
754 #define FORCEINLINE __inline __attribute__ ((always_inline))
755 #elif defined(_MSC_VER)
756 #define FORCEINLINE __forceinline
757 #endif
758 #endif
759 #ifndef NOINLINE
760 #if defined(__GNUC__)
761 #define NOINLINE __attribute__ ((noinline))
762 #elif defined(_MSC_VER)
763 #define NOINLINE __declspec(noinline)
764 #else
765 #define NOINLINE
766 #endif
767 #endif
769 #ifdef __cplusplus
770 extern "C" {
771 #ifndef FORCEINLINE
772 #define FORCEINLINE inline
773 #endif
774 #endif /* __cplusplus */
775 #ifndef FORCEINLINE
776 #define FORCEINLINE
777 #endif
779 #if !ONLY_MSPACES
781 /* ------------------- Declarations of public routines ------------------- */
783 #ifndef USE_DL_PREFIX
784 #define dlcalloc calloc
785 #define dlfree free
786 #define dlmalloc malloc
787 #define dlmemalign memalign
788 #define dlrealloc realloc
789 #define dlvalloc valloc
790 #define dlpvalloc pvalloc
791 #define dlmallinfo mallinfo
792 #define dlmallopt mallopt
793 #define dlmalloc_trim malloc_trim
794 #define dlmalloc_stats malloc_stats
795 #define dlmalloc_usable_size malloc_usable_size
796 #define dlmalloc_footprint malloc_footprint
797 #define dlmalloc_max_footprint malloc_max_footprint
798 #define dlindependent_calloc independent_calloc
799 #define dlindependent_comalloc independent_comalloc
800 #endif /* USE_DL_PREFIX */
804 malloc(size_t n)
805 Returns a pointer to a newly allocated chunk of at least n bytes, or
806 null if no space is available, in which case errno is set to ENOMEM
807 on ANSI C systems.
809 If n is zero, malloc returns a minimum-sized chunk. (The minimum
810 size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
811 systems.) Note that size_t is an unsigned type, so calls with
812 arguments that would be negative if signed are interpreted as
813 requests for huge amounts of space, which will often fail. The
814 maximum supported value of n differs across systems, but is in all
815 cases less than the maximum representable value of a size_t.
817 void* dlmalloc(size_t);
820 free(void* p)
821 Releases the chunk of memory pointed to by p, that had been previously
822 allocated using malloc or a related routine such as realloc.
823 It has no effect if p is null. If p was not malloced or already
824 freed, free(p) will by default cause the current program to abort.
826 void dlfree(void*);
829 calloc(size_t n_elements, size_t element_size);
830 Returns a pointer to n_elements * element_size bytes, with all locations
831 set to zero.
833 void* dlcalloc(size_t, size_t);
836 realloc(void* p, size_t n)
837 Returns a pointer to a chunk of size n that contains the same data
838 as does chunk p up to the minimum of (n, p's size) bytes, or null
839 if no space is available.
841 The returned pointer may or may not be the same as p. The algorithm
842 prefers extending p in most cases when possible, otherwise it
843 employs the equivalent of a malloc-copy-free sequence.
845 If p is null, realloc is equivalent to malloc.
847 If space is not available, realloc returns null, errno is set (if on
848 ANSI) and p is NOT freed.
850 if n is for fewer bytes than already held by p, the newly unused
851 space is lopped off and freed if possible. realloc with a size
852 argument of zero (re)allocates a minimum-sized chunk.
854 The old unix realloc convention of allowing the last-free'd chunk
855 to be used as an argument to realloc is not supported.
858 void* dlrealloc(void*, size_t);
861 memalign(size_t alignment, size_t n);
862 Returns a pointer to a newly allocated chunk of n bytes, aligned
863 in accord with the alignment argument.
865 The alignment argument should be a power of two. If the argument is
866 not a power of two, the nearest greater power is used.
867 8-byte alignment is guaranteed by normal malloc calls, so don't
868 bother calling memalign with an argument of 8 or less.
870 Overreliance on memalign is a sure way to fragment space.
872 void* dlmemalign(size_t, size_t);
875 valloc(size_t n);
876 Equivalent to memalign(pagesize, n), where pagesize is the page
877 size of the system. If the pagesize is unknown, 4096 is used.
879 void* dlvalloc(size_t);
882 mallopt(int parameter_number, int parameter_value)
883 Sets tunable parameters The format is to provide a
884 (parameter-number, parameter-value) pair. mallopt then sets the
885 corresponding parameter to the argument value if it can (i.e., so
886 long as the value is meaningful), and returns 1 if successful else
887 0. To workaround the fact that mallopt is specified to use int,
888 not size_t parameters, the value -1 is specially treated as the
889 maximum unsigned size_t value.
891 SVID/XPG/ANSI defines four standard param numbers for mallopt,
892 normally defined in malloc.h. None of these are use in this malloc,
893 so setting them has no effect. But this malloc also supports other
894 options in mallopt. See below for details. Briefly, supported
895 parameters are as follows (listed defaults are for "typical"
896 configurations).
898 Symbol param # default allowed param values
899 M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables)
900 M_GRANULARITY -2 page size any power of 2 >= page size
901 M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
903 int dlmallopt(int, int);
906 malloc_footprint();
907 Returns the number of bytes obtained from the system. The total
908 number of bytes allocated by malloc, realloc etc., is less than this
909 value. Unlike mallinfo, this function returns only a precomputed
910 result, so can be called frequently to monitor memory consumption.
911 Even if locks are otherwise defined, this function does not use them,
912 so results might not be up to date.
914 size_t dlmalloc_footprint(void);
917 malloc_max_footprint();
918 Returns the maximum number of bytes obtained from the system. This
919 value will be greater than current footprint if deallocated space
920 has been reclaimed by the system. The peak number of bytes allocated
921 by malloc, realloc etc., is less than this value. Unlike mallinfo,
922 this function returns only a precomputed result, so can be called
923 frequently to monitor memory consumption. Even if locks are
924 otherwise defined, this function does not use them, so results might
925 not be up to date.
927 size_t dlmalloc_max_footprint(void);
929 #if !NO_MALLINFO
931 mallinfo()
932 Returns (by copy) a struct containing various summary statistics:
934 arena: current total non-mmapped bytes allocated from system
935 ordblks: the number of free chunks
936 smblks: always zero.
937 hblks: current number of mmapped regions
938 hblkhd: total bytes held in mmapped regions
939 usmblks: the maximum total allocated space. This will be greater
940 than current total if trimming has occurred.
941 fsmblks: always zero
942 uordblks: current total allocated space (normal or mmapped)
943 fordblks: total free space
944 keepcost: the maximum number of bytes that could ideally be released
945 back to system via malloc_trim. ("ideally" means that
946 it ignores page restrictions etc.)
948 Because these fields are ints, but internal bookkeeping may
949 be kept as longs, the reported values may wrap around zero and
950 thus be inaccurate.
952 struct mallinfo dlmallinfo(void);
953 #endif /* NO_MALLINFO */
956 independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
958 independent_calloc is similar to calloc, but instead of returning a
959 single cleared space, it returns an array of pointers to n_elements
960 independent elements that can hold contents of size elem_size, each
961 of which starts out cleared, and can be independently freed,
962 realloc'ed etc. The elements are guaranteed to be adjacently
963 allocated (this is not guaranteed to occur with multiple callocs or
964 mallocs), which may also improve cache locality in some
965 applications.
967 The "chunks" argument is optional (i.e., may be null, which is
968 probably the most typical usage). If it is null, the returned array
969 is itself dynamically allocated and should also be freed when it is
970 no longer needed. Otherwise, the chunks array must be of at least
971 n_elements in length. It is filled in with the pointers to the
972 chunks.
974 In either case, independent_calloc returns this pointer array, or
975 null if the allocation failed. If n_elements is zero and "chunks"
976 is null, it returns a chunk representing an array with zero elements
977 (which should be freed if not wanted).
979 Each element must be individually freed when it is no longer
980 needed. If you'd like to instead be able to free all at once, you
981 should instead use regular calloc and assign pointers into this
982 space to represent elements. (In this case though, you cannot
983 independently free elements.)
985 independent_calloc simplifies and speeds up implementations of many
986 kinds of pools. It may also be useful when constructing large data
987 structures that initially have a fixed number of fixed-sized nodes,
988 but the number is not known at compile time, and some of the nodes
989 may later need to be freed. For example:
991 struct Node { int item; struct Node* next; };
993 struct Node* build_list() {
994 struct Node** pool;
995 int n = read_number_of_nodes_needed();
996 if (n <= 0) return 0;
997 pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
998 if (pool == 0) die();
999 // organize into a linked list...
1000 struct Node* first = pool[0];
1001 for (i = 0; i < n-1; ++i)
1002 pool[i]->next = pool[i+1];
1003 free(pool); // Can now free the array (or not, if it is needed later)
1004 return first;
1007 void** dlindependent_calloc(size_t, size_t, void**);
1010 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
1012 independent_comalloc allocates, all at once, a set of n_elements
1013 chunks with sizes indicated in the "sizes" array. It returns
1014 an array of pointers to these elements, each of which can be
1015 independently freed, realloc'ed etc. The elements are guaranteed to
1016 be adjacently allocated (this is not guaranteed to occur with
1017 multiple callocs or mallocs), which may also improve cache locality
1018 in some applications.
1020 The "chunks" argument is optional (i.e., may be null). If it is null
1021 the returned array is itself dynamically allocated and should also
1022 be freed when it is no longer needed. Otherwise, the chunks array
1023 must be of at least n_elements in length. It is filled in with the
1024 pointers to the chunks.
1026 In either case, independent_comalloc returns this pointer array, or
1027 null if the allocation failed. If n_elements is zero and chunks is
1028 null, it returns a chunk representing an array with zero elements
1029 (which should be freed if not wanted).
1031 Each element must be individually freed when it is no longer
1032 needed. If you'd like to instead be able to free all at once, you
1033 should instead use a single regular malloc, and assign pointers at
1034 particular offsets in the aggregate space. (In this case though, you
1035 cannot independently free elements.)
1037 independent_comallac differs from independent_calloc in that each
1038 element may have a different size, and also that it does not
1039 automatically clear elements.
1041 independent_comalloc can be used to speed up allocation in cases
1042 where several structs or objects must always be allocated at the
1043 same time. For example:
1045 struct Head { ... }
1046 struct Foot { ... }
1048 void send_message(char* msg) {
1049 int msglen = strlen(msg);
1050 size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
1051 void* chunks[3];
1052 if (independent_comalloc(3, sizes, chunks) == 0)
1053 die();
1054 struct Head* head = (struct Head*)(chunks[0]);
1055 char* body = (char*)(chunks[1]);
1056 struct Foot* foot = (struct Foot*)(chunks[2]);
1057 // ...
1060 In general though, independent_comalloc is worth using only for
1061 larger values of n_elements. For small values, you probably won't
1062 detect enough difference from series of malloc calls to bother.
1064 Overuse of independent_comalloc can increase overall memory usage,
1065 since it cannot reuse existing noncontiguous small chunks that
1066 might be available for some of the elements.
1068 void** dlindependent_comalloc(size_t, size_t*, void**);
1072 pvalloc(size_t n);
1073 Equivalent to valloc(minimum-page-that-holds(n)), that is,
1074 round up n to nearest pagesize.
1076 void* dlpvalloc(size_t);
1079 malloc_trim(size_t pad);
1081 If possible, gives memory back to the system (via negative arguments
1082 to sbrk) if there is unused memory at the `high' end of the malloc
1083 pool or in unused MMAP segments. You can call this after freeing
1084 large blocks of memory to potentially reduce the system-level memory
1085 requirements of a program. However, it cannot guarantee to reduce
1086 memory. Under some allocation patterns, some large free blocks of
1087 memory will be locked between two used chunks, so they cannot be
1088 given back to the system.
1090 The `pad' argument to malloc_trim represents the amount of free
1091 trailing space to leave untrimmed. If this argument is zero, only
1092 the minimum amount of memory to maintain internal data structures
1093 will be left. Non-zero arguments can be supplied to maintain enough
1094 trailing space to service future expected allocations without having
1095 to re-obtain memory from the system.
1097 Malloc_trim returns 1 if it actually released any memory, else 0.
1099 int dlmalloc_trim(size_t);
1102 malloc_stats();
1103 Prints on stderr the amount of space obtained from the system (both
1104 via sbrk and mmap), the maximum amount (which may be more than
1105 current if malloc_trim and/or munmap got called), and the current
1106 number of bytes allocated via malloc (or realloc, etc) but not yet
1107 freed. Note that this is the number of bytes allocated, not the
1108 number requested. It will be larger than the number requested
1109 because of alignment and bookkeeping overhead. Because it includes
1110 alignment wastage as being in use, this figure may be greater than
1111 zero even when no user-level chunks are allocated.
1113 The reported current and maximum system memory can be inaccurate if
1114 a program makes other calls to system memory allocation functions
1115 (normally sbrk) outside of malloc.
1117 malloc_stats prints only the most commonly interesting statistics.
1118 More information can be obtained by calling mallinfo.
1120 void dlmalloc_stats(void);
1122 #endif /* ONLY_MSPACES */
1125 malloc_usable_size(void* p);
1127 Returns the number of bytes you can actually use in
1128 an allocated chunk, which may be more than you requested (although
1129 often not) due to alignment and minimum size constraints.
1130 You can use this many bytes without worrying about
1131 overwriting other allocated objects. This is not a particularly great
1132 programming practice. malloc_usable_size can be more useful in
1133 debugging and assertions, for example:
1135 p = malloc(n);
1136 assert(malloc_usable_size(p) >= 256);
1138 size_t dlmalloc_usable_size(void*);
1141 #if MSPACES
1144 mspace is an opaque type representing an independent
1145 region of space that supports mspace_malloc, etc.
1147 typedef void* mspace;
1150 create_mspace creates and returns a new independent space with the
1151 given initial capacity, or, if 0, the default granularity size. It
1152 returns null if there is no system memory available to create the
1153 space. If argument locked is non-zero, the space uses a separate
1154 lock to control access. The capacity of the space will grow
1155 dynamically as needed to service mspace_malloc requests. You can
1156 control the sizes of incremental increases of this space by
1157 compiling with a different DEFAULT_GRANULARITY or dynamically
1158 setting with mallopt(M_GRANULARITY, value).
1160 mspace create_mspace(size_t capacity, int locked);
1163 destroy_mspace destroys the given space, and attempts to return all
1164 of its memory back to the system, returning the total number of
1165 bytes freed. After destruction, the results of access to all memory
1166 used by the space become undefined.
1168 size_t destroy_mspace(mspace msp);
1171 create_mspace_with_base uses the memory supplied as the initial base
1172 of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
1173 space is used for bookkeeping, so the capacity must be at least this
1174 large. (Otherwise 0 is returned.) When this initial space is
1175 exhausted, additional memory will be obtained from the system.
1176 Destroying this space will deallocate all additionally allocated
1177 space (if possible) but not the initial base.
1179 mspace create_mspace_with_base(void* base, size_t capacity, int locked);
1182 mspace_track_large_chunks controls whether requests for large chunks
1183 are allocated in their own untracked mmapped regions, separate from
1184 others in this mspace. By default large chunks are not tracked,
1185 which reduces fragmentation. However, such chunks are not
1186 necessarily released to the system upon destroy_mspace. Enabling
1187 tracking by setting to true may increase fragmentation, but avoids
1188 leakage when relying on destroy_mspace to release all memory
1189 allocated using this space. The function returns the previous
1190 setting.
1192 int mspace_track_large_chunks(mspace msp, int enable);
1196 mspace_malloc behaves as malloc, but operates within
1197 the given space.
1199 void* mspace_malloc(mspace msp, size_t bytes);
1202 mspace_free behaves as free, but operates within
1203 the given space.
1205 If compiled with FOOTERS==1, mspace_free is not actually needed.
1206 free may be called instead of mspace_free because freed chunks from
1207 any space are handled by their originating spaces.
1209 void mspace_free(mspace msp, void* mem);
1212 mspace_realloc behaves as realloc, but operates within
1213 the given space.
1215 If compiled with FOOTERS==1, mspace_realloc is not actually
1216 needed. realloc may be called instead of mspace_realloc because
1217 realloced chunks from any space are handled by their originating
1218 spaces.
1220 void* mspace_realloc(mspace msp, void* mem, size_t newsize);
1223 mspace_calloc behaves as calloc, but operates within
1224 the given space.
1226 void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
1229 mspace_memalign behaves as memalign, but operates within
1230 the given space.
1232 void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
1235 mspace_independent_calloc behaves as independent_calloc, but
1236 operates within the given space.
1238 void** mspace_independent_calloc(mspace msp, size_t n_elements,
1239 size_t elem_size, void* chunks[]);
1242 mspace_independent_comalloc behaves as independent_comalloc, but
1243 operates within the given space.
1245 void** mspace_independent_comalloc(mspace msp, size_t n_elements,
1246 size_t sizes[], void* chunks[]);
1249 mspace_footprint() returns the number of bytes obtained from the
1250 system for this space.
1252 size_t mspace_footprint(mspace msp);
1255 mspace_max_footprint() returns the peak number of bytes obtained from the
1256 system for this space.
1258 size_t mspace_max_footprint(mspace msp);
1261 #if !NO_MALLINFO
1263 mspace_mallinfo behaves as mallinfo, but reports properties of
1264 the given space.
1266 struct mallinfo mspace_mallinfo(mspace msp);
1267 #endif /* NO_MALLINFO */
1270 malloc_usable_size(void* p) behaves the same as malloc_usable_size;
1272 size_t mspace_usable_size(void* mem);
1275 mspace_malloc_stats behaves as malloc_stats, but reports
1276 properties of the given space.
1278 void mspace_malloc_stats(mspace msp);
1281 mspace_trim behaves as malloc_trim, but
1282 operates within the given space.
1284 int mspace_trim(mspace msp, size_t pad);
1287 An alias for mallopt.
1289 int mspace_mallopt(int, int);
1291 #endif /* MSPACES */
1293 #ifdef __cplusplus
1294 }; /* end of extern "C" */
1295 #endif /* __cplusplus */
1298 ========================================================================
1299 To make a fully customizable malloc.h header file, cut everything
1300 above this line, put into file malloc.h, edit to suit, and #include it
1301 on the next line, as well as in programs that use this malloc.
1302 ========================================================================
1305 /* #include "malloc.h" */
1307 /*------------------------------ internal #includes ---------------------- */
1309 #ifdef WIN32
1310 #pragma warning( disable : 4146 ) /* no "unsigned" warnings */
1311 #endif /* WIN32 */
1313 //#include <stdio.h> /* for printing in malloc_stats */
1315 #ifndef LACKS_ERRNO_H
1316 #include <errno.h> /* for MALLOC_FAILURE_ACTION */
1317 #endif /* LACKS_ERRNO_H */
1318 #if FOOTERS || DEBUG
1319 #include <time.h> /* for magic initialization */
1320 #endif /* FOOTERS */
1321 #ifndef LACKS_STDLIB_H
1322 #include <stdlib.h> /* for abort() */
1323 #endif /* LACKS_STDLIB_H */
1324 #ifdef DEBUG
1325 #if ABORT_ON_ASSERT_FAILURE
1326 #undef assert
1327 #define assert(x) if(!(x)) ABORT
1328 #else /* ABORT_ON_ASSERT_FAILURE */
1329 #include <assert.h>
1330 #endif /* ABORT_ON_ASSERT_FAILURE */
1331 #else /* DEBUG */
1332 #ifndef assert
1333 #define assert(x)
1334 #endif
1335 #define DEBUG 0
1336 #endif /* DEBUG */
1337 #ifndef LACKS_STRING_H
1338 #include <string.h> /* for memset etc */
1339 #endif /* LACKS_STRING_H */
1340 #if USE_BUILTIN_FFS
1341 #ifndef LACKS_STRINGS_H
1342 #include <strings.h> /* for ffs */
1343 #endif /* LACKS_STRINGS_H */
1344 #endif /* USE_BUILTIN_FFS */
1345 #if HAVE_MMAP
1346 #ifndef LACKS_SYS_MMAN_H
1347 /* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */
1348 #if (defined(linux) && !defined(__USE_GNU))
1349 #define __USE_GNU 1
1350 #include <sys/mman.h> /* for mmap */
1351 #undef __USE_GNU
1352 #else
1353 #include <sys/mman.h> /* for mmap */
1354 #endif /* linux */
1355 #endif /* LACKS_SYS_MMAN_H */
1356 #ifndef LACKS_FCNTL_H
1357 #include <fcntl.h>
1358 #endif /* LACKS_FCNTL_H */
1359 #endif /* HAVE_MMAP */
1360 #ifndef LACKS_UNISTD_H
1361 #include <unistd.h> /* for sbrk, sysconf */
1362 #else /* LACKS_UNISTD_H */
1363 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1364 extern void* sbrk(ptrdiff_t);
1365 #endif /* FreeBSD etc */
1366 #endif /* LACKS_UNISTD_H */
1368 /* Declarations for locking */
1369 #if USE_LOCKS
1370 #ifndef WIN32
1371 #include <pthread.h>
1372 #if defined (__SVR4) && defined (__sun) /* solaris */
1373 #include <thread.h>
1374 #endif /* solaris */
1375 #else
1376 #ifndef _M_AMD64
1377 /* These are already defined on AMD64 builds */
1378 #ifdef __cplusplus
1379 extern "C" {
1380 #endif /* __cplusplus */
1381 LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp);
1382 LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value);
1383 #ifdef __cplusplus
1385 #endif /* __cplusplus */
1386 #endif /* _M_AMD64 */
1387 #pragma intrinsic (_InterlockedCompareExchange)
1388 #pragma intrinsic (_InterlockedExchange)
1389 #define interlockedcompareexchange _InterlockedCompareExchange
1390 #define interlockedexchange _InterlockedExchange
1391 #endif /* Win32 */
1392 #endif /* USE_LOCKS */
1394 /* Declarations for bit scanning on win32 */
1395 #if defined(_MSC_VER) && _MSC_VER>=1300
1396 #ifndef BitScanForward /* Try to avoid pulling in WinNT.h */
1397 #ifdef __cplusplus
1398 extern "C" {
1399 #endif /* __cplusplus */
1400 unsigned char _BitScanForward(unsigned long *index, unsigned long mask);
1401 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);
1402 #ifdef __cplusplus
1404 #endif /* __cplusplus */
1406 #define BitScanForward _BitScanForward
1407 #define BitScanReverse _BitScanReverse
1408 #pragma intrinsic(_BitScanForward)
1409 #pragma intrinsic(_BitScanReverse)
1410 #endif /* BitScanForward */
1411 #endif /* defined(_MSC_VER) && _MSC_VER>=1300 */
1413 #ifndef WIN32
1414 #ifndef malloc_getpagesize
1415 # ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
1416 # ifndef _SC_PAGE_SIZE
1417 # define _SC_PAGE_SIZE _SC_PAGESIZE
1418 # endif
1419 # endif
1420 # ifdef _SC_PAGE_SIZE
1421 # define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
1422 # else
1423 # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
1424 extern size_t getpagesize();
1425 # define malloc_getpagesize getpagesize()
1426 # else
1427 # ifdef WIN32 /* use supplied emulation of getpagesize */
1428 # define malloc_getpagesize getpagesize()
1429 # else
1430 # ifndef LACKS_SYS_PARAM_H
1431 # include <sys/param.h>
1432 # endif
1433 # ifdef EXEC_PAGESIZE
1434 # define malloc_getpagesize EXEC_PAGESIZE
1435 # else
1436 # ifdef NBPG
1437 # ifndef CLSIZE
1438 # define malloc_getpagesize NBPG
1439 # else
1440 # define malloc_getpagesize (NBPG * CLSIZE)
1441 # endif
1442 # else
1443 # ifdef NBPC
1444 # define malloc_getpagesize NBPC
1445 # else
1446 # ifdef PAGESIZE
1447 # define malloc_getpagesize PAGESIZE
1448 # else /* just guess */
1449 # define malloc_getpagesize ((size_t)4096U)
1450 # endif
1451 # endif
1452 # endif
1453 # endif
1454 # endif
1455 # endif
1456 # endif
1457 #endif
1458 #endif
1462 /* ------------------- size_t and alignment properties -------------------- */
1464 /* The byte and bit size of a size_t */
1465 #define SIZE_T_SIZE (sizeof(size_t))
1466 #define SIZE_T_BITSIZE (sizeof(size_t) << 3)
1468 /* Some constants coerced to size_t */
1469 /* Annoying but necessary to avoid errors on some platforms */
1470 #define SIZE_T_ZERO ((size_t)0)
1471 #define SIZE_T_ONE ((size_t)1)
1472 #define SIZE_T_TWO ((size_t)2)
1473 #define SIZE_T_FOUR ((size_t)4)
1474 #define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)
1475 #define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)
1476 #define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
1477 #define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)
1479 /* The bit mask value corresponding to MALLOC_ALIGNMENT */
1480 #define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)
1482 /* True if address a has acceptable alignment */
1483 #define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
1485 /* the number of bytes to offset an address to align it */
1486 #define align_offset(A)\
1487 ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
1488 ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
1490 /* -------------------------- MMAP preliminaries ------------------------- */
1493 If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
1494 checks to fail so compiler optimizer can delete code rather than
1495 using so many "#if"s.
1499 /* MORECORE and MMAP must return MFAIL on failure */
1500 #define MFAIL ((void*)(MAX_SIZE_T))
1501 #define CMFAIL ((char*)(MFAIL)) /* defined for convenience */
1503 #if HAVE_MMAP
1505 #ifndef WIN32
1506 #define MUNMAP_DEFAULT(a, s) munmap((a), (s))
1507 #define MMAP_PROT (PROT_READ|PROT_WRITE)
1508 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1509 #define MAP_ANONYMOUS MAP_ANON
1510 #endif /* MAP_ANON */
1511 #ifdef MAP_ANONYMOUS
1512 #define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
1513 #define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
1514 #else /* MAP_ANONYMOUS */
1516 Nearly all versions of mmap support MAP_ANONYMOUS, so the following
1517 is unlikely to be needed, but is supplied just in case.
1519 #define MMAP_FLAGS (MAP_PRIVATE)
1520 static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
1521 #define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \
1522 (dev_zero_fd = open("/dev/zero", O_RDWR), \
1523 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
1524 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
1525 #endif /* MAP_ANONYMOUS */
1527 #define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s)
1529 #else /* WIN32 */
1531 /* Win32 MMAP via VirtualAlloc */
1532 static FORCEINLINE void* win32mmap(size_t size) {
1533 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
1534 return (ptr != 0)? ptr: MFAIL;
1537 /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
1538 static FORCEINLINE void* win32direct_mmap(size_t size) {
1539 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
1540 PAGE_READWRITE);
1541 return (ptr != 0)? ptr: MFAIL;
1544 /* This function supports releasing coalesed segments */
1545 static FORCEINLINE int win32munmap(void* ptr, size_t size) {
1546 MEMORY_BASIC_INFORMATION minfo;
1547 char* cptr = (char*)ptr;
1548 while (size) {
1549 if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
1550 return -1;
1551 if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
1552 minfo.State != MEM_COMMIT || minfo.RegionSize > size)
1553 return -1;
1554 if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
1555 return -1;
1556 cptr += minfo.RegionSize;
1557 size -= minfo.RegionSize;
1559 return 0;
1562 #define MMAP_DEFAULT(s) win32mmap(s)
1563 #define MUNMAP_DEFAULT(a, s) win32munmap((a), (s))
1564 #define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s)
1565 #endif /* WIN32 */
1566 #endif /* HAVE_MMAP */
1568 #if HAVE_MREMAP
1569 #ifndef WIN32
1570 #define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
1571 #endif /* WIN32 */
1572 #endif /* HAVE_MREMAP */
1576 * Define CALL_MORECORE
1578 #if HAVE_MORECORE
1579 #ifdef MORECORE
1580 #define CALL_MORECORE(S) MORECORE(S)
1581 #else /* MORECORE */
1582 #define CALL_MORECORE(S) MORECORE_DEFAULT(S)
1583 #endif /* MORECORE */
1584 #else /* HAVE_MORECORE */
1585 #define CALL_MORECORE(S) MFAIL
1586 #endif /* HAVE_MORECORE */
1589 * Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP
1591 #if HAVE_MMAP
1592 #define USE_MMAP_BIT (SIZE_T_ONE)
1594 #ifdef MMAP
1595 #define CALL_MMAP(s) MMAP(s)
1596 #else /* MMAP */
1597 #define CALL_MMAP(s) MMAP_DEFAULT(s)
1598 #endif /* MMAP */
1599 #ifdef MUNMAP
1600 #define CALL_MUNMAP(a, s) MUNMAP((a), (s))
1601 #else /* MUNMAP */
1602 #define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s))
1603 #endif /* MUNMAP */
1604 #ifdef DIRECT_MMAP
1605 #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)
1606 #else /* DIRECT_MMAP */
1607 #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s)
1608 #endif /* DIRECT_MMAP */
1609 #else /* HAVE_MMAP */
1610 #define USE_MMAP_BIT (SIZE_T_ZERO)
1612 #define MMAP(s) MFAIL
1613 #define MUNMAP(a, s) (-1)
1614 #define DIRECT_MMAP(s) MFAIL
1615 #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)
1616 #define CALL_MMAP(s) MMAP(s)
1617 #define CALL_MUNMAP(a, s) MUNMAP((a), (s))
1618 #endif /* HAVE_MMAP */
1621 * Define CALL_MREMAP
1623 #if HAVE_MMAP && HAVE_MREMAP
1624 #ifdef MREMAP
1625 #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv))
1626 #else /* MREMAP */
1627 #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv))
1628 #endif /* MREMAP */
1629 #else /* HAVE_MMAP && HAVE_MREMAP */
1630 #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
1631 #endif /* HAVE_MMAP && HAVE_MREMAP */
1633 /* mstate bit set if continguous morecore disabled or failed */
1634 #define USE_NONCONTIGUOUS_BIT (4U)
1636 /* segment bit set in create_mspace_with_base */
1637 #define EXTERN_BIT (8U)
1640 /* --------------------------- Lock preliminaries ------------------------ */
1643 When locks are defined, there is one global lock, plus
1644 one per-mspace lock.
1646 The global lock_ensures that mparams.magic and other unique
1647 mparams values are initialized only once. It also protects
1648 sequences of calls to MORECORE. In many cases sys_alloc requires
1649 two calls, that should not be interleaved with calls by other
1650 threads. This does not protect against direct calls to MORECORE
1651 by other threads not using this lock, so there is still code to
1652 cope the best we can on interference.
1654 Per-mspace locks surround calls to malloc, free, etc. To enable use
1655 in layered extensions, per-mspace locks are reentrant.
1657 Because lock-protected regions generally have bounded times, it is
1658 OK to use the supplied simple spinlocks in the custom versions for
1659 x86. Spinlocks are likely to improve performance for lightly
1660 contended applications, but worsen performance under heavy
1661 contention.
1663 If USE_LOCKS is > 1, the definitions of lock routines here are
1664 bypassed, in which case you will need to define the type MLOCK_T,
1665 and at least INITIAL_LOCK, ACQUIRE_LOCK, RELEASE_LOCK and possibly
1666 TRY_LOCK (which is not used in this malloc, but commonly needed in
1667 extensions.) You must also declare a
1668 static MLOCK_T malloc_global_mutex = { initialization values };.
1672 #if USE_LOCKS == 1
1674 #if USE_SPIN_LOCKS && SPIN_LOCKS_AVAILABLE
1675 #ifndef WIN32
1677 /* Custom pthread-style spin locks on x86 and x64 for gcc */
1678 struct pthread_mlock_t {
1679 volatile unsigned int l;
1680 unsigned int c;
1681 pthread_t threadid;
1683 #define MLOCK_T struct pthread_mlock_t
1684 #define CURRENT_THREAD pthread_self()
1685 #define INITIAL_LOCK(sl) ((sl)->threadid = 0, (sl)->l = (sl)->c = 0, 0)
1686 #define ACQUIRE_LOCK(sl) pthread_acquire_lock(sl)
1687 #define RELEASE_LOCK(sl) pthread_release_lock(sl)
1688 #define TRY_LOCK(sl) pthread_try_lock(sl)
1689 #define SPINS_PER_YIELD 63
1691 static MLOCK_T malloc_global_mutex = { 0, 0, 0};
1693 static FORCEINLINE int pthread_acquire_lock (MLOCK_T *sl) {
1694 int spins = 0;
1695 volatile unsigned int* lp = &sl->l;
1696 for (;;) {
1697 if (*lp != 0) {
1698 if (sl->threadid == CURRENT_THREAD) {
1699 ++sl->c;
1700 return 0;
1703 else {
1704 /* place args to cmpxchgl in locals to evade oddities in some gccs */
1705 int cmp = 0;
1706 int val = 1;
1707 int ret;
1708 __asm__ __volatile__ ("lock; cmpxchgl %1, %2"
1709 : "=a" (ret)
1710 : "r" (val), "m" (*(lp)), "0"(cmp)
1711 : "memory", "cc");
1712 if (!ret) {
1713 assert(!sl->threadid);
1714 sl->threadid = CURRENT_THREAD;
1715 sl->c = 1;
1716 return 0;
1719 if ((++spins & SPINS_PER_YIELD) == 0) {
1720 #if defined (__SVR4) && defined (__sun) /* solaris */
1721 thr_yield();
1722 #else
1723 #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
1724 sched_yield();
1725 #else /* no-op yield on unknown systems */
1727 #endif /* __linux__ || __FreeBSD__ || __APPLE__ */
1728 #endif /* solaris */
1733 static FORCEINLINE void pthread_release_lock (MLOCK_T *sl) {
1734 volatile unsigned int* lp = &sl->l;
1735 assert(*lp != 0);
1736 assert(sl->threadid == CURRENT_THREAD);
1737 if (--sl->c == 0) {
1738 sl->threadid = 0;
1739 int prev = 0;
1740 int ret;
1741 __asm__ __volatile__ ("lock; xchgl %0, %1"
1742 : "=r" (ret)
1743 : "m" (*(lp)), "0"(prev)
1744 : "memory");
1748 static FORCEINLINE int pthread_try_lock (MLOCK_T *sl) {
1749 volatile unsigned int* lp = &sl->l;
1750 if (*lp != 0) {
1751 if (sl->threadid == CURRENT_THREAD) {
1752 ++sl->c;
1753 return 1;
1756 else {
1757 int cmp = 0;
1758 int val = 1;
1759 int ret;
1760 __asm__ __volatile__ ("lock; cmpxchgl %1, %2"
1761 : "=a" (ret)
1762 : "r" (val), "m" (*(lp)), "0"(cmp)
1763 : "memory", "cc");
1764 if (!ret) {
1765 assert(!sl->threadid);
1766 sl->threadid = CURRENT_THREAD;
1767 sl->c = 1;
1768 return 1;
1771 return 0;
1775 #else /* WIN32 */
1776 /* Custom win32-style spin locks on x86 and x64 for MSC */
1777 struct win32_mlock_t {
1778 volatile long l;
1779 unsigned int c;
1780 long threadid;
1783 #define MLOCK_T struct win32_mlock_t
1784 #define CURRENT_THREAD GetCurrentThreadId()
1785 #define INITIAL_LOCK(sl) ((sl)->threadid = 0, (sl)->l = (sl)->c = 0, 0)
1786 #define ACQUIRE_LOCK(sl) win32_acquire_lock(sl)
1787 #define RELEASE_LOCK(sl) win32_release_lock(sl)
1788 #define TRY_LOCK(sl) win32_try_lock(sl)
1789 #define SPINS_PER_YIELD 63
1791 static MLOCK_T malloc_global_mutex = { 0, 0, 0};
1793 static FORCEINLINE int win32_acquire_lock (MLOCK_T *sl) {
1794 int spins = 0;
1795 for (;;) {
1796 if (sl->l != 0) {
1797 if (sl->threadid == CURRENT_THREAD) {
1798 ++sl->c;
1799 return 0;
1802 else {
1803 if (!interlockedexchange(&sl->l, 1)) {
1804 assert(!sl->threadid);
1805 sl->threadid = CURRENT_THREAD;
1806 sl->c = 1;
1807 return 0;
1810 if ((++spins & SPINS_PER_YIELD) == 0)
1811 SleepEx(0, FALSE);
1815 static FORCEINLINE void win32_release_lock (MLOCK_T *sl) {
1816 assert(sl->threadid == CURRENT_THREAD);
1817 assert(sl->l != 0);
1818 if (--sl->c == 0) {
1819 sl->threadid = 0;
1820 interlockedexchange (&sl->l, 0);
1824 static FORCEINLINE int win32_try_lock (MLOCK_T *sl) {
1825 if (sl->l != 0) {
1826 if (sl->threadid == CURRENT_THREAD) {
1827 ++sl->c;
1828 return 1;
1831 else {
1832 if (!interlockedexchange(&sl->l, 1)){
1833 assert(!sl->threadid);
1834 sl->threadid = CURRENT_THREAD;
1835 sl->c = 1;
1836 return 1;
1839 return 0;
1842 #endif /* WIN32 */
1843 #else /* USE_SPIN_LOCKS */
1845 #ifndef WIN32
1846 /* pthreads-based locks */
1848 #define MLOCK_T pthread_mutex_t
1849 #define CURRENT_THREAD pthread_self()
1850 #define INITIAL_LOCK(sl) pthread_init_lock(sl)
1851 #define ACQUIRE_LOCK(sl) pthread_mutex_lock(sl)
1852 #define RELEASE_LOCK(sl) pthread_mutex_unlock(sl)
1853 #define TRY_LOCK(sl) (!pthread_mutex_trylock(sl))
1855 static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER;
1857 /* Cope with old-style linux recursive lock initialization by adding */
1858 /* skipped internal declaration from pthread.h */
1859 #ifdef linux
1860 #ifndef PTHREAD_MUTEX_RECURSIVE
1861 extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr,
1862 int __kind));
1863 #define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP
1864 #define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y)
1865 #endif
1866 #endif
1868 static int pthread_init_lock (MLOCK_T *sl) {
1869 pthread_mutexattr_t attr;
1870 if (pthread_mutexattr_init(&attr)) return 1;
1871 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1;
1872 if (pthread_mutex_init(sl, &attr)) return 1;
1873 if (pthread_mutexattr_destroy(&attr)) return 1;
1874 return 0;
1877 #else /* WIN32 */
1878 /* Win32 critical sections */
1879 #define MLOCK_T CRITICAL_SECTION
1880 #define CURRENT_THREAD GetCurrentThreadId()
1881 #define INITIAL_LOCK(s) (!InitializeCriticalSectionAndSpinCount((s), 0x80000000|4000))
1882 #define ACQUIRE_LOCK(s) (EnterCriticalSection(sl), 0)
1883 #define RELEASE_LOCK(s) LeaveCriticalSection(sl)
1884 #define TRY_LOCK(s) TryEnterCriticalSection(sl)
1885 #define NEED_GLOBAL_LOCK_INIT
1887 static MLOCK_T malloc_global_mutex;
1888 static volatile long malloc_global_mutex_status;
1890 /* Use spin loop to initialize global lock */
1891 static void init_malloc_global_mutex() {
1892 for (;;) {
1893 long stat = malloc_global_mutex_status;
1894 if (stat > 0)
1895 return;
1896 /* transition to < 0 while initializing, then to > 0) */
1897 if (stat == 0 &&
1898 interlockedcompareexchange(&malloc_global_mutex_status, -1, 0) == 0) {
1899 InitializeCriticalSection(&malloc_global_mutex);
1900 interlockedexchange(&malloc_global_mutex_status,1);
1901 return;
1903 SleepEx(0, FALSE);
1907 #endif /* WIN32 */
1908 #endif /* USE_SPIN_LOCKS */
1909 #endif /* USE_LOCKS == 1 */
1911 /* ----------------------- User-defined locks ------------------------ */
1913 #if USE_LOCKS > 1
1914 /* Define your own lock implementation here */
1915 /* #define INITIAL_LOCK(sl) ... */
1916 /* #define ACQUIRE_LOCK(sl) ... */
1917 /* #define RELEASE_LOCK(sl) ... */
1918 /* #define TRY_LOCK(sl) ... */
1919 /* static MLOCK_T malloc_global_mutex = ... */
1920 #endif /* USE_LOCKS > 1 */
1922 /* ----------------------- Lock-based state ------------------------ */
1924 #if USE_LOCKS
1925 #define USE_LOCK_BIT (2U)
1926 #else /* USE_LOCKS */
1927 #define USE_LOCK_BIT (0U)
1928 #define INITIAL_LOCK(l)
1929 #endif /* USE_LOCKS */
1931 #if USE_LOCKS
1932 #ifndef ACQUIRE_MALLOC_GLOBAL_LOCK
1933 #define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex);
1934 #endif
1935 #ifndef RELEASE_MALLOC_GLOBAL_LOCK
1936 #define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex);
1937 #endif
1938 #else /* USE_LOCKS */
1939 #define ACQUIRE_MALLOC_GLOBAL_LOCK()
1940 #define RELEASE_MALLOC_GLOBAL_LOCK()
1941 #endif /* USE_LOCKS */
1944 /* ----------------------- Chunk representations ------------------------ */
1947 (The following includes lightly edited explanations by Colin Plumb.)
1949 The malloc_chunk declaration below is misleading (but accurate and
1950 necessary). It declares a "view" into memory allowing access to
1951 necessary fields at known offsets from a given base.
1953 Chunks of memory are maintained using a `boundary tag' method as
1954 originally described by Knuth. (See the paper by Paul Wilson
1955 ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
1956 techniques.) Sizes of free chunks are stored both in the front of
1957 each chunk and at the end. This makes consolidating fragmented
1958 chunks into bigger chunks fast. The head fields also hold bits
1959 representing whether chunks are free or in use.
1961 Here are some pictures to make it clearer. They are "exploded" to
1962 show that the state of a chunk can be thought of as extending from
1963 the high 31 bits of the head field of its header through the
1964 prev_foot and PINUSE_BIT bit of the following chunk header.
1966 A chunk that's in use looks like:
1968 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1969 | Size of previous chunk (if P = 0) |
1970 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1971 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
1972 | Size of this chunk 1| +-+
1973 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1975 +- -+
1977 +- -+
1979 +- size - sizeof(size_t) available payload bytes -+
1981 chunk-> +- -+
1983 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1984 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
1985 | Size of next chunk (may or may not be in use) | +-+
1986 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1988 And if it's free, it looks like this:
1990 chunk-> +- -+
1991 | User payload (must be in use, or we would have merged!) |
1992 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1993 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
1994 | Size of this chunk 0| +-+
1995 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1996 | Next pointer |
1997 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1998 | Prev pointer |
1999 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2001 +- size - sizeof(struct chunk) unused bytes -+
2003 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2004 | Size of this chunk |
2005 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2006 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
2007 | Size of next chunk (must be in use, or we would have merged)| +-+
2008 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2010 +- User payload -+
2012 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2015 Note that since we always merge adjacent free chunks, the chunks
2016 adjacent to a free chunk must be in use.
2018 Given a pointer to a chunk (which can be derived trivially from the
2019 payload pointer) we can, in O(1) time, find out whether the adjacent
2020 chunks are free, and if so, unlink them from the lists that they
2021 are on and merge them with the current chunk.
2023 Chunks always begin on even word boundaries, so the mem portion
2024 (which is returned to the user) is also on an even word boundary, and
2025 thus at least double-word aligned.
2027 The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
2028 chunk size (which is always a multiple of two words), is an in-use
2029 bit for the *previous* chunk. If that bit is *clear*, then the
2030 word before the current chunk size contains the previous chunk
2031 size, and can be used to find the front of the previous chunk.
2032 The very first chunk allocated always has this bit set, preventing
2033 access to non-existent (or non-owned) memory. If pinuse is set for
2034 any given chunk, then you CANNOT determine the size of the
2035 previous chunk, and might even get a memory addressing fault when
2036 trying to do so.
2038 The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
2039 the chunk size redundantly records whether the current chunk is
2040 inuse (unless the chunk is mmapped). This redundancy enables usage
2041 checks within free and realloc, and reduces indirection when freeing
2042 and consolidating chunks.
2044 Each freshly allocated chunk must have both cinuse and pinuse set.
2045 That is, each allocated chunk borders either a previously allocated
2046 and still in-use chunk, or the base of its memory arena. This is
2047 ensured by making all allocations from the the `lowest' part of any
2048 found chunk. Further, no free chunk physically borders another one,
2049 so each free chunk is known to be preceded and followed by either
2050 inuse chunks or the ends of memory.
2052 Note that the `foot' of the current chunk is actually represented
2053 as the prev_foot of the NEXT chunk. This makes it easier to
2054 deal with alignments etc but can be very confusing when trying
2055 to extend or adapt this code.
2057 The exceptions to all this are
2059 1. The special chunk `top' is the top-most available chunk (i.e.,
2060 the one bordering the end of available memory). It is treated
2061 specially. Top is never included in any bin, is used only if
2062 no other chunk is available, and is released back to the
2063 system if it is very large (see M_TRIM_THRESHOLD). In effect,
2064 the top chunk is treated as larger (and thus less well
2065 fitting) than any other available chunk. The top chunk
2066 doesn't update its trailing size field since there is no next
2067 contiguous chunk that would have to index off it. However,
2068 space is still allocated for it (TOP_FOOT_SIZE) to enable
2069 separation or merging when space is extended.
2071 3. Chunks allocated via mmap, have both cinuse and pinuse bits
2072 cleared in their head fields. Because they are allocated
2073 one-by-one, each must carry its own prev_foot field, which is
2074 also used to hold the offset this chunk has within its mmapped
2075 region, which is needed to preserve alignment. Each mmapped
2076 chunk is trailed by the first two fields of a fake next-chunk
2077 for sake of usage checks.
2081 struct malloc_chunk {
2082 size_t prev_foot; /* Size of previous chunk (if free). */
2083 size_t head; /* Size and inuse bits. */
2084 struct malloc_chunk* fd; /* double links -- used only if free. */
2085 struct malloc_chunk* bk;
2088 typedef struct malloc_chunk mchunk;
2089 typedef struct malloc_chunk* mchunkptr;
2090 typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */
2091 typedef unsigned int bindex_t; /* Described below */
2092 typedef unsigned int binmap_t; /* Described below */
2093 typedef unsigned int flag_t; /* The type of various bit flag sets */
2095 /* ------------------- Chunks sizes and alignments ----------------------- */
2097 #define MCHUNK_SIZE (sizeof(mchunk))
2099 #if FOOTERS
2100 #define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
2101 #else /* FOOTERS */
2102 #define CHUNK_OVERHEAD (SIZE_T_SIZE)
2103 #endif /* FOOTERS */
2105 /* MMapped chunks need a second word of overhead ... */
2106 #define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
2107 /* ... and additional padding for fake next-chunk at foot */
2108 #define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)
2110 /* The smallest size we can malloc is an aligned minimal chunk */
2111 #define MIN_CHUNK_SIZE\
2112 ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
2114 /* conversion from malloc headers to user pointers, and back */
2115 #define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))
2116 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
2117 /* chunk associated with aligned address A */
2118 #define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))
2120 /* Bounds on request (not chunk) sizes. */
2121 #define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)
2122 #define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
2124 /* pad request bytes into a usable size */
2125 #define pad_request(req) \
2126 (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
2128 /* pad request, checking for minimum (but not maximum) */
2129 #define request2size(req) \
2130 (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
2133 /* ------------------ Operations on head and foot fields ----------------- */
2136 The head field of a chunk is or'ed with PINUSE_BIT when previous
2137 adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
2138 use, unless mmapped, in which case both bits are cleared.
2140 FLAG4_BIT is not used by this malloc, but might be useful in extensions.
2143 #define PINUSE_BIT (SIZE_T_ONE)
2144 #define CINUSE_BIT (SIZE_T_TWO)
2145 #define FLAG4_BIT (SIZE_T_FOUR)
2146 #define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)
2147 #define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT)
2149 /* Head value for fenceposts */
2150 #define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)
2152 /* extraction of fields from head words */
2153 #define cinuse(p) ((p)->head & CINUSE_BIT)
2154 #define pinuse(p) ((p)->head & PINUSE_BIT)
2155 #define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT)
2156 #define is_mmapped(p) (((p)->head & INUSE_BITS) == 0)
2158 #define chunksize(p) ((p)->head & ~(FLAG_BITS))
2160 #define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)
2162 /* Treat space at ptr +/- offset as a chunk */
2163 #define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
2164 #define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
2166 /* Ptr to next or previous physical malloc_chunk. */
2167 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS)))
2168 #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
2170 /* extract next chunk's pinuse bit */
2171 #define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)
2173 /* Get/set size at footer */
2174 #define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)
2175 #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
2177 /* Set size, pinuse bit, and foot */
2178 #define set_size_and_pinuse_of_free_chunk(p, s)\
2179 ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
2181 /* Set size, pinuse bit, foot, and clear next pinuse */
2182 #define set_free_with_pinuse(p, s, n)\
2183 (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
2185 /* Get the internal overhead associated with chunk p */
2186 #define overhead_for(p)\
2187 (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
2189 /* Return true if malloced space is not necessarily cleared */
2190 #if MMAP_CLEARS
2191 #define calloc_must_clear(p) (!is_mmapped(p))
2192 #else /* MMAP_CLEARS */
2193 #define calloc_must_clear(p) (1)
2194 #endif /* MMAP_CLEARS */
2196 /* ---------------------- Overlaid data structures ----------------------- */
2199 When chunks are not in use, they are treated as nodes of either
2200 lists or trees.
2202 "Small" chunks are stored in circular doubly-linked lists, and look
2203 like this:
2205 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2206 | Size of previous chunk |
2207 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2208 `head:' | Size of chunk, in bytes |P|
2209 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2210 | Forward pointer to next chunk in list |
2211 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2212 | Back pointer to previous chunk in list |
2213 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2214 | Unused space (may be 0 bytes long) .
2217 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2218 `foot:' | Size of chunk, in bytes |
2219 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2221 Larger chunks are kept in a form of bitwise digital trees (aka
2222 tries) keyed on chunksizes. Because malloc_tree_chunks are only for
2223 free chunks greater than 256 bytes, their size doesn't impose any
2224 constraints on user chunk sizes. Each node looks like:
2226 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2227 | Size of previous chunk |
2228 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2229 `head:' | Size of chunk, in bytes |P|
2230 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2231 | Forward pointer to next chunk of same size |
2232 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2233 | Back pointer to previous chunk of same size |
2234 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2235 | Pointer to left child (child[0]) |
2236 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2237 | Pointer to right child (child[1]) |
2238 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2239 | Pointer to parent |
2240 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2241 | bin index of this chunk |
2242 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2243 | Unused space .
2245 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2246 `foot:' | Size of chunk, in bytes |
2247 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2249 Each tree holding treenodes is a tree of unique chunk sizes. Chunks
2250 of the same size are arranged in a circularly-linked list, with only
2251 the oldest chunk (the next to be used, in our FIFO ordering)
2252 actually in the tree. (Tree members are distinguished by a non-null
2253 parent pointer.) If a chunk with the same size an an existing node
2254 is inserted, it is linked off the existing node using pointers that
2255 work in the same way as fd/bk pointers of small chunks.
2257 Each tree contains a power of 2 sized range of chunk sizes (the
2258 smallest is 0x100 <= x < 0x180), which is is divided in half at each
2259 tree level, with the chunks in the smaller half of the range (0x100
2260 <= x < 0x140 for the top nose) in the left subtree and the larger
2261 half (0x140 <= x < 0x180) in the right subtree. This is, of course,
2262 done by inspecting individual bits.
2264 Using these rules, each node's left subtree contains all smaller
2265 sizes than its right subtree. However, the node at the root of each
2266 subtree has no particular ordering relationship to either. (The
2267 dividing line between the subtree sizes is based on trie relation.)
2268 If we remove the last chunk of a given size from the interior of the
2269 tree, we need to replace it with a leaf node. The tree ordering
2270 rules permit a node to be replaced by any leaf below it.
2272 The smallest chunk in a tree (a common operation in a best-fit
2273 allocator) can be found by walking a path to the leftmost leaf in
2274 the tree. Unlike a usual binary tree, where we follow left child
2275 pointers until we reach a null, here we follow the right child
2276 pointer any time the left one is null, until we reach a leaf with
2277 both child pointers null. The smallest chunk in the tree will be
2278 somewhere along that path.
2280 The worst case number of steps to add, find, or remove a node is
2281 bounded by the number of bits differentiating chunks within
2282 bins. Under current bin calculations, this ranges from 6 up to 21
2283 (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
2284 is of course much better.
2287 struct malloc_tree_chunk {
2288 /* The first four fields must be compatible with malloc_chunk */
2289 size_t prev_foot;
2290 size_t head;
2291 struct malloc_tree_chunk* fd;
2292 struct malloc_tree_chunk* bk;
2294 struct malloc_tree_chunk* child[2];
2295 struct malloc_tree_chunk* parent;
2296 bindex_t index;
2299 typedef struct malloc_tree_chunk tchunk;
2300 typedef struct malloc_tree_chunk* tchunkptr;
2301 typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
2303 /* A little helper macro for trees */
2304 #define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
2306 /* ----------------------------- Segments -------------------------------- */
2309 Each malloc space may include non-contiguous segments, held in a
2310 list headed by an embedded malloc_segment record representing the
2311 top-most space. Segments also include flags holding properties of
2312 the space. Large chunks that are directly allocated by mmap are not
2313 included in this list. They are instead independently created and
2314 destroyed without otherwise keeping track of them.
2316 Segment management mainly comes into play for spaces allocated by
2317 MMAP. Any call to MMAP might or might not return memory that is
2318 adjacent to an existing segment. MORECORE normally contiguously
2319 extends the current space, so this space is almost always adjacent,
2320 which is simpler and faster to deal with. (This is why MORECORE is
2321 used preferentially to MMAP when both are available -- see
2322 sys_alloc.) When allocating using MMAP, we don't use any of the
2323 hinting mechanisms (inconsistently) supported in various
2324 implementations of unix mmap, or distinguish reserving from
2325 committing memory. Instead, we just ask for space, and exploit
2326 contiguity when we get it. It is probably possible to do
2327 better than this on some systems, but no general scheme seems
2328 to be significantly better.
2330 Management entails a simpler variant of the consolidation scheme
2331 used for chunks to reduce fragmentation -- new adjacent memory is
2332 normally prepended or appended to an existing segment. However,
2333 there are limitations compared to chunk consolidation that mostly
2334 reflect the fact that segment processing is relatively infrequent
2335 (occurring only when getting memory from system) and that we
2336 don't expect to have huge numbers of segments:
2338 * Segments are not indexed, so traversal requires linear scans. (It
2339 would be possible to index these, but is not worth the extra
2340 overhead and complexity for most programs on most platforms.)
2341 * New segments are only appended to old ones when holding top-most
2342 memory; if they cannot be prepended to others, they are held in
2343 different segments.
2345 Except for the top-most segment of an mstate, each segment record
2346 is kept at the tail of its segment. Segments are added by pushing
2347 segment records onto the list headed by &mstate.seg for the
2348 containing mstate.
2350 Segment flags control allocation/merge/deallocation policies:
2351 * If EXTERN_BIT set, then we did not allocate this segment,
2352 and so should not try to deallocate or merge with others.
2353 (This currently holds only for the initial segment passed
2354 into create_mspace_with_base.)
2355 * If USE_MMAP_BIT set, the segment may be merged with
2356 other surrounding mmapped segments and trimmed/de-allocated
2357 using munmap.
2358 * If neither bit is set, then the segment was obtained using
2359 MORECORE so can be merged with surrounding MORECORE'd segments
2360 and deallocated/trimmed using MORECORE with negative arguments.
2363 struct malloc_segment {
2364 char* base; /* base address */
2365 size_t size; /* allocated size */
2366 struct malloc_segment* next; /* ptr to next segment */
2367 flag_t sflags; /* mmap and extern flag */
2370 #define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT)
2371 #define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)
2373 typedef struct malloc_segment msegment;
2374 typedef struct malloc_segment* msegmentptr;
2376 /* ---------------------------- malloc_state ----------------------------- */
2379 A malloc_state holds all of the bookkeeping for a space.
2380 The main fields are:
2383 The topmost chunk of the currently active segment. Its size is
2384 cached in topsize. The actual size of topmost space is
2385 topsize+TOP_FOOT_SIZE, which includes space reserved for adding
2386 fenceposts and segment records if necessary when getting more
2387 space from the system. The size at which to autotrim top is
2388 cached from mparams in trim_check, except that it is disabled if
2389 an autotrim fails.
2391 Designated victim (dv)
2392 This is the preferred chunk for servicing small requests that
2393 don't have exact fits. It is normally the chunk split off most
2394 recently to service another small request. Its size is cached in
2395 dvsize. The link fields of this chunk are not maintained since it
2396 is not kept in a bin.
2398 SmallBins
2399 An array of bin headers for free chunks. These bins hold chunks
2400 with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
2401 chunks of all the same size, spaced 8 bytes apart. To simplify
2402 use in double-linked lists, each bin header acts as a malloc_chunk
2403 pointing to the real first node, if it exists (else pointing to
2404 itself). This avoids special-casing for headers. But to avoid
2405 waste, we allocate only the fd/bk pointers of bins, and then use
2406 repositioning tricks to treat these as the fields of a chunk.
2408 TreeBins
2409 Treebins are pointers to the roots of trees holding a range of
2410 sizes. There are 2 equally spaced treebins for each power of two
2411 from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
2412 larger.
2414 Bin maps
2415 There is one bit map for small bins ("smallmap") and one for
2416 treebins ("treemap). Each bin sets its bit when non-empty, and
2417 clears the bit when empty. Bit operations are then used to avoid
2418 bin-by-bin searching -- nearly all "search" is done without ever
2419 looking at bins that won't be selected. The bit maps
2420 conservatively use 32 bits per map word, even if on 64bit system.
2421 For a good description of some of the bit-based techniques used
2422 here, see Henry S. Warren Jr's book "Hacker's Delight" (and
2423 supplement at http://hackersdelight.org/). Many of these are
2424 intended to reduce the branchiness of paths through malloc etc, as
2425 well as to reduce the number of memory locations read or written.
2427 Segments
2428 A list of segments headed by an embedded malloc_segment record
2429 representing the initial space.
2431 Address check support
2432 The least_addr field is the least address ever obtained from
2433 MORECORE or MMAP. Attempted frees and reallocs of any address less
2434 than this are trapped (unless INSECURE is defined).
2436 Magic tag
2437 A cross-check field that should always hold same value as mparams.magic.
2439 Flags
2440 Bits recording whether to use MMAP, locks, or contiguous MORECORE
2442 Statistics
2443 Each space keeps track of current and maximum system memory
2444 obtained via MORECORE or MMAP.
2446 Trim support
2447 Fields holding the amount of unused topmost memory that should trigger
2448 timming, and a counter to force periodic scanning to release unused
2449 non-topmost segments.
2451 Locking
2452 If USE_LOCKS is defined, the "mutex" lock is acquired and released
2453 around every public call using this mspace.
2455 Extension support
2456 A void* pointer and a size_t field that can be used to help implement
2457 extensions to this malloc.
2460 /* Bin types, widths and sizes */
2461 #define NSMALLBINS (32U)
2462 #define NTREEBINS (32U)
2463 #define SMALLBIN_SHIFT (3U)
2464 #define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)
2465 #define TREEBIN_SHIFT (8U)
2466 #define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)
2467 #define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)
2468 #define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
2470 struct malloc_state {
2471 binmap_t smallmap;
2472 binmap_t treemap;
2473 size_t dvsize;
2474 size_t topsize;
2475 char* least_addr;
2476 mchunkptr dv;
2477 mchunkptr top;
2478 size_t trim_check;
2479 size_t release_checks;
2480 size_t magic;
2481 mchunkptr smallbins[(NSMALLBINS+1)*2];
2482 tbinptr treebins[NTREEBINS];
2483 size_t footprint;
2484 size_t max_footprint;
2485 flag_t mflags;
2486 #if USE_LOCKS
2487 MLOCK_T mutex; /* locate lock among fields that rarely change */
2488 #endif /* USE_LOCKS */
2489 msegment seg;
2490 void* extp; /* Unused but available for extensions */
2491 size_t exts;
2494 typedef struct malloc_state* mstate;
2496 /* ------------- Global malloc_state and malloc_params ------------------- */
2499 malloc_params holds global properties, including those that can be
2500 dynamically set using mallopt. There is a single instance, mparams,
2501 initialized in init_mparams. Note that the non-zeroness of "magic"
2502 also serves as an initialization flag.
2505 struct malloc_params {
2506 volatile size_t magic;
2507 size_t page_size;
2508 size_t granularity;
2509 size_t mmap_threshold;
2510 size_t trim_threshold;
2511 flag_t default_mflags;
2514 static struct malloc_params mparams;
2516 /* Ensure mparams initialized */
2517 #define ensure_initialization() (void)(mparams.magic != 0 || init_mparams())
2519 #if !ONLY_MSPACES
2521 /* The global malloc_state used for all non-"mspace" calls */
2522 static struct malloc_state _gm_;
2523 #define gm (&_gm_)
2524 #define is_global(M) ((M) == &_gm_)
2526 #endif /* !ONLY_MSPACES */
2528 #define is_initialized(M) ((M)->top != 0)
2530 /* -------------------------- system alloc setup ------------------------- */
2532 /* Operations on mflags */
2534 #define use_lock(M) ((M)->mflags & USE_LOCK_BIT)
2535 #define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)
2536 #define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)
2538 #define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)
2539 #define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)
2540 #define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)
2542 #define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)
2543 #define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)
2545 #define set_lock(M,L)\
2546 ((M)->mflags = (L)?\
2547 ((M)->mflags | USE_LOCK_BIT) :\
2548 ((M)->mflags & ~USE_LOCK_BIT))
2550 /* page-align a size */
2551 #define page_align(S)\
2552 (((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE))
2554 /* granularity-align a size */
2555 #define granularity_align(S)\
2556 (((S) + (mparams.granularity - SIZE_T_ONE))\
2557 & ~(mparams.granularity - SIZE_T_ONE))
2560 /* For mmap, use granularity alignment on windows, else page-align */
2561 #ifdef WIN32
2562 #define mmap_align(S) granularity_align(S)
2563 #else
2564 #define mmap_align(S) page_align(S)
2565 #endif
2567 /* For sys_alloc, enough padding to ensure can malloc request on success */
2568 #define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT)
2570 #define is_page_aligned(S)\
2571 (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
2572 #define is_granularity_aligned(S)\
2573 (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
2575 /* True if segment S holds address A */
2576 #define segment_holds(S, A)\
2577 ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
2579 /* Return segment holding given address */
2580 static msegmentptr segment_holding(mstate m, char* addr) {
2581 msegmentptr sp = &m->seg;
2582 for (;;) {
2583 if (addr >= sp->base && addr < sp->base + sp->size)
2584 return sp;
2585 if ((sp = sp->next) == 0)
2586 return 0;
2590 /* Return true if segment contains a segment link */
2591 static int has_segment_link(mstate m, msegmentptr ss) {
2592 msegmentptr sp = &m->seg;
2593 for (;;) {
2594 if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
2595 return 1;
2596 if ((sp = sp->next) == 0)
2597 return 0;
2601 #ifndef MORECORE_CANNOT_TRIM
2602 #define should_trim(M,s) ((s) > (M)->trim_check)
2603 #else /* MORECORE_CANNOT_TRIM */
2604 #define should_trim(M,s) (0)
2605 #endif /* MORECORE_CANNOT_TRIM */
2608 TOP_FOOT_SIZE is padding at the end of a segment, including space
2609 that may be needed to place segment records and fenceposts when new
2610 noncontiguous segments are added.
2612 #define TOP_FOOT_SIZE\
2613 (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
2616 /* ------------------------------- Hooks -------------------------------- */
2619 PREACTION should be defined to return 0 on success, and nonzero on
2620 failure. If you are not using locking, you can redefine these to do
2621 anything you like.
2624 #if USE_LOCKS
2626 #define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
2627 #define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
2628 #else /* USE_LOCKS */
2630 #ifndef PREACTION
2631 #define PREACTION(M) (0)
2632 #endif /* PREACTION */
2634 #ifndef POSTACTION
2635 #define POSTACTION(M)
2636 #endif /* POSTACTION */
2638 #endif /* USE_LOCKS */
2641 CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
2642 USAGE_ERROR_ACTION is triggered on detected bad frees and
2643 reallocs. The argument p is an address that might have triggered the
2644 fault. It is ignored by the two predefined actions, but might be
2645 useful in custom actions that try to help diagnose errors.
2648 #if PROCEED_ON_ERROR
2650 /* A count of the number of corruption errors causing resets */
2651 int malloc_corruption_error_count;
2653 /* default corruption action */
2654 static void reset_on_error(mstate m);
2656 #define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)
2657 #define USAGE_ERROR_ACTION(m, p)
2659 #else /* PROCEED_ON_ERROR */
2661 #ifndef CORRUPTION_ERROR_ACTION
2662 #define CORRUPTION_ERROR_ACTION(m) ABORT
2663 #endif /* CORRUPTION_ERROR_ACTION */
2665 #ifndef USAGE_ERROR_ACTION
2666 #define USAGE_ERROR_ACTION(m,p) ABORT
2667 #endif /* USAGE_ERROR_ACTION */
2669 #endif /* PROCEED_ON_ERROR */
2671 /* -------------------------- Debugging setup ---------------------------- */
2673 #if ! DEBUG
2675 #define check_free_chunk(M,P)
2676 #define check_inuse_chunk(M,P)
2677 #define check_malloced_chunk(M,P,N)
2678 #define check_mmapped_chunk(M,P)
2679 #define check_malloc_state(M)
2680 #define check_top_chunk(M,P)
2682 #else /* DEBUG */
2683 #define check_free_chunk(M,P) do_check_free_chunk(M,P)
2684 #define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)
2685 #define check_top_chunk(M,P) do_check_top_chunk(M,P)
2686 #define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
2687 #define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)
2688 #define check_malloc_state(M) do_check_malloc_state(M)
2690 static void do_check_any_chunk(mstate m, mchunkptr p);
2691 static void do_check_top_chunk(mstate m, mchunkptr p);
2692 static void do_check_mmapped_chunk(mstate m, mchunkptr p);
2693 static void do_check_inuse_chunk(mstate m, mchunkptr p);
2694 static void do_check_free_chunk(mstate m, mchunkptr p);
2695 static void do_check_malloced_chunk(mstate m, void* mem, size_t s);
2696 static void do_check_tree(mstate m, tchunkptr t);
2697 static void do_check_treebin(mstate m, bindex_t i);
2698 static void do_check_smallbin(mstate m, bindex_t i);
2699 static void do_check_malloc_state(mstate m);
2700 static int bin_find(mstate m, mchunkptr x);
2701 static size_t traverse_and_check(mstate m);
2702 #endif /* DEBUG */
2704 /* ---------------------------- Indexing Bins ---------------------------- */
2706 #define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
2707 #define small_index(s) ((s) >> SMALLBIN_SHIFT)
2708 #define small_index2size(i) ((i) << SMALLBIN_SHIFT)
2709 #define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))
2711 /* addressing by index. See above about smallbin repositioning */
2712 #define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
2713 #define treebin_at(M,i) (&((M)->treebins[i]))
2715 /* assign tree index for size S to variable I. Use x86 asm if possible */
2716 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
2717 #define compute_tree_index(S, I)\
2719 unsigned int X = S >> TREEBIN_SHIFT;\
2720 if (X == 0)\
2721 I = 0;\
2722 else if (X > 0xFFFF)\
2723 I = NTREEBINS-1;\
2724 else {\
2725 unsigned int K;\
2726 __asm__("bsrl\t%1, %0\n\t" : "=r" (K) : "g" (X));\
2727 I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
2731 #elif defined (__INTEL_COMPILER)
2732 #define compute_tree_index(S, I)\
2734 size_t X = S >> TREEBIN_SHIFT;\
2735 if (X == 0)\
2736 I = 0;\
2737 else if (X > 0xFFFF)\
2738 I = NTREEBINS-1;\
2739 else {\
2740 unsigned int K = _bit_scan_reverse (X); \
2741 I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
2745 #elif defined(_MSC_VER) && _MSC_VER>=1300
2746 #define compute_tree_index(S, I)\
2748 size_t X = S >> TREEBIN_SHIFT;\
2749 if (X == 0)\
2750 I = 0;\
2751 else if (X > 0xFFFF)\
2752 I = NTREEBINS-1;\
2753 else {\
2754 unsigned int K;\
2755 _BitScanReverse((DWORD *) &K, X);\
2756 I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
2760 #else /* GNUC */
2761 #define compute_tree_index(S, I)\
2763 size_t X = S >> TREEBIN_SHIFT;\
2764 if (X == 0)\
2765 I = 0;\
2766 else if (X > 0xFFFF)\
2767 I = NTREEBINS-1;\
2768 else {\
2769 unsigned int Y = (unsigned int)X;\
2770 unsigned int N = ((Y - 0x100) >> 16) & 8;\
2771 unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
2772 N += K;\
2773 N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
2774 K = 14 - N + ((Y <<= K) >> 15);\
2775 I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
2778 #endif /* GNUC */
2780 /* Bit representing maximum resolved size in a treebin at i */
2781 #define bit_for_tree_index(i) \
2782 (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
2784 /* Shift placing maximum resolved bit in a treebin at i as sign bit */
2785 #define leftshift_for_tree_index(i) \
2786 ((i == NTREEBINS-1)? 0 : \
2787 ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
2789 /* The size of the smallest chunk held in bin with index i */
2790 #define minsize_for_tree_index(i) \
2791 ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \
2792 (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
2795 /* ------------------------ Operations on bin maps ----------------------- */
2797 /* bit corresponding to given index */
2798 #define idx2bit(i) ((binmap_t)(1) << (i))
2800 /* Mark/Clear bits with given index */
2801 #define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))
2802 #define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))
2803 #define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))
2805 #define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))
2806 #define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))
2807 #define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))
2809 /* isolate the least set bit of a bitmap */
2810 #define least_bit(x) ((x) & -(x))
2812 /* mask with all bits to left of least bit of x on */
2813 #define left_bits(x) ((x<<1) | -(x<<1))
2815 /* mask with all bits to left of or equal to least bit of x on */
2816 #define same_or_left_bits(x) ((x) | -(x))
2818 /* index corresponding to given bit. Use x86 asm if possible */
2820 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
2821 #define compute_bit2idx(X, I)\
2823 unsigned int J;\
2824 __asm__("bsfl\t%1, %0\n\t" : "=r" (J) : "g" (X));\
2825 I = (bindex_t)J;\
2828 #elif defined (__INTEL_COMPILER)
2829 #define compute_bit2idx(X, I)\
2831 unsigned int J;\
2832 J = _bit_scan_forward (X); \
2833 I = (bindex_t)J;\
2836 #elif defined(_MSC_VER) && _MSC_VER>=1300
2837 #define compute_bit2idx(X, I)\
2839 unsigned int J;\
2840 _BitScanForward((DWORD *) &J, X);\
2841 I = (bindex_t)J;\
2844 #elif USE_BUILTIN_FFS
2845 #define compute_bit2idx(X, I) I = ffs(X)-1
2847 #else
2848 #define compute_bit2idx(X, I)\
2850 unsigned int Y = X - 1;\
2851 unsigned int K = Y >> (16-4) & 16;\
2852 unsigned int N = K; Y >>= K;\
2853 N += K = Y >> (8-3) & 8; Y >>= K;\
2854 N += K = Y >> (4-2) & 4; Y >>= K;\
2855 N += K = Y >> (2-1) & 2; Y >>= K;\
2856 N += K = Y >> (1-0) & 1; Y >>= K;\
2857 I = (bindex_t)(N + Y);\
2859 #endif /* GNUC */
2862 /* ----------------------- Runtime Check Support ------------------------- */
2865 For security, the main invariant is that malloc/free/etc never
2866 writes to a static address other than malloc_state, unless static
2867 malloc_state itself has been corrupted, which cannot occur via
2868 malloc (because of these checks). In essence this means that we
2869 believe all pointers, sizes, maps etc held in malloc_state, but
2870 check all of those linked or offsetted from other embedded data
2871 structures. These checks are interspersed with main code in a way
2872 that tends to minimize their run-time cost.
2874 When FOOTERS is defined, in addition to range checking, we also
2875 verify footer fields of inuse chunks, which can be used guarantee
2876 that the mstate controlling malloc/free is intact. This is a
2877 streamlined version of the approach described by William Robertson
2878 et al in "Run-time Detection of Heap-based Overflows" LISA'03
2879 http://www.usenix.org/events/lisa03/tech/robertson.html The footer
2880 of an inuse chunk holds the xor of its mstate and a random seed,
2881 that is checked upon calls to free() and realloc(). This is
2882 (probablistically) unguessable from outside the program, but can be
2883 computed by any code successfully malloc'ing any chunk, so does not
2884 itself provide protection against code that has already broken
2885 security through some other means. Unlike Robertson et al, we
2886 always dynamically check addresses of all offset chunks (previous,
2887 next, etc). This turns out to be cheaper than relying on hashes.
2890 #if !INSECURE
2891 /* Check if address a is at least as high as any from MORECORE or MMAP */
2892 #define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
2893 /* Check if address of next chunk n is higher than base chunk p */
2894 #define ok_next(p, n) ((char*)(p) < (char*)(n))
2895 /* Check if p has inuse status */
2896 #define ok_inuse(p) is_inuse(p)
2897 /* Check if p has its pinuse bit on */
2898 #define ok_pinuse(p) pinuse(p)
2900 #else /* !INSECURE */
2901 #define ok_address(M, a) (1)
2902 #define ok_next(b, n) (1)
2903 #define ok_inuse(p) (1)
2904 #define ok_pinuse(p) (1)
2905 #endif /* !INSECURE */
2907 #if (FOOTERS && !INSECURE)
2908 /* Check if (alleged) mstate m has expected magic field */
2909 #define ok_magic(M) ((M)->magic == mparams.magic)
2910 #else /* (FOOTERS && !INSECURE) */
2911 #define ok_magic(M) (1)
2912 #endif /* (FOOTERS && !INSECURE) */
2915 /* In gcc, use __builtin_expect to minimize impact of checks */
2916 #if !INSECURE
2917 #if defined(__GNUC__) && __GNUC__ >= 3
2918 #define RTCHECK(e) __builtin_expect(e, 1)
2919 #else /* GNUC */
2920 #define RTCHECK(e) (e)
2921 #endif /* GNUC */
2922 #else /* !INSECURE */
2923 #define RTCHECK(e) (1)
2924 #endif /* !INSECURE */
2926 /* macros to set up inuse chunks with or without footers */
2928 #if !FOOTERS
2930 #define mark_inuse_foot(M,p,s)
2932 /* Macros for setting head/foot of non-mmapped chunks */
2934 /* Set cinuse bit and pinuse bit of next chunk */
2935 #define set_inuse(M,p,s)\
2936 ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
2937 ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
2939 /* Set cinuse and pinuse of this chunk and pinuse of next chunk */
2940 #define set_inuse_and_pinuse(M,p,s)\
2941 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2942 ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
2944 /* Set size, cinuse and pinuse bit of this chunk */
2945 #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
2946 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
2948 #else /* FOOTERS */
2950 /* Set foot of inuse chunk to be xor of mstate and seed */
2951 #define mark_inuse_foot(M,p,s)\
2952 (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
2954 #define get_mstate_for(p)\
2955 ((mstate)(((mchunkptr)((char*)(p) +\
2956 (chunksize(p))))->prev_foot ^ mparams.magic))
2958 #define set_inuse(M,p,s)\
2959 ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
2960 (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
2961 mark_inuse_foot(M,p,s))
2963 #define set_inuse_and_pinuse(M,p,s)\
2964 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2965 (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
2966 mark_inuse_foot(M,p,s))
2968 #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
2969 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2970 mark_inuse_foot(M, p, s))
2972 #endif /* !FOOTERS */
2974 /* ---------------------------- setting mparams -------------------------- */
2976 /* Initialize mparams */
2977 static int init_mparams(void) {
2978 #ifdef NEED_GLOBAL_LOCK_INIT
2979 if (malloc_global_mutex_status <= 0)
2980 init_malloc_global_mutex();
2981 #endif
2983 ACQUIRE_MALLOC_GLOBAL_LOCK();
2984 if (mparams.magic == 0) {
2985 size_t magic;
2986 size_t psize;
2987 size_t gsize;
2989 #ifndef WIN32
2990 psize = malloc_getpagesize;
2991 gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize);
2992 #else /* WIN32 */
2994 SYSTEM_INFO system_info;
2995 GetSystemInfo(&system_info);
2996 psize = system_info.dwPageSize;
2997 gsize = ((DEFAULT_GRANULARITY != 0)?
2998 DEFAULT_GRANULARITY : system_info.dwAllocationGranularity);
3000 #endif /* WIN32 */
3002 /* Sanity-check configuration:
3003 size_t must be unsigned and as wide as pointer type.
3004 ints must be at least 4 bytes.
3005 alignment must be at least 8.
3006 Alignment, min chunk size, and page size must all be powers of 2.
3008 if ((sizeof(size_t) != sizeof(char*)) ||
3009 (MAX_SIZE_T < MIN_CHUNK_SIZE) ||
3010 (sizeof(int) < 4) ||
3011 (MALLOC_ALIGNMENT < (size_t)8U) ||
3012 ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
3013 ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||
3014 ((gsize & (gsize-SIZE_T_ONE)) != 0) ||
3015 ((psize & (psize-SIZE_T_ONE)) != 0))
3016 ABORT;
3018 mparams.granularity = gsize;
3019 mparams.page_size = psize;
3020 mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
3021 mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
3022 #if MORECORE_CONTIGUOUS
3023 mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
3024 #else /* MORECORE_CONTIGUOUS */
3025 mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
3026 #endif /* MORECORE_CONTIGUOUS */
3028 #if !ONLY_MSPACES
3029 /* Set up lock for main malloc area */
3030 gm->mflags = mparams.default_mflags;
3031 INITIAL_LOCK(&gm->mutex);
3032 #endif
3035 #if USE_DEV_RANDOM
3036 int fd;
3037 unsigned char buf[sizeof(size_t)];
3038 /* Try to use /dev/urandom, else fall back on using time */
3039 if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
3040 read(fd, buf, sizeof(buf)) == sizeof(buf)) {
3041 magic = *((size_t *) buf);
3042 close(fd);
3044 else
3045 #endif /* USE_DEV_RANDOM */
3046 #ifdef WIN32
3047 magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U);
3048 #else
3049 magic = (size_t)(time(0) ^ (size_t)0x55555555U);
3050 #endif
3051 magic |= (size_t)8U; /* ensure nonzero */
3052 magic &= ~(size_t)7U; /* improve chances of fault for bad values */
3053 mparams.magic = magic;
3057 RELEASE_MALLOC_GLOBAL_LOCK();
3058 return 1;
3061 /* support for mallopt */
3062 static int change_mparam(int param_number, int value) {
3063 size_t val;
3064 ensure_initialization();
3065 val = (value == -1)? MAX_SIZE_T : (size_t)value;
3066 switch(param_number) {
3067 case M_TRIM_THRESHOLD:
3068 mparams.trim_threshold = val;
3069 return 1;
3070 case M_GRANULARITY:
3071 if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
3072 mparams.granularity = val;
3073 return 1;
3075 else
3076 return 0;
3077 case M_MMAP_THRESHOLD:
3078 mparams.mmap_threshold = val;
3079 return 1;
3080 default:
3081 return 0;
3085 #if DEBUG
3086 /* ------------------------- Debugging Support --------------------------- */
3088 /* Check properties of any chunk, whether free, inuse, mmapped etc */
3089 static void do_check_any_chunk(mstate m, mchunkptr p) {
3090 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
3091 assert(ok_address(m, p));
3094 /* Check properties of top chunk */
3095 static void do_check_top_chunk(mstate m, mchunkptr p) {
3096 msegmentptr sp = segment_holding(m, (char*)p);
3097 size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */
3098 assert(sp != 0);
3099 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
3100 assert(ok_address(m, p));
3101 assert(sz == m->topsize);
3102 assert(sz > 0);
3103 assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
3104 assert(pinuse(p));
3105 assert(!pinuse(chunk_plus_offset(p, sz)));
3108 /* Check properties of (inuse) mmapped chunks */
3109 static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
3110 size_t sz = chunksize(p);
3111 size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD);
3112 assert(is_mmapped(p));
3113 assert(use_mmap(m));
3114 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
3115 assert(ok_address(m, p));
3116 assert(!is_small(sz));
3117 assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
3118 assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
3119 assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
3122 /* Check properties of inuse chunks */
3123 static void do_check_inuse_chunk(mstate m, mchunkptr p) {
3124 do_check_any_chunk(m, p);
3125 assert(is_inuse(p));
3126 assert(next_pinuse(p));
3127 /* If not pinuse and not mmapped, previous chunk has OK offset */
3128 assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
3129 if (is_mmapped(p))
3130 do_check_mmapped_chunk(m, p);
3133 /* Check properties of free chunks */
3134 static void do_check_free_chunk(mstate m, mchunkptr p) {
3135 size_t sz = chunksize(p);
3136 mchunkptr next = chunk_plus_offset(p, sz);
3137 do_check_any_chunk(m, p);
3138 assert(!is_inuse(p));
3139 assert(!next_pinuse(p));
3140 assert (!is_mmapped(p));
3141 if (p != m->dv && p != m->top) {
3142 if (sz >= MIN_CHUNK_SIZE) {
3143 assert((sz & CHUNK_ALIGN_MASK) == 0);
3144 assert(is_aligned(chunk2mem(p)));
3145 assert(next->prev_foot == sz);
3146 assert(pinuse(p));
3147 assert (next == m->top || is_inuse(next));
3148 assert(p->fd->bk == p);
3149 assert(p->bk->fd == p);
3151 else /* markers are always of size SIZE_T_SIZE */
3152 assert(sz == SIZE_T_SIZE);
3156 /* Check properties of malloced chunks at the point they are malloced */
3157 static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
3158 if (mem != 0) {
3159 mchunkptr p = mem2chunk(mem);
3160 size_t sz = p->head & ~INUSE_BITS;
3161 do_check_inuse_chunk(m, p);
3162 assert((sz & CHUNK_ALIGN_MASK) == 0);
3163 assert(sz >= MIN_CHUNK_SIZE);
3164 assert(sz >= s);
3165 /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
3166 assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
3170 /* Check a tree and its subtrees. */
3171 static void do_check_tree(mstate m, tchunkptr t) {
3172 tchunkptr head = 0;
3173 tchunkptr u = t;
3174 bindex_t tindex = t->index;
3175 size_t tsize = chunksize(t);
3176 bindex_t idx;
3177 compute_tree_index(tsize, idx);
3178 assert(tindex == idx);
3179 assert(tsize >= MIN_LARGE_SIZE);
3180 assert(tsize >= minsize_for_tree_index(idx));
3181 assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
3183 do { /* traverse through chain of same-sized nodes */
3184 do_check_any_chunk(m, ((mchunkptr)u));
3185 assert(u->index == tindex);
3186 assert(chunksize(u) == tsize);
3187 assert(!is_inuse(u));
3188 assert(!next_pinuse(u));
3189 assert(u->fd->bk == u);
3190 assert(u->bk->fd == u);
3191 if (u->parent == 0) {
3192 assert(u->child[0] == 0);
3193 assert(u->child[1] == 0);
3195 else {
3196 assert(head == 0); /* only one node on chain has parent */
3197 head = u;
3198 assert(u->parent != u);
3199 assert (u->parent->child[0] == u ||
3200 u->parent->child[1] == u ||
3201 *((tbinptr*)(u->parent)) == u);
3202 if (u->child[0] != 0) {
3203 assert(u->child[0]->parent == u);
3204 assert(u->child[0] != u);
3205 do_check_tree(m, u->child[0]);
3207 if (u->child[1] != 0) {
3208 assert(u->child[1]->parent == u);
3209 assert(u->child[1] != u);
3210 do_check_tree(m, u->child[1]);
3212 if (u->child[0] != 0 && u->child[1] != 0) {
3213 assert(chunksize(u->child[0]) < chunksize(u->child[1]));
3216 u = u->fd;
3217 } while (u != t);
3218 assert(head != 0);
3221 /* Check all the chunks in a treebin. */
3222 static void do_check_treebin(mstate m, bindex_t i) {
3223 tbinptr* tb = treebin_at(m, i);
3224 tchunkptr t = *tb;
3225 int empty = (m->treemap & (1U << i)) == 0;
3226 if (t == 0)
3227 assert(empty);
3228 if (!empty)
3229 do_check_tree(m, t);
3232 /* Check all the chunks in a smallbin. */
3233 static void do_check_smallbin(mstate m, bindex_t i) {
3234 sbinptr b = smallbin_at(m, i);
3235 mchunkptr p = b->bk;
3236 unsigned int empty = (m->smallmap & (1U << i)) == 0;
3237 if (p == b)
3238 assert(empty);
3239 if (!empty) {
3240 for (; p != b; p = p->bk) {
3241 size_t size = chunksize(p);
3242 mchunkptr q;
3243 /* each chunk claims to be free */
3244 do_check_free_chunk(m, p);
3245 /* chunk belongs in bin */
3246 assert(small_index(size) == i);
3247 assert(p->bk == b || chunksize(p->bk) == chunksize(p));
3248 /* chunk is followed by an inuse chunk */
3249 q = next_chunk(p);
3250 if (q->head != FENCEPOST_HEAD)
3251 do_check_inuse_chunk(m, q);
3256 /* Find x in a bin. Used in other check functions. */
3257 static int bin_find(mstate m, mchunkptr x) {
3258 size_t size = chunksize(x);
3259 if (is_small(size)) {
3260 bindex_t sidx = small_index(size);
3261 sbinptr b = smallbin_at(m, sidx);
3262 if (smallmap_is_marked(m, sidx)) {
3263 mchunkptr p = b;
3264 do {
3265 if (p == x)
3266 return 1;
3267 } while ((p = p->fd) != b);
3270 else {
3271 bindex_t tidx;
3272 compute_tree_index(size, tidx);
3273 if (treemap_is_marked(m, tidx)) {
3274 tchunkptr t = *treebin_at(m, tidx);
3275 size_t sizebits = size << leftshift_for_tree_index(tidx);
3276 while (t != 0 && chunksize(t) != size) {
3277 t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
3278 sizebits <<= 1;
3280 if (t != 0) {
3281 tchunkptr u = t;
3282 do {
3283 if (u == (tchunkptr)x)
3284 return 1;
3285 } while ((u = u->fd) != t);
3289 return 0;
3292 /* Traverse each chunk and check it; return total */
3293 static size_t traverse_and_check(mstate m) {
3294 size_t sum = 0;
3295 if (is_initialized(m)) {
3296 msegmentptr s = &m->seg;
3297 sum += m->topsize + TOP_FOOT_SIZE;
3298 while (s != 0) {
3299 mchunkptr q = align_as_chunk(s->base);
3300 mchunkptr lastq = 0;
3301 assert(pinuse(q));
3302 while (segment_holds(s, q) &&
3303 q != m->top && q->head != FENCEPOST_HEAD) {
3304 sum += chunksize(q);
3305 if (is_inuse(q)) {
3306 assert(!bin_find(m, q));
3307 do_check_inuse_chunk(m, q);
3309 else {
3310 assert(q == m->dv || bin_find(m, q));
3311 assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */
3312 do_check_free_chunk(m, q);
3314 lastq = q;
3315 q = next_chunk(q);
3317 s = s->next;
3320 return sum;
3323 /* Check all properties of malloc_state. */
3324 static void do_check_malloc_state(mstate m) {
3325 bindex_t i;
3326 size_t total;
3327 /* check bins */
3328 for (i = 0; i < NSMALLBINS; ++i)
3329 do_check_smallbin(m, i);
3330 for (i = 0; i < NTREEBINS; ++i)
3331 do_check_treebin(m, i);
3333 if (m->dvsize != 0) { /* check dv chunk */
3334 do_check_any_chunk(m, m->dv);
3335 assert(m->dvsize == chunksize(m->dv));
3336 assert(m->dvsize >= MIN_CHUNK_SIZE);
3337 assert(bin_find(m, m->dv) == 0);
3340 if (m->top != 0) { /* check top chunk */
3341 do_check_top_chunk(m, m->top);
3342 /*assert(m->topsize == chunksize(m->top)); redundant */
3343 assert(m->topsize > 0);
3344 assert(bin_find(m, m->top) == 0);
3347 total = traverse_and_check(m);
3348 assert(total <= m->footprint);
3349 assert(m->footprint <= m->max_footprint);
3351 #endif /* DEBUG */
3353 /* ----------------------------- statistics ------------------------------ */
3355 #if !NO_MALLINFO
3356 static struct mallinfo internal_mallinfo(mstate m) {
3357 struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
3358 ensure_initialization();
3359 if (!PREACTION(m)) {
3360 check_malloc_state(m);
3361 if (is_initialized(m)) {
3362 size_t nfree = SIZE_T_ONE; /* top always free */
3363 size_t mfree = m->topsize + TOP_FOOT_SIZE;
3364 size_t sum = mfree;
3365 msegmentptr s = &m->seg;
3366 while (s != 0) {
3367 mchunkptr q = align_as_chunk(s->base);
3368 while (segment_holds(s, q) &&
3369 q != m->top && q->head != FENCEPOST_HEAD) {
3370 size_t sz = chunksize(q);
3371 sum += sz;
3372 if (!is_inuse(q)) {
3373 mfree += sz;
3374 ++nfree;
3376 q = next_chunk(q);
3378 s = s->next;
3381 nm.arena = sum;
3382 nm.ordblks = nfree;
3383 nm.hblkhd = m->footprint - sum;
3384 nm.usmblks = m->max_footprint;
3385 nm.uordblks = m->footprint - mfree;
3386 nm.fordblks = mfree;
3387 nm.keepcost = m->topsize;
3390 POSTACTION(m);
3392 return nm;
3394 #endif /* !NO_MALLINFO */
3396 static void internal_malloc_stats(mstate m) {
3397 ensure_initialization();
3398 if (!PREACTION(m)) {
3399 size_t maxfp = 0;
3400 size_t fp = 0;
3401 size_t used = 0;
3402 check_malloc_state(m);
3403 if (is_initialized(m)) {
3404 msegmentptr s = &m->seg;
3405 maxfp = m->max_footprint;
3406 fp = m->footprint;
3407 used = fp - (m->topsize + TOP_FOOT_SIZE);
3409 while (s != 0) {
3410 mchunkptr q = align_as_chunk(s->base);
3411 while (segment_holds(s, q) &&
3412 q != m->top && q->head != FENCEPOST_HEAD) {
3413 if (!is_inuse(q))
3414 used -= chunksize(q);
3415 q = next_chunk(q);
3417 s = s->next;
3421 printf("max system bytes = %10lu\n", (unsigned long)(maxfp));
3422 printf("system bytes = %10lu\n", (unsigned long)(fp));
3423 printf("in use bytes = %10lu\n", (unsigned long)(used));
3425 POSTACTION(m);
3429 /* ----------------------- Operations on smallbins ----------------------- */
3432 Various forms of linking and unlinking are defined as macros. Even
3433 the ones for trees, which are very long but have very short typical
3434 paths. This is ugly but reduces reliance on inlining support of
3435 compilers.
3438 /* Link a free chunk into a smallbin */
3439 #define insert_small_chunk(M, P, S) {\
3440 bindex_t I = small_index(S);\
3441 mchunkptr B = smallbin_at(M, I);\
3442 mchunkptr F = B;\
3443 assert(S >= MIN_CHUNK_SIZE);\
3444 if (!smallmap_is_marked(M, I))\
3445 mark_smallmap(M, I);\
3446 else if (RTCHECK(ok_address(M, B->fd)))\
3447 F = B->fd;\
3448 else {\
3449 CORRUPTION_ERROR_ACTION(M);\
3451 B->fd = P;\
3452 F->bk = P;\
3453 P->fd = F;\
3454 P->bk = B;\
3457 /* Unlink a chunk from a smallbin */
3458 #define unlink_small_chunk(M, P, S) {\
3459 mchunkptr F = P->fd;\
3460 mchunkptr B = P->bk;\
3461 bindex_t I = small_index(S);\
3462 assert(P != B);\
3463 assert(P != F);\
3464 assert(chunksize(P) == small_index2size(I));\
3465 if (F == B)\
3466 clear_smallmap(M, I);\
3467 else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
3468 (B == smallbin_at(M,I) || ok_address(M, B)))) {\
3469 F->bk = B;\
3470 B->fd = F;\
3472 else {\
3473 CORRUPTION_ERROR_ACTION(M);\
3477 /* Unlink the first chunk from a smallbin */
3478 #define unlink_first_small_chunk(M, B, P, I) {\
3479 mchunkptr F = P->fd;\
3480 assert(P != B);\
3481 assert(P != F);\
3482 assert(chunksize(P) == small_index2size(I));\
3483 if (B == F)\
3484 clear_smallmap(M, I);\
3485 else if (RTCHECK(ok_address(M, F))) {\
3486 B->fd = F;\
3487 F->bk = B;\
3489 else {\
3490 CORRUPTION_ERROR_ACTION(M);\
3496 /* Replace dv node, binning the old one */
3497 /* Used only when dvsize known to be small */
3498 #define replace_dv(M, P, S) {\
3499 size_t DVS = M->dvsize;\
3500 if (DVS != 0) {\
3501 mchunkptr DV = M->dv;\
3502 assert(is_small(DVS));\
3503 insert_small_chunk(M, DV, DVS);\
3505 M->dvsize = S;\
3506 M->dv = P;\
3509 /* ------------------------- Operations on trees ------------------------- */
3511 /* Insert chunk into tree */
3512 #define insert_large_chunk(M, X, S) {\
3513 tbinptr* H;\
3514 bindex_t I;\
3515 compute_tree_index(S, I);\
3516 H = treebin_at(M, I);\
3517 X->index = I;\
3518 X->child[0] = X->child[1] = 0;\
3519 if (!treemap_is_marked(M, I)) {\
3520 mark_treemap(M, I);\
3521 *H = X;\
3522 X->parent = (tchunkptr)H;\
3523 X->fd = X->bk = X;\
3525 else {\
3526 tchunkptr T = *H;\
3527 size_t K = S << leftshift_for_tree_index(I);\
3528 for (;;) {\
3529 if (chunksize(T) != S) {\
3530 tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
3531 K <<= 1;\
3532 if (*C != 0)\
3533 T = *C;\
3534 else if (RTCHECK(ok_address(M, C))) {\
3535 *C = X;\
3536 X->parent = T;\
3537 X->fd = X->bk = X;\
3538 break;\
3540 else {\
3541 CORRUPTION_ERROR_ACTION(M);\
3542 break;\
3545 else {\
3546 tchunkptr F = T->fd;\
3547 if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
3548 T->fd = F->bk = X;\
3549 X->fd = F;\
3550 X->bk = T;\
3551 X->parent = 0;\
3552 break;\
3554 else {\
3555 CORRUPTION_ERROR_ACTION(M);\
3556 break;\
3564 Unlink steps:
3566 1. If x is a chained node, unlink it from its same-sized fd/bk links
3567 and choose its bk node as its replacement.
3568 2. If x was the last node of its size, but not a leaf node, it must
3569 be replaced with a leaf node (not merely one with an open left or
3570 right), to make sure that lefts and rights of descendents
3571 correspond properly to bit masks. We use the rightmost descendent
3572 of x. We could use any other leaf, but this is easy to locate and
3573 tends to counteract removal of leftmosts elsewhere, and so keeps
3574 paths shorter than minimally guaranteed. This doesn't loop much
3575 because on average a node in a tree is near the bottom.
3576 3. If x is the base of a chain (i.e., has parent links) relink
3577 x's parent and children to x's replacement (or null if none).
3580 #define unlink_large_chunk(M, X) {\
3581 tchunkptr XP = X->parent;\
3582 tchunkptr R;\
3583 if (X->bk != X) {\
3584 tchunkptr F = X->fd;\
3585 R = X->bk;\
3586 if (RTCHECK(ok_address(M, F))) {\
3587 F->bk = R;\
3588 R->fd = F;\
3590 else {\
3591 CORRUPTION_ERROR_ACTION(M);\
3594 else {\
3595 tchunkptr* RP;\
3596 if (((R = *(RP = &(X->child[1]))) != 0) ||\
3597 ((R = *(RP = &(X->child[0]))) != 0)) {\
3598 tchunkptr* CP;\
3599 while ((*(CP = &(R->child[1])) != 0) ||\
3600 (*(CP = &(R->child[0])) != 0)) {\
3601 R = *(RP = CP);\
3603 if (RTCHECK(ok_address(M, RP)))\
3604 *RP = 0;\
3605 else {\
3606 CORRUPTION_ERROR_ACTION(M);\
3610 if (XP != 0) {\
3611 tbinptr* H = treebin_at(M, X->index);\
3612 if (X == *H) {\
3613 if ((*H = R) == 0) \
3614 clear_treemap(M, X->index);\
3616 else if (RTCHECK(ok_address(M, XP))) {\
3617 if (XP->child[0] == X) \
3618 XP->child[0] = R;\
3619 else \
3620 XP->child[1] = R;\
3622 else\
3623 CORRUPTION_ERROR_ACTION(M);\
3624 if (R != 0) {\
3625 if (RTCHECK(ok_address(M, R))) {\
3626 tchunkptr C0, C1;\
3627 R->parent = XP;\
3628 if ((C0 = X->child[0]) != 0) {\
3629 if (RTCHECK(ok_address(M, C0))) {\
3630 R->child[0] = C0;\
3631 C0->parent = R;\
3633 else\
3634 CORRUPTION_ERROR_ACTION(M);\
3636 if ((C1 = X->child[1]) != 0) {\
3637 if (RTCHECK(ok_address(M, C1))) {\
3638 R->child[1] = C1;\
3639 C1->parent = R;\
3641 else\
3642 CORRUPTION_ERROR_ACTION(M);\
3645 else\
3646 CORRUPTION_ERROR_ACTION(M);\
3651 /* Relays to large vs small bin operations */
3653 #define insert_chunk(M, P, S)\
3654 if (is_small(S)) insert_small_chunk(M, P, S)\
3655 else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
3657 #define unlink_chunk(M, P, S)\
3658 if (is_small(S)) unlink_small_chunk(M, P, S)\
3659 else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
3662 /* Relays to internal calls to malloc/free from realloc, memalign etc */
3664 #if ONLY_MSPACES
3665 #define internal_malloc(m, b) mspace_malloc(m, b)
3666 #define internal_free(m, mem) mspace_free(m,mem);
3667 #else /* ONLY_MSPACES */
3668 #if MSPACES
3669 #define internal_malloc(m, b)\
3670 (m == gm)? dlmalloc(b) : mspace_malloc(m, b)
3671 #define internal_free(m, mem)\
3672 if (m == gm) dlfree(mem); else mspace_free(m,mem);
3673 #else /* MSPACES */
3674 #define internal_malloc(m, b) dlmalloc(b)
3675 #define internal_free(m, mem) dlfree(mem)
3676 #endif /* MSPACES */
3677 #endif /* ONLY_MSPACES */
3679 /* ----------------------- Direct-mmapping chunks ----------------------- */
3682 Directly mmapped chunks are set up with an offset to the start of
3683 the mmapped region stored in the prev_foot field of the chunk. This
3684 allows reconstruction of the required argument to MUNMAP when freed,
3685 and also allows adjustment of the returned chunk to meet alignment
3686 requirements (especially in memalign).
3689 /* Malloc using mmap */
3690 static void* mmap_alloc(mstate m, size_t nb) {
3691 size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
3692 if (mmsize > nb) { /* Check for wrap around 0 */
3693 char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));
3694 if (mm != CMFAIL) {
3695 size_t offset = align_offset(chunk2mem(mm));
3696 size_t psize = mmsize - offset - MMAP_FOOT_PAD;
3697 mchunkptr p = (mchunkptr)(mm + offset);
3698 p->prev_foot = offset;
3699 p->head = psize;
3700 mark_inuse_foot(m, p, psize);
3701 chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
3702 chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
3704 if (m->least_addr == 0 || mm < m->least_addr)
3705 m->least_addr = mm;
3706 if ((m->footprint += mmsize) > m->max_footprint)
3707 m->max_footprint = m->footprint;
3708 assert(is_aligned(chunk2mem(p)));
3709 check_mmapped_chunk(m, p);
3710 return chunk2mem(p);
3713 return 0;
3716 /* Realloc using mmap */
3717 static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) {
3718 size_t oldsize = chunksize(oldp);
3719 if (is_small(nb)) /* Can't shrink mmap regions below small size */
3720 return 0;
3721 /* Keep old chunk if big enough but not too big */
3722 if (oldsize >= nb + SIZE_T_SIZE &&
3723 (oldsize - nb) <= (mparams.granularity << 1))
3724 return oldp;
3725 else {
3726 size_t offset = oldp->prev_foot;
3727 size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
3728 size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
3729 char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
3730 oldmmsize, newmmsize, 1);
3731 if (cp != CMFAIL) {
3732 mchunkptr newp = (mchunkptr)(cp + offset);
3733 size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
3734 newp->head = psize;
3735 mark_inuse_foot(m, newp, psize);
3736 chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
3737 chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
3739 if (cp < m->least_addr)
3740 m->least_addr = cp;
3741 if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
3742 m->max_footprint = m->footprint;
3743 check_mmapped_chunk(m, newp);
3744 return newp;
3747 return 0;
3750 /* -------------------------- mspace management -------------------------- */
3752 /* Initialize top chunk and its size */
3753 static void init_top(mstate m, mchunkptr p, size_t psize) {
3754 /* Ensure alignment */
3755 size_t offset = align_offset(chunk2mem(p));
3756 p = (mchunkptr)((char*)p + offset);
3757 psize -= offset;
3759 m->top = p;
3760 m->topsize = psize;
3761 p->head = psize | PINUSE_BIT;
3762 /* set size of fake trailing chunk holding overhead space only once */
3763 chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
3764 m->trim_check = mparams.trim_threshold; /* reset on each update */
3767 /* Initialize bins for a new mstate that is otherwise zeroed out */
3768 static void init_bins(mstate m) {
3769 /* Establish circular links for smallbins */
3770 bindex_t i;
3771 for (i = 0; i < NSMALLBINS; ++i) {
3772 sbinptr bin = smallbin_at(m,i);
3773 bin->fd = bin->bk = bin;
3777 #if PROCEED_ON_ERROR
3779 /* default corruption action */
3780 static void reset_on_error(mstate m) {
3781 int i;
3782 ++malloc_corruption_error_count;
3783 /* Reinitialize fields to forget about all memory */
3784 m->smallbins = m->treebins = 0;
3785 m->dvsize = m->topsize = 0;
3786 m->seg.base = 0;
3787 m->seg.size = 0;
3788 m->seg.next = 0;
3789 m->top = m->dv = 0;
3790 for (i = 0; i < NTREEBINS; ++i)
3791 *treebin_at(m, i) = 0;
3792 init_bins(m);
3794 #endif /* PROCEED_ON_ERROR */
3796 /* Allocate chunk and prepend remainder with chunk in successor base. */
3797 static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
3798 size_t nb) {
3799 mchunkptr p = align_as_chunk(newbase);
3800 mchunkptr oldfirst = align_as_chunk(oldbase);
3801 size_t psize = (char*)oldfirst - (char*)p;
3802 mchunkptr q = chunk_plus_offset(p, nb);
3803 size_t qsize = psize - nb;
3804 set_size_and_pinuse_of_inuse_chunk(m, p, nb);
3806 assert((char*)oldfirst > (char*)q);
3807 assert(pinuse(oldfirst));
3808 assert(qsize >= MIN_CHUNK_SIZE);
3810 /* consolidate remainder with first chunk of old base */
3811 if (oldfirst == m->top) {
3812 size_t tsize = m->topsize += qsize;
3813 m->top = q;
3814 q->head = tsize | PINUSE_BIT;
3815 check_top_chunk(m, q);
3817 else if (oldfirst == m->dv) {
3818 size_t dsize = m->dvsize += qsize;
3819 m->dv = q;
3820 set_size_and_pinuse_of_free_chunk(q, dsize);
3822 else {
3823 if (!is_inuse(oldfirst)) {
3824 size_t nsize = chunksize(oldfirst);
3825 unlink_chunk(m, oldfirst, nsize);
3826 oldfirst = chunk_plus_offset(oldfirst, nsize);
3827 qsize += nsize;
3829 set_free_with_pinuse(q, qsize, oldfirst);
3830 insert_chunk(m, q, qsize);
3831 check_free_chunk(m, q);
3834 check_malloced_chunk(m, chunk2mem(p), nb);
3835 return chunk2mem(p);
3838 /* Add a segment to hold a new noncontiguous region */
3839 static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
3840 /* Determine locations and sizes of segment, fenceposts, old top */
3841 char* old_top = (char*)m->top;
3842 msegmentptr oldsp = segment_holding(m, old_top);
3843 char* old_end = oldsp->base + oldsp->size;
3844 size_t ssize = pad_request(sizeof(struct malloc_segment));
3845 char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
3846 size_t offset = align_offset(chunk2mem(rawsp));
3847 char* asp = rawsp + offset;
3848 char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
3849 mchunkptr sp = (mchunkptr)csp;
3850 msegmentptr ss = (msegmentptr)(chunk2mem(sp));
3851 mchunkptr tnext = chunk_plus_offset(sp, ssize);
3852 mchunkptr p = tnext;
3853 int nfences = 0;
3855 /* reset top to new space */
3856 init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
3858 /* Set up segment record */
3859 assert(is_aligned(ss));
3860 set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
3861 *ss = m->seg; /* Push current record */
3862 m->seg.base = tbase;
3863 m->seg.size = tsize;
3864 m->seg.sflags = mmapped;
3865 m->seg.next = ss;
3867 /* Insert trailing fenceposts */
3868 for (;;) {
3869 mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
3870 p->head = FENCEPOST_HEAD;
3871 ++nfences;
3872 if ((char*)(&(nextp->head)) < old_end)
3873 p = nextp;
3874 else
3875 break;
3877 assert(nfences >= 2);
3879 /* Insert the rest of old top into a bin as an ordinary free chunk */
3880 if (csp != old_top) {
3881 mchunkptr q = (mchunkptr)old_top;
3882 size_t psize = csp - old_top;
3883 mchunkptr tn = chunk_plus_offset(q, psize);
3884 set_free_with_pinuse(q, psize, tn);
3885 insert_chunk(m, q, psize);
3888 check_top_chunk(m, m->top);
3891 /* -------------------------- System allocation -------------------------- */
3893 /* Get memory from system using MORECORE or MMAP */
3894 static void* sys_alloc(mstate m, size_t nb) {
3895 char* tbase = CMFAIL;
3896 size_t tsize = 0;
3897 flag_t mmap_flag = 0;
3899 ensure_initialization();
3901 /* Directly map large chunks, but only if already initialized */
3902 if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) {
3903 void* mem = mmap_alloc(m, nb);
3904 if (mem != 0)
3905 return mem;
3909 Try getting memory in any of three ways (in most-preferred to
3910 least-preferred order):
3911 1. A call to MORECORE that can normally contiguously extend memory.
3912 (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
3913 or main space is mmapped or a previous contiguous call failed)
3914 2. A call to MMAP new space (disabled if not HAVE_MMAP).
3915 Note that under the default settings, if MORECORE is unable to
3916 fulfill a request, and HAVE_MMAP is true, then mmap is
3917 used as a noncontiguous system allocator. This is a useful backup
3918 strategy for systems with holes in address spaces -- in this case
3919 sbrk cannot contiguously expand the heap, but mmap may be able to
3920 find space.
3921 3. A call to MORECORE that cannot usually contiguously extend memory.
3922 (disabled if not HAVE_MORECORE)
3924 In all cases, we need to request enough bytes from system to ensure
3925 we can malloc nb bytes upon success, so pad with enough space for
3926 top_foot, plus alignment-pad to make sure we don't lose bytes if
3927 not on boundary, and round this up to a granularity unit.
3930 if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
3931 char* br = CMFAIL;
3932 msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
3933 size_t asize = 0;
3934 ACQUIRE_MALLOC_GLOBAL_LOCK();
3936 if (ss == 0) { /* First time through or recovery */
3937 char* base = (char*)CALL_MORECORE(0);
3938 if (base != CMFAIL) {
3939 asize = granularity_align(nb + SYS_ALLOC_PADDING);
3940 /* Adjust to end on a page boundary */
3941 if (!is_page_aligned(base))
3942 asize += (page_align((size_t)base) - (size_t)base);
3943 /* Can't call MORECORE if size is negative when treated as signed */
3944 if (asize < HALF_MAX_SIZE_T &&
3945 (br = (char*)(CALL_MORECORE(asize))) == base) {
3946 tbase = base;
3947 tsize = asize;
3951 else {
3952 /* Subtract out existing available top space from MORECORE request. */
3953 asize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING);
3954 /* Use mem here only if it did continuously extend old space */
3955 if (asize < HALF_MAX_SIZE_T &&
3956 (br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) {
3957 tbase = br;
3958 tsize = asize;
3962 if (tbase == CMFAIL) { /* Cope with partial failure */
3963 if (br != CMFAIL) { /* Try to use/extend the space we did get */
3964 if (asize < HALF_MAX_SIZE_T &&
3965 asize < nb + SYS_ALLOC_PADDING) {
3966 size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - asize);
3967 if (esize < HALF_MAX_SIZE_T) {
3968 char* end = (char*)CALL_MORECORE(esize);
3969 if (end != CMFAIL)
3970 asize += esize;
3971 else { /* Can't use; try to release */
3972 (void) CALL_MORECORE(-asize);
3973 br = CMFAIL;
3978 if (br != CMFAIL) { /* Use the space we did get */
3979 tbase = br;
3980 tsize = asize;
3982 else
3983 disable_contiguous(m); /* Don't try contiguous path in the future */
3986 RELEASE_MALLOC_GLOBAL_LOCK();
3989 if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */
3990 size_t rsize = granularity_align(nb + SYS_ALLOC_PADDING);
3991 if (rsize > nb) { /* Fail if wraps around zero */
3992 char* mp = (char*)(CALL_MMAP(rsize));
3993 if (mp != CMFAIL) {
3994 tbase = mp;
3995 tsize = rsize;
3996 mmap_flag = USE_MMAP_BIT;
4001 if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
4002 size_t asize = granularity_align(nb + SYS_ALLOC_PADDING);
4003 if (asize < HALF_MAX_SIZE_T) {
4004 char* br = CMFAIL;
4005 char* end = CMFAIL;
4006 ACQUIRE_MALLOC_GLOBAL_LOCK();
4007 br = (char*)(CALL_MORECORE(asize));
4008 end = (char*)(CALL_MORECORE(0));
4009 RELEASE_MALLOC_GLOBAL_LOCK();
4010 if (br != CMFAIL && end != CMFAIL && br < end) {
4011 size_t ssize = end - br;
4012 if (ssize > nb + TOP_FOOT_SIZE) {
4013 tbase = br;
4014 tsize = ssize;
4020 if (tbase != CMFAIL) {
4022 if ((m->footprint += tsize) > m->max_footprint)
4023 m->max_footprint = m->footprint;
4025 if (!is_initialized(m)) { /* first-time initialization */
4026 if (m->least_addr == 0 || tbase < m->least_addr)
4027 m->least_addr = tbase;
4028 m->seg.base = tbase;
4029 m->seg.size = tsize;
4030 m->seg.sflags = mmap_flag;
4031 m->magic = mparams.magic;
4032 m->release_checks = MAX_RELEASE_CHECK_RATE;
4033 init_bins(m);
4034 #if !ONLY_MSPACES
4035 if (is_global(m))
4036 init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
4037 else
4038 #endif
4040 /* Offset top by embedded malloc_state */
4041 mchunkptr mn = next_chunk(mem2chunk(m));
4042 init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
4046 else {
4047 /* Try to merge with an existing segment */
4048 msegmentptr sp = &m->seg;
4049 /* Only consider most recent segment if traversal suppressed */
4050 while (sp != 0 && tbase != sp->base + sp->size)
4051 sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
4052 if (sp != 0 &&
4053 !is_extern_segment(sp) &&
4054 (sp->sflags & USE_MMAP_BIT) == mmap_flag &&
4055 segment_holds(sp, m->top)) { /* append */
4056 sp->size += tsize;
4057 init_top(m, m->top, m->topsize + tsize);
4059 else {
4060 if (tbase < m->least_addr)
4061 m->least_addr = tbase;
4062 sp = &m->seg;
4063 while (sp != 0 && sp->base != tbase + tsize)
4064 sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
4065 if (sp != 0 &&
4066 !is_extern_segment(sp) &&
4067 (sp->sflags & USE_MMAP_BIT) == mmap_flag) {
4068 char* oldbase = sp->base;
4069 sp->base = tbase;
4070 sp->size += tsize;
4071 return prepend_alloc(m, tbase, oldbase, nb);
4073 else
4074 add_segment(m, tbase, tsize, mmap_flag);
4078 if (nb < m->topsize) { /* Allocate from new or extended top space */
4079 size_t rsize = m->topsize -= nb;
4080 mchunkptr p = m->top;
4081 mchunkptr r = m->top = chunk_plus_offset(p, nb);
4082 r->head = rsize | PINUSE_BIT;
4083 set_size_and_pinuse_of_inuse_chunk(m, p, nb);
4084 check_top_chunk(m, m->top);
4085 check_malloced_chunk(m, chunk2mem(p), nb);
4086 return chunk2mem(p);
4090 MALLOC_FAILURE_ACTION;
4091 return 0;
4094 /* ----------------------- system deallocation -------------------------- */
4096 /* Unmap and unlink any mmapped segments that don't contain used chunks */
4097 static size_t release_unused_segments(mstate m) {
4098 size_t released = 0;
4099 int nsegs = 0;
4100 msegmentptr pred = &m->seg;
4101 msegmentptr sp = pred->next;
4102 while (sp != 0) {
4103 char* base = sp->base;
4104 size_t size = sp->size;
4105 msegmentptr next = sp->next;
4106 ++nsegs;
4107 if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
4108 mchunkptr p = align_as_chunk(base);
4109 size_t psize = chunksize(p);
4110 /* Can unmap if first chunk holds entire segment and not pinned */
4111 if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
4112 tchunkptr tp = (tchunkptr)p;
4113 assert(segment_holds(sp, (char*)sp));
4114 if (p == m->dv) {
4115 m->dv = 0;
4116 m->dvsize = 0;
4118 else {
4119 unlink_large_chunk(m, tp);
4121 if (CALL_MUNMAP(base, size) == 0) {
4122 released += size;
4123 m->footprint -= size;
4124 /* unlink obsoleted record */
4125 sp = pred;
4126 sp->next = next;
4128 else { /* back out if cannot unmap */
4129 insert_large_chunk(m, tp, psize);
4133 if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */
4134 break;
4135 pred = sp;
4136 sp = next;
4138 /* Reset check counter */
4139 m->release_checks = ((nsegs > MAX_RELEASE_CHECK_RATE)?
4140 nsegs : MAX_RELEASE_CHECK_RATE);
4141 return released;
4144 static int sys_trim(mstate m, size_t pad) {
4145 size_t released = 0;
4146 ensure_initialization();
4147 if (pad < MAX_REQUEST && is_initialized(m)) {
4148 pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
4150 if (m->topsize > pad) {
4151 /* Shrink top space in granularity-size units, keeping at least one */
4152 size_t unit = mparams.granularity;
4153 size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
4154 SIZE_T_ONE) * unit;
4155 msegmentptr sp = segment_holding(m, (char*)m->top);
4157 if (!is_extern_segment(sp)) {
4158 if (is_mmapped_segment(sp)) {
4159 if (HAVE_MMAP &&
4160 sp->size >= extra &&
4161 !has_segment_link(m, sp)) { /* can't shrink if pinned */
4162 //size_t newsize = sp->size - extra;
4163 /* Prefer mremap, fall back to munmap */
4164 if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
4165 (CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
4166 released = extra;
4170 else if (HAVE_MORECORE) {
4171 if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
4172 extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
4173 ACQUIRE_MALLOC_GLOBAL_LOCK();
4175 /* Make sure end of memory is where we last set it. */
4176 char* old_br = (char*)(CALL_MORECORE(0));
4177 if (old_br == sp->base + sp->size) {
4178 char* rel_br = (char*)(CALL_MORECORE(-extra));
4179 char* new_br = (char*)(CALL_MORECORE(0));
4180 if (rel_br != CMFAIL && new_br < old_br)
4181 released = old_br - new_br;
4184 RELEASE_MALLOC_GLOBAL_LOCK();
4188 if (released != 0) {
4189 sp->size -= released;
4190 m->footprint -= released;
4191 init_top(m, m->top, m->topsize - released);
4192 check_top_chunk(m, m->top);
4196 /* Unmap any unused mmapped segments */
4197 if (HAVE_MMAP)
4198 released += release_unused_segments(m);
4200 /* On failure, disable autotrim to avoid repeated failed future calls */
4201 if (released == 0 && m->topsize > m->trim_check)
4202 m->trim_check = MAX_SIZE_T;
4205 return (released != 0)? 1 : 0;
4209 /* ---------------------------- malloc support --------------------------- */
4211 /* allocate a large request from the best fitting chunk in a treebin */
4212 static void* tmalloc_large(mstate m, size_t nb) {
4213 tchunkptr v = 0;
4214 size_t rsize = -nb; /* Unsigned negation */
4215 tchunkptr t;
4216 bindex_t idx;
4217 compute_tree_index(nb, idx);
4218 if ((t = *treebin_at(m, idx)) != 0) {
4219 /* Traverse tree for this bin looking for node with size == nb */
4220 size_t sizebits = nb << leftshift_for_tree_index(idx);
4221 tchunkptr rst = 0; /* The deepest untaken right subtree */
4222 for (;;) {
4223 tchunkptr rt;
4224 size_t trem = chunksize(t) - nb;
4225 if (trem < rsize) {
4226 v = t;
4227 if ((rsize = trem) == 0)
4228 break;
4230 rt = t->child[1];
4231 t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
4232 if (rt != 0 && rt != t)
4233 rst = rt;
4234 if (t == 0) {
4235 t = rst; /* set t to least subtree holding sizes > nb */
4236 break;
4238 sizebits <<= 1;
4241 if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
4242 binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
4243 if (leftbits != 0) {
4244 bindex_t i;
4245 binmap_t leastbit = least_bit(leftbits);
4246 compute_bit2idx(leastbit, i);
4247 t = *treebin_at(m, i);
4251 while (t != 0) { /* find smallest of tree or subtree */
4252 size_t trem = chunksize(t) - nb;
4253 if (trem < rsize) {
4254 rsize = trem;
4255 v = t;
4257 t = leftmost_child(t);
4260 /* If dv is a better fit, return 0 so malloc will use it */
4261 if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
4262 if (RTCHECK(ok_address(m, v))) { /* split */
4263 mchunkptr r = chunk_plus_offset(v, nb);
4264 assert(chunksize(v) == rsize + nb);
4265 if (RTCHECK(ok_next(v, r))) {
4266 unlink_large_chunk(m, v);
4267 if (rsize < MIN_CHUNK_SIZE)
4268 set_inuse_and_pinuse(m, v, (rsize + nb));
4269 else {
4270 set_size_and_pinuse_of_inuse_chunk(m, v, nb);
4271 set_size_and_pinuse_of_free_chunk(r, rsize);
4272 insert_chunk(m, r, rsize);
4274 return chunk2mem(v);
4277 CORRUPTION_ERROR_ACTION(m);
4279 return 0;
4282 /* allocate a small request from the best fitting chunk in a treebin */
4283 static void* tmalloc_small(mstate m, size_t nb) {
4284 tchunkptr t, v;
4285 size_t rsize;
4286 bindex_t i;
4287 binmap_t leastbit = least_bit(m->treemap);
4288 compute_bit2idx(leastbit, i);
4289 v = t = *treebin_at(m, i);
4290 rsize = chunksize(t) - nb;
4292 while ((t = leftmost_child(t)) != 0) {
4293 size_t trem = chunksize(t) - nb;
4294 if (trem < rsize) {
4295 rsize = trem;
4296 v = t;
4300 if (RTCHECK(ok_address(m, v))) {
4301 mchunkptr r = chunk_plus_offset(v, nb);
4302 assert(chunksize(v) == rsize + nb);
4303 if (RTCHECK(ok_next(v, r))) {
4304 unlink_large_chunk(m, v);
4305 if (rsize < MIN_CHUNK_SIZE)
4306 set_inuse_and_pinuse(m, v, (rsize + nb));
4307 else {
4308 set_size_and_pinuse_of_inuse_chunk(m, v, nb);
4309 set_size_and_pinuse_of_free_chunk(r, rsize);
4310 replace_dv(m, r, rsize);
4312 return chunk2mem(v);
4316 CORRUPTION_ERROR_ACTION(m);
4317 return 0;
4320 /* --------------------------- realloc support --------------------------- */
4322 static void* internal_realloc(mstate m, void* oldmem, size_t bytes) {
4323 if (bytes >= MAX_REQUEST) {
4324 MALLOC_FAILURE_ACTION;
4325 return 0;
4327 if (!PREACTION(m)) {
4328 mchunkptr oldp = mem2chunk(oldmem);
4329 size_t oldsize = chunksize(oldp);
4330 mchunkptr next = chunk_plus_offset(oldp, oldsize);
4331 mchunkptr newp = 0;
4332 void* extra = 0;
4334 /* Try to either shrink or extend into top. Else malloc-copy-free */
4336 if (RTCHECK(ok_address(m, oldp) && ok_inuse(oldp) &&
4337 ok_next(oldp, next) && ok_pinuse(next))) {
4338 size_t nb = request2size(bytes);
4339 if (is_mmapped(oldp))
4340 newp = mmap_resize(m, oldp, nb);
4341 else if (oldsize >= nb) { /* already big enough */
4342 size_t rsize = oldsize - nb;
4343 newp = oldp;
4344 if (rsize >= MIN_CHUNK_SIZE) {
4345 mchunkptr remainder = chunk_plus_offset(newp, nb);
4346 set_inuse(m, newp, nb);
4347 set_inuse_and_pinuse(m, remainder, rsize);
4348 extra = chunk2mem(remainder);
4351 else if (next == m->top && oldsize + m->topsize > nb) {
4352 /* Expand into top */
4353 size_t newsize = oldsize + m->topsize;
4354 size_t newtopsize = newsize - nb;
4355 mchunkptr newtop = chunk_plus_offset(oldp, nb);
4356 set_inuse(m, oldp, nb);
4357 newtop->head = newtopsize |PINUSE_BIT;
4358 m->top = newtop;
4359 m->topsize = newtopsize;
4360 newp = oldp;
4363 else {
4364 USAGE_ERROR_ACTION(m, oldmem);
4365 POSTACTION(m);
4366 return 0;
4368 #if DEBUG
4369 if (newp != 0) {
4370 check_inuse_chunk(m, newp); /* Check requires lock */
4372 #endif
4374 POSTACTION(m);
4376 if (newp != 0) {
4377 if (extra != 0) {
4378 internal_free(m, extra);
4380 return chunk2mem(newp);
4382 else {
4383 void* newmem = internal_malloc(m, bytes);
4384 if (newmem != 0) {
4385 size_t oc = oldsize - overhead_for(oldp);
4386 memcpy(newmem, oldmem, (oc < bytes)? oc : bytes);
4387 internal_free(m, oldmem);
4389 return newmem;
4392 return 0;
4395 /* --------------------------- memalign support -------------------------- */
4397 static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
4398 if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */
4399 return internal_malloc(m, bytes);
4400 if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
4401 alignment = MIN_CHUNK_SIZE;
4402 if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
4403 size_t a = MALLOC_ALIGNMENT << 1;
4404 while (a < alignment) a <<= 1;
4405 alignment = a;
4408 if (bytes >= MAX_REQUEST - alignment) {
4409 if (m != 0) { /* Test isn't needed but avoids compiler warning */
4410 MALLOC_FAILURE_ACTION;
4413 else {
4414 size_t nb = request2size(bytes);
4415 size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
4416 char* mem = (char*)internal_malloc(m, req);
4417 if (mem != 0) {
4418 void* leader = 0;
4419 void* trailer = 0;
4420 mchunkptr p = mem2chunk(mem);
4422 if (PREACTION(m)) return 0;
4423 if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */
4425 Find an aligned spot inside chunk. Since we need to give
4426 back leading space in a chunk of at least MIN_CHUNK_SIZE, if
4427 the first calculation places us at a spot with less than
4428 MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
4429 We've allocated enough total room so that this is always
4430 possible.
4432 char* br = (char*)mem2chunk((size_t)(((size_t)(mem +
4433 alignment -
4434 SIZE_T_ONE)) &
4435 -alignment));
4436 char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
4437 br : br+alignment;
4438 mchunkptr newp = (mchunkptr)pos;
4439 size_t leadsize = pos - (char*)(p);
4440 size_t newsize = chunksize(p) - leadsize;
4442 if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
4443 newp->prev_foot = p->prev_foot + leadsize;
4444 newp->head = newsize;
4446 else { /* Otherwise, give back leader, use the rest */
4447 set_inuse(m, newp, newsize);
4448 set_inuse(m, p, leadsize);
4449 leader = chunk2mem(p);
4451 p = newp;
4454 /* Give back spare room at the end */
4455 if (!is_mmapped(p)) {
4456 size_t size = chunksize(p);
4457 if (size > nb + MIN_CHUNK_SIZE) {
4458 size_t remainder_size = size - nb;
4459 mchunkptr remainder = chunk_plus_offset(p, nb);
4460 set_inuse(m, p, nb);
4461 set_inuse(m, remainder, remainder_size);
4462 trailer = chunk2mem(remainder);
4466 assert (chunksize(p) >= nb);
4467 assert((((size_t)(chunk2mem(p))) % alignment) == 0);
4468 check_inuse_chunk(m, p);
4469 POSTACTION(m);
4470 if (leader != 0) {
4471 internal_free(m, leader);
4473 if (trailer != 0) {
4474 internal_free(m, trailer);
4476 return chunk2mem(p);
4479 return 0;
4482 /* ------------------------ comalloc/coalloc support --------------------- */
4484 static void** ialloc(mstate m,
4485 size_t n_elements,
4486 size_t* sizes,
4487 int opts,
4488 void* chunks[]) {
4490 This provides common support for independent_X routines, handling
4491 all of the combinations that can result.
4493 The opts arg has:
4494 bit 0 set if all elements are same size (using sizes[0])
4495 bit 1 set if elements should be zeroed
4498 size_t element_size; /* chunksize of each element, if all same */
4499 size_t contents_size; /* total size of elements */
4500 size_t array_size; /* request size of pointer array */
4501 void* mem; /* malloced aggregate space */
4502 mchunkptr p; /* corresponding chunk */
4503 size_t remainder_size; /* remaining bytes while splitting */
4504 void** marray; /* either "chunks" or malloced ptr array */
4505 mchunkptr array_chunk; /* chunk for malloced ptr array */
4506 flag_t was_enabled; /* to disable mmap */
4507 size_t size;
4508 size_t i;
4510 ensure_initialization();
4511 /* compute array length, if needed */
4512 if (chunks != 0) {
4513 if (n_elements == 0)
4514 return chunks; /* nothing to do */
4515 marray = chunks;
4516 array_size = 0;
4518 else {
4519 /* if empty req, must still return chunk representing empty array */
4520 if (n_elements == 0)
4521 return (void**)internal_malloc(m, 0);
4522 marray = 0;
4523 array_size = request2size(n_elements * (sizeof(void*)));
4526 /* compute total element size */
4527 if (opts & 0x1) { /* all-same-size */
4528 element_size = request2size(*sizes);
4529 contents_size = n_elements * element_size;
4531 else { /* add up all the sizes */
4532 element_size = 0;
4533 contents_size = 0;
4534 for (i = 0; i != n_elements; ++i)
4535 contents_size += request2size(sizes[i]);
4538 size = contents_size + array_size;
4541 Allocate the aggregate chunk. First disable direct-mmapping so
4542 malloc won't use it, since we would not be able to later
4543 free/realloc space internal to a segregated mmap region.
4545 was_enabled = use_mmap(m);
4546 disable_mmap(m);
4547 mem = internal_malloc(m, size - CHUNK_OVERHEAD);
4548 if (was_enabled)
4549 enable_mmap(m);
4550 if (mem == 0)
4551 return 0;
4553 if (PREACTION(m)) return 0;
4554 p = mem2chunk(mem);
4555 remainder_size = chunksize(p);
4557 assert(!is_mmapped(p));
4559 if (opts & 0x2) { /* optionally clear the elements */
4560 memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
4563 /* If not provided, allocate the pointer array as final part of chunk */
4564 if (marray == 0) {
4565 size_t array_chunk_size;
4566 array_chunk = chunk_plus_offset(p, contents_size);
4567 array_chunk_size = remainder_size - contents_size;
4568 marray = (void**) (chunk2mem(array_chunk));
4569 set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
4570 remainder_size = contents_size;
4573 /* split out elements */
4574 for (i = 0; ; ++i) {
4575 marray[i] = chunk2mem(p);
4576 if (i != n_elements-1) {
4577 if (element_size != 0)
4578 size = element_size;
4579 else
4580 size = request2size(sizes[i]);
4581 remainder_size -= size;
4582 set_size_and_pinuse_of_inuse_chunk(m, p, size);
4583 p = chunk_plus_offset(p, size);
4585 else { /* the final element absorbs any overallocation slop */
4586 set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
4587 break;
4591 #if DEBUG
4592 if (marray != chunks) {
4593 /* final element must have exactly exhausted chunk */
4594 if (element_size != 0) {
4595 assert(remainder_size == element_size);
4597 else {
4598 assert(remainder_size == request2size(sizes[i]));
4600 check_inuse_chunk(m, mem2chunk(marray));
4602 for (i = 0; i != n_elements; ++i)
4603 check_inuse_chunk(m, mem2chunk(marray[i]));
4605 #endif /* DEBUG */
4607 POSTACTION(m);
4608 return marray;
4612 /* -------------------------- public routines ---------------------------- */
4614 #if !ONLY_MSPACES
4616 void* dlmalloc(size_t bytes) {
4618 Basic algorithm:
4619 If a small request (< 256 bytes minus per-chunk overhead):
4620 1. If one exists, use a remainderless chunk in associated smallbin.
4621 (Remainderless means that there are too few excess bytes to
4622 represent as a chunk.)
4623 2. If it is big enough, use the dv chunk, which is normally the
4624 chunk adjacent to the one used for the most recent small request.
4625 3. If one exists, split the smallest available chunk in a bin,
4626 saving remainder in dv.
4627 4. If it is big enough, use the top chunk.
4628 5. If available, get memory from system and use it
4629 Otherwise, for a large request:
4630 1. Find the smallest available binned chunk that fits, and use it
4631 if it is better fitting than dv chunk, splitting if necessary.
4632 2. If better fitting than any binned chunk, use the dv chunk.
4633 3. If it is big enough, use the top chunk.
4634 4. If request size >= mmap threshold, try to directly mmap this chunk.
4635 5. If available, get memory from system and use it
4637 The ugly goto's here ensure that postaction occurs along all paths.
4640 #if USE_LOCKS
4641 ensure_initialization(); /* initialize in sys_alloc if not using locks */
4642 #endif
4644 if (!PREACTION(gm)) {
4645 void* mem;
4646 size_t nb;
4647 if (bytes <= MAX_SMALL_REQUEST) {
4648 bindex_t idx;
4649 binmap_t smallbits;
4650 nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
4651 idx = small_index(nb);
4652 smallbits = gm->smallmap >> idx;
4654 if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
4655 mchunkptr b, p;
4656 idx += ~smallbits & 1; /* Uses next bin if idx empty */
4657 b = smallbin_at(gm, idx);
4658 p = b->fd;
4659 assert(chunksize(p) == small_index2size(idx));
4660 unlink_first_small_chunk(gm, b, p, idx);
4661 set_inuse_and_pinuse(gm, p, small_index2size(idx));
4662 mem = chunk2mem(p);
4663 check_malloced_chunk(gm, mem, nb);
4664 goto postaction;
4667 else if (nb > gm->dvsize) {
4668 if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
4669 mchunkptr b, p, r;
4670 size_t rsize;
4671 bindex_t i;
4672 binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
4673 binmap_t leastbit = least_bit(leftbits);
4674 compute_bit2idx(leastbit, i);
4675 b = smallbin_at(gm, i);
4676 p = b->fd;
4677 assert(chunksize(p) == small_index2size(i));
4678 unlink_first_small_chunk(gm, b, p, i);
4679 rsize = small_index2size(i) - nb;
4680 /* Fit here cannot be remainderless if 4byte sizes */
4681 if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
4682 set_inuse_and_pinuse(gm, p, small_index2size(i));
4683 else {
4684 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4685 r = chunk_plus_offset(p, nb);
4686 set_size_and_pinuse_of_free_chunk(r, rsize);
4687 replace_dv(gm, r, rsize);
4689 mem = chunk2mem(p);
4690 check_malloced_chunk(gm, mem, nb);
4691 goto postaction;
4694 else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
4695 check_malloced_chunk(gm, mem, nb);
4696 goto postaction;
4700 else if (bytes >= MAX_REQUEST)
4701 nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
4702 else {
4703 nb = pad_request(bytes);
4704 if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
4705 check_malloced_chunk(gm, mem, nb);
4706 goto postaction;
4710 if (nb <= gm->dvsize) {
4711 size_t rsize = gm->dvsize - nb;
4712 mchunkptr p = gm->dv;
4713 if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
4714 mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
4715 gm->dvsize = rsize;
4716 set_size_and_pinuse_of_free_chunk(r, rsize);
4717 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4719 else { /* exhaust dv */
4720 size_t dvs = gm->dvsize;
4721 gm->dvsize = 0;
4722 gm->dv = 0;
4723 set_inuse_and_pinuse(gm, p, dvs);
4725 mem = chunk2mem(p);
4726 check_malloced_chunk(gm, mem, nb);
4727 goto postaction;
4730 else if (nb < gm->topsize) { /* Split top */
4731 size_t rsize = gm->topsize -= nb;
4732 mchunkptr p = gm->top;
4733 mchunkptr r = gm->top = chunk_plus_offset(p, nb);
4734 r->head = rsize | PINUSE_BIT;
4735 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4736 mem = chunk2mem(p);
4737 check_top_chunk(gm, gm->top);
4738 check_malloced_chunk(gm, mem, nb);
4739 goto postaction;
4742 mem = sys_alloc(gm, nb);
4744 postaction:
4745 POSTACTION(gm);
4746 return mem;
4749 return 0;
4752 void dlfree(void* mem) {
4754 Consolidate freed chunks with preceeding or succeeding bordering
4755 free chunks, if they exist, and then place in a bin. Intermixed
4756 with special cases for top, dv, mmapped chunks, and usage errors.
4759 if (mem != 0) {
4760 mchunkptr p = mem2chunk(mem);
4761 #if FOOTERS
4762 mstate fm = get_mstate_for(p);
4763 if (!ok_magic(fm)) {
4764 USAGE_ERROR_ACTION(fm, p);
4765 return;
4767 #else /* FOOTERS */
4768 #define fm gm
4769 #endif /* FOOTERS */
4770 if (!PREACTION(fm)) {
4771 check_inuse_chunk(fm, p);
4772 if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
4773 size_t psize = chunksize(p);
4774 mchunkptr next = chunk_plus_offset(p, psize);
4775 if (!pinuse(p)) {
4776 size_t prevsize = p->prev_foot;
4777 if (is_mmapped(p)) {
4778 psize += prevsize + MMAP_FOOT_PAD;
4779 if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
4780 fm->footprint -= psize;
4781 goto postaction;
4783 else {
4784 mchunkptr prev = chunk_minus_offset(p, prevsize);
4785 psize += prevsize;
4786 p = prev;
4787 if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
4788 if (p != fm->dv) {
4789 unlink_chunk(fm, p, prevsize);
4791 else if ((next->head & INUSE_BITS) == INUSE_BITS) {
4792 fm->dvsize = psize;
4793 set_free_with_pinuse(p, psize, next);
4794 goto postaction;
4797 else
4798 goto erroraction;
4802 if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
4803 if (!cinuse(next)) { /* consolidate forward */
4804 if (next == fm->top) {
4805 size_t tsize = fm->topsize += psize;
4806 fm->top = p;
4807 p->head = tsize | PINUSE_BIT;
4808 if (p == fm->dv) {
4809 fm->dv = 0;
4810 fm->dvsize = 0;
4812 if (should_trim(fm, tsize))
4813 sys_trim(fm, 0);
4814 goto postaction;
4816 else if (next == fm->dv) {
4817 size_t dsize = fm->dvsize += psize;
4818 fm->dv = p;
4819 set_size_and_pinuse_of_free_chunk(p, dsize);
4820 goto postaction;
4822 else {
4823 size_t nsize = chunksize(next);
4824 psize += nsize;
4825 unlink_chunk(fm, next, nsize);
4826 set_size_and_pinuse_of_free_chunk(p, psize);
4827 if (p == fm->dv) {
4828 fm->dvsize = psize;
4829 goto postaction;
4833 else
4834 set_free_with_pinuse(p, psize, next);
4836 if (is_small(psize)) {
4837 insert_small_chunk(fm, p, psize);
4838 check_free_chunk(fm, p);
4840 else {
4841 tchunkptr tp = (tchunkptr)p;
4842 insert_large_chunk(fm, tp, psize);
4843 check_free_chunk(fm, p);
4844 if (--fm->release_checks == 0)
4845 release_unused_segments(fm);
4847 goto postaction;
4850 erroraction:
4851 USAGE_ERROR_ACTION(fm, p);
4852 postaction:
4853 POSTACTION(fm);
4856 #if !FOOTERS
4857 #undef fm
4858 #endif /* FOOTERS */
4861 void* dlcalloc(size_t n_elements, size_t elem_size) {
4862 void* mem;
4863 size_t req = 0;
4864 if (n_elements != 0) {
4865 req = n_elements * elem_size;
4866 if (((n_elements | elem_size) & ~(size_t)0xffff) &&
4867 (req / n_elements != elem_size))
4868 req = MAX_SIZE_T; /* force downstream failure on overflow */
4870 mem = dlmalloc(req);
4871 if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
4872 memset(mem, 0, req);
4873 return mem;
4876 void* dlrealloc(void* oldmem, size_t bytes) {
4877 if (oldmem == 0)
4878 return dlmalloc(bytes);
4879 #ifdef REALLOC_ZERO_BYTES_FREES
4880 if (bytes == 0) {
4881 dlfree(oldmem);
4882 return 0;
4884 #endif /* REALLOC_ZERO_BYTES_FREES */
4885 else {
4886 #if ! FOOTERS
4887 mstate m = gm;
4888 #else /* FOOTERS */
4889 mstate m = get_mstate_for(mem2chunk(oldmem));
4890 if (!ok_magic(m)) {
4891 USAGE_ERROR_ACTION(m, oldmem);
4892 return 0;
4894 #endif /* FOOTERS */
4895 return internal_realloc(m, oldmem, bytes);
4899 void* dlmemalign(size_t alignment, size_t bytes) {
4900 return internal_memalign(gm, alignment, bytes);
4903 void** dlindependent_calloc(size_t n_elements, size_t elem_size,
4904 void* chunks[]) {
4905 size_t sz = elem_size; /* serves as 1-element array */
4906 return ialloc(gm, n_elements, &sz, 3, chunks);
4909 void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
4910 void* chunks[]) {
4911 return ialloc(gm, n_elements, sizes, 0, chunks);
4914 void* dlvalloc(size_t bytes) {
4915 size_t pagesz;
4916 ensure_initialization();
4917 pagesz = mparams.page_size;
4918 return dlmemalign(pagesz, bytes);
4921 void* dlpvalloc(size_t bytes) {
4922 size_t pagesz;
4923 ensure_initialization();
4924 pagesz = mparams.page_size;
4925 return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
4928 int dlmalloc_trim(size_t pad) {
4929 int result = 0;
4930 ensure_initialization();
4931 if (!PREACTION(gm)) {
4932 result = sys_trim(gm, pad);
4933 POSTACTION(gm);
4935 return result;
4938 size_t dlmalloc_footprint(void) {
4939 return gm->footprint;
4942 size_t dlmalloc_max_footprint(void) {
4943 return gm->max_footprint;
4946 #if !NO_MALLINFO
4947 struct mallinfo dlmallinfo(void) {
4948 return internal_mallinfo(gm);
4950 #endif /* NO_MALLINFO */
4952 void dlmalloc_stats() {
4953 internal_malloc_stats(gm);
4956 int dlmallopt(int param_number, int value) {
4957 return change_mparam(param_number, value);
4960 #endif /* !ONLY_MSPACES */
4962 size_t dlmalloc_usable_size(void* mem) {
4963 if (mem != 0) {
4964 mchunkptr p = mem2chunk(mem);
4965 if (is_inuse(p))
4966 return chunksize(p) - overhead_for(p);
4968 return 0;
4971 /* ----------------------------- user mspaces ---------------------------- */
4973 #if MSPACES
4975 static mstate init_user_mstate(char* tbase, size_t tsize) {
4976 size_t msize = pad_request(sizeof(struct malloc_state));
4977 mchunkptr mn;
4978 mchunkptr msp = align_as_chunk(tbase);
4979 mstate m = (mstate)(chunk2mem(msp));
4980 memset(m, 0, msize);
4981 INITIAL_LOCK(&m->mutex);
4982 msp->head = (msize|INUSE_BITS);
4983 m->seg.base = m->least_addr = tbase;
4984 m->seg.size = m->footprint = m->max_footprint = tsize;
4985 m->magic = mparams.magic;
4986 m->release_checks = MAX_RELEASE_CHECK_RATE;
4987 m->mflags = mparams.default_mflags;
4988 m->extp = 0;
4989 m->exts = 0;
4990 disable_contiguous(m);
4991 init_bins(m);
4992 mn = next_chunk(mem2chunk(m));
4993 init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
4994 check_top_chunk(m, m->top);
4995 return m;
4998 mspace create_mspace(size_t capacity, int locked) {
4999 mstate m = 0;
5000 size_t msize;
5001 ensure_initialization();
5002 msize = pad_request(sizeof(struct malloc_state));
5003 if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
5004 size_t rs = ((capacity == 0)? mparams.granularity :
5005 (capacity + TOP_FOOT_SIZE + msize));
5006 size_t tsize = granularity_align(rs);
5007 char* tbase = (char*)(CALL_MMAP(tsize));
5008 if (tbase != CMFAIL) {
5009 m = init_user_mstate(tbase, tsize);
5010 m->seg.sflags = USE_MMAP_BIT;
5011 set_lock(m, locked);
5014 return (mspace)m;
5017 mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
5018 mstate m = 0;
5019 size_t msize;
5020 ensure_initialization();
5021 msize = pad_request(sizeof(struct malloc_state));
5022 if (capacity > msize + TOP_FOOT_SIZE &&
5023 capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
5024 m = init_user_mstate((char*)base, capacity);
5025 m->seg.sflags = EXTERN_BIT;
5026 set_lock(m, locked);
5028 return (mspace)m;
5031 int mspace_track_large_chunks(mspace msp, int enable) {
5032 int ret = 0;
5033 mstate ms = (mstate)msp;
5034 if (!PREACTION(ms)) {
5035 if (!use_mmap(ms))
5036 ret = 1;
5037 if (!enable)
5038 enable_mmap(ms);
5039 else
5040 disable_mmap(ms);
5041 POSTACTION(ms);
5043 return ret;
5046 size_t destroy_mspace(mspace msp) {
5047 size_t freed = 0;
5048 mstate ms = (mstate)msp;
5049 if (ok_magic(ms)) {
5050 msegmentptr sp = &ms->seg;
5051 while (sp != 0) {
5052 char* base = sp->base;
5053 size_t size = sp->size;
5054 flag_t flag = sp->sflags;
5055 sp = sp->next;
5056 if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) &&
5057 CALL_MUNMAP(base, size) == 0)
5058 freed += size;
5061 else {
5062 USAGE_ERROR_ACTION(ms,ms);
5064 return freed;
5068 mspace versions of routines are near-clones of the global
5069 versions. This is not so nice but better than the alternatives.
5073 void* mspace_malloc(mspace msp, size_t bytes) {
5074 mstate ms = (mstate)msp;
5075 if (!ok_magic(ms)) {
5076 USAGE_ERROR_ACTION(ms,ms);
5077 return 0;
5079 if (!PREACTION(ms)) {
5080 void* mem;
5081 size_t nb;
5082 if (bytes <= MAX_SMALL_REQUEST) {
5083 bindex_t idx;
5084 binmap_t smallbits;
5085 nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
5086 idx = small_index(nb);
5087 smallbits = ms->smallmap >> idx;
5089 if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
5090 mchunkptr b, p;
5091 idx += ~smallbits & 1; /* Uses next bin if idx empty */
5092 b = smallbin_at(ms, idx);
5093 p = b->fd;
5094 assert(chunksize(p) == small_index2size(idx));
5095 unlink_first_small_chunk(ms, b, p, idx);
5096 set_inuse_and_pinuse(ms, p, small_index2size(idx));
5097 mem = chunk2mem(p);
5098 check_malloced_chunk(ms, mem, nb);
5099 goto postaction;
5102 else if (nb > ms->dvsize) {
5103 if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
5104 mchunkptr b, p, r;
5105 size_t rsize;
5106 bindex_t i;
5107 binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
5108 binmap_t leastbit = least_bit(leftbits);
5109 compute_bit2idx(leastbit, i);
5110 b = smallbin_at(ms, i);
5111 p = b->fd;
5112 assert(chunksize(p) == small_index2size(i));
5113 unlink_first_small_chunk(ms, b, p, i);
5114 rsize = small_index2size(i) - nb;
5115 /* Fit here cannot be remainderless if 4byte sizes */
5116 if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
5117 set_inuse_and_pinuse(ms, p, small_index2size(i));
5118 else {
5119 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
5120 r = chunk_plus_offset(p, nb);
5121 set_size_and_pinuse_of_free_chunk(r, rsize);
5122 replace_dv(ms, r, rsize);
5124 mem = chunk2mem(p);
5125 check_malloced_chunk(ms, mem, nb);
5126 goto postaction;
5129 else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
5130 check_malloced_chunk(ms, mem, nb);
5131 goto postaction;
5135 else if (bytes >= MAX_REQUEST)
5136 nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
5137 else {
5138 nb = pad_request(bytes);
5139 if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
5140 check_malloced_chunk(ms, mem, nb);
5141 goto postaction;
5145 if (nb <= ms->dvsize) {
5146 size_t rsize = ms->dvsize - nb;
5147 mchunkptr p = ms->dv;
5148 if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
5149 mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
5150 ms->dvsize = rsize;
5151 set_size_and_pinuse_of_free_chunk(r, rsize);
5152 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
5154 else { /* exhaust dv */
5155 size_t dvs = ms->dvsize;
5156 ms->dvsize = 0;
5157 ms->dv = 0;
5158 set_inuse_and_pinuse(ms, p, dvs);
5160 mem = chunk2mem(p);
5161 check_malloced_chunk(ms, mem, nb);
5162 goto postaction;
5165 else if (nb < ms->topsize) { /* Split top */
5166 size_t rsize = ms->topsize -= nb;
5167 mchunkptr p = ms->top;
5168 mchunkptr r = ms->top = chunk_plus_offset(p, nb);
5169 r->head = rsize | PINUSE_BIT;
5170 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
5171 mem = chunk2mem(p);
5172 check_top_chunk(ms, ms->top);
5173 check_malloced_chunk(ms, mem, nb);
5174 goto postaction;
5177 mem = sys_alloc(ms, nb);
5179 postaction:
5180 POSTACTION(ms);
5181 return mem;
5184 return 0;
5187 void mspace_free(mspace msp, void* mem) {
5188 if (mem != 0) {
5189 mchunkptr p = mem2chunk(mem);
5190 #if FOOTERS
5191 mstate fm = get_mstate_for(p);
5192 msp = msp; /* placate people compiling -Wunused */
5193 #else /* FOOTERS */
5194 mstate fm = (mstate)msp;
5195 #endif /* FOOTERS */
5196 if (!ok_magic(fm)) {
5197 USAGE_ERROR_ACTION(fm, p);
5198 return;
5200 if (!PREACTION(fm)) {
5201 check_inuse_chunk(fm, p);
5202 if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
5203 size_t psize = chunksize(p);
5204 mchunkptr next = chunk_plus_offset(p, psize);
5205 if (!pinuse(p)) {
5206 size_t prevsize = p->prev_foot;
5207 if (is_mmapped(p)) {
5208 psize += prevsize + MMAP_FOOT_PAD;
5209 if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
5210 fm->footprint -= psize;
5211 goto postaction;
5213 else {
5214 mchunkptr prev = chunk_minus_offset(p, prevsize);
5215 psize += prevsize;
5216 p = prev;
5217 if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
5218 if (p != fm->dv) {
5219 unlink_chunk(fm, p, prevsize);
5221 else if ((next->head & INUSE_BITS) == INUSE_BITS) {
5222 fm->dvsize = psize;
5223 set_free_with_pinuse(p, psize, next);
5224 goto postaction;
5227 else
5228 goto erroraction;
5232 if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
5233 if (!cinuse(next)) { /* consolidate forward */
5234 if (next == fm->top) {
5235 size_t tsize = fm->topsize += psize;
5236 fm->top = p;
5237 p->head = tsize | PINUSE_BIT;
5238 if (p == fm->dv) {
5239 fm->dv = 0;
5240 fm->dvsize = 0;
5242 if (should_trim(fm, tsize))
5243 sys_trim(fm, 0);
5244 goto postaction;
5246 else if (next == fm->dv) {
5247 size_t dsize = fm->dvsize += psize;
5248 fm->dv = p;
5249 set_size_and_pinuse_of_free_chunk(p, dsize);
5250 goto postaction;
5252 else {
5253 size_t nsize = chunksize(next);
5254 psize += nsize;
5255 unlink_chunk(fm, next, nsize);
5256 set_size_and_pinuse_of_free_chunk(p, psize);
5257 if (p == fm->dv) {
5258 fm->dvsize = psize;
5259 goto postaction;
5263 else
5264 set_free_with_pinuse(p, psize, next);
5266 if (is_small(psize)) {
5267 insert_small_chunk(fm, p, psize);
5268 check_free_chunk(fm, p);
5270 else {
5271 tchunkptr tp = (tchunkptr)p;
5272 insert_large_chunk(fm, tp, psize);
5273 check_free_chunk(fm, p);
5274 if (--fm->release_checks == 0)
5275 release_unused_segments(fm);
5277 goto postaction;
5280 erroraction:
5281 USAGE_ERROR_ACTION(fm, p);
5282 postaction:
5283 POSTACTION(fm);
5288 void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
5289 void* mem;
5290 size_t req = 0;
5291 mstate ms = (mstate)msp;
5292 if (!ok_magic(ms)) {
5293 USAGE_ERROR_ACTION(ms,ms);
5294 return 0;
5296 if (n_elements != 0) {
5297 req = n_elements * elem_size;
5298 if (((n_elements | elem_size) & ~(size_t)0xffff) &&
5299 (req / n_elements != elem_size))
5300 req = MAX_SIZE_T; /* force downstream failure on overflow */
5302 mem = internal_malloc(ms, req);
5303 if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
5304 memset(mem, 0, req);
5305 return mem;
5308 void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
5309 if (oldmem == 0)
5310 return mspace_malloc(msp, bytes);
5311 #ifdef REALLOC_ZERO_BYTES_FREES
5312 if (bytes == 0) {
5313 mspace_free(msp, oldmem);
5314 return 0;
5316 #endif /* REALLOC_ZERO_BYTES_FREES */
5317 else {
5318 #if FOOTERS
5319 mchunkptr p = mem2chunk(oldmem);
5320 mstate ms = get_mstate_for(p);
5321 #else /* FOOTERS */
5322 mstate ms = (mstate)msp;
5323 #endif /* FOOTERS */
5324 if (!ok_magic(ms)) {
5325 USAGE_ERROR_ACTION(ms,ms);
5326 return 0;
5328 return internal_realloc(ms, oldmem, bytes);
5332 void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
5333 mstate ms = (mstate)msp;
5334 if (!ok_magic(ms)) {
5335 USAGE_ERROR_ACTION(ms,ms);
5336 return 0;
5338 return internal_memalign(ms, alignment, bytes);
5341 void** mspace_independent_calloc(mspace msp, size_t n_elements,
5342 size_t elem_size, void* chunks[]) {
5343 size_t sz = elem_size; /* serves as 1-element array */
5344 mstate ms = (mstate)msp;
5345 if (!ok_magic(ms)) {
5346 USAGE_ERROR_ACTION(ms,ms);
5347 return 0;
5349 return ialloc(ms, n_elements, &sz, 3, chunks);
5352 void** mspace_independent_comalloc(mspace msp, size_t n_elements,
5353 size_t sizes[], void* chunks[]) {
5354 mstate ms = (mstate)msp;
5355 if (!ok_magic(ms)) {
5356 USAGE_ERROR_ACTION(ms,ms);
5357 return 0;
5359 return ialloc(ms, n_elements, sizes, 0, chunks);
5362 int mspace_trim(mspace msp, size_t pad) {
5363 int result = 0;
5364 mstate ms = (mstate)msp;
5365 if (ok_magic(ms)) {
5366 if (!PREACTION(ms)) {
5367 result = sys_trim(ms, pad);
5368 POSTACTION(ms);
5371 else {
5372 USAGE_ERROR_ACTION(ms,ms);
5374 return result;
5377 void mspace_malloc_stats(mspace msp) {
5378 mstate ms = (mstate)msp;
5379 if (ok_magic(ms)) {
5380 internal_malloc_stats(ms);
5382 else {
5383 USAGE_ERROR_ACTION(ms,ms);
5387 size_t mspace_footprint(mspace msp) {
5388 size_t result = 0;
5389 mstate ms = (mstate)msp;
5390 if (ok_magic(ms)) {
5391 result = ms->footprint;
5393 else {
5394 USAGE_ERROR_ACTION(ms,ms);
5396 return result;
5400 size_t mspace_max_footprint(mspace msp) {
5401 size_t result = 0;
5402 mstate ms = (mstate)msp;
5403 if (ok_magic(ms)) {
5404 result = ms->max_footprint;
5406 else {
5407 USAGE_ERROR_ACTION(ms,ms);
5409 return result;
5413 #if !NO_MALLINFO
5414 struct mallinfo mspace_mallinfo(mspace msp) {
5415 mstate ms = (mstate)msp;
5416 if (!ok_magic(ms)) {
5417 USAGE_ERROR_ACTION(ms,ms);
5419 return internal_mallinfo(ms);
5421 #endif /* NO_MALLINFO */
5423 size_t mspace_usable_size(void* mem) {
5424 if (mem != 0) {
5425 mchunkptr p = mem2chunk(mem);
5426 if (is_inuse(p))
5427 return chunksize(p) - overhead_for(p);
5429 return 0;
5432 int mspace_mallopt(int param_number, int value) {
5433 return change_mparam(param_number, value);
5436 #endif /* MSPACES */
5439 /* -------------------- Alternative MORECORE functions ------------------- */
5442 Guidelines for creating a custom version of MORECORE:
5444 * For best performance, MORECORE should allocate in multiples of pagesize.
5445 * MORECORE may allocate more memory than requested. (Or even less,
5446 but this will usually result in a malloc failure.)
5447 * MORECORE must not allocate memory when given argument zero, but
5448 instead return one past the end address of memory from previous
5449 nonzero call.
5450 * For best performance, consecutive calls to MORECORE with positive
5451 arguments should return increasing addresses, indicating that
5452 space has been contiguously extended.
5453 * Even though consecutive calls to MORECORE need not return contiguous
5454 addresses, it must be OK for malloc'ed chunks to span multiple
5455 regions in those cases where they do happen to be contiguous.
5456 * MORECORE need not handle negative arguments -- it may instead
5457 just return MFAIL when given negative arguments.
5458 Negative arguments are always multiples of pagesize. MORECORE
5459 must not misinterpret negative args as large positive unsigned
5460 args. You can suppress all such calls from even occurring by defining
5461 MORECORE_CANNOT_TRIM,
5463 As an example alternative MORECORE, here is a custom allocator
5464 kindly contributed for pre-OSX macOS. It uses virtually but not
5465 necessarily physically contiguous non-paged memory (locked in,
5466 present and won't get swapped out). You can use it by uncommenting
5467 this section, adding some #includes, and setting up the appropriate
5468 defines above:
5470 #define MORECORE osMoreCore
5472 There is also a shutdown routine that should somehow be called for
5473 cleanup upon program exit.
5475 #define MAX_POOL_ENTRIES 100
5476 #define MINIMUM_MORECORE_SIZE (64 * 1024U)
5477 static int next_os_pool;
5478 void *our_os_pools[MAX_POOL_ENTRIES];
5480 void *osMoreCore(int size)
5482 void *ptr = 0;
5483 static void *sbrk_top = 0;
5485 if (size > 0)
5487 if (size < MINIMUM_MORECORE_SIZE)
5488 size = MINIMUM_MORECORE_SIZE;
5489 if (CurrentExecutionLevel() == kTaskLevel)
5490 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
5491 if (ptr == 0)
5493 return (void *) MFAIL;
5495 // save ptrs so they can be freed during cleanup
5496 our_os_pools[next_os_pool] = ptr;
5497 next_os_pool++;
5498 ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
5499 sbrk_top = (char *) ptr + size;
5500 return ptr;
5502 else if (size < 0)
5504 // we don't currently support shrink behavior
5505 return (void *) MFAIL;
5507 else
5509 return sbrk_top;
5513 // cleanup any allocated memory pools
5514 // called as last thing before shutting down driver
5516 void osCleanupMem(void)
5518 void **ptr;
5520 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
5521 if (*ptr)
5523 PoolDeallocate(*ptr);
5524 *ptr = 0;
5531 /* -----------------------------------------------------------------------
5532 History:
5533 V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee)
5534 * Use zeros instead of prev foot for is_mmapped
5535 * Add mspace_track_large_chunks; thanks to Jean Brouwers
5536 * Fix set_inuse in internal_realloc; thanks to Jean Brouwers
5537 * Fix insufficient sys_alloc padding when using 16byte alignment
5538 * Fix bad error check in mspace_footprint
5539 * Adaptations for ptmalloc; thanks to Wolfram Gloger.
5540 * Reentrant spin locks; thanks to Earl Chew and others
5541 * Win32 improvements; thanks to Niall Douglas and Earl Chew
5542 * Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options
5543 * Extension hook in malloc_state
5544 * Various small adjustments to reduce warnings on some compilers
5545 * Various configuration extensions/changes for more platforms. Thanks
5546 to all who contributed these.
5548 V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)
5549 * Add max_footprint functions
5550 * Ensure all appropriate literals are size_t
5551 * Fix conditional compilation problem for some #define settings
5552 * Avoid concatenating segments with the one provided
5553 in create_mspace_with_base
5554 * Rename some variables to avoid compiler shadowing warnings
5555 * Use explicit lock initialization.
5556 * Better handling of sbrk interference.
5557 * Simplify and fix segment insertion, trimming and mspace_destroy
5558 * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
5559 * Thanks especially to Dennis Flanagan for help on these.
5561 V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)
5562 * Fix memalign brace error.
5564 V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)
5565 * Fix improper #endif nesting in C++
5566 * Add explicit casts needed for C++
5568 V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)
5569 * Use trees for large bins
5570 * Support mspaces
5571 * Use segments to unify sbrk-based and mmap-based system allocation,
5572 removing need for emulation on most platforms without sbrk.
5573 * Default safety checks
5574 * Optional footer checks. Thanks to William Robertson for the idea.
5575 * Internal code refactoring
5576 * Incorporate suggestions and platform-specific changes.
5577 Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
5578 Aaron Bachmann, Emery Berger, and others.
5579 * Speed up non-fastbin processing enough to remove fastbins.
5580 * Remove useless cfree() to avoid conflicts with other apps.
5581 * Remove internal memcpy, memset. Compilers handle builtins better.
5582 * Remove some options that no one ever used and rename others.
5584 V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
5585 * Fix malloc_state bitmap array misdeclaration
5587 V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)
5588 * Allow tuning of FIRST_SORTED_BIN_SIZE
5589 * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
5590 * Better detection and support for non-contiguousness of MORECORE.
5591 Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
5592 * Bypass most of malloc if no frees. Thanks To Emery Berger.
5593 * Fix freeing of old top non-contiguous chunk im sysmalloc.
5594 * Raised default trim and map thresholds to 256K.
5595 * Fix mmap-related #defines. Thanks to Lubos Lunak.
5596 * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
5597 * Branch-free bin calculation
5598 * Default trim and mmap thresholds now 256K.
5600 V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
5601 * Introduce independent_comalloc and independent_calloc.
5602 Thanks to Michael Pachos for motivation and help.
5603 * Make optional .h file available
5604 * Allow > 2GB requests on 32bit systems.
5605 * new WIN32 sbrk, mmap, munmap, lock code from <Walter@GeNeSys-e.de>.
5606 Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
5607 and Anonymous.
5608 * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
5609 helping test this.)
5610 * memalign: check alignment arg
5611 * realloc: don't try to shift chunks backwards, since this
5612 leads to more fragmentation in some programs and doesn't
5613 seem to help in any others.
5614 * Collect all cases in malloc requiring system memory into sysmalloc
5615 * Use mmap as backup to sbrk
5616 * Place all internal state in malloc_state
5617 * Introduce fastbins (although similar to 2.5.1)
5618 * Many minor tunings and cosmetic improvements
5619 * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
5620 * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
5621 Thanks to Tony E. Bennett <tbennett@nvidia.com> and others.
5622 * Include errno.h to support default failure action.
5624 V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
5625 * return null for negative arguments
5626 * Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
5627 * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
5628 (e.g. WIN32 platforms)
5629 * Cleanup header file inclusion for WIN32 platforms
5630 * Cleanup code to avoid Microsoft Visual C++ compiler complaints
5631 * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
5632 memory allocation routines
5633 * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
5634 * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
5635 usage of 'assert' in non-WIN32 code
5636 * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
5637 avoid infinite loop
5638 * Always call 'fREe()' rather than 'free()'
5640 V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
5641 * Fixed ordering problem with boundary-stamping
5643 V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
5644 * Added pvalloc, as recommended by H.J. Liu
5645 * Added 64bit pointer support mainly from Wolfram Gloger
5646 * Added anonymously donated WIN32 sbrk emulation
5647 * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
5648 * malloc_extend_top: fix mask error that caused wastage after
5649 foreign sbrks
5650 * Add linux mremap support code from HJ Liu
5652 V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
5653 * Integrated most documentation with the code.
5654 * Add support for mmap, with help from
5655 Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
5656 * Use last_remainder in more cases.
5657 * Pack bins using idea from colin@nyx10.cs.du.edu
5658 * Use ordered bins instead of best-fit threshhold
5659 * Eliminate block-local decls to simplify tracing and debugging.
5660 * Support another case of realloc via move into top
5661 * Fix error occuring when initial sbrk_base not word-aligned.
5662 * Rely on page size for units instead of SBRK_UNIT to
5663 avoid surprises about sbrk alignment conventions.
5664 * Add mallinfo, mallopt. Thanks to Raymond Nijssen
5665 (raymond@es.ele.tue.nl) for the suggestion.
5666 * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
5667 * More precautions for cases where other routines call sbrk,
5668 courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
5669 * Added macros etc., allowing use in linux libc from
5670 H.J. Lu (hjl@gnu.ai.mit.edu)
5671 * Inverted this history list
5673 V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
5674 * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
5675 * Removed all preallocation code since under current scheme
5676 the work required to undo bad preallocations exceeds
5677 the work saved in good cases for most test programs.
5678 * No longer use return list or unconsolidated bins since
5679 no scheme using them consistently outperforms those that don't
5680 given above changes.
5681 * Use best fit for very large chunks to prevent some worst-cases.
5682 * Added some support for debugging
5684 V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
5685 * Removed footers when chunks are in use. Thanks to
5686 Paul Wilson (wilson@cs.texas.edu) for the suggestion.
5688 V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
5689 * Added malloc_trim, with help from Wolfram Gloger
5690 (wmglo@Dent.MED.Uni-Muenchen.DE).
5692 V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
5694 V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
5695 * realloc: try to expand in both directions
5696 * malloc: swap order of clean-bin strategy;
5697 * realloc: only conditionally expand backwards
5698 * Try not to scavenge used bins
5699 * Use bin counts as a guide to preallocation
5700 * Occasionally bin return list chunks in first scan
5701 * Add a few optimizations from colin@nyx10.cs.du.edu
5703 V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
5704 * faster bin computation & slightly different binning
5705 * merged all consolidations to one part of malloc proper
5706 (eliminating old malloc_find_space & malloc_clean_bin)
5707 * Scan 2 returns chunks (not just 1)
5708 * Propagate failure in realloc if malloc returns 0
5709 * Add stuff to allow compilation on non-ANSI compilers
5710 from kpv@research.att.com
5712 V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
5713 * removed potential for odd address access in prev_chunk
5714 * removed dependency on getpagesize.h
5715 * misc cosmetics and a bit more internal documentation
5716 * anticosmetics: mangled names in macros to evade debugger strangeness
5717 * tested on sparc, hp-700, dec-mips, rs6000
5718 with gcc & native cc (hp, dec only) allowing
5719 Detlefs & Zorn comparison study (in SIGPLAN Notices.)
5721 Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
5722 * Based loosely on libg++-1.2X malloc. (It retains some of the overall
5723 structure of old version, but most details differ.)