blob: e049a76c6bc08a350cd6f0e3963d814f160e1052 [file] [log] [blame]
Franklin Weia855d622017-01-21 15:18:31 -05001/*
2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2012 Sam Lantinga
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Sam Lantinga
20 slouken@libsdl.org
21*/
22#include "SDL_config.h"
23
24/* This file contains portable memory management functions for SDL */
25
26#include "SDL_stdinc.h"
27
28#ifndef HAVE_MALLOC
29
30#define LACKS_SYS_TYPES_H
31#define LACKS_STDIO_H
32#define LACKS_STRINGS_H
33#define LACKS_STRING_H
34#define LACKS_STDLIB_H
35#define ABORT
36
37/*
38 This is a version (aka dlmalloc) of malloc/free/realloc written by
39 Doug Lea and released to the public domain, as explained at
40 http://creativecommons.org/licenses/publicdomain. Send questions,
41 comments, complaints, performance data, etc to dl@cs.oswego.edu
42
43* Version 2.8.3 Thu Sep 22 11:16:15 2005 Doug Lea (dl at gee)
44
45 Note: There may be an updated version of this malloc obtainable at
46 ftp://gee.cs.oswego.edu/pub/misc/malloc.c
47 Check before installing!
48
49* Quickstart
50
51 This library is all in one file to simplify the most common usage:
52 ftp it, compile it (-O3), and link it into another program. All of
53 the compile-time options default to reasonable values for use on
54 most platforms. You might later want to step through various
55 compile-time and dynamic tuning options.
56
57 For convenience, an include file for code using this malloc is at:
58 ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
59 You don't really need this .h file unless you call functions not
60 defined in your system include files. The .h file contains only the
61 excerpts from this file needed for using this malloc on ANSI C/C++
62 systems, so long as you haven't changed compile-time options about
63 naming and tuning parameters. If you do, then you can create your
64 own malloc.h that does include all settings by cutting at the point
65 indicated below. Note that you may already by default be using a C
66 library containing a malloc that is based on some version of this
67 malloc (for example in linux). You might still want to use the one
68 in this file to customize settings or to avoid overheads associated
69 with library versions.
70
71* Vital statistics:
72
73 Supported pointer/size_t representation: 4 or 8 bytes
74 size_t MUST be an unsigned type of the same width as
75 pointers. (If you are using an ancient system that declares
76 size_t as a signed type, or need it to be a different width
77 than pointers, you can use a previous release of this malloc
78 (e.g. 2.7.2) supporting these.)
79
80 Alignment: 8 bytes (default)
81 This suffices for nearly all current machines and C compilers.
82 However, you can define MALLOC_ALIGNMENT to be wider than this
83 if necessary (up to 128bytes), at the expense of using more space.
84
85 Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
86 8 or 16 bytes (if 8byte sizes)
87 Each malloced chunk has a hidden word of overhead holding size
88 and status information, and additional cross-check word
89 if FOOTERS is defined.
90
91 Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
92 8-byte ptrs: 32 bytes (including overhead)
93
94 Even a request for zero bytes (i.e., malloc(0)) returns a
95 pointer to something of the minimum allocatable size.
96 The maximum overhead wastage (i.e., number of extra bytes
97 allocated than were requested in malloc) is less than or equal
98 to the minimum size, except for requests >= mmap_threshold that
99 are serviced via mmap(), where the worst case wastage is about
100 32 bytes plus the remainder from a system page (the minimal
101 mmap unit); typically 4096 or 8192 bytes.
102
103 Security: static-safe; optionally more or less
104 The "security" of malloc refers to the ability of malicious
105 code to accentuate the effects of errors (for example, freeing
106 space that is not currently malloc'ed or overwriting past the
107 ends of chunks) in code that calls malloc. This malloc
108 guarantees not to modify any memory locations below the base of
109 heap, i.e., static variables, even in the presence of usage
110 errors. The routines additionally detect most improper frees
111 and reallocs. All this holds as long as the static bookkeeping
112 for malloc itself is not corrupted by some other means. This
113 is only one aspect of security -- these checks do not, and
114 cannot, detect all possible programming errors.
115
116 If FOOTERS is defined nonzero, then each allocated chunk
117 carries an additional check word to verify that it was malloced
118 from its space. These check words are the same within each
119 execution of a program using malloc, but differ across
120 executions, so externally crafted fake chunks cannot be
121 freed. This improves security by rejecting frees/reallocs that
122 could corrupt heap memory, in addition to the checks preventing
123 writes to statics that are always on. This may further improve
124 security at the expense of time and space overhead. (Note that
125 FOOTERS may also be worth using with MSPACES.)
126
127 By default detected errors cause the program to abort (calling
128 "abort()"). You can override this to instead proceed past
129 errors by defining PROCEED_ON_ERROR. In this case, a bad free
130 has no effect, and a malloc that encounters a bad address
131 caused by user overwrites will ignore the bad address by
132 dropping pointers and indices to all known memory. This may
133 be appropriate for programs that should continue if at all
134 possible in the face of programming errors, although they may
135 run out of memory because dropped memory is never reclaimed.
136
137 If you don't like either of these options, you can define
138 CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
139 else. And if if you are sure that your program using malloc has
140 no errors or vulnerabilities, you can define INSECURE to 1,
141 which might (or might not) provide a small performance improvement.
142
143 Thread-safety: NOT thread-safe unless USE_LOCKS defined
144 When USE_LOCKS is defined, each public call to malloc, free,
145 etc is surrounded with either a pthread mutex or a win32
146 spinlock (depending on WIN32). This is not especially fast, and
147 can be a major bottleneck. It is designed only to provide
148 minimal protection in concurrent environments, and to provide a
149 basis for extensions. If you are using malloc in a concurrent
150 program, consider instead using ptmalloc, which is derived from
151 a version of this malloc. (See http://www.malloc.de).
152
153 System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
154 This malloc can use unix sbrk or any emulation (invoked using
155 the CALL_MORECORE macro) and/or mmap/munmap or any emulation
156 (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
157 memory. On most unix systems, it tends to work best if both
158 MORECORE and MMAP are enabled. On Win32, it uses emulations
159 based on VirtualAlloc. It also uses common C library functions
160 like memset.
161
162 Compliance: I believe it is compliant with the Single Unix Specification
163 (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
164 others as well.
165
166* Overview of algorithms
167
168 This is not the fastest, most space-conserving, most portable, or
169 most tunable malloc ever written. However it is among the fastest
170 while also being among the most space-conserving, portable and
171 tunable. Consistent balance across these factors results in a good
172 general-purpose allocator for malloc-intensive programs.
173
174 In most ways, this malloc is a best-fit allocator. Generally, it
175 chooses the best-fitting existing chunk for a request, with ties
176 broken in approximately least-recently-used order. (This strategy
177 normally maintains low fragmentation.) However, for requests less
178 than 256bytes, it deviates from best-fit when there is not an
179 exactly fitting available chunk by preferring to use space adjacent
180 to that used for the previous small request, as well as by breaking
181 ties in approximately most-recently-used order. (These enhance
182 locality of series of small allocations.) And for very large requests
183 (>= 256Kb by default), it relies on system memory mapping
184 facilities, if supported. (This helps avoid carrying around and
185 possibly fragmenting memory used only for large chunks.)
186
187 All operations (except malloc_stats and mallinfo) have execution
188 times that are bounded by a constant factor of the number of bits in
189 a size_t, not counting any clearing in calloc or copying in realloc,
190 or actions surrounding MORECORE and MMAP that have times
191 proportional to the number of non-contiguous regions returned by
192 system allocation routines, which is often just 1.
193
194 The implementation is not very modular and seriously overuses
195 macros. Perhaps someday all C compilers will do as good a job
196 inlining modular code as can now be done by brute-force expansion,
197 but now, enough of them seem not to.
198
199 Some compilers issue a lot of warnings about code that is
200 dead/unreachable only on some platforms, and also about intentional
201 uses of negation on unsigned types. All known cases of each can be
202 ignored.
203
204 For a longer but out of date high-level description, see
205 http://gee.cs.oswego.edu/dl/html/malloc.html
206
207* MSPACES
208 If MSPACES is defined, then in addition to malloc, free, etc.,
209 this file also defines mspace_malloc, mspace_free, etc. These
210 are versions of malloc routines that take an "mspace" argument
211 obtained using create_mspace, to control all internal bookkeeping.
212 If ONLY_MSPACES is defined, only these versions are compiled.
213 So if you would like to use this allocator for only some allocations,
214 and your system malloc for others, you can compile with
215 ONLY_MSPACES and then do something like...
216 static mspace mymspace = create_mspace(0,0); // for example
217 #define mymalloc(bytes) mspace_malloc(mymspace, bytes)
218
219 (Note: If you only need one instance of an mspace, you can instead
220 use "USE_DL_PREFIX" to relabel the global malloc.)
221
222 You can similarly create thread-local allocators by storing
223 mspaces as thread-locals. For example:
224 static __thread mspace tlms = 0;
225 void* tlmalloc(size_t bytes) {
226 if (tlms == 0) tlms = create_mspace(0, 0);
227 return mspace_malloc(tlms, bytes);
228 }
229 void tlfree(void* mem) { mspace_free(tlms, mem); }
230
231 Unless FOOTERS is defined, each mspace is completely independent.
232 You cannot allocate from one and free to another (although
233 conformance is only weakly checked, so usage errors are not always
234 caught). If FOOTERS is defined, then each chunk carries around a tag
235 indicating its originating mspace, and frees are directed to their
236 originating spaces.
237
238 ------------------------- Compile-time options ---------------------------
239
240Be careful in setting #define values for numerical constants of type
241size_t. On some systems, literal values are not automatically extended
242to size_t precision unless they are explicitly casted.
243
Franklin Weia855d622017-01-21 15:18:31 -0500244MALLOC_ALIGNMENT default: (size_t)8
245 Controls the minimum alignment for malloc'ed chunks. It must be a
246 power of two and at least 8, even on machines for which smaller
247 alignments would suffice. It may be defined as larger than this
248 though. Note however that code and data structures are optimized for
249 the case of 8-byte alignment.
250
251MSPACES default: 0 (false)
252 If true, compile in support for independent allocation spaces.
253 This is only supported if HAVE_MMAP is true.
254
255ONLY_MSPACES default: 0 (false)
256 If true, only compile in mspace versions, not regular versions.
257
258USE_LOCKS default: 0 (false)
259 Causes each call to each public routine to be surrounded with
260 pthread or WIN32 mutex lock/unlock. (If set true, this can be
261 overridden on a per-mspace basis for mspace versions.)
262
263FOOTERS default: 0
264 If true, provide extra checking and dispatching by placing
265 information in the footers of allocated chunks. This adds
266 space and time overhead.
267
268INSECURE default: 0
269 If true, omit checks for usage errors and heap space overwrites.
270
271USE_DL_PREFIX default: NOT defined
272 Causes compiler to prefix all public routines with the string 'dl'.
273 This can be useful when you only want to use this malloc in one part
274 of a program, using your regular system malloc elsewhere.
275
276ABORT default: defined as abort()
277 Defines how to abort on failed checks. On most systems, a failed
278 check cannot die with an "assert" or even print an informative
279 message, because the underlying print routines in turn call malloc,
280 which will fail again. Generally, the best policy is to simply call
281 abort(). It's not very useful to do more than this because many
282 errors due to overwriting will show up as address faults (null, odd
283 addresses etc) rather than malloc-triggered checks, so will also
284 abort. Also, most compilers know that abort() does not return, so
285 can better optimize code conditionally calling it.
286
287PROCEED_ON_ERROR default: defined as 0 (false)
288 Controls whether detected bad addresses cause them to bypassed
289 rather than aborting. If set, detected bad arguments to free and
290 realloc are ignored. And all bookkeeping information is zeroed out
291 upon a detected overwrite of freed heap space, thus losing the
292 ability to ever return it from malloc again, but enabling the
293 application to proceed. If PROCEED_ON_ERROR is defined, the
294 static variable malloc_corruption_error_count is compiled in
295 and can be examined to see if errors have occurred. This option
296 generates slower code than the default abort policy.
297
298DEBUG default: NOT defined
299 The DEBUG setting is mainly intended for people trying to modify
300 this code or diagnose problems when porting to new platforms.
301 However, it may also be able to better isolate user errors than just
302 using runtime checks. The assertions in the check routines spell
303 out in more detail the assumptions and invariants underlying the
304 algorithms. The checking is fairly extensive, and will slow down
305 execution noticeably. Calling malloc_stats or mallinfo with DEBUG
306 set will attempt to check every non-mmapped allocated and free chunk
307 in the course of computing the summaries.
308
309ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
310 Debugging assertion failures can be nearly impossible if your
311 version of the assert macro causes malloc to be called, which will
312 lead to a cascade of further failures, blowing the runtime stack.
313 ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
314 which will usually make debugging easier.
315
316MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
317 The action to take before "return 0" when malloc fails to be able to
318 return memory because there is none available.
319
320HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
321 True if this system supports sbrk or an emulation of it.
322
323MORECORE default: sbrk
324 The name of the sbrk-style system routine to call to obtain more
325 memory. See below for guidance on writing custom MORECORE
326 functions. The type of the argument to sbrk/MORECORE varies across
327 systems. It cannot be size_t, because it supports negative
328 arguments, so it is normally the signed type of the same width as
329 size_t (sometimes declared as "intptr_t"). It doesn't much matter
330 though. Internally, we only call it with arguments less than half
331 the max value of a size_t, which should work across all reasonable
332 possibilities, although sometimes generating compiler warnings. See
333 near the end of this file for guidelines for creating a custom
334 version of MORECORE.
335
336MORECORE_CONTIGUOUS default: 1 (true)
337 If true, take advantage of fact that consecutive calls to MORECORE
338 with positive arguments always return contiguous increasing
339 addresses. This is true of unix sbrk. It does not hurt too much to
340 set it true anyway, since malloc copes with non-contiguities.
341 Setting it false when definitely non-contiguous saves time
342 and possibly wasted space it would take to discover this though.
343
344MORECORE_CANNOT_TRIM default: NOT defined
345 True if MORECORE cannot release space back to the system when given
346 negative arguments. This is generally necessary only if you are
347 using a hand-crafted MORECORE function that cannot handle negative
348 arguments.
349
350HAVE_MMAP default: 1 (true)
351 True if this system supports mmap or an emulation of it. If so, and
352 HAVE_MORECORE is not true, MMAP is used for all system
353 allocation. If set and HAVE_MORECORE is true as well, MMAP is
354 primarily used to directly allocate very large blocks. It is also
355 used as a backup strategy in cases where MORECORE fails to provide
356 space from system. Note: A single call to MUNMAP is assumed to be
357 able to unmap memory that may have be allocated using multiple calls
358 to MMAP, so long as they are adjacent.
359
360HAVE_MREMAP default: 1 on linux, else 0
361 If true realloc() uses mremap() to re-allocate large blocks and
362 extend or shrink allocation spaces.
363
364MMAP_CLEARS default: 1 on unix
365 True if mmap clears memory so calloc doesn't need to. This is true
366 for standard unix mmap using /dev/zero.
367
368USE_BUILTIN_FFS default: 0 (i.e., not used)
369 Causes malloc to use the builtin ffs() function to compute indices.
370 Some compilers may recognize and intrinsify ffs to be faster than the
371 supplied C version. Also, the case of x86 using gcc is special-cased
372 to an asm instruction, so is already as fast as it can be, and so
373 this setting has no effect. (On most x86s, the asm version is only
374 slightly faster than the C version.)
375
376malloc_getpagesize default: derive from system includes, or 4096.
377 The system page size. To the extent possible, this malloc manages
378 memory from the system in page-size units. This may be (and
379 usually is) a function rather than a constant. This is ignored
380 if WIN32, where page size is determined using getSystemInfo during
381 initialization.
382
383USE_DEV_RANDOM default: 0 (i.e., not used)
384 Causes malloc to use /dev/random to initialize secure magic seed for
385 stamping footers. Otherwise, the current time is used.
386
387NO_MALLINFO default: 0
388 If defined, don't compile "mallinfo". This can be a simple way
389 of dealing with mismatches between system declarations and
390 those in this file.
391
392MALLINFO_FIELD_TYPE default: size_t
393 The type of the fields in the mallinfo struct. This was originally
394 defined as "int" in SVID etc, but is more usefully defined as
395 size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
396
397REALLOC_ZERO_BYTES_FREES default: not defined
398 This should be set if a call to realloc with zero bytes should
399 be the same as a call to free. Some people think it should. Otherwise,
400 since this malloc returns a unique pointer for malloc(0), so does
401 realloc(p, 0).
402
403LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
404LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
405LACKS_STDLIB_H default: NOT defined unless on WIN32
406 Define these if your system does not have these header files.
407 You might need to manually insert some of the declarations they provide.
408
409DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
410 system_info.dwAllocationGranularity in WIN32,
411 otherwise 64K.
412 Also settable using mallopt(M_GRANULARITY, x)
413 The unit for allocating and deallocating memory from the system. On
414 most systems with contiguous MORECORE, there is no reason to
415 make this more than a page. However, systems with MMAP tend to
416 either require or encourage larger granularities. You can increase
417 this value to prevent system allocation functions to be called so
418 often, especially if they are slow. The value must be at least one
419 page and must be a power of two. Setting to 0 causes initialization
420 to either page size or win32 region size. (Note: In previous
421 versions of malloc, the equivalent of this option was called
422 "TOP_PAD")
423
424DEFAULT_TRIM_THRESHOLD default: 2MB
425 Also settable using mallopt(M_TRIM_THRESHOLD, x)
426 The maximum amount of unused top-most memory to keep before
427 releasing via malloc_trim in free(). Automatic trimming is mainly
428 useful in long-lived programs using contiguous MORECORE. Because
429 trimming via sbrk can be slow on some systems, and can sometimes be
430 wasteful (in cases where programs immediately afterward allocate
431 more large chunks) the value should be high enough so that your
432 overall system performance would improve by releasing this much
433 memory. As a rough guide, you might set to a value close to the
434 average size of a process (program) running on your system.
435 Releasing this much memory would allow such a process to run in
436 memory. Generally, it is worth tuning trim thresholds when a
437 program undergoes phases where several large chunks are allocated
438 and released in ways that can reuse each other's storage, perhaps
439 mixed with phases where there are no such chunks at all. The trim
440 value must be greater than page size to have any useful effect. To
441 disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
442 some people use of mallocing a huge space and then freeing it at
443 program startup, in an attempt to reserve system memory, doesn't
444 have the intended effect under automatic trimming, since that memory
445 will immediately be returned to the system.
446
447DEFAULT_MMAP_THRESHOLD default: 256K
448 Also settable using mallopt(M_MMAP_THRESHOLD, x)
449 The request size threshold for using MMAP to directly service a
450 request. Requests of at least this size that cannot be allocated
451 using already-existing space will be serviced via mmap. (If enough
452 normal freed space already exists it is used instead.) Using mmap
453 segregates relatively large chunks of memory so that they can be
454 individually obtained and released from the host system. A request
455 serviced through mmap is never reused by any other request (at least
456 not directly; the system may just so happen to remap successive
457 requests to the same locations). Segregating space in this way has
458 the benefits that: Mmapped space can always be individually released
459 back to the system, which helps keep the system level memory demands
460 of a long-lived program low. Also, mapped memory doesn't become
461 `locked' between other chunks, as can happen with normally allocated
462 chunks, which means that even trimming via malloc_trim would not
463 release them. However, it has the disadvantage that the space
464 cannot be reclaimed, consolidated, and then used to service later
465 requests, as happens with normal chunks. The advantages of mmap
466 nearly always outweigh disadvantages for "large" chunks, but the
467 value of "large" may vary across systems. The default is an
468 empirically derived value that works well in most systems. You can
469 disable mmap by setting to MAX_SIZE_T.
470
471*/
472
Franklin Weia855d622017-01-21 15:18:31 -0500473#if defined(DARWIN) || defined(_DARWIN)
474/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
475#ifndef HAVE_MORECORE
476#define HAVE_MORECORE 0
477#define HAVE_MMAP 1
478#endif /* HAVE_MORECORE */
479#endif /* DARWIN */
480
481#ifndef LACKS_SYS_TYPES_H
482#include <sys/types.h> /* For size_t */
483#endif /* LACKS_SYS_TYPES_H */
484
485/* The maximum possible size_t value has all bits set */
486#define MAX_SIZE_T (~(size_t)0)
487
488#ifndef ONLY_MSPACES
489#define ONLY_MSPACES 0
490#endif /* ONLY_MSPACES */
491#ifndef MSPACES
492#if ONLY_MSPACES
493#define MSPACES 1
494#else /* ONLY_MSPACES */
495#define MSPACES 0
496#endif /* ONLY_MSPACES */
497#endif /* MSPACES */
498#ifndef MALLOC_ALIGNMENT
499#define MALLOC_ALIGNMENT ((size_t)8U)
500#endif /* MALLOC_ALIGNMENT */
501#ifndef FOOTERS
502#define FOOTERS 0
503#endif /* FOOTERS */
504#ifndef ABORT
505#define ABORT abort()
506#endif /* ABORT */
507#ifndef ABORT_ON_ASSERT_FAILURE
508#define ABORT_ON_ASSERT_FAILURE 1
509#endif /* ABORT_ON_ASSERT_FAILURE */
510#ifndef PROCEED_ON_ERROR
511#define PROCEED_ON_ERROR 0
512#endif /* PROCEED_ON_ERROR */
513#ifndef USE_LOCKS
514#define USE_LOCKS 0
515#endif /* USE_LOCKS */
516#ifndef INSECURE
517#define INSECURE 0
518#endif /* INSECURE */
519#ifndef HAVE_MMAP
520#define HAVE_MMAP 1
521#endif /* HAVE_MMAP */
522#ifndef MMAP_CLEARS
523#define MMAP_CLEARS 1
524#endif /* MMAP_CLEARS */
525#ifndef HAVE_MREMAP
526#ifdef linux
527#define HAVE_MREMAP 1
528#else /* linux */
529#define HAVE_MREMAP 0
530#endif /* linux */
531#endif /* HAVE_MREMAP */
532#ifndef MALLOC_FAILURE_ACTION
533#define MALLOC_FAILURE_ACTION errno = ENOMEM;
534#endif /* MALLOC_FAILURE_ACTION */
535#ifndef HAVE_MORECORE
536#if ONLY_MSPACES
537#define HAVE_MORECORE 0
538#else /* ONLY_MSPACES */
539#define HAVE_MORECORE 1
540#endif /* ONLY_MSPACES */
541#endif /* HAVE_MORECORE */
542#if !HAVE_MORECORE
543#define MORECORE_CONTIGUOUS 0
544#else /* !HAVE_MORECORE */
545#ifndef MORECORE
546#define MORECORE sbrk
547#endif /* MORECORE */
548#ifndef MORECORE_CONTIGUOUS
549#define MORECORE_CONTIGUOUS 1
550#endif /* MORECORE_CONTIGUOUS */
551#endif /* HAVE_MORECORE */
552#ifndef DEFAULT_GRANULARITY
553#if MORECORE_CONTIGUOUS
554#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
555#else /* MORECORE_CONTIGUOUS */
556#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
557#endif /* MORECORE_CONTIGUOUS */
558#endif /* DEFAULT_GRANULARITY */
559#ifndef DEFAULT_TRIM_THRESHOLD
560#ifndef MORECORE_CANNOT_TRIM
561#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
562#else /* MORECORE_CANNOT_TRIM */
563#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
564#endif /* MORECORE_CANNOT_TRIM */
565#endif /* DEFAULT_TRIM_THRESHOLD */
566#ifndef DEFAULT_MMAP_THRESHOLD
567#if HAVE_MMAP
568#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
569#else /* HAVE_MMAP */
570#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
571#endif /* HAVE_MMAP */
572#endif /* DEFAULT_MMAP_THRESHOLD */
573#ifndef USE_BUILTIN_FFS
574#define USE_BUILTIN_FFS 0
575#endif /* USE_BUILTIN_FFS */
576#ifndef USE_DEV_RANDOM
577#define USE_DEV_RANDOM 0
578#endif /* USE_DEV_RANDOM */
579#ifndef NO_MALLINFO
580#define NO_MALLINFO 0
581#endif /* NO_MALLINFO */
582#ifndef MALLINFO_FIELD_TYPE
583#define MALLINFO_FIELD_TYPE size_t
584#endif /* MALLINFO_FIELD_TYPE */
585
586#define memset SDL_memset
587#define memcpy SDL_memcpy
588#define malloc SDL_malloc
589#define calloc SDL_calloc
590#define realloc SDL_realloc
591#define free SDL_free
592
593/*
594 mallopt tuning options. SVID/XPG defines four standard parameter
595 numbers for mallopt, normally defined in malloc.h. None of these
596 are used in this malloc, so setting them has no effect. But this
597 malloc does support the following options.
598*/
599
600#define M_TRIM_THRESHOLD (-1)
601#define M_GRANULARITY (-2)
602#define M_MMAP_THRESHOLD (-3)
603
604/* ------------------------ Mallinfo declarations ------------------------ */
605
606#if !NO_MALLINFO
607/*
608 This version of malloc supports the standard SVID/XPG mallinfo
609 routine that returns a struct containing usage properties and
610 statistics. It should work on any system that has a
611 /usr/include/malloc.h defining struct mallinfo. The main
612 declaration needed is the mallinfo struct that is returned (by-copy)
613 by mallinfo(). The malloinfo struct contains a bunch of fields that
614 are not even meaningful in this version of malloc. These fields are
615 are instead filled by mallinfo() with other numbers that might be of
616 interest.
617
618 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
619 /usr/include/malloc.h file that includes a declaration of struct
620 mallinfo. If so, it is included; else a compliant version is
621 declared below. These must be precisely the same for mallinfo() to
622 work. The original SVID version of this struct, defined on most
623 systems with mallinfo, declares all fields as ints. But some others
624 define as unsigned long. If your system defines the fields using a
625 type of different width than listed here, you MUST #include your
626 system version and #define HAVE_USR_INCLUDE_MALLOC_H.
627*/
628
629/* #define HAVE_USR_INCLUDE_MALLOC_H */
630
631#ifdef HAVE_USR_INCLUDE_MALLOC_H
632#include "/usr/include/malloc.h"
633#else /* HAVE_USR_INCLUDE_MALLOC_H */
634
635struct mallinfo {
636 MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
637 MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
638 MALLINFO_FIELD_TYPE smblks; /* always 0 */
639 MALLINFO_FIELD_TYPE hblks; /* always 0 */
640 MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
641 MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
642 MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
643 MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
644 MALLINFO_FIELD_TYPE fordblks; /* total free space */
645 MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
646};
647
648#endif /* HAVE_USR_INCLUDE_MALLOC_H */
649#endif /* NO_MALLINFO */
650
651#ifdef __cplusplus
652extern "C" {
653#endif /* __cplusplus */
654
655#if !ONLY_MSPACES
656
657/* ------------------- Declarations of public routines ------------------- */
658
659#ifndef USE_DL_PREFIX
660#define dlcalloc calloc
661#define dlfree free
662#define dlmalloc malloc
663#define dlmemalign memalign
664#define dlrealloc realloc
665#define dlvalloc valloc
666#define dlpvalloc pvalloc
667#define dlmallinfo mallinfo
668#define dlmallopt mallopt
669#define dlmalloc_trim malloc_trim
670#define dlmalloc_stats malloc_stats
671#define dlmalloc_usable_size malloc_usable_size
672#define dlmalloc_footprint malloc_footprint
673#define dlmalloc_max_footprint malloc_max_footprint
674#define dlindependent_calloc independent_calloc
675#define dlindependent_comalloc independent_comalloc
676#endif /* USE_DL_PREFIX */
677
678
679/*
680 malloc(size_t n)
681 Returns a pointer to a newly allocated chunk of at least n bytes, or
682 null if no space is available, in which case errno is set to ENOMEM
683 on ANSI C systems.
684
685 If n is zero, malloc returns a minimum-sized chunk. (The minimum
686 size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
687 systems.) Note that size_t is an unsigned type, so calls with
688 arguments that would be negative if signed are interpreted as
689 requests for huge amounts of space, which will often fail. The
690 maximum supported value of n differs across systems, but is in all
691 cases less than the maximum representable value of a size_t.
692*/
693void* dlmalloc(size_t);
694
695/*
696 free(void* p)
697 Releases the chunk of memory pointed to by p, that had been previously
698 allocated using malloc or a related routine such as realloc.
699 It has no effect if p is null. If p was not malloced or already
700 freed, free(p) will by default cause the current program to abort.
701*/
702void dlfree(void*);
703
704/*
705 calloc(size_t n_elements, size_t element_size);
706 Returns a pointer to n_elements * element_size bytes, with all locations
707 set to zero.
708*/
709void* dlcalloc(size_t, size_t);
710
711/*
712 realloc(void* p, size_t n)
713 Returns a pointer to a chunk of size n that contains the same data
714 as does chunk p up to the minimum of (n, p's size) bytes, or null
715 if no space is available.
716
717 The returned pointer may or may not be the same as p. The algorithm
718 prefers extending p in most cases when possible, otherwise it
719 employs the equivalent of a malloc-copy-free sequence.
720
721 If p is null, realloc is equivalent to malloc.
722
723 If space is not available, realloc returns null, errno is set (if on
724 ANSI) and p is NOT freed.
725
726 if n is for fewer bytes than already held by p, the newly unused
727 space is lopped off and freed if possible. realloc with a size
728 argument of zero (re)allocates a minimum-sized chunk.
729
730 The old unix realloc convention of allowing the last-free'd chunk
731 to be used as an argument to realloc is not supported.
732*/
733
734void* dlrealloc(void*, size_t);
735
736/*
737 memalign(size_t alignment, size_t n);
738 Returns a pointer to a newly allocated chunk of n bytes, aligned
739 in accord with the alignment argument.
740
741 The alignment argument should be a power of two. If the argument is
742 not a power of two, the nearest greater power is used.
743 8-byte alignment is guaranteed by normal malloc calls, so don't
744 bother calling memalign with an argument of 8 or less.
745
746 Overreliance on memalign is a sure way to fragment space.
747*/
748void* dlmemalign(size_t, size_t);
749
750/*
751 valloc(size_t n);
752 Equivalent to memalign(pagesize, n), where pagesize is the page
753 size of the system. If the pagesize is unknown, 4096 is used.
754*/
755void* dlvalloc(size_t);
756
757/*
758 mallopt(int parameter_number, int parameter_value)
759 Sets tunable parameters The format is to provide a
760 (parameter-number, parameter-value) pair. mallopt then sets the
761 corresponding parameter to the argument value if it can (i.e., so
762 long as the value is meaningful), and returns 1 if successful else
763 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
764 normally defined in malloc.h. None of these are use in this malloc,
765 so setting them has no effect. But this malloc also supports other
766 options in mallopt. See below for details. Briefly, supported
767 parameters are as follows (listed defaults are for "typical"
768 configurations).
769
770 Symbol param # default allowed param values
771 M_TRIM_THRESHOLD -1 2*1024*1024 any (MAX_SIZE_T disables)
772 M_GRANULARITY -2 page size any power of 2 >= page size
773 M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
774*/
775int dlmallopt(int, int);
776
777/*
778 malloc_footprint();
779 Returns the number of bytes obtained from the system. The total
780 number of bytes allocated by malloc, realloc etc., is less than this
781 value. Unlike mallinfo, this function returns only a precomputed
782 result, so can be called frequently to monitor memory consumption.
783 Even if locks are otherwise defined, this function does not use them,
784 so results might not be up to date.
785*/
786size_t dlmalloc_footprint(void);
787
788/*
789 malloc_max_footprint();
790 Returns the maximum number of bytes obtained from the system. This
791 value will be greater than current footprint if deallocated space
792 has been reclaimed by the system. The peak number of bytes allocated
793 by malloc, realloc etc., is less than this value. Unlike mallinfo,
794 this function returns only a precomputed result, so can be called
795 frequently to monitor memory consumption. Even if locks are
796 otherwise defined, this function does not use them, so results might
797 not be up to date.
798*/
799size_t dlmalloc_max_footprint(void);
800
801#if !NO_MALLINFO
802/*
803 mallinfo()
804 Returns (by copy) a struct containing various summary statistics:
805
806 arena: current total non-mmapped bytes allocated from system
807 ordblks: the number of free chunks
808 smblks: always zero.
809 hblks: current number of mmapped regions
810 hblkhd: total bytes held in mmapped regions
811 usmblks: the maximum total allocated space. This will be greater
812 than current total if trimming has occurred.
813 fsmblks: always zero
814 uordblks: current total allocated space (normal or mmapped)
815 fordblks: total free space
816 keepcost: the maximum number of bytes that could ideally be released
817 back to system via malloc_trim. ("ideally" means that
818 it ignores page restrictions etc.)
819
820 Because these fields are ints, but internal bookkeeping may
821 be kept as longs, the reported values may wrap around zero and
822 thus be inaccurate.
823*/
824struct mallinfo dlmallinfo(void);
825#endif /* NO_MALLINFO */
826
827/*
828 independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
829
830 independent_calloc is similar to calloc, but instead of returning a
831 single cleared space, it returns an array of pointers to n_elements
832 independent elements that can hold contents of size elem_size, each
833 of which starts out cleared, and can be independently freed,
834 realloc'ed etc. The elements are guaranteed to be adjacently
835 allocated (this is not guaranteed to occur with multiple callocs or
836 mallocs), which may also improve cache locality in some
837 applications.
838
839 The "chunks" argument is optional (i.e., may be null, which is
840 probably the most typical usage). If it is null, the returned array
841 is itself dynamically allocated and should also be freed when it is
842 no longer needed. Otherwise, the chunks array must be of at least
843 n_elements in length. It is filled in with the pointers to the
844 chunks.
845
846 In either case, independent_calloc returns this pointer array, or
847 null if the allocation failed. If n_elements is zero and "chunks"
848 is null, it returns a chunk representing an array with zero elements
849 (which should be freed if not wanted).
850
851 Each element must be individually freed when it is no longer
852 needed. If you'd like to instead be able to free all at once, you
853 should instead use regular calloc and assign pointers into this
854 space to represent elements. (In this case though, you cannot
855 independently free elements.)
856
857 independent_calloc simplifies and speeds up implementations of many
858 kinds of pools. It may also be useful when constructing large data
859 structures that initially have a fixed number of fixed-sized nodes,
860 but the number is not known at compile time, and some of the nodes
861 may later need to be freed. For example:
862
863 struct Node { int item; struct Node* next; };
864
865 struct Node* build_list() {
866 struct Node** pool;
867 int n = read_number_of_nodes_needed();
868 if (n <= 0) return 0;
869 pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
870 if (pool == 0) die();
871 // organize into a linked list...
872 struct Node* first = pool[0];
873 for (i = 0; i < n-1; ++i)
874 pool[i]->next = pool[i+1];
875 free(pool); // Can now free the array (or not, if it is needed later)
876 return first;
877 }
878*/
879void** dlindependent_calloc(size_t, size_t, void**);
880
881/*
882 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
883
884 independent_comalloc allocates, all at once, a set of n_elements
885 chunks with sizes indicated in the "sizes" array. It returns
886 an array of pointers to these elements, each of which can be
887 independently freed, realloc'ed etc. The elements are guaranteed to
888 be adjacently allocated (this is not guaranteed to occur with
889 multiple callocs or mallocs), which may also improve cache locality
890 in some applications.
891
892 The "chunks" argument is optional (i.e., may be null). If it is null
893 the returned array is itself dynamically allocated and should also
894 be freed when it is no longer needed. Otherwise, the chunks array
895 must be of at least n_elements in length. It is filled in with the
896 pointers to the chunks.
897
898 In either case, independent_comalloc returns this pointer array, or
899 null if the allocation failed. If n_elements is zero and chunks is
900 null, it returns a chunk representing an array with zero elements
901 (which should be freed if not wanted).
902
903 Each element must be individually freed when it is no longer
904 needed. If you'd like to instead be able to free all at once, you
905 should instead use a single regular malloc, and assign pointers at
906 particular offsets in the aggregate space. (In this case though, you
907 cannot independently free elements.)
908
909 independent_comallac differs from independent_calloc in that each
910 element may have a different size, and also that it does not
911 automatically clear elements.
912
913 independent_comalloc can be used to speed up allocation in cases
914 where several structs or objects must always be allocated at the
915 same time. For example:
916
917 struct Head { ... }
918 struct Foot { ... }
919
920 void send_message(char* msg) {
921 int msglen = strlen(msg);
922 size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
923 void* chunks[3];
924 if (independent_comalloc(3, sizes, chunks) == 0)
925 die();
926 struct Head* head = (struct Head*)(chunks[0]);
927 char* body = (char*)(chunks[1]);
928 struct Foot* foot = (struct Foot*)(chunks[2]);
929 // ...
930 }
931
932 In general though, independent_comalloc is worth using only for
933 larger values of n_elements. For small values, you probably won't
934 detect enough difference from series of malloc calls to bother.
935
936 Overuse of independent_comalloc can increase overall memory usage,
937 since it cannot reuse existing noncontiguous small chunks that
938 might be available for some of the elements.
939*/
940void** dlindependent_comalloc(size_t, size_t*, void**);
941
942
943/*
944 pvalloc(size_t n);
945 Equivalent to valloc(minimum-page-that-holds(n)), that is,
946 round up n to nearest pagesize.
947 */
948void* dlpvalloc(size_t);
949
950/*
951 malloc_trim(size_t pad);
952
953 If possible, gives memory back to the system (via negative arguments
954 to sbrk) if there is unused memory at the `high' end of the malloc
955 pool or in unused MMAP segments. You can call this after freeing
956 large blocks of memory to potentially reduce the system-level memory
957 requirements of a program. However, it cannot guarantee to reduce
958 memory. Under some allocation patterns, some large free blocks of
959 memory will be locked between two used chunks, so they cannot be
960 given back to the system.
961
962 The `pad' argument to malloc_trim represents the amount of free
963 trailing space to leave untrimmed. If this argument is zero, only
964 the minimum amount of memory to maintain internal data structures
965 will be left. Non-zero arguments can be supplied to maintain enough
966 trailing space to service future expected allocations without having
967 to re-obtain memory from the system.
968
969 Malloc_trim returns 1 if it actually released any memory, else 0.
970*/
971int dlmalloc_trim(size_t);
972
973/*
974 malloc_usable_size(void* p);
975
976 Returns the number of bytes you can actually use in
977 an allocated chunk, which may be more than you requested (although
978 often not) due to alignment and minimum size constraints.
979 You can use this many bytes without worrying about
980 overwriting other allocated objects. This is not a particularly great
981 programming practice. malloc_usable_size can be more useful in
982 debugging and assertions, for example:
983
984 p = malloc(n);
985 assert(malloc_usable_size(p) >= 256);
986*/
987size_t dlmalloc_usable_size(void*);
988
989/*
990 malloc_stats();
991 Prints on stderr the amount of space obtained from the system (both
992 via sbrk and mmap), the maximum amount (which may be more than
993 current if malloc_trim and/or munmap got called), and the current
994 number of bytes allocated via malloc (or realloc, etc) but not yet
995 freed. Note that this is the number of bytes allocated, not the
996 number requested. It will be larger than the number requested
997 because of alignment and bookkeeping overhead. Because it includes
998 alignment wastage as being in use, this figure may be greater than
999 zero even when no user-level chunks are allocated.
1000
1001 The reported current and maximum system memory can be inaccurate if
1002 a program makes other calls to system memory allocation functions
1003 (normally sbrk) outside of malloc.
1004
1005 malloc_stats prints only the most commonly interesting statistics.
1006 More information can be obtained by calling mallinfo.
1007*/
1008void dlmalloc_stats(void);
1009
1010#endif /* ONLY_MSPACES */
1011
1012#if MSPACES
1013
1014/*
1015 mspace is an opaque type representing an independent
1016 region of space that supports mspace_malloc, etc.
1017*/
1018typedef void* mspace;
1019
1020/*
1021 create_mspace creates and returns a new independent space with the
1022 given initial capacity, or, if 0, the default granularity size. It
1023 returns null if there is no system memory available to create the
1024 space. If argument locked is non-zero, the space uses a separate
1025 lock to control access. The capacity of the space will grow
1026 dynamically as needed to service mspace_malloc requests. You can
1027 control the sizes of incremental increases of this space by
1028 compiling with a different DEFAULT_GRANULARITY or dynamically
1029 setting with mallopt(M_GRANULARITY, value).
1030*/
1031mspace create_mspace(size_t capacity, int locked);
1032
1033/*
1034 destroy_mspace destroys the given space, and attempts to return all
1035 of its memory back to the system, returning the total number of
1036 bytes freed. After destruction, the results of access to all memory
1037 used by the space become undefined.
1038*/
1039size_t destroy_mspace(mspace msp);
1040
1041/*
1042 create_mspace_with_base uses the memory supplied as the initial base
1043 of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
1044 space is used for bookkeeping, so the capacity must be at least this
1045 large. (Otherwise 0 is returned.) When this initial space is
1046 exhausted, additional memory will be obtained from the system.
1047 Destroying this space will deallocate all additionally allocated
1048 space (if possible) but not the initial base.
1049*/
1050mspace create_mspace_with_base(void* base, size_t capacity, int locked);
1051
1052/*
1053 mspace_malloc behaves as malloc, but operates within
1054 the given space.
1055*/
1056void* mspace_malloc(mspace msp, size_t bytes);
1057
1058/*
1059 mspace_free behaves as free, but operates within
1060 the given space.
1061
1062 If compiled with FOOTERS==1, mspace_free is not actually needed.
1063 free may be called instead of mspace_free because freed chunks from
1064 any space are handled by their originating spaces.
1065*/
1066void mspace_free(mspace msp, void* mem);
1067
1068/*
1069 mspace_realloc behaves as realloc, but operates within
1070 the given space.
1071
1072 If compiled with FOOTERS==1, mspace_realloc is not actually
1073 needed. realloc may be called instead of mspace_realloc because
1074 realloced chunks from any space are handled by their originating
1075 spaces.
1076*/
1077void* mspace_realloc(mspace msp, void* mem, size_t newsize);
1078
1079/*
1080 mspace_calloc behaves as calloc, but operates within
1081 the given space.
1082*/
1083void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
1084
1085/*
1086 mspace_memalign behaves as memalign, but operates within
1087 the given space.
1088*/
1089void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
1090
1091/*
1092 mspace_independent_calloc behaves as independent_calloc, but
1093 operates within the given space.
1094*/
1095void** mspace_independent_calloc(mspace msp, size_t n_elements,
1096 size_t elem_size, void* chunks[]);
1097
1098/*
1099 mspace_independent_comalloc behaves as independent_comalloc, but
1100 operates within the given space.
1101*/
1102void** mspace_independent_comalloc(mspace msp, size_t n_elements,
1103 size_t sizes[], void* chunks[]);
1104
1105/*
1106 mspace_footprint() returns the number of bytes obtained from the
1107 system for this space.
1108*/
1109size_t mspace_footprint(mspace msp);
1110
1111/*
1112 mspace_max_footprint() returns the peak number of bytes obtained from the
1113 system for this space.
1114*/
1115size_t mspace_max_footprint(mspace msp);
1116
1117
1118#if !NO_MALLINFO
1119/*
1120 mspace_mallinfo behaves as mallinfo, but reports properties of
1121 the given space.
1122*/
1123struct mallinfo mspace_mallinfo(mspace msp);
1124#endif /* NO_MALLINFO */
1125
1126/*
1127 mspace_malloc_stats behaves as malloc_stats, but reports
1128 properties of the given space.
1129*/
1130void mspace_malloc_stats(mspace msp);
1131
1132/*
1133 mspace_trim behaves as malloc_trim, but
1134 operates within the given space.
1135*/
1136int mspace_trim(mspace msp, size_t pad);
1137
1138/*
1139 An alias for mallopt.
1140*/
1141int mspace_mallopt(int, int);
1142
1143#endif /* MSPACES */
1144
1145#ifdef __cplusplus
1146}; /* end of extern "C" */
1147#endif /* __cplusplus */
1148
1149/*
1150 ========================================================================
1151 To make a fully customizable malloc.h header file, cut everything
1152 above this line, put into file malloc.h, edit to suit, and #include it
1153 on the next line, as well as in programs that use this malloc.
1154 ========================================================================
1155*/
1156
1157/* #include "malloc.h" */
1158
1159/*------------------------------ internal #includes ---------------------- */
1160
1161#ifdef _MSC_VER
1162#pragma warning( disable : 4146 ) /* no "unsigned" warnings */
1163#endif /* _MSC_VER */
1164
1165#ifndef LACKS_STDIO_H
1166#include <stdio.h> /* for printing in malloc_stats */
1167#endif
1168
1169#ifndef LACKS_ERRNO_H
1170#include <errno.h> /* for MALLOC_FAILURE_ACTION */
1171#endif /* LACKS_ERRNO_H */
1172#if FOOTERS
1173#include <time.h> /* for magic initialization */
1174#endif /* FOOTERS */
1175#ifndef LACKS_STDLIB_H
1176#include <stdlib.h> /* for abort() */
1177#endif /* LACKS_STDLIB_H */
1178#ifdef DEBUG
1179#if ABORT_ON_ASSERT_FAILURE
1180#define assert(x) if(!(x)) ABORT
1181#else /* ABORT_ON_ASSERT_FAILURE */
1182#include <assert.h>
1183#endif /* ABORT_ON_ASSERT_FAILURE */
1184#else /* DEBUG */
1185#define assert(x)
1186#endif /* DEBUG */
1187#ifndef LACKS_STRING_H
1188#include <string.h> /* for memset etc */
1189#endif /* LACKS_STRING_H */
1190#if USE_BUILTIN_FFS
1191#ifndef LACKS_STRINGS_H
1192#include <strings.h> /* for ffs */
1193#endif /* LACKS_STRINGS_H */
1194#endif /* USE_BUILTIN_FFS */
1195#if HAVE_MMAP
1196#ifndef LACKS_SYS_MMAN_H
1197#include <sys/mman.h> /* for mmap */
1198#endif /* LACKS_SYS_MMAN_H */
1199#ifndef LACKS_FCNTL_H
1200#include <fcntl.h>
1201#endif /* LACKS_FCNTL_H */
1202#endif /* HAVE_MMAP */
1203#if HAVE_MORECORE
1204#ifndef LACKS_UNISTD_H
1205#include <unistd.h> /* for sbrk */
1206#else /* LACKS_UNISTD_H */
1207#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1208extern void* sbrk(ptrdiff_t);
1209#endif /* FreeBSD etc */
1210#endif /* LACKS_UNISTD_H */
1211#endif /* HAVE_MMAP */
1212
1213#ifndef WIN32
1214#ifndef malloc_getpagesize
1215# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
1216# ifndef _SC_PAGE_SIZE
1217# define _SC_PAGE_SIZE _SC_PAGESIZE
1218# endif
1219# endif
1220# ifdef _SC_PAGE_SIZE
1221# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
1222# else
1223# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
1224 extern size_t getpagesize();
1225# define malloc_getpagesize getpagesize()
1226# else
1227# ifdef WIN32 /* use supplied emulation of getpagesize */
1228# define malloc_getpagesize getpagesize()
1229# else
1230# ifndef LACKS_SYS_PARAM_H
1231# include <sys/param.h>
1232# endif
1233# ifdef EXEC_PAGESIZE
1234# define malloc_getpagesize EXEC_PAGESIZE
1235# else
1236# ifdef NBPG
1237# ifndef CLSIZE
1238# define malloc_getpagesize NBPG
1239# else
1240# define malloc_getpagesize (NBPG * CLSIZE)
1241# endif
1242# else
1243# ifdef NBPC
1244# define malloc_getpagesize NBPC
1245# else
1246# ifdef PAGESIZE
1247# define malloc_getpagesize PAGESIZE
1248# else /* just guess */
1249# define malloc_getpagesize ((size_t)4096U)
1250# endif
1251# endif
1252# endif
1253# endif
1254# endif
1255# endif
1256# endif
1257#endif
1258#endif
1259
1260/* ------------------- size_t and alignment properties -------------------- */
1261
1262/* The byte and bit size of a size_t */
1263#define SIZE_T_SIZE (sizeof(size_t))
1264#define SIZE_T_BITSIZE (sizeof(size_t) << 3)
1265
1266/* Some constants coerced to size_t */
1267/* Annoying but necessary to avoid errors on some plaftorms */
1268#define SIZE_T_ZERO ((size_t)0)
1269#define SIZE_T_ONE ((size_t)1)
1270#define SIZE_T_TWO ((size_t)2)
1271#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)
1272#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)
1273#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
1274#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)
1275
1276/* The bit mask value corresponding to MALLOC_ALIGNMENT */
1277#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)
1278
1279/* True if address a has acceptable alignment */
1280#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
1281
1282/* the number of bytes to offset an address to align it */
1283#define align_offset(A)\
1284 ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
1285 ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
1286
1287/* -------------------------- MMAP preliminaries ------------------------- */
1288
1289/*
1290 If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
1291 checks to fail so compiler optimizer can delete code rather than
1292 using so many "#if"s.
1293*/
1294
1295
1296/* MORECORE and MMAP must return MFAIL on failure */
1297#define MFAIL ((void*)(MAX_SIZE_T))
1298#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */
1299
1300#if !HAVE_MMAP
1301#define IS_MMAPPED_BIT (SIZE_T_ZERO)
1302#define USE_MMAP_BIT (SIZE_T_ZERO)
1303#define CALL_MMAP(s) MFAIL
1304#define CALL_MUNMAP(a, s) (-1)
1305#define DIRECT_MMAP(s) MFAIL
1306
1307#else /* HAVE_MMAP */
1308#define IS_MMAPPED_BIT (SIZE_T_ONE)
1309#define USE_MMAP_BIT (SIZE_T_ONE)
1310
1311#ifndef WIN32
1312#define CALL_MUNMAP(a, s) munmap((a), (s))
1313#define MMAP_PROT (PROT_READ|PROT_WRITE)
1314#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1315#define MAP_ANONYMOUS MAP_ANON
1316#endif /* MAP_ANON */
1317#ifdef MAP_ANONYMOUS
1318#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
1319#define CALL_MMAP(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
1320#else /* MAP_ANONYMOUS */
1321/*
1322 Nearly all versions of mmap support MAP_ANONYMOUS, so the following
1323 is unlikely to be needed, but is supplied just in case.
1324*/
1325#define MMAP_FLAGS (MAP_PRIVATE)
1326static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
1327#define CALL_MMAP(s) ((dev_zero_fd < 0) ? \
1328 (dev_zero_fd = open("/dev/zero", O_RDWR), \
1329 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
1330 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
1331#endif /* MAP_ANONYMOUS */
1332
1333#define DIRECT_MMAP(s) CALL_MMAP(s)
1334#else /* WIN32 */
1335
1336/* Win32 MMAP via VirtualAlloc */
1337static void* win32mmap(size_t size) {
1338 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
1339 return (ptr != 0)? ptr: MFAIL;
1340}
1341
1342/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
1343static void* win32direct_mmap(size_t size) {
1344 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
1345 PAGE_READWRITE);
1346 return (ptr != 0)? ptr: MFAIL;
1347}
1348
1349/* This function supports releasing coalesed segments */
1350static int win32munmap(void* ptr, size_t size) {
1351 MEMORY_BASIC_INFORMATION minfo;
1352 char* cptr = ptr;
1353 while (size) {
1354 if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
1355 return -1;
1356 if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
1357 minfo.State != MEM_COMMIT || minfo.RegionSize > size)
1358 return -1;
1359 if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
1360 return -1;
1361 cptr += minfo.RegionSize;
1362 size -= minfo.RegionSize;
1363 }
1364 return 0;
1365}
1366
1367#define CALL_MMAP(s) win32mmap(s)
1368#define CALL_MUNMAP(a, s) win32munmap((a), (s))
1369#define DIRECT_MMAP(s) win32direct_mmap(s)
1370#endif /* WIN32 */
1371#endif /* HAVE_MMAP */
1372
1373#if HAVE_MMAP && HAVE_MREMAP
1374#define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
1375#else /* HAVE_MMAP && HAVE_MREMAP */
1376#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
1377#endif /* HAVE_MMAP && HAVE_MREMAP */
1378
1379#if HAVE_MORECORE
1380#define CALL_MORECORE(S) MORECORE(S)
1381#else /* HAVE_MORECORE */
1382#define CALL_MORECORE(S) MFAIL
1383#endif /* HAVE_MORECORE */
1384
1385/* mstate bit set if continguous morecore disabled or failed */
1386#define USE_NONCONTIGUOUS_BIT (4U)
1387
1388/* segment bit set in create_mspace_with_base */
1389#define EXTERN_BIT (8U)
1390
1391
1392/* --------------------------- Lock preliminaries ------------------------ */
1393
1394#if USE_LOCKS
1395
1396/*
1397 When locks are defined, there are up to two global locks:
1398
1399 * If HAVE_MORECORE, morecore_mutex protects sequences of calls to
1400 MORECORE. In many cases sys_alloc requires two calls, that should
1401 not be interleaved with calls by other threads. This does not
1402 protect against direct calls to MORECORE by other threads not
1403 using this lock, so there is still code to cope the best we can on
1404 interference.
1405
1406 * magic_init_mutex ensures that mparams.magic and other
1407 unique mparams values are initialized only once.
1408*/
1409
1410#ifndef WIN32
1411/* By default use posix locks */
1412#include <pthread.h>
1413#define MLOCK_T pthread_mutex_t
1414#define INITIAL_LOCK(l) pthread_mutex_init(l, NULL)
1415#define ACQUIRE_LOCK(l) pthread_mutex_lock(l)
1416#define RELEASE_LOCK(l) pthread_mutex_unlock(l)
1417
1418#if HAVE_MORECORE
1419static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER;
1420#endif /* HAVE_MORECORE */
1421
1422static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER;
1423
1424#else /* WIN32 */
1425/*
1426 Because lock-protected regions have bounded times, and there
1427 are no recursive lock calls, we can use simple spinlocks.
1428*/
1429
1430#define MLOCK_T long
1431static int win32_acquire_lock (MLOCK_T *sl) {
1432 for (;;) {
1433#ifdef InterlockedCompareExchangePointer
1434 if (!InterlockedCompareExchange(sl, 1, 0))
1435 return 0;
1436#else /* Use older void* version */
1437 if (!InterlockedCompareExchange((void**)sl, (void*)1, (void*)0))
1438 return 0;
1439#endif /* InterlockedCompareExchangePointer */
1440 Sleep (0);
1441 }
1442}
1443
1444static void win32_release_lock (MLOCK_T *sl) {
1445 InterlockedExchange (sl, 0);
1446}
1447
1448#define INITIAL_LOCK(l) *(l)=0
1449#define ACQUIRE_LOCK(l) win32_acquire_lock(l)
1450#define RELEASE_LOCK(l) win32_release_lock(l)
1451#if HAVE_MORECORE
1452static MLOCK_T morecore_mutex;
1453#endif /* HAVE_MORECORE */
1454static MLOCK_T magic_init_mutex;
1455#endif /* WIN32 */
1456
1457#define USE_LOCK_BIT (2U)
1458#else /* USE_LOCKS */
1459#define USE_LOCK_BIT (0U)
1460#define INITIAL_LOCK(l)
1461#endif /* USE_LOCKS */
1462
1463#if USE_LOCKS && HAVE_MORECORE
1464#define ACQUIRE_MORECORE_LOCK() ACQUIRE_LOCK(&morecore_mutex);
1465#define RELEASE_MORECORE_LOCK() RELEASE_LOCK(&morecore_mutex);
1466#else /* USE_LOCKS && HAVE_MORECORE */
1467#define ACQUIRE_MORECORE_LOCK()
1468#define RELEASE_MORECORE_LOCK()
1469#endif /* USE_LOCKS && HAVE_MORECORE */
1470
1471#if USE_LOCKS
1472#define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex);
1473#define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex);
1474#else /* USE_LOCKS */
1475#define ACQUIRE_MAGIC_INIT_LOCK()
1476#define RELEASE_MAGIC_INIT_LOCK()
1477#endif /* USE_LOCKS */
1478
1479
1480/* ----------------------- Chunk representations ------------------------ */
1481
1482/*
1483 (The following includes lightly edited explanations by Colin Plumb.)
1484
1485 The malloc_chunk declaration below is misleading (but accurate and
1486 necessary). It declares a "view" into memory allowing access to
1487 necessary fields at known offsets from a given base.
1488
1489 Chunks of memory are maintained using a `boundary tag' method as
1490 originally described by Knuth. (See the paper by Paul Wilson
1491 ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
1492 techniques.) Sizes of free chunks are stored both in the front of
1493 each chunk and at the end. This makes consolidating fragmented
1494 chunks into bigger chunks fast. The head fields also hold bits
1495 representing whether chunks are free or in use.
1496
1497 Here are some pictures to make it clearer. They are "exploded" to
1498 show that the state of a chunk can be thought of as extending from
1499 the high 31 bits of the head field of its header through the
1500 prev_foot and PINUSE_BIT bit of the following chunk header.
1501
1502 A chunk that's in use looks like:
1503
1504 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1505 | Size of previous chunk (if P = 1) |
1506 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1507 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
1508 | Size of this chunk 1| +-+
1509 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1510 | |
1511 +- -+
1512 | |
1513 +- -+
1514 | :
1515 +- size - sizeof(size_t) available payload bytes -+
1516 : |
1517 chunk-> +- -+
1518 | |
1519 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1520 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
1521 | Size of next chunk (may or may not be in use) | +-+
1522 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1523
1524 And if it's free, it looks like this:
1525
1526 chunk-> +- -+
1527 | User payload (must be in use, or we would have merged!) |
1528 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1529 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
1530 | Size of this chunk 0| +-+
1531 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1532 | Next pointer |
1533 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1534 | Prev pointer |
1535 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1536 | :
1537 +- size - sizeof(struct chunk) unused bytes -+
1538 : |
1539 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1540 | Size of this chunk |
1541 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1542 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
1543 | Size of next chunk (must be in use, or we would have merged)| +-+
1544 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1545 | :
1546 +- User payload -+
1547 : |
1548 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1549 |0|
1550 +-+
1551 Note that since we always merge adjacent free chunks, the chunks
1552 adjacent to a free chunk must be in use.
1553
1554 Given a pointer to a chunk (which can be derived trivially from the
1555 payload pointer) we can, in O(1) time, find out whether the adjacent
1556 chunks are free, and if so, unlink them from the lists that they
1557 are on and merge them with the current chunk.
1558
1559 Chunks always begin on even word boundaries, so the mem portion
1560 (which is returned to the user) is also on an even word boundary, and
1561 thus at least double-word aligned.
1562
1563 The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
1564 chunk size (which is always a multiple of two words), is an in-use
1565 bit for the *previous* chunk. If that bit is *clear*, then the
1566 word before the current chunk size contains the previous chunk
1567 size, and can be used to find the front of the previous chunk.
1568 The very first chunk allocated always has this bit set, preventing
1569 access to non-existent (or non-owned) memory. If pinuse is set for
1570 any given chunk, then you CANNOT determine the size of the
1571 previous chunk, and might even get a memory addressing fault when
1572 trying to do so.
1573
1574 The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
1575 the chunk size redundantly records whether the current chunk is
1576 inuse. This redundancy enables usage checks within free and realloc,
1577 and reduces indirection when freeing and consolidating chunks.
1578
1579 Each freshly allocated chunk must have both cinuse and pinuse set.
1580 That is, each allocated chunk borders either a previously allocated
1581 and still in-use chunk, or the base of its memory arena. This is
1582 ensured by making all allocations from the the `lowest' part of any
1583 found chunk. Further, no free chunk physically borders another one,
1584 so each free chunk is known to be preceded and followed by either
1585 inuse chunks or the ends of memory.
1586
1587 Note that the `foot' of the current chunk is actually represented
1588 as the prev_foot of the NEXT chunk. This makes it easier to
1589 deal with alignments etc but can be very confusing when trying
1590 to extend or adapt this code.
1591
1592 The exceptions to all this are
1593
1594 1. The special chunk `top' is the top-most available chunk (i.e.,
1595 the one bordering the end of available memory). It is treated
1596 specially. Top is never included in any bin, is used only if
1597 no other chunk is available, and is released back to the
1598 system if it is very large (see M_TRIM_THRESHOLD). In effect,
1599 the top chunk is treated as larger (and thus less well
1600 fitting) than any other available chunk. The top chunk
1601 doesn't update its trailing size field since there is no next
1602 contiguous chunk that would have to index off it. However,
1603 space is still allocated for it (TOP_FOOT_SIZE) to enable
1604 separation or merging when space is extended.
1605
1606 3. Chunks allocated via mmap, which have the lowest-order bit
1607 (IS_MMAPPED_BIT) set in their prev_foot fields, and do not set
1608 PINUSE_BIT in their head fields. Because they are allocated
1609 one-by-one, each must carry its own prev_foot field, which is
1610 also used to hold the offset this chunk has within its mmapped
1611 region, which is needed to preserve alignment. Each mmapped
1612 chunk is trailed by the first two fields of a fake next-chunk
1613 for sake of usage checks.
1614
1615*/
1616
1617struct malloc_chunk {
1618 size_t prev_foot; /* Size of previous chunk (if free). */
1619 size_t head; /* Size and inuse bits. */
1620 struct malloc_chunk* fd; /* double links -- used only if free. */
1621 struct malloc_chunk* bk;
1622};
1623
1624typedef struct malloc_chunk mchunk;
1625typedef struct malloc_chunk* mchunkptr;
1626typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */
1627typedef size_t bindex_t; /* Described below */
1628typedef unsigned int binmap_t; /* Described below */
1629typedef unsigned int flag_t; /* The type of various bit flag sets */
1630
1631/* ------------------- Chunks sizes and alignments ----------------------- */
1632
1633#define MCHUNK_SIZE (sizeof(mchunk))
1634
1635#if FOOTERS
1636#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
1637#else /* FOOTERS */
1638#define CHUNK_OVERHEAD (SIZE_T_SIZE)
1639#endif /* FOOTERS */
1640
1641/* MMapped chunks need a second word of overhead ... */
1642#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
1643/* ... and additional padding for fake next-chunk at foot */
1644#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)
1645
1646/* The smallest size we can malloc is an aligned minimal chunk */
1647#define MIN_CHUNK_SIZE\
1648 ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
1649
1650/* conversion from malloc headers to user pointers, and back */
1651#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))
1652#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
1653/* chunk associated with aligned address A */
1654#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))
1655
1656/* Bounds on request (not chunk) sizes. */
1657#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)
1658#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
1659
1660/* pad request bytes into a usable size */
1661#define pad_request(req) \
1662 (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
1663
1664/* pad request, checking for minimum (but not maximum) */
1665#define request2size(req) \
1666 (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
1667
1668
1669/* ------------------ Operations on head and foot fields ----------------- */
1670
1671/*
1672 The head field of a chunk is or'ed with PINUSE_BIT when previous
1673 adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
1674 use. If the chunk was obtained with mmap, the prev_foot field has
1675 IS_MMAPPED_BIT set, otherwise holding the offset of the base of the
1676 mmapped region to the base of the chunk.
1677*/
1678
1679#define PINUSE_BIT (SIZE_T_ONE)
1680#define CINUSE_BIT (SIZE_T_TWO)
1681#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)
1682
1683/* Head value for fenceposts */
1684#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)
1685
1686/* extraction of fields from head words */
1687#define cinuse(p) ((p)->head & CINUSE_BIT)
1688#define pinuse(p) ((p)->head & PINUSE_BIT)
1689#define chunksize(p) ((p)->head & ~(INUSE_BITS))
1690
1691#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)
1692#define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT)
1693
1694/* Treat space at ptr +/- offset as a chunk */
1695#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
1696#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
1697
1698/* Ptr to next or previous physical malloc_chunk. */
1699#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS)))
1700#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
1701
1702/* extract next chunk's pinuse bit */
1703#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)
1704
1705/* Get/set size at footer */
1706#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)
1707#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
1708
1709/* Set size, pinuse bit, and foot */
1710#define set_size_and_pinuse_of_free_chunk(p, s)\
1711 ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
1712
1713/* Set size, pinuse bit, foot, and clear next pinuse */
1714#define set_free_with_pinuse(p, s, n)\
1715 (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
1716
1717#define is_mmapped(p)\
1718 (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT))
1719
1720/* Get the internal overhead associated with chunk p */
1721#define overhead_for(p)\
1722 (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
1723
1724/* Return true if malloced space is not necessarily cleared */
1725#if MMAP_CLEARS
1726#define calloc_must_clear(p) (!is_mmapped(p))
1727#else /* MMAP_CLEARS */
1728#define calloc_must_clear(p) (1)
1729#endif /* MMAP_CLEARS */
1730
1731/* ---------------------- Overlaid data structures ----------------------- */
1732
1733/*
1734 When chunks are not in use, they are treated as nodes of either
1735 lists or trees.
1736
1737 "Small" chunks are stored in circular doubly-linked lists, and look
1738 like this:
1739
1740 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1741 | Size of previous chunk |
1742 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1743 `head:' | Size of chunk, in bytes |P|
1744 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1745 | Forward pointer to next chunk in list |
1746 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1747 | Back pointer to previous chunk in list |
1748 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1749 | Unused space (may be 0 bytes long) .
1750 . .
1751 . |
1752nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1753 `foot:' | Size of chunk, in bytes |
1754 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1755
1756 Larger chunks are kept in a form of bitwise digital trees (aka
1757 tries) keyed on chunksizes. Because malloc_tree_chunks are only for
1758 free chunks greater than 256 bytes, their size doesn't impose any
1759 constraints on user chunk sizes. Each node looks like:
1760
1761 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1762 | Size of previous chunk |
1763 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1764 `head:' | Size of chunk, in bytes |P|
1765 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1766 | Forward pointer to next chunk of same size |
1767 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1768 | Back pointer to previous chunk of same size |
1769 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1770 | Pointer to left child (child[0]) |
1771 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1772 | Pointer to right child (child[1]) |
1773 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1774 | Pointer to parent |
1775 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1776 | bin index of this chunk |
1777 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1778 | Unused space .
1779 . |
1780nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1781 `foot:' | Size of chunk, in bytes |
1782 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1783
1784 Each tree holding treenodes is a tree of unique chunk sizes. Chunks
1785 of the same size are arranged in a circularly-linked list, with only
1786 the oldest chunk (the next to be used, in our FIFO ordering)
1787 actually in the tree. (Tree members are distinguished by a non-null
1788 parent pointer.) If a chunk with the same size an an existing node
1789 is inserted, it is linked off the existing node using pointers that
1790 work in the same way as fd/bk pointers of small chunks.
1791
1792 Each tree contains a power of 2 sized range of chunk sizes (the
1793 smallest is 0x100 <= x < 0x180), which is is divided in half at each
1794 tree level, with the chunks in the smaller half of the range (0x100
1795 <= x < 0x140 for the top nose) in the left subtree and the larger
1796 half (0x140 <= x < 0x180) in the right subtree. This is, of course,
1797 done by inspecting individual bits.
1798
1799 Using these rules, each node's left subtree contains all smaller
1800 sizes than its right subtree. However, the node at the root of each
1801 subtree has no particular ordering relationship to either. (The
1802 dividing line between the subtree sizes is based on trie relation.)
1803 If we remove the last chunk of a given size from the interior of the
1804 tree, we need to replace it with a leaf node. The tree ordering
1805 rules permit a node to be replaced by any leaf below it.
1806
1807 The smallest chunk in a tree (a common operation in a best-fit
1808 allocator) can be found by walking a path to the leftmost leaf in
1809 the tree. Unlike a usual binary tree, where we follow left child
1810 pointers until we reach a null, here we follow the right child
1811 pointer any time the left one is null, until we reach a leaf with
1812 both child pointers null. The smallest chunk in the tree will be
1813 somewhere along that path.
1814
1815 The worst case number of steps to add, find, or remove a node is
1816 bounded by the number of bits differentiating chunks within
1817 bins. Under current bin calculations, this ranges from 6 up to 21
1818 (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
1819 is of course much better.
1820*/
1821
1822struct malloc_tree_chunk {
1823 /* The first four fields must be compatible with malloc_chunk */
1824 size_t prev_foot;
1825 size_t head;
1826 struct malloc_tree_chunk* fd;
1827 struct malloc_tree_chunk* bk;
1828
1829 struct malloc_tree_chunk* child[2];
1830 struct malloc_tree_chunk* parent;
1831 bindex_t index;
1832};
1833
1834typedef struct malloc_tree_chunk tchunk;
1835typedef struct malloc_tree_chunk* tchunkptr;
1836typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
1837
1838/* A little helper macro for trees */
1839#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
1840
1841/* ----------------------------- Segments -------------------------------- */
1842
1843/*
1844 Each malloc space may include non-contiguous segments, held in a
1845 list headed by an embedded malloc_segment record representing the
1846 top-most space. Segments also include flags holding properties of
1847 the space. Large chunks that are directly allocated by mmap are not
1848 included in this list. They are instead independently created and
1849 destroyed without otherwise keeping track of them.
1850
1851 Segment management mainly comes into play for spaces allocated by
1852 MMAP. Any call to MMAP might or might not return memory that is
1853 adjacent to an existing segment. MORECORE normally contiguously
1854 extends the current space, so this space is almost always adjacent,
1855 which is simpler and faster to deal with. (This is why MORECORE is
1856 used preferentially to MMAP when both are available -- see
1857 sys_alloc.) When allocating using MMAP, we don't use any of the
1858 hinting mechanisms (inconsistently) supported in various
1859 implementations of unix mmap, or distinguish reserving from
1860 committing memory. Instead, we just ask for space, and exploit
1861 contiguity when we get it. It is probably possible to do
1862 better than this on some systems, but no general scheme seems
1863 to be significantly better.
1864
1865 Management entails a simpler variant of the consolidation scheme
1866 used for chunks to reduce fragmentation -- new adjacent memory is
1867 normally prepended or appended to an existing segment. However,
1868 there are limitations compared to chunk consolidation that mostly
1869 reflect the fact that segment processing is relatively infrequent
1870 (occurring only when getting memory from system) and that we
1871 don't expect to have huge numbers of segments:
1872
1873 * Segments are not indexed, so traversal requires linear scans. (It
1874 would be possible to index these, but is not worth the extra
1875 overhead and complexity for most programs on most platforms.)
1876 * New segments are only appended to old ones when holding top-most
1877 memory; if they cannot be prepended to others, they are held in
1878 different segments.
1879
1880 Except for the top-most segment of an mstate, each segment record
1881 is kept at the tail of its segment. Segments are added by pushing
1882 segment records onto the list headed by &mstate.seg for the
1883 containing mstate.
1884
1885 Segment flags control allocation/merge/deallocation policies:
1886 * If EXTERN_BIT set, then we did not allocate this segment,
1887 and so should not try to deallocate or merge with others.
1888 (This currently holds only for the initial segment passed
1889 into create_mspace_with_base.)
1890 * If IS_MMAPPED_BIT set, the segment may be merged with
1891 other surrounding mmapped segments and trimmed/de-allocated
1892 using munmap.
1893 * If neither bit is set, then the segment was obtained using
1894 MORECORE so can be merged with surrounding MORECORE'd segments
1895 and deallocated/trimmed using MORECORE with negative arguments.
1896*/
1897
1898struct malloc_segment {
1899 char* base; /* base address */
1900 size_t size; /* allocated size */
1901 struct malloc_segment* next; /* ptr to next segment */
1902 flag_t sflags; /* mmap and extern flag */
1903};
1904
1905#define is_mmapped_segment(S) ((S)->sflags & IS_MMAPPED_BIT)
1906#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)
1907
1908typedef struct malloc_segment msegment;
1909typedef struct malloc_segment* msegmentptr;
1910
1911/* ---------------------------- malloc_state ----------------------------- */
1912
1913/*
1914 A malloc_state holds all of the bookkeeping for a space.
1915 The main fields are:
1916
1917 Top
1918 The topmost chunk of the currently active segment. Its size is
1919 cached in topsize. The actual size of topmost space is
1920 topsize+TOP_FOOT_SIZE, which includes space reserved for adding
1921 fenceposts and segment records if necessary when getting more
1922 space from the system. The size at which to autotrim top is
1923 cached from mparams in trim_check, except that it is disabled if
1924 an autotrim fails.
1925
1926 Designated victim (dv)
1927 This is the preferred chunk for servicing small requests that
1928 don't have exact fits. It is normally the chunk split off most
1929 recently to service another small request. Its size is cached in
1930 dvsize. The link fields of this chunk are not maintained since it
1931 is not kept in a bin.
1932
1933 SmallBins
1934 An array of bin headers for free chunks. These bins hold chunks
1935 with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
1936 chunks of all the same size, spaced 8 bytes apart. To simplify
1937 use in double-linked lists, each bin header acts as a malloc_chunk
1938 pointing to the real first node, if it exists (else pointing to
1939 itself). This avoids special-casing for headers. But to avoid
1940 waste, we allocate only the fd/bk pointers of bins, and then use
1941 repositioning tricks to treat these as the fields of a chunk.
1942
1943 TreeBins
1944 Treebins are pointers to the roots of trees holding a range of
1945 sizes. There are 2 equally spaced treebins for each power of two
1946 from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
1947 larger.
1948
1949 Bin maps
1950 There is one bit map for small bins ("smallmap") and one for
1951 treebins ("treemap). Each bin sets its bit when non-empty, and
1952 clears the bit when empty. Bit operations are then used to avoid
1953 bin-by-bin searching -- nearly all "search" is done without ever
1954 looking at bins that won't be selected. The bit maps
1955 conservatively use 32 bits per map word, even if on 64bit system.
1956 For a good description of some of the bit-based techniques used
1957 here, see Henry S. Warren Jr's book "Hacker's Delight" (and
1958 supplement at http://hackersdelight.org/). Many of these are
1959 intended to reduce the branchiness of paths through malloc etc, as
1960 well as to reduce the number of memory locations read or written.
1961
1962 Segments
1963 A list of segments headed by an embedded malloc_segment record
1964 representing the initial space.
1965
1966 Address check support
1967 The least_addr field is the least address ever obtained from
1968 MORECORE or MMAP. Attempted frees and reallocs of any address less
1969 than this are trapped (unless INSECURE is defined).
1970
1971 Magic tag
1972 A cross-check field that should always hold same value as mparams.magic.
1973
1974 Flags
1975 Bits recording whether to use MMAP, locks, or contiguous MORECORE
1976
1977 Statistics
1978 Each space keeps track of current and maximum system memory
1979 obtained via MORECORE or MMAP.
1980
1981 Locking
1982 If USE_LOCKS is defined, the "mutex" lock is acquired and released
1983 around every public call using this mspace.
1984*/
1985
1986/* Bin types, widths and sizes */
1987#define NSMALLBINS (32U)
1988#define NTREEBINS (32U)
1989#define SMALLBIN_SHIFT (3U)
1990#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)
1991#define TREEBIN_SHIFT (8U)
1992#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)
1993#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)
1994#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
1995
1996struct malloc_state {
1997 binmap_t smallmap;
1998 binmap_t treemap;
1999 size_t dvsize;
2000 size_t topsize;
2001 char* least_addr;
2002 mchunkptr dv;
2003 mchunkptr top;
2004 size_t trim_check;
2005 size_t magic;
2006 mchunkptr smallbins[(NSMALLBINS+1)*2];
2007 tbinptr treebins[NTREEBINS];
2008 size_t footprint;
2009 size_t max_footprint;
2010 flag_t mflags;
2011#if USE_LOCKS
2012 MLOCK_T mutex; /* locate lock among fields that rarely change */
2013#endif /* USE_LOCKS */
2014 msegment seg;
2015};
2016
2017typedef struct malloc_state* mstate;
2018
2019/* ------------- Global malloc_state and malloc_params ------------------- */
2020
2021/*
2022 malloc_params holds global properties, including those that can be
2023 dynamically set using mallopt. There is a single instance, mparams,
2024 initialized in init_mparams.
2025*/
2026
2027struct malloc_params {
2028 size_t magic;
2029 size_t page_size;
2030 size_t granularity;
2031 size_t mmap_threshold;
2032 size_t trim_threshold;
2033 flag_t default_mflags;
2034};
2035
2036static struct malloc_params mparams;
2037
2038/* The global malloc_state used for all non-"mspace" calls */
2039static struct malloc_state _gm_;
2040#define gm (&_gm_)
2041#define is_global(M) ((M) == &_gm_)
2042#define is_initialized(M) ((M)->top != 0)
2043
2044/* -------------------------- system alloc setup ------------------------- */
2045
2046/* Operations on mflags */
2047
2048#define use_lock(M) ((M)->mflags & USE_LOCK_BIT)
2049#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)
2050#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)
2051
2052#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)
2053#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)
2054#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)
2055
2056#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)
2057#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)
2058
2059#define set_lock(M,L)\
2060 ((M)->mflags = (L)?\
2061 ((M)->mflags | USE_LOCK_BIT) :\
2062 ((M)->mflags & ~USE_LOCK_BIT))
2063
2064/* page-align a size */
2065#define page_align(S)\
2066 (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE))
2067
2068/* granularity-align a size */
2069#define granularity_align(S)\
2070 (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE))
2071
2072#define is_page_aligned(S)\
2073 (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
2074#define is_granularity_aligned(S)\
2075 (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
2076
2077/* True if segment S holds address A */
2078#define segment_holds(S, A)\
2079 ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
2080
2081/* Return segment holding given address */
2082static msegmentptr segment_holding(mstate m, char* addr) {
2083 msegmentptr sp = &m->seg;
2084 for (;;) {
2085 if (addr >= sp->base && addr < sp->base + sp->size)
2086 return sp;
2087 if ((sp = sp->next) == 0)
2088 return 0;
2089 }
2090}
2091
2092/* Return true if segment contains a segment link */
2093static int has_segment_link(mstate m, msegmentptr ss) {
2094 msegmentptr sp = &m->seg;
2095 for (;;) {
2096 if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
2097 return 1;
2098 if ((sp = sp->next) == 0)
2099 return 0;
2100 }
2101}
2102
2103#ifndef MORECORE_CANNOT_TRIM
2104#define should_trim(M,s) ((s) > (M)->trim_check)
2105#else /* MORECORE_CANNOT_TRIM */
2106#define should_trim(M,s) (0)
2107#endif /* MORECORE_CANNOT_TRIM */
2108
2109/*
2110 TOP_FOOT_SIZE is padding at the end of a segment, including space
2111 that may be needed to place segment records and fenceposts when new
2112 noncontiguous segments are added.
2113*/
2114#define TOP_FOOT_SIZE\
2115 (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
2116
2117
2118/* ------------------------------- Hooks -------------------------------- */
2119
2120/*
2121 PREACTION should be defined to return 0 on success, and nonzero on
2122 failure. If you are not using locking, you can redefine these to do
2123 anything you like.
2124*/
2125
2126#if USE_LOCKS
2127
2128/* Ensure locks are initialized */
2129#define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams())
2130
2131#define PREACTION(M) ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
2132#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
2133#else /* USE_LOCKS */
2134
2135#ifndef PREACTION
2136#define PREACTION(M) (0)
2137#endif /* PREACTION */
2138
2139#ifndef POSTACTION
2140#define POSTACTION(M)
2141#endif /* POSTACTION */
2142
2143#endif /* USE_LOCKS */
2144
2145/*
2146 CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
2147 USAGE_ERROR_ACTION is triggered on detected bad frees and
2148 reallocs. The argument p is an address that might have triggered the
2149 fault. It is ignored by the two predefined actions, but might be
2150 useful in custom actions that try to help diagnose errors.
2151*/
2152
2153#if PROCEED_ON_ERROR
2154
2155/* A count of the number of corruption errors causing resets */
2156int malloc_corruption_error_count;
2157
2158/* default corruption action */
2159static void reset_on_error(mstate m);
2160
2161#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)
2162#define USAGE_ERROR_ACTION(m, p)
2163
2164#else /* PROCEED_ON_ERROR */
2165
2166#ifndef CORRUPTION_ERROR_ACTION
2167#define CORRUPTION_ERROR_ACTION(m) ABORT
2168#endif /* CORRUPTION_ERROR_ACTION */
2169
2170#ifndef USAGE_ERROR_ACTION
2171#define USAGE_ERROR_ACTION(m,p) ABORT
2172#endif /* USAGE_ERROR_ACTION */
2173
2174#endif /* PROCEED_ON_ERROR */
2175
2176/* -------------------------- Debugging setup ---------------------------- */
2177
2178#if ! DEBUG
2179
2180#define check_free_chunk(M,P)
2181#define check_inuse_chunk(M,P)
2182#define check_malloced_chunk(M,P,N)
2183#define check_mmapped_chunk(M,P)
2184#define check_malloc_state(M)
2185#define check_top_chunk(M,P)
2186
2187#else /* DEBUG */
2188#define check_free_chunk(M,P) do_check_free_chunk(M,P)
2189#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)
2190#define check_top_chunk(M,P) do_check_top_chunk(M,P)
2191#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
2192#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)
2193#define check_malloc_state(M) do_check_malloc_state(M)
2194
2195static void do_check_any_chunk(mstate m, mchunkptr p);
2196static void do_check_top_chunk(mstate m, mchunkptr p);
2197static void do_check_mmapped_chunk(mstate m, mchunkptr p);
2198static void do_check_inuse_chunk(mstate m, mchunkptr p);
2199static void do_check_free_chunk(mstate m, mchunkptr p);
2200static void do_check_malloced_chunk(mstate m, void* mem, size_t s);
2201static void do_check_tree(mstate m, tchunkptr t);
2202static void do_check_treebin(mstate m, bindex_t i);
2203static void do_check_smallbin(mstate m, bindex_t i);
2204static void do_check_malloc_state(mstate m);
2205static int bin_find(mstate m, mchunkptr x);
2206static size_t traverse_and_check(mstate m);
2207#endif /* DEBUG */
2208
2209/* ---------------------------- Indexing Bins ---------------------------- */
2210
2211#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
2212#define small_index(s) ((s) >> SMALLBIN_SHIFT)
2213#define small_index2size(i) ((i) << SMALLBIN_SHIFT)
2214#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))
2215
2216/* addressing by index. See above about smallbin repositioning */
2217#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
2218#define treebin_at(M,i) (&((M)->treebins[i]))
2219
2220/* assign tree index for size S to variable I */
2221#if defined(__GNUC__) && defined(i386)
2222#define compute_tree_index(S, I)\
2223{\
2224 size_t X = S >> TREEBIN_SHIFT;\
2225 if (X == 0)\
2226 I = 0;\
2227 else if (X > 0xFFFF)\
2228 I = NTREEBINS-1;\
2229 else {\
2230 unsigned int K;\
2231 __asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm" (X));\
2232 I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
2233 }\
2234}
2235#else /* GNUC */
2236#define compute_tree_index(S, I)\
2237{\
2238 size_t X = S >> TREEBIN_SHIFT;\
2239 if (X == 0)\
2240 I = 0;\
2241 else if (X > 0xFFFF)\
2242 I = NTREEBINS-1;\
2243 else {\
2244 unsigned int Y = (unsigned int)X;\
2245 unsigned int N = ((Y - 0x100) >> 16) & 8;\
2246 unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
2247 N += K;\
2248 N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
2249 K = 14 - N + ((Y <<= K) >> 15);\
2250 I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
2251 }\
2252}
2253#endif /* GNUC */
2254
2255/* Bit representing maximum resolved size in a treebin at i */
2256#define bit_for_tree_index(i) \
2257 (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
2258
2259/* Shift placing maximum resolved bit in a treebin at i as sign bit */
2260#define leftshift_for_tree_index(i) \
2261 ((i == NTREEBINS-1)? 0 : \
2262 ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
2263
2264/* The size of the smallest chunk held in bin with index i */
2265#define minsize_for_tree_index(i) \
2266 ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \
2267 (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
2268
2269
2270/* ------------------------ Operations on bin maps ----------------------- */
2271
2272/* bit corresponding to given index */
2273#define idx2bit(i) ((binmap_t)(1) << (i))
2274
2275/* Mark/Clear bits with given index */
2276#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))
2277#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))
2278#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))
2279
2280#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))
2281#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))
2282#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))
2283
2284/* index corresponding to given bit */
2285
2286#if defined(__GNUC__) && defined(i386)
2287#define compute_bit2idx(X, I)\
2288{\
2289 unsigned int J;\
2290 __asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\
2291 I = (bindex_t)J;\
2292}
2293
2294#else /* GNUC */
2295#if USE_BUILTIN_FFS
2296#define compute_bit2idx(X, I) I = ffs(X)-1
2297
2298#else /* USE_BUILTIN_FFS */
2299#define compute_bit2idx(X, I)\
2300{\
2301 unsigned int Y = X - 1;\
2302 unsigned int K = Y >> (16-4) & 16;\
2303 unsigned int N = K; Y >>= K;\
2304 N += K = Y >> (8-3) & 8; Y >>= K;\
2305 N += K = Y >> (4-2) & 4; Y >>= K;\
2306 N += K = Y >> (2-1) & 2; Y >>= K;\
2307 N += K = Y >> (1-0) & 1; Y >>= K;\
2308 I = (bindex_t)(N + Y);\
2309}
2310#endif /* USE_BUILTIN_FFS */
2311#endif /* GNUC */
2312
2313/* isolate the least set bit of a bitmap */
2314#define least_bit(x) ((x) & -(x))
2315
2316/* mask with all bits to left of least bit of x on */
2317#define left_bits(x) ((x<<1) | -(x<<1))
2318
2319/* mask with all bits to left of or equal to least bit of x on */
2320#define same_or_left_bits(x) ((x) | -(x))
2321
2322
2323/* ----------------------- Runtime Check Support ------------------------- */
2324
2325/*
2326 For security, the main invariant is that malloc/free/etc never
2327 writes to a static address other than malloc_state, unless static
2328 malloc_state itself has been corrupted, which cannot occur via
2329 malloc (because of these checks). In essence this means that we
2330 believe all pointers, sizes, maps etc held in malloc_state, but
2331 check all of those linked or offsetted from other embedded data
2332 structures. These checks are interspersed with main code in a way
2333 that tends to minimize their run-time cost.
2334
2335 When FOOTERS is defined, in addition to range checking, we also
2336 verify footer fields of inuse chunks, which can be used guarantee
2337 that the mstate controlling malloc/free is intact. This is a
2338 streamlined version of the approach described by William Robertson
2339 et al in "Run-time Detection of Heap-based Overflows" LISA'03
2340 http://www.usenix.org/events/lisa03/tech/robertson.html The footer
2341 of an inuse chunk holds the xor of its mstate and a random seed,
2342 that is checked upon calls to free() and realloc(). This is
2343 (probablistically) unguessable from outside the program, but can be
2344 computed by any code successfully malloc'ing any chunk, so does not
2345 itself provide protection against code that has already broken
2346 security through some other means. Unlike Robertson et al, we
2347 always dynamically check addresses of all offset chunks (previous,
2348 next, etc). This turns out to be cheaper than relying on hashes.
2349*/
2350
2351#if !INSECURE
2352/* Check if address a is at least as high as any from MORECORE or MMAP */
2353#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
2354/* Check if address of next chunk n is higher than base chunk p */
2355#define ok_next(p, n) ((char*)(p) < (char*)(n))
2356/* Check if p has its cinuse bit on */
2357#define ok_cinuse(p) cinuse(p)
2358/* Check if p has its pinuse bit on */
2359#define ok_pinuse(p) pinuse(p)
2360
2361#else /* !INSECURE */
2362#define ok_address(M, a) (1)
2363#define ok_next(b, n) (1)
2364#define ok_cinuse(p) (1)
2365#define ok_pinuse(p) (1)
2366#endif /* !INSECURE */
2367
2368#if (FOOTERS && !INSECURE)
2369/* Check if (alleged) mstate m has expected magic field */
2370#define ok_magic(M) ((M)->magic == mparams.magic)
2371#else /* (FOOTERS && !INSECURE) */
2372#define ok_magic(M) (1)
2373#endif /* (FOOTERS && !INSECURE) */
2374
2375
2376/* In gcc, use __builtin_expect to minimize impact of checks */
2377#if !INSECURE
2378#if defined(__GNUC__) && __GNUC__ >= 3
2379#define RTCHECK(e) __builtin_expect(e, 1)
2380#else /* GNUC */
2381#define RTCHECK(e) (e)
2382#endif /* GNUC */
2383#else /* !INSECURE */
2384#define RTCHECK(e) (1)
2385#endif /* !INSECURE */
2386
2387/* macros to set up inuse chunks with or without footers */
2388
2389#if !FOOTERS
2390
2391#define mark_inuse_foot(M,p,s)
2392
2393/* Set cinuse bit and pinuse bit of next chunk */
2394#define set_inuse(M,p,s)\
2395 ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
2396 ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
2397
2398/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
2399#define set_inuse_and_pinuse(M,p,s)\
2400 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2401 ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
2402
2403/* Set size, cinuse and pinuse bit of this chunk */
2404#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
2405 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
2406
2407#else /* FOOTERS */
2408
2409/* Set foot of inuse chunk to be xor of mstate and seed */
2410#define mark_inuse_foot(M,p,s)\
2411 (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
2412
2413#define get_mstate_for(p)\
2414 ((mstate)(((mchunkptr)((char*)(p) +\
2415 (chunksize(p))))->prev_foot ^ mparams.magic))
2416
2417#define set_inuse(M,p,s)\
2418 ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
2419 (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
2420 mark_inuse_foot(M,p,s))
2421
2422#define set_inuse_and_pinuse(M,p,s)\
2423 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2424 (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
2425 mark_inuse_foot(M,p,s))
2426
2427#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
2428 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
2429 mark_inuse_foot(M, p, s))
2430
2431#endif /* !FOOTERS */
2432
2433/* ---------------------------- setting mparams -------------------------- */
2434
2435/* Initialize mparams */
2436static int init_mparams(void) {
2437 if (mparams.page_size == 0) {
2438 size_t s;
2439
2440 mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
2441 mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
2442#if MORECORE_CONTIGUOUS
2443 mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
2444#else /* MORECORE_CONTIGUOUS */
2445 mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
2446#endif /* MORECORE_CONTIGUOUS */
2447
2448#if (FOOTERS && !INSECURE)
2449 {
2450#if USE_DEV_RANDOM
2451 int fd;
2452 unsigned char buf[sizeof(size_t)];
2453 /* Try to use /dev/urandom, else fall back on using time */
2454 if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
2455 read(fd, buf, sizeof(buf)) == sizeof(buf)) {
2456 s = *((size_t *) buf);
2457 close(fd);
2458 }
2459 else
2460#endif /* USE_DEV_RANDOM */
2461 s = (size_t)(time(0) ^ (size_t)0x55555555U);
2462
2463 s |= (size_t)8U; /* ensure nonzero */
2464 s &= ~(size_t)7U; /* improve chances of fault for bad values */
2465
2466 }
2467#else /* (FOOTERS && !INSECURE) */
2468 s = (size_t)0x58585858U;
2469#endif /* (FOOTERS && !INSECURE) */
2470 ACQUIRE_MAGIC_INIT_LOCK();
2471 if (mparams.magic == 0) {
2472 mparams.magic = s;
2473 /* Set up lock for main malloc area */
2474 INITIAL_LOCK(&gm->mutex);
2475 gm->mflags = mparams.default_mflags;
2476 }
2477 RELEASE_MAGIC_INIT_LOCK();
2478
2479#ifndef WIN32
2480 mparams.page_size = malloc_getpagesize;
2481 mparams.granularity = ((DEFAULT_GRANULARITY != 0)?
2482 DEFAULT_GRANULARITY : mparams.page_size);
2483#else /* WIN32 */
2484 {
2485 SYSTEM_INFO system_info;
2486 GetSystemInfo(&system_info);
2487 mparams.page_size = system_info.dwPageSize;
2488 mparams.granularity = system_info.dwAllocationGranularity;
2489 }
2490#endif /* WIN32 */
2491
2492 /* Sanity-check configuration:
2493 size_t must be unsigned and as wide as pointer type.
2494 ints must be at least 4 bytes.
2495 alignment must be at least 8.
2496 Alignment, min chunk size, and page size must all be powers of 2.
2497 */
2498 if ((sizeof(size_t) != sizeof(char*)) ||
2499 (MAX_SIZE_T < MIN_CHUNK_SIZE) ||
2500 (sizeof(int) < 4) ||
2501 (MALLOC_ALIGNMENT < (size_t)8U) ||
2502 ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
2503 ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||
2504 ((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) ||
2505 ((mparams.page_size & (mparams.page_size-SIZE_T_ONE)) != 0))
2506 ABORT;
2507 }
2508 return 0;
2509}
2510
2511/* support for mallopt */
2512static int change_mparam(int param_number, int value) {
2513 size_t val = (size_t)value;
2514 init_mparams();
2515 switch(param_number) {
2516 case M_TRIM_THRESHOLD:
2517 mparams.trim_threshold = val;
2518 return 1;
2519 case M_GRANULARITY:
2520 if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
2521 mparams.granularity = val;
2522 return 1;
2523 }
2524 else
2525 return 0;
2526 case M_MMAP_THRESHOLD:
2527 mparams.mmap_threshold = val;
2528 return 1;
2529 default:
2530 return 0;
2531 }
2532}
2533
2534#if DEBUG
2535/* ------------------------- Debugging Support --------------------------- */
2536
2537/* Check properties of any chunk, whether free, inuse, mmapped etc */
2538static void do_check_any_chunk(mstate m, mchunkptr p) {
2539 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
2540 assert(ok_address(m, p));
2541}
2542
2543/* Check properties of top chunk */
2544static void do_check_top_chunk(mstate m, mchunkptr p) {
2545 msegmentptr sp = segment_holding(m, (char*)p);
2546 size_t sz = chunksize(p);
2547 assert(sp != 0);
2548 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
2549 assert(ok_address(m, p));
2550 assert(sz == m->topsize);
2551 assert(sz > 0);
2552 assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
2553 assert(pinuse(p));
2554 assert(!next_pinuse(p));
2555}
2556
2557/* Check properties of (inuse) mmapped chunks */
2558static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
2559 size_t sz = chunksize(p);
2560 size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD);
2561 assert(is_mmapped(p));
2562 assert(use_mmap(m));
2563 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
2564 assert(ok_address(m, p));
2565 assert(!is_small(sz));
2566 assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
2567 assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
2568 assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
2569}
2570
2571/* Check properties of inuse chunks */
2572static void do_check_inuse_chunk(mstate m, mchunkptr p) {
2573 do_check_any_chunk(m, p);
2574 assert(cinuse(p));
2575 assert(next_pinuse(p));
2576 /* If not pinuse and not mmapped, previous chunk has OK offset */
2577 assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
2578 if (is_mmapped(p))
2579 do_check_mmapped_chunk(m, p);
2580}
2581
2582/* Check properties of free chunks */
2583static void do_check_free_chunk(mstate m, mchunkptr p) {
2584 size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
2585 mchunkptr next = chunk_plus_offset(p, sz);
2586 do_check_any_chunk(m, p);
2587 assert(!cinuse(p));
2588 assert(!next_pinuse(p));
2589 assert (!is_mmapped(p));
2590 if (p != m->dv && p != m->top) {
2591 if (sz >= MIN_CHUNK_SIZE) {
2592 assert((sz & CHUNK_ALIGN_MASK) == 0);
2593 assert(is_aligned(chunk2mem(p)));
2594 assert(next->prev_foot == sz);
2595 assert(pinuse(p));
2596 assert (next == m->top || cinuse(next));
2597 assert(p->fd->bk == p);
2598 assert(p->bk->fd == p);
2599 }
2600 else /* markers are always of size SIZE_T_SIZE */
2601 assert(sz == SIZE_T_SIZE);
2602 }
2603}
2604
2605/* Check properties of malloced chunks at the point they are malloced */
2606static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
2607 if (mem != 0) {
2608 mchunkptr p = mem2chunk(mem);
2609 size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
2610 do_check_inuse_chunk(m, p);
2611 assert((sz & CHUNK_ALIGN_MASK) == 0);
2612 assert(sz >= MIN_CHUNK_SIZE);
2613 assert(sz >= s);
2614 /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
2615 assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
2616 }
2617}
2618
2619/* Check a tree and its subtrees. */
2620static void do_check_tree(mstate m, tchunkptr t) {
2621 tchunkptr head = 0;
2622 tchunkptr u = t;
2623 bindex_t tindex = t->index;
2624 size_t tsize = chunksize(t);
2625 bindex_t idx;
2626 compute_tree_index(tsize, idx);
2627 assert(tindex == idx);
2628 assert(tsize >= MIN_LARGE_SIZE);
2629 assert(tsize >= minsize_for_tree_index(idx));
2630 assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
2631
2632 do { /* traverse through chain of same-sized nodes */
2633 do_check_any_chunk(m, ((mchunkptr)u));
2634 assert(u->index == tindex);
2635 assert(chunksize(u) == tsize);
2636 assert(!cinuse(u));
2637 assert(!next_pinuse(u));
2638 assert(u->fd->bk == u);
2639 assert(u->bk->fd == u);
2640 if (u->parent == 0) {
2641 assert(u->child[0] == 0);
2642 assert(u->child[1] == 0);
2643 }
2644 else {
2645 assert(head == 0); /* only one node on chain has parent */
2646 head = u;
2647 assert(u->parent != u);
2648 assert (u->parent->child[0] == u ||
2649 u->parent->child[1] == u ||
2650 *((tbinptr*)(u->parent)) == u);
2651 if (u->child[0] != 0) {
2652 assert(u->child[0]->parent == u);
2653 assert(u->child[0] != u);
2654 do_check_tree(m, u->child[0]);
2655 }
2656 if (u->child[1] != 0) {
2657 assert(u->child[1]->parent == u);
2658 assert(u->child[1] != u);
2659 do_check_tree(m, u->child[1]);
2660 }
2661 if (u->child[0] != 0 && u->child[1] != 0) {
2662 assert(chunksize(u->child[0]) < chunksize(u->child[1]));
2663 }
2664 }
2665 u = u->fd;
2666 } while (u != t);
2667 assert(head != 0);
2668}
2669
2670/* Check all the chunks in a treebin. */
2671static void do_check_treebin(mstate m, bindex_t i) {
2672 tbinptr* tb = treebin_at(m, i);
2673 tchunkptr t = *tb;
2674 int empty = (m->treemap & (1U << i)) == 0;
2675 if (t == 0)
2676 assert(empty);
2677 if (!empty)
2678 do_check_tree(m, t);
2679}
2680
2681/* Check all the chunks in a smallbin. */
2682static void do_check_smallbin(mstate m, bindex_t i) {
2683 sbinptr b = smallbin_at(m, i);
2684 mchunkptr p = b->bk;
2685 unsigned int empty = (m->smallmap & (1U << i)) == 0;
2686 if (p == b)
2687 assert(empty);
2688 if (!empty) {
2689 for (; p != b; p = p->bk) {
2690 size_t size = chunksize(p);
2691 mchunkptr q;
2692 /* each chunk claims to be free */
2693 do_check_free_chunk(m, p);
2694 /* chunk belongs in bin */
2695 assert(small_index(size) == i);
2696 assert(p->bk == b || chunksize(p->bk) == chunksize(p));
2697 /* chunk is followed by an inuse chunk */
2698 q = next_chunk(p);
2699 if (q->head != FENCEPOST_HEAD)
2700 do_check_inuse_chunk(m, q);
2701 }
2702 }
2703}
2704
2705/* Find x in a bin. Used in other check functions. */
2706static int bin_find(mstate m, mchunkptr x) {
2707 size_t size = chunksize(x);
2708 if (is_small(size)) {
2709 bindex_t sidx = small_index(size);
2710 sbinptr b = smallbin_at(m, sidx);
2711 if (smallmap_is_marked(m, sidx)) {
2712 mchunkptr p = b;
2713 do {
2714 if (p == x)
2715 return 1;
2716 } while ((p = p->fd) != b);
2717 }
2718 }
2719 else {
2720 bindex_t tidx;
2721 compute_tree_index(size, tidx);
2722 if (treemap_is_marked(m, tidx)) {
2723 tchunkptr t = *treebin_at(m, tidx);
2724 size_t sizebits = size << leftshift_for_tree_index(tidx);
2725 while (t != 0 && chunksize(t) != size) {
2726 t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
2727 sizebits <<= 1;
2728 }
2729 if (t != 0) {
2730 tchunkptr u = t;
2731 do {
2732 if (u == (tchunkptr)x)
2733 return 1;
2734 } while ((u = u->fd) != t);
2735 }
2736 }
2737 }
2738 return 0;
2739}
2740
2741/* Traverse each chunk and check it; return total */
2742static size_t traverse_and_check(mstate m) {
2743 size_t sum = 0;
2744 if (is_initialized(m)) {
2745 msegmentptr s = &m->seg;
2746 sum += m->topsize + TOP_FOOT_SIZE;
2747 while (s != 0) {
2748 mchunkptr q = align_as_chunk(s->base);
2749 mchunkptr lastq = 0;
2750 assert(pinuse(q));
2751 while (segment_holds(s, q) &&
2752 q != m->top && q->head != FENCEPOST_HEAD) {
2753 sum += chunksize(q);
2754 if (cinuse(q)) {
2755 assert(!bin_find(m, q));
2756 do_check_inuse_chunk(m, q);
2757 }
2758 else {
2759 assert(q == m->dv || bin_find(m, q));
2760 assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */
2761 do_check_free_chunk(m, q);
2762 }
2763 lastq = q;
2764 q = next_chunk(q);
2765 }
2766 s = s->next;
2767 }
2768 }
2769 return sum;
2770}
2771
2772/* Check all properties of malloc_state. */
2773static void do_check_malloc_state(mstate m) {
2774 bindex_t i;
2775 size_t total;
2776 /* check bins */
2777 for (i = 0; i < NSMALLBINS; ++i)
2778 do_check_smallbin(m, i);
2779 for (i = 0; i < NTREEBINS; ++i)
2780 do_check_treebin(m, i);
2781
2782 if (m->dvsize != 0) { /* check dv chunk */
2783 do_check_any_chunk(m, m->dv);
2784 assert(m->dvsize == chunksize(m->dv));
2785 assert(m->dvsize >= MIN_CHUNK_SIZE);
2786 assert(bin_find(m, m->dv) == 0);
2787 }
2788
2789 if (m->top != 0) { /* check top chunk */
2790 do_check_top_chunk(m, m->top);
2791 assert(m->topsize == chunksize(m->top));
2792 assert(m->topsize > 0);
2793 assert(bin_find(m, m->top) == 0);
2794 }
2795
2796 total = traverse_and_check(m);
2797 assert(total <= m->footprint);
2798 assert(m->footprint <= m->max_footprint);
2799}
2800#endif /* DEBUG */
2801
2802/* ----------------------------- statistics ------------------------------ */
2803
2804#if !NO_MALLINFO
2805static struct mallinfo internal_mallinfo(mstate m) {
2806 struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
2807 if (!PREACTION(m)) {
2808 check_malloc_state(m);
2809 if (is_initialized(m)) {
2810 size_t nfree = SIZE_T_ONE; /* top always free */
2811 size_t mfree = m->topsize + TOP_FOOT_SIZE;
2812 size_t sum = mfree;
2813 msegmentptr s = &m->seg;
2814 while (s != 0) {
2815 mchunkptr q = align_as_chunk(s->base);
2816 while (segment_holds(s, q) &&
2817 q != m->top && q->head != FENCEPOST_HEAD) {
2818 size_t sz = chunksize(q);
2819 sum += sz;
2820 if (!cinuse(q)) {
2821 mfree += sz;
2822 ++nfree;
2823 }
2824 q = next_chunk(q);
2825 }
2826 s = s->next;
2827 }
2828
2829 nm.arena = sum;
2830 nm.ordblks = nfree;
2831 nm.hblkhd = m->footprint - sum;
2832 nm.usmblks = m->max_footprint;
2833 nm.uordblks = m->footprint - mfree;
2834 nm.fordblks = mfree;
2835 nm.keepcost = m->topsize;
2836 }
2837
2838 POSTACTION(m);
2839 }
2840 return nm;
2841}
2842#endif /* !NO_MALLINFO */
2843
2844static void internal_malloc_stats(mstate m) {
2845 if (!PREACTION(m)) {
2846 size_t maxfp = 0;
2847 size_t fp = 0;
2848 size_t used = 0;
2849 check_malloc_state(m);
2850 if (is_initialized(m)) {
2851 msegmentptr s = &m->seg;
2852 maxfp = m->max_footprint;
2853 fp = m->footprint;
2854 used = fp - (m->topsize + TOP_FOOT_SIZE);
2855
2856 while (s != 0) {
2857 mchunkptr q = align_as_chunk(s->base);
2858 while (segment_holds(s, q) &&
2859 q != m->top && q->head != FENCEPOST_HEAD) {
2860 if (!cinuse(q))
2861 used -= chunksize(q);
2862 q = next_chunk(q);
2863 }
2864 s = s->next;
2865 }
2866 }
2867
2868#ifndef LACKS_STDIO_H
2869 fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));
2870 fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp));
2871 fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used));
2872#endif
2873
2874 POSTACTION(m);
2875 }
2876}
2877
2878/* ----------------------- Operations on smallbins ----------------------- */
2879
2880/*
2881 Various forms of linking and unlinking are defined as macros. Even
2882 the ones for trees, which are very long but have very short typical
2883 paths. This is ugly but reduces reliance on inlining support of
2884 compilers.
2885*/
2886
2887/* Link a free chunk into a smallbin */
2888#define insert_small_chunk(M, P, S) {\
2889 bindex_t I = small_index(S);\
2890 mchunkptr B = smallbin_at(M, I);\
2891 mchunkptr F = B;\
2892 assert(S >= MIN_CHUNK_SIZE);\
2893 if (!smallmap_is_marked(M, I))\
2894 mark_smallmap(M, I);\
2895 else if (RTCHECK(ok_address(M, B->fd)))\
2896 F = B->fd;\
2897 else {\
2898 CORRUPTION_ERROR_ACTION(M);\
2899 }\
2900 B->fd = P;\
2901 F->bk = P;\
2902 P->fd = F;\
2903 P->bk = B;\
2904}
2905
2906/* Unlink a chunk from a smallbin */
2907#define unlink_small_chunk(M, P, S) {\
2908 mchunkptr F = P->fd;\
2909 mchunkptr B = P->bk;\
2910 bindex_t I = small_index(S);\
2911 assert(P != B);\
2912 assert(P != F);\
2913 assert(chunksize(P) == small_index2size(I));\
2914 if (F == B)\
2915 clear_smallmap(M, I);\
2916 else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
2917 (B == smallbin_at(M,I) || ok_address(M, B)))) {\
2918 F->bk = B;\
2919 B->fd = F;\
2920 }\
2921 else {\
2922 CORRUPTION_ERROR_ACTION(M);\
2923 }\
2924}
2925
2926/* Unlink the first chunk from a smallbin */
2927#define unlink_first_small_chunk(M, B, P, I) {\
2928 mchunkptr F = P->fd;\
2929 assert(P != B);\
2930 assert(P != F);\
2931 assert(chunksize(P) == small_index2size(I));\
2932 if (B == F)\
2933 clear_smallmap(M, I);\
2934 else if (RTCHECK(ok_address(M, F))) {\
2935 B->fd = F;\
2936 F->bk = B;\
2937 }\
2938 else {\
2939 CORRUPTION_ERROR_ACTION(M);\
2940 }\
2941}
2942
2943/* Replace dv node, binning the old one */
2944/* Used only when dvsize known to be small */
2945#define replace_dv(M, P, S) {\
2946 size_t DVS = M->dvsize;\
2947 if (DVS != 0) {\
2948 mchunkptr DV = M->dv;\
2949 assert(is_small(DVS));\
2950 insert_small_chunk(M, DV, DVS);\
2951 }\
2952 M->dvsize = S;\
2953 M->dv = P;\
2954}
2955
2956/* ------------------------- Operations on trees ------------------------- */
2957
2958/* Insert chunk into tree */
2959#define insert_large_chunk(M, X, S) {\
2960 tbinptr* H;\
2961 bindex_t I;\
2962 compute_tree_index(S, I);\
2963 H = treebin_at(M, I);\
2964 X->index = I;\
2965 X->child[0] = X->child[1] = 0;\
2966 if (!treemap_is_marked(M, I)) {\
2967 mark_treemap(M, I);\
2968 *H = X;\
2969 X->parent = (tchunkptr)H;\
2970 X->fd = X->bk = X;\
2971 }\
2972 else {\
2973 tchunkptr T = *H;\
2974 size_t K = S << leftshift_for_tree_index(I);\
2975 for (;;) {\
2976 if (chunksize(T) != S) {\
2977 tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
2978 K <<= 1;\
2979 if (*C != 0)\
2980 T = *C;\
2981 else if (RTCHECK(ok_address(M, C))) {\
2982 *C = X;\
2983 X->parent = T;\
2984 X->fd = X->bk = X;\
2985 break;\
2986 }\
2987 else {\
2988 CORRUPTION_ERROR_ACTION(M);\
2989 break;\
2990 }\
2991 }\
2992 else {\
2993 tchunkptr F = T->fd;\
2994 if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
2995 T->fd = F->bk = X;\
2996 X->fd = F;\
2997 X->bk = T;\
2998 X->parent = 0;\
2999 break;\
3000 }\
3001 else {\
3002 CORRUPTION_ERROR_ACTION(M);\
3003 break;\
3004 }\
3005 }\
3006 }\
3007 }\
3008}
3009
3010/*
3011 Unlink steps:
3012
3013 1. If x is a chained node, unlink it from its same-sized fd/bk links
3014 and choose its bk node as its replacement.
3015 2. If x was the last node of its size, but not a leaf node, it must
3016 be replaced with a leaf node (not merely one with an open left or
3017 right), to make sure that lefts and rights of descendents
3018 correspond properly to bit masks. We use the rightmost descendent
3019 of x. We could use any other leaf, but this is easy to locate and
3020 tends to counteract removal of leftmosts elsewhere, and so keeps
3021 paths shorter than minimally guaranteed. This doesn't loop much
3022 because on average a node in a tree is near the bottom.
3023 3. If x is the base of a chain (i.e., has parent links) relink
3024 x's parent and children to x's replacement (or null if none).
3025*/
3026
3027#define unlink_large_chunk(M, X) {\
3028 tchunkptr XP = X->parent;\
3029 tchunkptr R;\
3030 if (X->bk != X) {\
3031 tchunkptr F = X->fd;\
3032 R = X->bk;\
3033 if (RTCHECK(ok_address(M, F))) {\
3034 F->bk = R;\
3035 R->fd = F;\
3036 }\
3037 else {\
3038 CORRUPTION_ERROR_ACTION(M);\
3039 }\
3040 }\
3041 else {\
3042 tchunkptr* RP;\
3043 if (((R = *(RP = &(X->child[1]))) != 0) ||\