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