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