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