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