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