]> git.ipfire.org Git - thirdparty/glibc.git/blame - malloc/malloc.c
* sysdeps/i386/dl-machine.h (elf_machine_load_address): Add a dummy
[thirdparty/glibc.git] / malloc / malloc.c
CommitLineData
f65fd747 1/* Malloc implementation for multiple threads without lock contention.
a9177ff5 2 Copyright (C) 1996,1997,1998,1999,2000,01,02 Free Software Foundation, Inc.
f65fd747 3 This file is part of the GNU C Library.
fa8d436c
UD
4 Contributed by Wolfram Gloger <wg@malloc.de>
5 and Doug Lea <dl@cs.oswego.edu>, 2001.
f65fd747
UD
6
7 The GNU C Library is free software; you can redistribute it and/or
fa8d436c
UD
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
f65fd747
UD
11
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
fa8d436c 15 Library General Public License for more details.
f65fd747 16
fa8d436c
UD
17 You should have received a copy of the GNU Library General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
f65fd747 21
fa8d436c
UD
22/*
23 This is a version (aka ptmalloc2) of malloc/free/realloc written by
24 Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
25
26* Version ptmalloc2-20011215
27 $Id$
28 based on:
29 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
f65fd747 30
fa8d436c
UD
31 Note: There may be an updated version of this malloc obtainable at
32 http://www.malloc.de/malloc/ptmalloc2.tar.gz
33 Check before installing!
f65fd747 34
fa8d436c 35* Quickstart
f65fd747 36
fa8d436c
UD
37 In order to compile this implementation, a Makefile is provided with
38 the ptmalloc2 distribution, which has pre-defined targets for some
39 popular systems (e.g. "make posix" for Posix threads). All that is
40 typically required with regard to compiler flags is the selection of
41 the thread package via defining one out of USE_PTHREADS, USE_THR or
42 USE_SPROC. Check the thread-m.h file for what effects this has.
43 Many/most systems will additionally require USE_TSD_DATA_HACK to be
44 defined, so this is the default for "make posix".
f65fd747
UD
45
46* Why use this malloc?
47
48 This is not the fastest, most space-conserving, most portable, or
49 most tunable malloc ever written. However it is among the fastest
50 while also being among the most space-conserving, portable and tunable.
51 Consistent balance across these factors results in a good general-purpose
fa8d436c
UD
52 allocator for malloc-intensive programs.
53
54 The main properties of the algorithms are:
55 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
56 with ties normally decided via FIFO (i.e. least recently used).
57 * For small (<= 64 bytes by default) requests, it is a caching
58 allocator, that maintains pools of quickly recycled chunks.
59 * In between, and for combinations of large and small requests, it does
60 the best it can trying to meet both goals at once.
61 * For very large requests (>= 128KB by default), it relies on system
62 memory mapping facilities, if supported.
63
64 For a longer but slightly out of date high-level description, see
65 http://gee.cs.oswego.edu/dl/html/malloc.html
66
67 You may already by default be using a C library containing a malloc
68 that is based on some version of this malloc (for example in
69 linux). You might still want to use the one in this file in order to
70 customize settings or to avoid overheads associated with library
71 versions.
72
73* Contents, described in more detail in "description of public routines" below.
74
75 Standard (ANSI/SVID/...) functions:
76 malloc(size_t n);
77 calloc(size_t n_elements, size_t element_size);
78 free(Void_t* p);
79 realloc(Void_t* p, size_t n);
80 memalign(size_t alignment, size_t n);
81 valloc(size_t n);
82 mallinfo()
83 mallopt(int parameter_number, int parameter_value)
84
85 Additional functions:
86 independent_calloc(size_t n_elements, size_t size, Void_t* chunks[]);
87 independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]);
88 pvalloc(size_t n);
89 cfree(Void_t* p);
90 malloc_trim(size_t pad);
91 malloc_usable_size(Void_t* p);
92 malloc_stats();
f65fd747
UD
93
94* Vital statistics:
95
fa8d436c 96 Supported pointer representation: 4 or 8 bytes
a9177ff5 97 Supported size_t representation: 4 or 8 bytes
f65fd747 98 Note that size_t is allowed to be 4 bytes even if pointers are 8.
fa8d436c
UD
99 You can adjust this by defining INTERNAL_SIZE_T
100
101 Alignment: 2 * sizeof(size_t) (default)
102 (i.e., 8 byte alignment with 4byte size_t). This suffices for
103 nearly all current machines and C compilers. However, you can
104 define MALLOC_ALIGNMENT to be wider than this if necessary.
f65fd747 105
fa8d436c
UD
106 Minimum overhead per allocated chunk: 4 or 8 bytes
107 Each malloced chunk has a hidden word of overhead holding size
f65fd747
UD
108 and status information.
109
110 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
111 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
112
113 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
114 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
fa8d436c
UD
115 needed; 4 (8) for a trailing size field and 8 (16) bytes for
116 free list pointers. Thus, the minimum allocatable size is
117 16/24/32 bytes.
f65fd747
UD
118
119 Even a request for zero bytes (i.e., malloc(0)) returns a
120 pointer to something of the minimum allocatable size.
121
fa8d436c
UD
122 The maximum overhead wastage (i.e., number of extra bytes
123 allocated than were requested in malloc) is less than or equal
124 to the minimum size, except for requests >= mmap_threshold that
125 are serviced via mmap(), where the worst case wastage is 2 *
126 sizeof(size_t) bytes plus the remainder from a system page (the
127 minimal mmap unit); typically 4096 or 8192 bytes.
f65fd747 128
a9177ff5 129 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
fa8d436c
UD
130 8-byte size_t: 2^64 minus about two pages
131
132 It is assumed that (possibly signed) size_t values suffice to
f65fd747
UD
133 represent chunk sizes. `Possibly signed' is due to the fact
134 that `size_t' may be defined on a system as either a signed or
fa8d436c
UD
135 an unsigned type. The ISO C standard says that it must be
136 unsigned, but a few systems are known not to adhere to this.
137 Additionally, even when size_t is unsigned, sbrk (which is by
138 default used to obtain memory from system) accepts signed
139 arguments, and may not be able to handle size_t-wide arguments
140 with negative sign bit. Generally, values that would
141 appear as negative after accounting for overhead and alignment
142 are supported only via mmap(), which does not have this
143 limitation.
144
145 Requests for sizes outside the allowed range will perform an optional
146 failure action and then return null. (Requests may also
147 also fail because a system is out of memory.)
148
149 Thread-safety: thread-safe unless NO_THREADS is defined
150
151 Compliance: I believe it is compliant with the 1997 Single Unix Specification
a9177ff5 152 (See http://www.opennc.org). Also SVID/XPG, ANSI C, and probably
fa8d436c 153 others as well.
f65fd747
UD
154
155* Synopsis of compile-time options:
156
157 People have reported using previous versions of this malloc on all
158 versions of Unix, sometimes by tweaking some of the defines
159 below. It has been tested most extensively on Solaris and
fa8d436c
UD
160 Linux. It is also reported to work on WIN32 platforms.
161 People also report using it in stand-alone embedded systems.
162
163 The implementation is in straight, hand-tuned ANSI C. It is not
164 at all modular. (Sorry!) It uses a lot of macros. To be at all
165 usable, this code should be compiled using an optimizing compiler
166 (for example gcc -O3) that can simplify expressions and control
167 paths. (FAQ: some macros import variables as arguments rather than
168 declare locals because people reported that some debuggers
169 otherwise get confused.)
170
171 OPTION DEFAULT VALUE
172
173 Compilation Environment options:
174
175 __STD_C derived from C compiler defines
176 WIN32 NOT defined
177 HAVE_MEMCPY defined
178 USE_MEMCPY 1 if HAVE_MEMCPY is defined
a9177ff5 179 HAVE_MMAP defined as 1
fa8d436c
UD
180 MMAP_CLEARS 1
181 HAVE_MREMAP 0 unless linux defined
182 USE_ARENAS the same as HAVE_MMAP
183 malloc_getpagesize derived from system #includes, or 4096 if not
184 HAVE_USR_INCLUDE_MALLOC_H NOT defined
185 LACKS_UNISTD_H NOT defined unless WIN32
186 LACKS_SYS_PARAM_H NOT defined unless WIN32
187 LACKS_SYS_MMAN_H NOT defined unless WIN32
188
189 Changing default word sizes:
190
191 INTERNAL_SIZE_T size_t
192 MALLOC_ALIGNMENT 2 * sizeof(INTERNAL_SIZE_T)
193
194 Configuration and functionality options:
195
196 USE_DL_PREFIX NOT defined
197 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
198 USE_MALLOC_LOCK NOT defined
199 MALLOC_DEBUG NOT defined
200 REALLOC_ZERO_BYTES_FREES 1
201 MALLOC_FAILURE_ACTION errno = ENOMEM, if __STD_C defined, else no-op
202 TRIM_FASTBINS 0
203
204 Options for customizing MORECORE:
205
206 MORECORE sbrk
207 MORECORE_FAILURE -1
a9177ff5 208 MORECORE_CONTIGUOUS 1
fa8d436c
UD
209 MORECORE_CANNOT_TRIM NOT defined
210 MORECORE_CLEARS 1
a9177ff5 211 MMAP_AS_MORECORE_SIZE (1024 * 1024)
fa8d436c
UD
212
213 Tuning options that are also dynamically changeable via mallopt:
214
215 DEFAULT_MXFAST 64
216 DEFAULT_TRIM_THRESHOLD 128 * 1024
217 DEFAULT_TOP_PAD 0
218 DEFAULT_MMAP_THRESHOLD 128 * 1024
219 DEFAULT_MMAP_MAX 65536
220
221 There are several other #defined constants and macros that you
222 probably don't want to touch unless you are extending or adapting malloc. */
f65fd747
UD
223
224/*
fa8d436c
UD
225 __STD_C should be nonzero if using ANSI-standard C compiler, a C++
226 compiler, or a C compiler sufficiently close to ANSI to get away
227 with it.
f65fd747
UD
228*/
229
f65fd747 230#ifndef __STD_C
fa8d436c 231#if defined(__STDC__) || defined(__cplusplus)
f65fd747
UD
232#define __STD_C 1
233#else
234#define __STD_C 0
a9177ff5 235#endif
f65fd747
UD
236#endif /*__STD_C*/
237
fa8d436c
UD
238
239/*
240 Void_t* is the pointer type that malloc should say it returns
241*/
242
f65fd747 243#ifndef Void_t
fa8d436c 244#if (__STD_C || defined(WIN32))
f65fd747
UD
245#define Void_t void
246#else
247#define Void_t char
248#endif
249#endif /*Void_t*/
250
251#if __STD_C
fa8d436c
UD
252#include <stddef.h> /* for size_t */
253#include <stdlib.h> /* for getenv(), abort() */
f65fd747 254#else
fa8d436c 255#include <sys/types.h>
f65fd747
UD
256#endif
257
258#ifdef __cplusplus
259extern "C" {
260#endif
261
fa8d436c 262/* define LACKS_UNISTD_H if your system does not have a <unistd.h>. */
f65fd747 263
fa8d436c 264/* #define LACKS_UNISTD_H */
f65fd747 265
fa8d436c
UD
266#ifndef LACKS_UNISTD_H
267#include <unistd.h>
268#endif
f65fd747 269
fa8d436c
UD
270/* define LACKS_SYS_PARAM_H if your system does not have a <sys/param.h>. */
271
272/* #define LACKS_SYS_PARAM_H */
273
274
275#include <stdio.h> /* needed for malloc_stats */
276#include <errno.h> /* needed for optional MALLOC_FAILURE_ACTION */
f65fd747 277
f65fd747 278
fa8d436c
UD
279/*
280 Debugging:
281
282 Because freed chunks may be overwritten with bookkeeping fields, this
283 malloc will often die when freed memory is overwritten by user
284 programs. This can be very effective (albeit in an annoying way)
285 in helping track down dangling pointers.
286
287 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
288 enabled that will catch more memory errors. You probably won't be
289 able to make much sense of the actual assertion errors, but they
290 should help you locate incorrectly overwritten memory. The checking
291 is fairly extensive, and will slow down execution
292 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
293 will attempt to check every non-mmapped allocated and free chunk in
294 the course of computing the summmaries. (By nature, mmapped regions
295 cannot be checked very much automatically.)
296
297 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
298 this code. The assertions in the check routines spell out in more
299 detail the assumptions and invariants underlying the algorithms.
300
301 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
302 checking that all accesses to malloced memory stay within their
303 bounds. However, there are several add-ons and adaptations of this
304 or other mallocs available that do this.
f65fd747
UD
305*/
306
307#if MALLOC_DEBUG
308#include <assert.h>
309#else
310#define assert(x) ((void)0)
311#endif
312
313
314/*
315 INTERNAL_SIZE_T is the word-size used for internal bookkeeping
fa8d436c
UD
316 of chunk sizes.
317
318 The default version is the same as size_t.
319
320 While not strictly necessary, it is best to define this as an
321 unsigned type, even if size_t is a signed type. This may avoid some
322 artificial size limitations on some systems.
323
324 On a 64-bit machine, you may be able to reduce malloc overhead by
325 defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
326 expense of not being able to handle more than 2^32 of malloced
327 space. If this limitation is acceptable, you are encouraged to set
328 this unless you are on a platform requiring 16byte alignments. In
329 this case the alignment requirements turn out to negate any
330 potential advantages of decreasing size_t word size.
331
332 Implementors: Beware of the possible combinations of:
333 - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
334 and might be the same width as int or as long
335 - size_t might have different width and signedness as INTERNAL_SIZE_T
336 - int and long might be 32 or 64 bits, and might be the same width
337 To deal with this, most comparisons and difference computations
338 among INTERNAL_SIZE_Ts should cast them to unsigned long, being
339 aware of the fact that casting an unsigned int to a wider long does
340 not sign-extend. (This also makes checking for negative numbers
341 awkward.) Some of these casts result in harmless compiler warnings
342 on some systems.
f65fd747
UD
343*/
344
345#ifndef INTERNAL_SIZE_T
346#define INTERNAL_SIZE_T size_t
347#endif
348
fa8d436c
UD
349/* The corresponding word size */
350#define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
351
352
353/*
354 MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
355 It must be a power of two at least 2 * SIZE_SZ, even on machines
356 for which smaller alignments would suffice. It may be defined as
357 larger than this though. Note however that code and data structures
358 are optimized for the case of 8-byte alignment.
359*/
360
361
362#ifndef MALLOC_ALIGNMENT
363#define MALLOC_ALIGNMENT (2 * SIZE_SZ)
364#endif
365
366/* The corresponding bit mask value */
367#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
368
369
370
371/*
372 REALLOC_ZERO_BYTES_FREES should be set if a call to
373 realloc with zero bytes should be the same as a call to free.
374 This is required by the C standard. Otherwise, since this malloc
375 returns a unique pointer for malloc(0), so does realloc(p, 0).
376*/
377
378#ifndef REALLOC_ZERO_BYTES_FREES
379#define REALLOC_ZERO_BYTES_FREES 1
380#endif
381
382/*
383 TRIM_FASTBINS controls whether free() of a very small chunk can
384 immediately lead to trimming. Setting to true (1) can reduce memory
385 footprint, but will almost always slow down programs that use a lot
386 of small chunks.
387
388 Define this only if you are willing to give up some speed to more
389 aggressively reduce system-level memory footprint when releasing
390 memory in programs that use many small chunks. You can get
391 essentially the same effect by setting MXFAST to 0, but this can
392 lead to even greater slowdowns in programs using many small chunks.
393 TRIM_FASTBINS is an in-between compile-time option, that disables
394 only those chunks bordering topmost memory from being placed in
395 fastbins.
396*/
397
398#ifndef TRIM_FASTBINS
399#define TRIM_FASTBINS 0
400#endif
401
402
f65fd747 403/*
fa8d436c 404 USE_DL_PREFIX will prefix all public routines with the string 'dl'.
a9177ff5 405 This is necessary when you only want to use this malloc in one part
fa8d436c
UD
406 of a program, using your regular system malloc elsewhere.
407*/
408
409/* #define USE_DL_PREFIX */
410
411
a9177ff5 412/*
fa8d436c
UD
413 Two-phase name translation.
414 All of the actual routines are given mangled names.
415 When wrappers are used, they become the public callable versions.
416 When DL_PREFIX is used, the callable names are prefixed.
f65fd747
UD
417*/
418
fa8d436c
UD
419#ifdef USE_DL_PREFIX
420#define public_cALLOc dlcalloc
421#define public_fREe dlfree
422#define public_cFREe dlcfree
423#define public_mALLOc dlmalloc
424#define public_mEMALIGn dlmemalign
425#define public_rEALLOc dlrealloc
426#define public_vALLOc dlvalloc
427#define public_pVALLOc dlpvalloc
428#define public_mALLINFo dlmallinfo
429#define public_mALLOPt dlmallopt
430#define public_mTRIm dlmalloc_trim
431#define public_mSTATs dlmalloc_stats
432#define public_mUSABLe dlmalloc_usable_size
433#define public_iCALLOc dlindependent_calloc
434#define public_iCOMALLOc dlindependent_comalloc
435#define public_gET_STATe dlget_state
436#define public_sET_STATe dlset_state
437#else /* USE_DL_PREFIX */
438#ifdef _LIBC
439
440/* Special defines for the GNU C library. */
441#define public_cALLOc __libc_calloc
442#define public_fREe __libc_free
443#define public_cFREe __libc_cfree
444#define public_mALLOc __libc_malloc
445#define public_mEMALIGn __libc_memalign
446#define public_rEALLOc __libc_realloc
447#define public_vALLOc __libc_valloc
448#define public_pVALLOc __libc_pvalloc
449#define public_mALLINFo __libc_mallinfo
450#define public_mALLOPt __libc_mallopt
451#define public_mTRIm __malloc_trim
452#define public_mSTATs __malloc_stats
453#define public_mUSABLe __malloc_usable_size
454#define public_iCALLOc __libc_independent_calloc
455#define public_iCOMALLOc __libc_independent_comalloc
456#define public_gET_STATe __malloc_get_state
457#define public_sET_STATe __malloc_set_state
458#define malloc_getpagesize __getpagesize()
459#define open __open
460#define mmap __mmap
461#define munmap __munmap
462#define mremap __mremap
463#define mprotect __mprotect
464#define MORECORE (*__morecore)
465#define MORECORE_FAILURE 0
466
467Void_t * __default_morecore (ptrdiff_t);
468Void_t *(*__morecore)(ptrdiff_t) = __default_morecore;
f65fd747 469
fa8d436c
UD
470#else /* !_LIBC */
471#define public_cALLOc calloc
472#define public_fREe free
473#define public_cFREe cfree
474#define public_mALLOc malloc
475#define public_mEMALIGn memalign
476#define public_rEALLOc realloc
477#define public_vALLOc valloc
478#define public_pVALLOc pvalloc
479#define public_mALLINFo mallinfo
480#define public_mALLOPt mallopt
481#define public_mTRIm malloc_trim
482#define public_mSTATs malloc_stats
483#define public_mUSABLe malloc_usable_size
484#define public_iCALLOc independent_calloc
485#define public_iCOMALLOc independent_comalloc
486#define public_gET_STATe malloc_get_state
487#define public_sET_STATe malloc_set_state
488#endif /* _LIBC */
489#endif /* USE_DL_PREFIX */
f65fd747 490
d9af917d
UD
491#ifndef _LIBC
492#define __builtin_expect(expr, val) (expr)
3ba06713
UD
493
494#define fwrite(buf, size, count, fp) _IO_fwrite (buf, size, count, fp)
d9af917d 495#endif
f65fd747
UD
496
497/*
498 HAVE_MEMCPY should be defined if you are not otherwise using
499 ANSI STD C, but still have memcpy and memset in your C library
500 and want to use them in calloc and realloc. Otherwise simple
fa8d436c 501 macro versions are defined below.
f65fd747
UD
502
503 USE_MEMCPY should be defined as 1 if you actually want to
504 have memset and memcpy called. People report that the macro
fa8d436c 505 versions are faster than libc versions on some systems.
a9177ff5 506
fa8d436c
UD
507 Even if USE_MEMCPY is set to 1, loops to copy/clear small chunks
508 (of <= 36 bytes) are manually unrolled in realloc and calloc.
f65fd747
UD
509*/
510
fa8d436c 511#define HAVE_MEMCPY
f65fd747
UD
512
513#ifndef USE_MEMCPY
514#ifdef HAVE_MEMCPY
515#define USE_MEMCPY 1
516#else
517#define USE_MEMCPY 0
518#endif
519#endif
520
fa8d436c 521
f65fd747
UD
522#if (__STD_C || defined(HAVE_MEMCPY))
523
c2afe833
RM
524#ifdef _LIBC
525# include <string.h>
526#else
fa8d436c
UD
527#ifdef WIN32
528/* On Win32 memset and memcpy are already declared in windows.h */
529#else
f65fd747
UD
530#if __STD_C
531void* memset(void*, int, size_t);
532void* memcpy(void*, const void*, size_t);
533#else
534Void_t* memset();
535Void_t* memcpy();
fa8d436c 536#endif
f65fd747
UD
537#endif
538#endif
c2afe833 539#endif
f65fd747 540
fa8d436c
UD
541/*
542 MALLOC_FAILURE_ACTION is the action to take before "return 0" when
543 malloc fails to be able to return memory, either because memory is
544 exhausted or because of illegal arguments.
a9177ff5
RM
545
546 By default, sets errno if running on STD_C platform, else does nothing.
fa8d436c 547*/
09f5e163 548
fa8d436c
UD
549#ifndef MALLOC_FAILURE_ACTION
550#if __STD_C
551#define MALLOC_FAILURE_ACTION \
552 errno = ENOMEM;
f65fd747 553
fa8d436c
UD
554#else
555#define MALLOC_FAILURE_ACTION
556#endif
557#endif
f65fd747 558
fa8d436c
UD
559/*
560 MORECORE-related declarations. By default, rely on sbrk
561*/
09f5e163 562
f65fd747 563
fa8d436c
UD
564#ifdef LACKS_UNISTD_H
565#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
566#if __STD_C
567extern Void_t* sbrk(ptrdiff_t);
568#else
569extern Void_t* sbrk();
570#endif
571#endif
572#endif
f65fd747 573
fa8d436c
UD
574/*
575 MORECORE is the name of the routine to call to obtain more memory
576 from the system. See below for general guidance on writing
577 alternative MORECORE functions, as well as a version for WIN32 and a
578 sample version for pre-OSX macos.
579*/
f65fd747 580
fa8d436c
UD
581#ifndef MORECORE
582#define MORECORE sbrk
583#endif
f65fd747 584
fa8d436c
UD
585/*
586 MORECORE_FAILURE is the value returned upon failure of MORECORE
587 as well as mmap. Since it cannot be an otherwise valid memory address,
588 and must reflect values of standard sys calls, you probably ought not
589 try to redefine it.
590*/
09f5e163 591
fa8d436c
UD
592#ifndef MORECORE_FAILURE
593#define MORECORE_FAILURE (-1)
594#endif
595
596/*
597 If MORECORE_CONTIGUOUS is true, take advantage of fact that
598 consecutive calls to MORECORE with positive arguments always return
599 contiguous increasing addresses. This is true of unix sbrk. Even
600 if not defined, when regions happen to be contiguous, malloc will
601 permit allocations spanning regions obtained from different
602 calls. But defining this when applicable enables some stronger
603 consistency checks and space efficiencies.
604*/
f65fd747 605
fa8d436c
UD
606#ifndef MORECORE_CONTIGUOUS
607#define MORECORE_CONTIGUOUS 1
f65fd747
UD
608#endif
609
fa8d436c
UD
610/*
611 Define MORECORE_CANNOT_TRIM if your version of MORECORE
612 cannot release space back to the system when given negative
613 arguments. This is generally necessary only if you are using
614 a hand-crafted MORECORE function that cannot handle negative arguments.
615*/
616
617/* #define MORECORE_CANNOT_TRIM */
f65fd747 618
fa8d436c
UD
619/* MORECORE_CLEARS (default 1)
620 The degree to which the routine mapped to MORECORE zeroes out
621 memory: never (0), only for newly allocated space (1) or always
622 (2). The distinction between (1) and (2) is necessary because on
623 some systems, if the application first decrements and then
624 increments the break value, the contents of the reallocated space
625 are unspecified.
626*/
627
628#ifndef MORECORE_CLEARS
629#define MORECORE_CLEARS 1
7cabd57c
UD
630#endif
631
fa8d436c 632
f65fd747 633/*
fa8d436c
UD
634 Define HAVE_MMAP as true to optionally make malloc() use mmap() to
635 allocate very large blocks. These will be returned to the
636 operating system immediately after a free(). Also, if mmap
637 is available, it is used as a backup strategy in cases where
638 MORECORE fails to provide space from system.
639
640 This malloc is best tuned to work with mmap for large requests.
641 If you do not have mmap, operations involving very large chunks (1MB
642 or so) may be slower than you'd like.
f65fd747
UD
643*/
644
645#ifndef HAVE_MMAP
fa8d436c
UD
646#define HAVE_MMAP 1
647
a9177ff5 648/*
fa8d436c
UD
649 Standard unix mmap using /dev/zero clears memory so calloc doesn't
650 need to.
651*/
652
653#ifndef MMAP_CLEARS
654#define MMAP_CLEARS 1
655#endif
656
657#else /* no mmap */
658#ifndef MMAP_CLEARS
659#define MMAP_CLEARS 0
660#endif
661#endif
662
663
a9177ff5 664/*
fa8d436c
UD
665 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
666 sbrk fails, and mmap is used as a backup (which is done only if
667 HAVE_MMAP). The value must be a multiple of page size. This
668 backup strategy generally applies only when systems have "holes" in
669 address space, so sbrk cannot perform contiguous expansion, but
670 there is still space available on system. On systems for which
671 this is known to be useful (i.e. most linux kernels), this occurs
672 only when programs allocate huge amounts of memory. Between this,
673 and the fact that mmap regions tend to be limited, the size should
674 be large, to avoid too many mmap calls and thus avoid running out
675 of kernel resources.
676*/
677
678#ifndef MMAP_AS_MORECORE_SIZE
679#define MMAP_AS_MORECORE_SIZE (1024 * 1024)
f65fd747
UD
680#endif
681
682/*
683 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
684 large blocks. This is currently only possible on Linux with
685 kernel versions newer than 1.3.77.
686*/
687
688#ifndef HAVE_MREMAP
fa8d436c
UD
689#ifdef linux
690#define HAVE_MREMAP 1
691#else
692#define HAVE_MREMAP 0
f65fd747
UD
693#endif
694
fa8d436c
UD
695#endif /* HAVE_MMAP */
696
e9b3e3c5
UD
697/* Define USE_ARENAS to enable support for multiple `arenas'. These
698 are allocated using mmap(), are necessary for threads and
699 occasionally useful to overcome address space limitations affecting
700 sbrk(). */
701
702#ifndef USE_ARENAS
703#define USE_ARENAS HAVE_MMAP
704#endif
705
f65fd747
UD
706
707/*
fa8d436c
UD
708 The system page size. To the extent possible, this malloc manages
709 memory from the system in page-size units. Note that this value is
710 cached during initialization into a field of malloc_state. So even
711 if malloc_getpagesize is a function, it is only called once.
712
713 The following mechanics for getpagesize were adapted from bsd/gnu
714 getpagesize.h. If none of the system-probes here apply, a value of
715 4096 is used, which should be OK: If they don't apply, then using
716 the actual value probably doesn't impact performance.
f65fd747
UD
717*/
718
fa8d436c 719
f65fd747 720#ifndef malloc_getpagesize
fa8d436c
UD
721
722#ifndef LACKS_UNISTD_H
723# include <unistd.h>
724#endif
725
f65fd747
UD
726# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
727# ifndef _SC_PAGE_SIZE
728# define _SC_PAGE_SIZE _SC_PAGESIZE
729# endif
730# endif
fa8d436c 731
f65fd747
UD
732# ifdef _SC_PAGE_SIZE
733# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
734# else
735# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
736 extern size_t getpagesize();
737# define malloc_getpagesize getpagesize()
738# else
fa8d436c 739# ifdef WIN32 /* use supplied emulation of getpagesize */
a9177ff5 740# define malloc_getpagesize getpagesize()
f65fd747 741# else
fa8d436c
UD
742# ifndef LACKS_SYS_PARAM_H
743# include <sys/param.h>
744# endif
745# ifdef EXEC_PAGESIZE
746# define malloc_getpagesize EXEC_PAGESIZE
f65fd747 747# else
fa8d436c
UD
748# ifdef NBPG
749# ifndef CLSIZE
750# define malloc_getpagesize NBPG
751# else
752# define malloc_getpagesize (NBPG * CLSIZE)
753# endif
f65fd747 754# else
fa8d436c
UD
755# ifdef NBPC
756# define malloc_getpagesize NBPC
f65fd747 757# else
fa8d436c
UD
758# ifdef PAGESIZE
759# define malloc_getpagesize PAGESIZE
760# else /* just guess */
a9177ff5 761# define malloc_getpagesize (4096)
fa8d436c 762# endif
f65fd747
UD
763# endif
764# endif
765# endif
766# endif
767# endif
768# endif
769#endif
770
f65fd747 771/*
f65fd747 772 This version of malloc supports the standard SVID/XPG mallinfo
fa8d436c
UD
773 routine that returns a struct containing usage properties and
774 statistics. It should work on any SVID/XPG compliant system that has
775 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
776 install such a thing yourself, cut out the preliminary declarations
777 as described above and below and save them in a malloc.h file. But
778 there's no compelling reason to bother to do this.)
f65fd747
UD
779
780 The main declaration needed is the mallinfo struct that is returned
781 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
fa8d436c
UD
782 bunch of fields that are not even meaningful in this version of
783 malloc. These fields are are instead filled by mallinfo() with
784 other numbers that might be of interest.
f65fd747
UD
785
786 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
787 /usr/include/malloc.h file that includes a declaration of struct
788 mallinfo. If so, it is included; else an SVID2/XPG2 compliant
789 version is declared below. These must be precisely the same for
fa8d436c
UD
790 mallinfo() to work. The original SVID version of this struct,
791 defined on most systems with mallinfo, declares all fields as
792 ints. But some others define as unsigned long. If your system
793 defines the fields using a type of different width than listed here,
794 you must #include your system version and #define
795 HAVE_USR_INCLUDE_MALLOC_H.
f65fd747
UD
796*/
797
798/* #define HAVE_USR_INCLUDE_MALLOC_H */
799
fa8d436c
UD
800#ifdef HAVE_USR_INCLUDE_MALLOC_H
801#include "/usr/include/malloc.h"
f65fd747
UD
802#endif
803
f65fd747 804
fa8d436c 805/* ---------- description of public routines ------------ */
f65fd747
UD
806
807/*
fa8d436c
UD
808 malloc(size_t n)
809 Returns a pointer to a newly allocated chunk of at least n bytes, or null
810 if no space is available. Additionally, on failure, errno is
811 set to ENOMEM on ANSI C systems.
812
813 If n is zero, malloc returns a minumum-sized chunk. (The minimum
814 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
815 systems.) On most systems, size_t is an unsigned type, so calls
816 with negative arguments are interpreted as requests for huge amounts
817 of space, which will often fail. The maximum supported value of n
818 differs across systems, but is in all cases less than the maximum
819 representable value of a size_t.
f65fd747 820*/
fa8d436c
UD
821#if __STD_C
822Void_t* public_mALLOc(size_t);
823#else
824Void_t* public_mALLOc();
825#endif
f65fd747 826
fa8d436c
UD
827/*
828 free(Void_t* p)
829 Releases the chunk of memory pointed to by p, that had been previously
830 allocated using malloc or a related routine such as realloc.
831 It has no effect if p is null. It can have arbitrary (i.e., bad!)
832 effects if p has already been freed.
833
834 Unless disabled (using mallopt), freeing very large spaces will
835 when possible, automatically trigger operations that give
836 back unused memory to the system, thus reducing program footprint.
837*/
838#if __STD_C
839void public_fREe(Void_t*);
840#else
841void public_fREe();
842#endif
f65fd747 843
fa8d436c
UD
844/*
845 calloc(size_t n_elements, size_t element_size);
846 Returns a pointer to n_elements * element_size bytes, with all locations
847 set to zero.
848*/
849#if __STD_C
850Void_t* public_cALLOc(size_t, size_t);
851#else
852Void_t* public_cALLOc();
f65fd747
UD
853#endif
854
855/*
fa8d436c
UD
856 realloc(Void_t* p, size_t n)
857 Returns a pointer to a chunk of size n that contains the same data
858 as does chunk p up to the minimum of (n, p's size) bytes, or null
a9177ff5 859 if no space is available.
f65fd747 860
fa8d436c
UD
861 The returned pointer may or may not be the same as p. The algorithm
862 prefers extending p when possible, otherwise it employs the
863 equivalent of a malloc-copy-free sequence.
f65fd747 864
a9177ff5 865 If p is null, realloc is equivalent to malloc.
f65fd747 866
fa8d436c
UD
867 If space is not available, realloc returns null, errno is set (if on
868 ANSI) and p is NOT freed.
f65fd747 869
fa8d436c
UD
870 if n is for fewer bytes than already held by p, the newly unused
871 space is lopped off and freed if possible. Unless the #define
872 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
873 zero (re)allocates a minimum-sized chunk.
f65fd747 874
fa8d436c
UD
875 Large chunks that were internally obtained via mmap will always
876 be reallocated using malloc-copy-free sequences unless
877 the system supports MREMAP (currently only linux).
f65fd747 878
fa8d436c
UD
879 The old unix realloc convention of allowing the last-free'd chunk
880 to be used as an argument to realloc is not supported.
f65fd747 881*/
fa8d436c
UD
882#if __STD_C
883Void_t* public_rEALLOc(Void_t*, size_t);
884#else
885Void_t* public_rEALLOc();
886#endif
f65fd747 887
fa8d436c
UD
888/*
889 memalign(size_t alignment, size_t n);
890 Returns a pointer to a newly allocated chunk of n bytes, aligned
891 in accord with the alignment argument.
892
893 The alignment argument should be a power of two. If the argument is
894 not a power of two, the nearest greater power is used.
895 8-byte alignment is guaranteed by normal malloc calls, so don't
896 bother calling memalign with an argument of 8 or less.
897
898 Overreliance on memalign is a sure way to fragment space.
899*/
900#if __STD_C
901Void_t* public_mEMALIGn(size_t, size_t);
902#else
903Void_t* public_mEMALIGn();
f65fd747
UD
904#endif
905
906/*
fa8d436c
UD
907 valloc(size_t n);
908 Equivalent to memalign(pagesize, n), where pagesize is the page
909 size of the system. If the pagesize is unknown, 4096 is used.
910*/
911#if __STD_C
912Void_t* public_vALLOc(size_t);
913#else
914Void_t* public_vALLOc();
915#endif
916
f65fd747 917
f65fd747 918
fa8d436c
UD
919/*
920 mallopt(int parameter_number, int parameter_value)
921 Sets tunable parameters The format is to provide a
922 (parameter-number, parameter-value) pair. mallopt then sets the
923 corresponding parameter to the argument value if it can (i.e., so
924 long as the value is meaningful), and returns 1 if successful else
925 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
926 normally defined in malloc.h. Only one of these (M_MXFAST) is used
927 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
928 so setting them has no effect. But this malloc also supports four
929 other options in mallopt. See below for details. Briefly, supported
930 parameters are as follows (listed defaults are for "typical"
931 configurations).
932
933 Symbol param # default allowed param values
934 M_MXFAST 1 64 0-80 (0 disables fastbins)
935 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
a9177ff5 936 M_TOP_PAD -2 0 any
fa8d436c
UD
937 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
938 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
939*/
940#if __STD_C
941int public_mALLOPt(int, int);
942#else
943int public_mALLOPt();
944#endif
945
946
947/*
948 mallinfo()
949 Returns (by copy) a struct containing various summary statistics:
950
a9177ff5
RM
951 arena: current total non-mmapped bytes allocated from system
952 ordblks: the number of free chunks
fa8d436c
UD
953 smblks: the number of fastbin blocks (i.e., small chunks that
954 have been freed but not use resused or consolidated)
a9177ff5
RM
955 hblks: current number of mmapped regions
956 hblkhd: total bytes held in mmapped regions
fa8d436c
UD
957 usmblks: the maximum total allocated space. This will be greater
958 than current total if trimming has occurred.
a9177ff5 959 fsmblks: total bytes held in fastbin blocks
fa8d436c 960 uordblks: current total allocated space (normal or mmapped)
a9177ff5 961 fordblks: total free space
fa8d436c
UD
962 keepcost: the maximum number of bytes that could ideally be released
963 back to system via malloc_trim. ("ideally" means that
964 it ignores page restrictions etc.)
965
966 Because these fields are ints, but internal bookkeeping may
a9177ff5 967 be kept as longs, the reported values may wrap around zero and
fa8d436c
UD
968 thus be inaccurate.
969*/
970#if __STD_C
971struct mallinfo public_mALLINFo(void);
972#else
973struct mallinfo public_mALLINFo();
974#endif
f65fd747 975
fa8d436c
UD
976/*
977 independent_calloc(size_t n_elements, size_t element_size, Void_t* chunks[]);
978
979 independent_calloc is similar to calloc, but instead of returning a
980 single cleared space, it returns an array of pointers to n_elements
981 independent elements that can hold contents of size elem_size, each
982 of which starts out cleared, and can be independently freed,
983 realloc'ed etc. The elements are guaranteed to be adjacently
984 allocated (this is not guaranteed to occur with multiple callocs or
985 mallocs), which may also improve cache locality in some
986 applications.
987
988 The "chunks" argument is optional (i.e., may be null, which is
989 probably the most typical usage). If it is null, the returned array
990 is itself dynamically allocated and should also be freed when it is
991 no longer needed. Otherwise, the chunks array must be of at least
992 n_elements in length. It is filled in with the pointers to the
993 chunks.
994
995 In either case, independent_calloc returns this pointer array, or
996 null if the allocation failed. If n_elements is zero and "chunks"
997 is null, it returns a chunk representing an array with zero elements
998 (which should be freed if not wanted).
999
1000 Each element must be individually freed when it is no longer
1001 needed. If you'd like to instead be able to free all at once, you
1002 should instead use regular calloc and assign pointers into this
1003 space to represent elements. (In this case though, you cannot
1004 independently free elements.)
a9177ff5 1005
fa8d436c
UD
1006 independent_calloc simplifies and speeds up implementations of many
1007 kinds of pools. It may also be useful when constructing large data
1008 structures that initially have a fixed number of fixed-sized nodes,
1009 but the number is not known at compile time, and some of the nodes
1010 may later need to be freed. For example:
1011
1012 struct Node { int item; struct Node* next; };
a9177ff5 1013
fa8d436c
UD
1014 struct Node* build_list() {
1015 struct Node** pool;
1016 int n = read_number_of_nodes_needed();
1017 if (n <= 0) return 0;
1018 pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
a9177ff5
RM
1019 if (pool == 0) die();
1020 // organize into a linked list...
fa8d436c 1021 struct Node* first = pool[0];
a9177ff5 1022 for (i = 0; i < n-1; ++i)
fa8d436c
UD
1023 pool[i]->next = pool[i+1];
1024 free(pool); // Can now free the array (or not, if it is needed later)
1025 return first;
1026 }
1027*/
1028#if __STD_C
1029Void_t** public_iCALLOc(size_t, size_t, Void_t**);
1030#else
1031Void_t** public_iCALLOc();
1032#endif
f65fd747 1033
fa8d436c
UD
1034/*
1035 independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]);
1036
1037 independent_comalloc allocates, all at once, a set of n_elements
1038 chunks with sizes indicated in the "sizes" array. It returns
1039 an array of pointers to these elements, each of which can be
1040 independently freed, realloc'ed etc. The elements are guaranteed to
1041 be adjacently allocated (this is not guaranteed to occur with
1042 multiple callocs or mallocs), which may also improve cache locality
1043 in some applications.
1044
1045 The "chunks" argument is optional (i.e., may be null). If it is null
1046 the returned array is itself dynamically allocated and should also
1047 be freed when it is no longer needed. Otherwise, the chunks array
1048 must be of at least n_elements in length. It is filled in with the
1049 pointers to the chunks.
1050
1051 In either case, independent_comalloc returns this pointer array, or
1052 null if the allocation failed. If n_elements is zero and chunks is
1053 null, it returns a chunk representing an array with zero elements
1054 (which should be freed if not wanted).
a9177ff5 1055
fa8d436c
UD
1056 Each element must be individually freed when it is no longer
1057 needed. If you'd like to instead be able to free all at once, you
1058 should instead use a single regular malloc, and assign pointers at
a9177ff5 1059 particular offsets in the aggregate space. (In this case though, you
fa8d436c
UD
1060 cannot independently free elements.)
1061
1062 independent_comallac differs from independent_calloc in that each
1063 element may have a different size, and also that it does not
1064 automatically clear elements.
1065
1066 independent_comalloc can be used to speed up allocation in cases
1067 where several structs or objects must always be allocated at the
1068 same time. For example:
1069
1070 struct Head { ... }
1071 struct Foot { ... }
1072
1073 void send_message(char* msg) {
1074 int msglen = strlen(msg);
1075 size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
1076 void* chunks[3];
1077 if (independent_comalloc(3, sizes, chunks) == 0)
1078 die();
1079 struct Head* head = (struct Head*)(chunks[0]);
1080 char* body = (char*)(chunks[1]);
1081 struct Foot* foot = (struct Foot*)(chunks[2]);
1082 // ...
1083 }
f65fd747 1084
fa8d436c
UD
1085 In general though, independent_comalloc is worth using only for
1086 larger values of n_elements. For small values, you probably won't
1087 detect enough difference from series of malloc calls to bother.
f65fd747 1088
fa8d436c
UD
1089 Overuse of independent_comalloc can increase overall memory usage,
1090 since it cannot reuse existing noncontiguous small chunks that
1091 might be available for some of the elements.
f65fd747 1092*/
fa8d436c
UD
1093#if __STD_C
1094Void_t** public_iCOMALLOc(size_t, size_t*, Void_t**);
1095#else
1096Void_t** public_iCOMALLOc();
1097#endif
f65fd747
UD
1098
1099
fa8d436c
UD
1100/*
1101 pvalloc(size_t n);
1102 Equivalent to valloc(minimum-page-that-holds(n)), that is,
1103 round up n to nearest pagesize.
1104 */
1105#if __STD_C
1106Void_t* public_pVALLOc(size_t);
1107#else
1108Void_t* public_pVALLOc();
1109#endif
f65fd747 1110
fa8d436c
UD
1111/*
1112 cfree(Void_t* p);
1113 Equivalent to free(p).
1114
1115 cfree is needed/defined on some systems that pair it with calloc,
a9177ff5 1116 for odd historical reasons (such as: cfree is used in example
fa8d436c
UD
1117 code in the first edition of K&R).
1118*/
1119#if __STD_C
1120void public_cFREe(Void_t*);
f65fd747 1121#else
fa8d436c
UD
1122void public_cFREe();
1123#endif
1124
1125/*
1126 malloc_trim(size_t pad);
1127
1128 If possible, gives memory back to the system (via negative
1129 arguments to sbrk) if there is unused memory at the `high' end of
1130 the malloc pool. You can call this after freeing large blocks of
1131 memory to potentially reduce the system-level memory requirements
1132 of a program. However, it cannot guarantee to reduce memory. Under
1133 some allocation patterns, some large free blocks of memory will be
1134 locked between two used chunks, so they cannot be given back to
1135 the system.
a9177ff5 1136
fa8d436c
UD
1137 The `pad' argument to malloc_trim represents the amount of free
1138 trailing space to leave untrimmed. If this argument is zero,
1139 only the minimum amount of memory to maintain internal data
1140 structures will be left (one page or less). Non-zero arguments
1141 can be supplied to maintain enough trailing space to service
1142 future expected allocations without having to re-obtain memory
1143 from the system.
a9177ff5 1144
fa8d436c
UD
1145 Malloc_trim returns 1 if it actually released any memory, else 0.
1146 On systems that do not support "negative sbrks", it will always
1147 rreturn 0.
1148*/
1149#if __STD_C
1150int public_mTRIm(size_t);
1151#else
1152int public_mTRIm();
1153#endif
1154
1155/*
1156 malloc_usable_size(Void_t* p);
1157
1158 Returns the number of bytes you can actually use in
1159 an allocated chunk, which may be more than you requested (although
1160 often not) due to alignment and minimum size constraints.
1161 You can use this many bytes without worrying about
1162 overwriting other allocated objects. This is not a particularly great
1163 programming practice. malloc_usable_size can be more useful in
1164 debugging and assertions, for example:
1165
1166 p = malloc(n);
1167 assert(malloc_usable_size(p) >= 256);
1168
1169*/
1170#if __STD_C
1171size_t public_mUSABLe(Void_t*);
1172#else
1173size_t public_mUSABLe();
f65fd747 1174#endif
fa8d436c
UD
1175
1176/*
1177 malloc_stats();
1178 Prints on stderr the amount of space obtained from the system (both
1179 via sbrk and mmap), the maximum amount (which may be more than
1180 current if malloc_trim and/or munmap got called), and the current
1181 number of bytes allocated via malloc (or realloc, etc) but not yet
1182 freed. Note that this is the number of bytes allocated, not the
1183 number requested. It will be larger than the number requested
1184 because of alignment and bookkeeping overhead. Because it includes
1185 alignment wastage as being in use, this figure may be greater than
1186 zero even when no user-level chunks are allocated.
1187
1188 The reported current and maximum system memory can be inaccurate if
1189 a program makes other calls to system memory allocation functions
1190 (normally sbrk) outside of malloc.
1191
1192 malloc_stats prints only the most commonly interesting statistics.
1193 More information can be obtained by calling mallinfo.
1194
1195*/
1196#if __STD_C
1197void public_mSTATs(void);
1198#else
1199void public_mSTATs();
f65fd747
UD
1200#endif
1201
f7ddf3d3
UD
1202/*
1203 malloc_get_state(void);
1204
1205 Returns the state of all malloc variables in an opaque data
1206 structure.
1207*/
1208#if __STD_C
1209Void_t* public_gET_STATe(void);
1210#else
1211Void_t* public_gET_STATe();
1212#endif
1213
1214/*
1215 malloc_set_state(Void_t* state);
1216
1217 Restore the state of all malloc variables from data obtained with
1218 malloc_get_state().
1219*/
1220#if __STD_C
1221int public_sET_STATe(Void_t*);
1222#else
1223int public_sET_STATe();
1224#endif
1225
1226#ifdef _LIBC
1227/*
1228 posix_memalign(void **memptr, size_t alignment, size_t size);
1229
1230 POSIX wrapper like memalign(), checking for validity of size.
1231*/
1232int __posix_memalign(void **, size_t, size_t);
1233#endif
1234
fa8d436c
UD
1235/* mallopt tuning options */
1236
f65fd747 1237/*
fa8d436c
UD
1238 M_MXFAST is the maximum request size used for "fastbins", special bins
1239 that hold returned chunks without consolidating their spaces. This
1240 enables future requests for chunks of the same size to be handled
1241 very quickly, but can increase fragmentation, and thus increase the
1242 overall memory footprint of a program.
1243
1244 This malloc manages fastbins very conservatively yet still
1245 efficiently, so fragmentation is rarely a problem for values less
1246 than or equal to the default. The maximum supported value of MXFAST
1247 is 80. You wouldn't want it any higher than this anyway. Fastbins
1248 are designed especially for use with many small structs, objects or
1249 strings -- the default handles structs/objects/arrays with sizes up
1250 to 8 4byte fields, or small strings representing words, tokens,
1251 etc. Using fastbins for larger objects normally worsens
1252 fragmentation without improving speed.
1253
1254 M_MXFAST is set in REQUEST size units. It is internally used in
1255 chunksize units, which adds padding and alignment. You can reduce
1256 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
1257 algorithm to be a closer approximation of fifo-best-fit in all cases,
1258 not just for larger requests, but will generally cause it to be
1259 slower.
f65fd747
UD
1260*/
1261
1262
fa8d436c
UD
1263/* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
1264#ifndef M_MXFAST
a9177ff5 1265#define M_MXFAST 1
fa8d436c 1266#endif
f65fd747 1267
fa8d436c
UD
1268#ifndef DEFAULT_MXFAST
1269#define DEFAULT_MXFAST 64
10dc2a90
UD
1270#endif
1271
10dc2a90 1272
fa8d436c
UD
1273/*
1274 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
1275 to keep before releasing via malloc_trim in free().
1276
1277 Automatic trimming is mainly useful in long-lived programs.
1278 Because trimming via sbrk can be slow on some systems, and can
1279 sometimes be wasteful (in cases where programs immediately
1280 afterward allocate more large chunks) the value should be high
1281 enough so that your overall system performance would improve by
1282 releasing this much memory.
1283
1284 The trim threshold and the mmap control parameters (see below)
1285 can be traded off with one another. Trimming and mmapping are
1286 two different ways of releasing unused memory back to the
1287 system. Between these two, it is often possible to keep
1288 system-level demands of a long-lived program down to a bare
1289 minimum. For example, in one test suite of sessions measuring
1290 the XF86 X server on Linux, using a trim threshold of 128K and a
1291 mmap threshold of 192K led to near-minimal long term resource
1292 consumption.
1293
1294 If you are using this malloc in a long-lived program, it should
1295 pay to experiment with these values. As a rough guide, you
1296 might set to a value close to the average size of a process
1297 (program) running on your system. Releasing this much memory
1298 would allow such a process to run in memory. Generally, it's
1299 worth it to tune for trimming rather tham memory mapping when a
1300 program undergoes phases where several large chunks are
1301 allocated and released in ways that can reuse each other's
1302 storage, perhaps mixed with phases where there are no such
1303 chunks at all. And in well-behaved long-lived programs,
1304 controlling release of large blocks via trimming versus mapping
1305 is usually faster.
1306
1307 However, in most programs, these parameters serve mainly as
1308 protection against the system-level effects of carrying around
1309 massive amounts of unneeded memory. Since frequent calls to
1310 sbrk, mmap, and munmap otherwise degrade performance, the default
1311 parameters are set to relatively high values that serve only as
1312 safeguards.
1313
1314 The trim value It must be greater than page size to have any useful
a9177ff5 1315 effect. To disable trimming completely, you can set to
fa8d436c
UD
1316 (unsigned long)(-1)
1317
1318 Trim settings interact with fastbin (MXFAST) settings: Unless
1319 TRIM_FASTBINS is defined, automatic trimming never takes place upon
1320 freeing a chunk with size less than or equal to MXFAST. Trimming is
1321 instead delayed until subsequent freeing of larger chunks. However,
1322 you can still force an attempted trim by calling malloc_trim.
1323
1324 Also, trimming is not generally possible in cases where
1325 the main arena is obtained via mmap.
1326
1327 Note that the trick some people use of mallocing a huge space and
1328 then freeing it at program startup, in an attempt to reserve system
1329 memory, doesn't have the intended effect under automatic trimming,
1330 since that memory will immediately be returned to the system.
1331*/
1332
1333#define M_TRIM_THRESHOLD -1
1334
1335#ifndef DEFAULT_TRIM_THRESHOLD
1336#define DEFAULT_TRIM_THRESHOLD (128 * 1024)
1337#endif
1338
1339/*
1340 M_TOP_PAD is the amount of extra `padding' space to allocate or
1341 retain whenever sbrk is called. It is used in two ways internally:
1342
1343 * When sbrk is called to extend the top of the arena to satisfy
1344 a new malloc request, this much padding is added to the sbrk
1345 request.
1346
1347 * When malloc_trim is called automatically from free(),
1348 it is used as the `pad' argument.
1349
1350 In both cases, the actual amount of padding is rounded
1351 so that the end of the arena is always a system page boundary.
1352
1353 The main reason for using padding is to avoid calling sbrk so
1354 often. Having even a small pad greatly reduces the likelihood
1355 that nearly every malloc request during program start-up (or
1356 after trimming) will invoke sbrk, which needlessly wastes
1357 time.
1358
1359 Automatic rounding-up to page-size units is normally sufficient
1360 to avoid measurable overhead, so the default is 0. However, in
1361 systems where sbrk is relatively slow, it can pay to increase
1362 this value, at the expense of carrying around more memory than
1363 the program needs.
1364*/
10dc2a90 1365
fa8d436c 1366#define M_TOP_PAD -2
10dc2a90 1367
fa8d436c
UD
1368#ifndef DEFAULT_TOP_PAD
1369#define DEFAULT_TOP_PAD (0)
1370#endif
f65fd747 1371
fa8d436c
UD
1372/*
1373 M_MMAP_THRESHOLD is the request size threshold for using mmap()
1374 to service a request. Requests of at least this size that cannot
1375 be allocated using already-existing space will be serviced via mmap.
1376 (If enough normal freed space already exists it is used instead.)
1377
1378 Using mmap segregates relatively large chunks of memory so that
1379 they can be individually obtained and released from the host
1380 system. A request serviced through mmap is never reused by any
1381 other request (at least not directly; the system may just so
1382 happen to remap successive requests to the same locations).
1383
1384 Segregating space in this way has the benefits that:
1385
a9177ff5
RM
1386 1. Mmapped space can ALWAYS be individually released back
1387 to the system, which helps keep the system level memory
1388 demands of a long-lived program low.
fa8d436c
UD
1389 2. Mapped memory can never become `locked' between
1390 other chunks, as can happen with normally allocated chunks, which
1391 means that even trimming via malloc_trim would not release them.
1392 3. On some systems with "holes" in address spaces, mmap can obtain
1393 memory that sbrk cannot.
1394
1395 However, it has the disadvantages that:
1396
1397 1. The space cannot be reclaimed, consolidated, and then
1398 used to service later requests, as happens with normal chunks.
1399 2. It can lead to more wastage because of mmap page alignment
1400 requirements
1401 3. It causes malloc performance to be more dependent on host
1402 system memory management support routines which may vary in
1403 implementation quality and may impose arbitrary
1404 limitations. Generally, servicing a request via normal
1405 malloc steps is faster than going through a system's mmap.
1406
1407 The advantages of mmap nearly always outweigh disadvantages for
1408 "large" chunks, but the value of "large" varies across systems. The
1409 default is an empirically derived value that works well in most
1410 systems.
f65fd747
UD
1411*/
1412
fa8d436c 1413#define M_MMAP_THRESHOLD -3
f65fd747 1414
fa8d436c
UD
1415#ifndef DEFAULT_MMAP_THRESHOLD
1416#define DEFAULT_MMAP_THRESHOLD (128 * 1024)
1417#endif
1418
1419/*
1420 M_MMAP_MAX is the maximum number of requests to simultaneously
1421 service using mmap. This parameter exists because
1422 some systems have a limited number of internal tables for
1423 use by mmap, and using more than a few of them may degrade
1424 performance.
1425
1426 The default is set to a value that serves only as a safeguard.
1427 Setting to 0 disables use of mmap for servicing large requests. If
1428 HAVE_MMAP is not set, the default value is 0, and attempts to set it
1429 to non-zero values in mallopt will fail.
1430*/
f65fd747 1431
fa8d436c
UD
1432#define M_MMAP_MAX -4
1433
1434#ifndef DEFAULT_MMAP_MAX
1435#if HAVE_MMAP
1436#define DEFAULT_MMAP_MAX (65536)
1437#else
1438#define DEFAULT_MMAP_MAX (0)
1439#endif
f65fd747
UD
1440#endif
1441
fa8d436c
UD
1442#ifdef __cplusplus
1443}; /* end of extern "C" */
1444#endif
f65fd747 1445
100351c3 1446#include <malloc.h>
fa8d436c 1447#include "thread-m.h"
f65fd747 1448
fa8d436c
UD
1449#ifndef BOUNDED_N
1450#define BOUNDED_N(ptr, sz) (ptr)
1451#endif
1452#ifndef RETURN_ADDRESS
1453#define RETURN_ADDRESS(X_) (NULL)
9ae6fc54 1454#endif
431c33c0
UD
1455
1456/* On some platforms we can compile internal, not exported functions better.
1457 Let the environment provide a macro and define it to be empty if it
1458 is not available. */
1459#ifndef internal_function
1460# define internal_function
1461#endif
1462
fa8d436c
UD
1463/* Forward declarations. */
1464struct malloc_chunk;
1465typedef struct malloc_chunk* mchunkptr;
431c33c0 1466
fa8d436c 1467/* Internal routines. */
f65fd747 1468
fa8d436c 1469#if __STD_C
f65fd747 1470
fa8d436c
UD
1471Void_t* _int_malloc(mstate, size_t);
1472void _int_free(mstate, Void_t*);
1473Void_t* _int_realloc(mstate, Void_t*, size_t);
1474Void_t* _int_memalign(mstate, size_t, size_t);
1475Void_t* _int_valloc(mstate, size_t);
1476static Void_t* _int_pvalloc(mstate, size_t);
1477/*static Void_t* cALLOc(size_t, size_t);*/
1478static Void_t** _int_icalloc(mstate, size_t, size_t, Void_t**);
1479static Void_t** _int_icomalloc(mstate, size_t, size_t*, Void_t**);
1480static int mTRIm(size_t);
1481static size_t mUSABLe(Void_t*);
1482static void mSTATs(void);
1483static int mALLOPt(int, int);
1484static struct mallinfo mALLINFo(mstate);
1485
1486static Void_t* internal_function mem2mem_check(Void_t *p, size_t sz);
1487static int internal_function top_check(void);
1488static void internal_function munmap_chunk(mchunkptr p);
a9177ff5 1489#if HAVE_MREMAP
fa8d436c 1490static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
a9177ff5 1491#endif
fa8d436c
UD
1492
1493static Void_t* malloc_check(size_t sz, const Void_t *caller);
1494static void free_check(Void_t* mem, const Void_t *caller);
1495static Void_t* realloc_check(Void_t* oldmem, size_t bytes,
1496 const Void_t *caller);
1497static Void_t* memalign_check(size_t alignment, size_t bytes,
1498 const Void_t *caller);
1499#ifndef NO_THREADS
1500static Void_t* malloc_starter(size_t sz, const Void_t *caller);
1501static void free_starter(Void_t* mem, const Void_t *caller);
1502static Void_t* malloc_atfork(size_t sz, const Void_t *caller);
1503static void free_atfork(Void_t* mem, const Void_t *caller);
1504#endif
f65fd747 1505
fa8d436c 1506#else
f65fd747 1507
fa8d436c
UD
1508Void_t* _int_malloc();
1509void _int_free();
1510Void_t* _int_realloc();
1511Void_t* _int_memalign();
1512Void_t* _int_valloc();
1513Void_t* _int_pvalloc();
1514/*static Void_t* cALLOc();*/
1515static Void_t** _int_icalloc();
1516static Void_t** _int_icomalloc();
1517static int mTRIm();
1518static size_t mUSABLe();
1519static void mSTATs();
1520static int mALLOPt();
1521static struct mallinfo mALLINFo();
f65fd747 1522
fa8d436c 1523#endif
f65fd747 1524
f65fd747 1525
f65fd747 1526
f65fd747 1527
fa8d436c 1528/* ------------- Optional versions of memcopy ---------------- */
f65fd747 1529
a1648746 1530
fa8d436c 1531#if USE_MEMCPY
a1648746 1532
a9177ff5 1533/*
fa8d436c
UD
1534 Note: memcpy is ONLY invoked with non-overlapping regions,
1535 so the (usually slower) memmove is not needed.
1536*/
a1648746 1537
fa8d436c
UD
1538#define MALLOC_COPY(dest, src, nbytes) memcpy(dest, src, nbytes)
1539#define MALLOC_ZERO(dest, nbytes) memset(dest, 0, nbytes)
f65fd747 1540
fa8d436c 1541#else /* !USE_MEMCPY */
f65fd747 1542
fa8d436c 1543/* Use Duff's device for good zeroing/copying performance. */
f65fd747 1544
fa8d436c
UD
1545#define MALLOC_ZERO(charp, nbytes) \
1546do { \
1547 INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \
1548 unsigned long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \
1549 long mcn; \
1550 if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
1551 switch (mctmp) { \
1552 case 0: for(;;) { *mzp++ = 0; \
1553 case 7: *mzp++ = 0; \
1554 case 6: *mzp++ = 0; \
1555 case 5: *mzp++ = 0; \
1556 case 4: *mzp++ = 0; \
1557 case 3: *mzp++ = 0; \
1558 case 2: *mzp++ = 0; \
1559 case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \
1560 } \
1561} while(0)
f65fd747 1562
fa8d436c
UD
1563#define MALLOC_COPY(dest,src,nbytes) \
1564do { \
1565 INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \
1566 INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \
1567 unsigned long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \
1568 long mcn; \
1569 if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
1570 switch (mctmp) { \
1571 case 0: for(;;) { *mcdst++ = *mcsrc++; \
1572 case 7: *mcdst++ = *mcsrc++; \
1573 case 6: *mcdst++ = *mcsrc++; \
1574 case 5: *mcdst++ = *mcsrc++; \
1575 case 4: *mcdst++ = *mcsrc++; \
1576 case 3: *mcdst++ = *mcsrc++; \
1577 case 2: *mcdst++ = *mcsrc++; \
1578 case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \
1579 } \
1580} while(0)
f65fd747 1581
f65fd747
UD
1582#endif
1583
fa8d436c 1584/* ------------------ MMAP support ------------------ */
f65fd747 1585
f65fd747 1586
fa8d436c 1587#if HAVE_MMAP
f65fd747 1588
fa8d436c
UD
1589#include <fcntl.h>
1590#ifndef LACKS_SYS_MMAN_H
1591#include <sys/mman.h>
1592#endif
f65fd747 1593
fa8d436c
UD
1594#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1595# define MAP_ANONYMOUS MAP_ANON
1596#endif
1597#if !defined(MAP_FAILED)
1598# define MAP_FAILED ((char*)-1)
1599#endif
f65fd747 1600
fa8d436c
UD
1601#ifndef MAP_NORESERVE
1602# ifdef MAP_AUTORESRV
1603# define MAP_NORESERVE MAP_AUTORESRV
1604# else
1605# define MAP_NORESERVE 0
1606# endif
f65fd747
UD
1607#endif
1608
a9177ff5
RM
1609/*
1610 Nearly all versions of mmap support MAP_ANONYMOUS,
fa8d436c
UD
1611 so the following is unlikely to be needed, but is
1612 supplied just in case.
1613*/
f65fd747 1614
fa8d436c 1615#ifndef MAP_ANONYMOUS
f65fd747 1616
fa8d436c 1617static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
2f6d1f1b 1618
fa8d436c
UD
1619#define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \
1620 (dev_zero_fd = open("/dev/zero", O_RDWR), \
1621 mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \
1622 mmap((addr), (size), (prot), (flags), dev_zero_fd, 0))
f65fd747 1623
fa8d436c 1624#else
f65fd747 1625
fa8d436c
UD
1626#define MMAP(addr, size, prot, flags) \
1627 (mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0))
f65fd747 1628
e9b3e3c5 1629#endif
f65fd747
UD
1630
1631
fa8d436c
UD
1632#endif /* HAVE_MMAP */
1633
1634
f65fd747 1635/*
fa8d436c 1636 ----------------------- Chunk representations -----------------------
f65fd747
UD
1637*/
1638
1639
fa8d436c
UD
1640/*
1641 This struct declaration is misleading (but accurate and necessary).
1642 It declares a "view" into memory allowing access to necessary
1643 fields at known offsets from a given base. See explanation below.
1644*/
1645
1646struct malloc_chunk {
1647
1648 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
1649 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
1650
1651 struct malloc_chunk* fd; /* double links -- used only if free. */
f65fd747
UD
1652 struct malloc_chunk* bk;
1653};
1654
f65fd747
UD
1655
1656/*
f65fd747
UD
1657 malloc_chunk details:
1658
1659 (The following includes lightly edited explanations by Colin Plumb.)
1660
1661 Chunks of memory are maintained using a `boundary tag' method as
1662 described in e.g., Knuth or Standish. (See the paper by Paul
1663 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1664 survey of such techniques.) Sizes of free chunks are stored both
1665 in the front of each chunk and at the end. This makes
1666 consolidating fragmented chunks into bigger chunks very fast. The
1667 size fields also hold bits representing whether chunks are free or
1668 in use.
1669
1670 An allocated chunk looks like this:
1671
1672
1673 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1674 | Size of previous chunk, if allocated | |
1675 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1676 | Size of chunk, in bytes |P|
1677 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1678 | User data starts here... .
1679 . .
1680 . (malloc_usable_space() bytes) .
1681 . |
1682nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1683 | Size of chunk |
1684 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1685
1686
1687 Where "chunk" is the front of the chunk for the purpose of most of
1688 the malloc code, but "mem" is the pointer that is returned to the
1689 user. "Nextchunk" is the beginning of the next contiguous chunk.
1690
fa8d436c 1691 Chunks always begin on even word boundries, so the mem portion
f65fd747 1692 (which is returned to the user) is also on an even word boundary, and
fa8d436c 1693 thus at least double-word aligned.
f65fd747
UD
1694
1695 Free chunks are stored in circular doubly-linked lists, and look like this:
1696
1697 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1698 | Size of previous chunk |
1699 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1700 `head:' | Size of chunk, in bytes |P|
1701 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1702 | Forward pointer to next chunk in list |
1703 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1704 | Back pointer to previous chunk in list |
1705 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1706 | Unused space (may be 0 bytes long) .
1707 . .
1708 . |
1709nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1710 `foot:' | Size of chunk, in bytes |
1711 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1712
1713 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1714 chunk size (which is always a multiple of two words), is an in-use
1715 bit for the *previous* chunk. If that bit is *clear*, then the
1716 word before the current chunk size contains the previous chunk
1717 size, and can be used to find the front of the previous chunk.
fa8d436c
UD
1718 The very first chunk allocated always has this bit set,
1719 preventing access to non-existent (or non-owned) memory. If
1720 prev_inuse is set for any given chunk, then you CANNOT determine
1721 the size of the previous chunk, and might even get a memory
1722 addressing fault when trying to do so.
f65fd747
UD
1723
1724 Note that the `foot' of the current chunk is actually represented
fa8d436c
UD
1725 as the prev_size of the NEXT chunk. This makes it easier to
1726 deal with alignments etc but can be very confusing when trying
1727 to extend or adapt this code.
f65fd747
UD
1728
1729 The two exceptions to all this are
1730
fa8d436c
UD
1731 1. The special chunk `top' doesn't bother using the
1732 trailing size field since there is no next contiguous chunk
1733 that would have to index off it. After initialization, `top'
1734 is forced to always exist. If it would become less than
1735 MINSIZE bytes long, it is replenished.
f65fd747
UD
1736
1737 2. Chunks allocated via mmap, which have the second-lowest-order
1738 bit (IS_MMAPPED) set in their size fields. Because they are
fa8d436c 1739 allocated one-by-one, each must contain its own trailing size field.
f65fd747
UD
1740
1741*/
1742
1743/*
fa8d436c
UD
1744 ---------- Size and alignment checks and conversions ----------
1745*/
f65fd747 1746
fa8d436c 1747/* conversion from malloc headers to user pointers, and back */
f65fd747 1748
fa8d436c
UD
1749#define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
1750#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
f65fd747 1751
fa8d436c
UD
1752/* The smallest possible chunk */
1753#define MIN_CHUNK_SIZE (sizeof(struct malloc_chunk))
f65fd747 1754
fa8d436c 1755/* The smallest size we can malloc is an aligned minimal chunk */
f65fd747 1756
fa8d436c
UD
1757#define MINSIZE \
1758 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
f65fd747 1759
fa8d436c 1760/* Check if m has acceptable alignment */
f65fd747 1761
fa8d436c 1762#define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
f65fd747 1763
f65fd747 1764
a9177ff5 1765/*
fa8d436c
UD
1766 Check if a request is so large that it would wrap around zero when
1767 padded and aligned. To simplify some other code, the bound is made
1768 low enough so that adding MINSIZE will also not wrap around zero.
1769*/
f65fd747 1770
fa8d436c
UD
1771#define REQUEST_OUT_OF_RANGE(req) \
1772 ((unsigned long)(req) >= \
a9177ff5 1773 (unsigned long)(INTERNAL_SIZE_T)(-2 * MINSIZE))
f65fd747 1774
fa8d436c 1775/* pad request bytes into a usable size -- internal version */
f65fd747 1776
fa8d436c
UD
1777#define request2size(req) \
1778 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1779 MINSIZE : \
1780 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
f65fd747 1781
fa8d436c 1782/* Same, except also perform argument check */
f65fd747 1783
fa8d436c
UD
1784#define checked_request2size(req, sz) \
1785 if (REQUEST_OUT_OF_RANGE(req)) { \
1786 MALLOC_FAILURE_ACTION; \
1787 return 0; \
1788 } \
a9177ff5 1789 (sz) = request2size(req);
f65fd747
UD
1790
1791/*
fa8d436c 1792 --------------- Physical chunk operations ---------------
f65fd747
UD
1793*/
1794
10dc2a90 1795
fa8d436c
UD
1796/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1797#define PREV_INUSE 0x1
f65fd747 1798
fa8d436c
UD
1799/* extract inuse bit of previous chunk */
1800#define prev_inuse(p) ((p)->size & PREV_INUSE)
f65fd747 1801
f65fd747 1802
fa8d436c
UD
1803/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1804#define IS_MMAPPED 0x2
f65fd747 1805
fa8d436c
UD
1806/* check for mmap()'ed chunk */
1807#define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
f65fd747 1808
f65fd747 1809
fa8d436c
UD
1810/* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1811 from a non-main arena. This is only set immediately before handing
1812 the chunk to the user, if necessary. */
1813#define NON_MAIN_ARENA 0x4
f65fd747 1814
fa8d436c
UD
1815/* check for chunk from non-main arena */
1816#define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)
f65fd747
UD
1817
1818
a9177ff5
RM
1819/*
1820 Bits to mask off when extracting size
f65fd747 1821
fa8d436c
UD
1822 Note: IS_MMAPPED is intentionally not masked off from size field in
1823 macros for which mmapped chunks should never be seen. This should
1824 cause helpful core dumps to occur if it is tried by accident by
1825 people extending or adapting this malloc.
f65fd747 1826*/
fa8d436c 1827#define SIZE_BITS (PREV_INUSE|IS_MMAPPED|NON_MAIN_ARENA)
f65fd747 1828
fa8d436c
UD
1829/* Get size, ignoring use bits */
1830#define chunksize(p) ((p)->size & ~(SIZE_BITS))
f65fd747 1831
f65fd747 1832
fa8d436c
UD
1833/* Ptr to next physical malloc_chunk. */
1834#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~SIZE_BITS) ))
f65fd747 1835
fa8d436c
UD
1836/* Ptr to previous physical malloc_chunk */
1837#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
f65fd747 1838
fa8d436c
UD
1839/* Treat space at ptr + offset as a chunk */
1840#define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
1841
1842/* extract p's inuse bit */
1843#define inuse(p)\
1844((((mchunkptr)(((char*)(p))+((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE)
f65fd747 1845
fa8d436c
UD
1846/* set/clear chunk as being inuse without otherwise disturbing */
1847#define set_inuse(p)\
1848((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE
f65fd747 1849
fa8d436c
UD
1850#define clear_inuse(p)\
1851((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE)
f65fd747
UD
1852
1853
fa8d436c
UD
1854/* check/set/clear inuse bits in known places */
1855#define inuse_bit_at_offset(p, s)\
1856 (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
f65fd747 1857
fa8d436c
UD
1858#define set_inuse_bit_at_offset(p, s)\
1859 (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
f65fd747 1860
fa8d436c
UD
1861#define clear_inuse_bit_at_offset(p, s)\
1862 (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
f65fd747 1863
f65fd747 1864
fa8d436c
UD
1865/* Set size at head, without disturbing its use bit */
1866#define set_head_size(p, s) ((p)->size = (((p)->size & SIZE_BITS) | (s)))
f65fd747 1867
fa8d436c
UD
1868/* Set size/use field */
1869#define set_head(p, s) ((p)->size = (s))
f65fd747 1870
fa8d436c
UD
1871/* Set size at footer (only when chunk is not in use) */
1872#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
f65fd747
UD
1873
1874
fa8d436c
UD
1875/*
1876 -------------------- Internal data structures --------------------
1877
1878 All internal state is held in an instance of malloc_state defined
1879 below. There are no other static variables, except in two optional
a9177ff5
RM
1880 cases:
1881 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
fa8d436c
UD
1882 * If HAVE_MMAP is true, but mmap doesn't support
1883 MAP_ANONYMOUS, a dummy file descriptor for mmap.
1884
1885 Beware of lots of tricks that minimize the total bookkeeping space
1886 requirements. The result is a little over 1K bytes (for 4byte
1887 pointers and size_t.)
1888*/
f65fd747
UD
1889
1890/*
fa8d436c
UD
1891 Bins
1892
1893 An array of bin headers for free chunks. Each bin is doubly
1894 linked. The bins are approximately proportionally (log) spaced.
1895 There are a lot of these bins (128). This may look excessive, but
1896 works very well in practice. Most bins hold sizes that are
1897 unusual as malloc request sizes, but are more usual for fragments
1898 and consolidated sets of chunks, which is what these bins hold, so
1899 they can be found quickly. All procedures maintain the invariant
1900 that no consolidated chunk physically borders another one, so each
1901 chunk in a list is known to be preceeded and followed by either
1902 inuse chunks or the ends of memory.
1903
1904 Chunks in bins are kept in size order, with ties going to the
1905 approximately least recently used chunk. Ordering isn't needed
1906 for the small bins, which all contain the same-sized chunks, but
1907 facilitates best-fit allocation for larger chunks. These lists
1908 are just sequential. Keeping them in order almost never requires
1909 enough traversal to warrant using fancier ordered data
a9177ff5 1910 structures.
fa8d436c
UD
1911
1912 Chunks of the same size are linked with the most
1913 recently freed at the front, and allocations are taken from the
1914 back. This results in LRU (FIFO) allocation order, which tends
1915 to give each chunk an equal opportunity to be consolidated with
1916 adjacent freed chunks, resulting in larger free chunks and less
1917 fragmentation.
1918
1919 To simplify use in double-linked lists, each bin header acts
1920 as a malloc_chunk. This avoids special-casing for headers.
1921 But to conserve space and improve locality, we allocate
1922 only the fd/bk pointers of bins, and then use repositioning tricks
a9177ff5 1923 to treat these as the fields of a malloc_chunk*.
f65fd747
UD
1924*/
1925
fa8d436c 1926typedef struct malloc_chunk* mbinptr;
f65fd747 1927
fa8d436c
UD
1928/* addressing -- note that bin_at(0) does not exist */
1929#define bin_at(m, i) ((mbinptr)((char*)&((m)->bins[(i)<<1]) - (SIZE_SZ<<1)))
f65fd747 1930
fa8d436c
UD
1931/* analog of ++bin */
1932#define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1)))
f65fd747 1933
fa8d436c
UD
1934/* Reminders about list directionality within bins */
1935#define first(b) ((b)->fd)
1936#define last(b) ((b)->bk)
f65fd747 1937
fa8d436c
UD
1938/* Take a chunk off a bin list */
1939#define unlink(P, BK, FD) { \
1940 FD = P->fd; \
1941 BK = P->bk; \
1942 FD->bk = BK; \
1943 BK->fd = FD; \
1944}
f65fd747 1945
fa8d436c
UD
1946/*
1947 Indexing
1948
1949 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1950 8 bytes apart. Larger bins are approximately logarithmically spaced:
f65fd747 1951
fa8d436c
UD
1952 64 bins of size 8
1953 32 bins of size 64
1954 16 bins of size 512
1955 8 bins of size 4096
1956 4 bins of size 32768
1957 2 bins of size 262144
1958 1 bin of size what's left
f65fd747 1959
fa8d436c
UD
1960 There is actually a little bit of slop in the numbers in bin_index
1961 for the sake of speed. This makes no difference elsewhere.
f65fd747 1962
fa8d436c
UD
1963 The bins top out around 1MB because we expect to service large
1964 requests via mmap.
1965*/
f65fd747 1966
fa8d436c
UD
1967#define NBINS 128
1968#define NSMALLBINS 64
1969#define SMALLBIN_WIDTH 8
1970#define MIN_LARGE_SIZE 512
f65fd747 1971
fa8d436c
UD
1972#define in_smallbin_range(sz) \
1973 ((unsigned long)(sz) < (unsigned long)MIN_LARGE_SIZE)
f65fd747 1974
fa8d436c 1975#define smallbin_index(sz) (((unsigned)(sz)) >> 3)
f65fd747 1976
fa8d436c
UD
1977#define largebin_index(sz) \
1978(((((unsigned long)(sz)) >> 6) <= 32)? 56 + (((unsigned long)(sz)) >> 6): \
1979 ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \
1980 ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \
1981 ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \
1982 ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \
1983 126)
f65fd747 1984
fa8d436c
UD
1985#define bin_index(sz) \
1986 ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz))
f65fd747 1987
f65fd747
UD
1988
1989/*
fa8d436c
UD
1990 Unsorted chunks
1991
1992 All remainders from chunk splits, as well as all returned chunks,
1993 are first placed in the "unsorted" bin. They are then placed
1994 in regular bins after malloc gives them ONE chance to be used before
1995 binning. So, basically, the unsorted_chunks list acts as a queue,
1996 with chunks being placed on it in free (and malloc_consolidate),
1997 and taken off (to be either used or placed in bins) in malloc.
1998
1999 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
2000 does not have to be taken into account in size comparisons.
f65fd747
UD
2001*/
2002
fa8d436c
UD
2003/* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
2004#define unsorted_chunks(M) (bin_at(M, 1))
f65fd747 2005
fa8d436c
UD
2006/*
2007 Top
2008
2009 The top-most available chunk (i.e., the one bordering the end of
2010 available memory) is treated specially. It is never included in
2011 any bin, is used only if no other chunk is available, and is
2012 released back to the system if it is very large (see
2013 M_TRIM_THRESHOLD). Because top initially
2014 points to its own bin with initial zero size, thus forcing
2015 extension on the first malloc request, we avoid having any special
2016 code in malloc to check whether it even exists yet. But we still
2017 need to do so when getting memory from system, so we make
2018 initial_top treat the bin as a legal but unusable chunk during the
2019 interval between initialization and the first call to
2020 sYSMALLOc. (This is somewhat delicate, since it relies on
2021 the 2 preceding words to be zero during this interval as well.)
2022*/
f65fd747 2023
fa8d436c
UD
2024/* Conveniently, the unsorted bin can be used as dummy top on first call */
2025#define initial_top(M) (unsorted_chunks(M))
f65fd747 2026
fa8d436c
UD
2027/*
2028 Binmap
f65fd747 2029
fa8d436c
UD
2030 To help compensate for the large number of bins, a one-level index
2031 structure is used for bin-by-bin searching. `binmap' is a
2032 bitvector recording whether bins are definitely empty so they can
2033 be skipped over during during traversals. The bits are NOT always
2034 cleared as soon as bins are empty, but instead only
2035 when they are noticed to be empty during traversal in malloc.
2036*/
f65fd747 2037
fa8d436c
UD
2038/* Conservatively use 32 bits per map word, even if on 64bit system */
2039#define BINMAPSHIFT 5
2040#define BITSPERMAP (1U << BINMAPSHIFT)
2041#define BINMAPSIZE (NBINS / BITSPERMAP)
f65fd747 2042
fa8d436c
UD
2043#define idx2block(i) ((i) >> BINMAPSHIFT)
2044#define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1))))
f65fd747 2045
fa8d436c
UD
2046#define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i))
2047#define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i)))
2048#define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i))
f65fd747 2049
fa8d436c
UD
2050/*
2051 Fastbins
2052
2053 An array of lists holding recently freed small chunks. Fastbins
2054 are not doubly linked. It is faster to single-link them, and
2055 since chunks are never removed from the middles of these lists,
2056 double linking is not necessary. Also, unlike regular bins, they
2057 are not even processed in FIFO order (they use faster LIFO) since
2058 ordering doesn't much matter in the transient contexts in which
2059 fastbins are normally used.
2060
2061 Chunks in fastbins keep their inuse bit set, so they cannot
2062 be consolidated with other free chunks. malloc_consolidate
2063 releases all chunks in fastbins and consolidates them with
a9177ff5 2064 other free chunks.
fa8d436c 2065*/
f65fd747 2066
fa8d436c 2067typedef struct malloc_chunk* mfastbinptr;
f65fd747 2068
fa8d436c
UD
2069/* offset 2 to use otherwise unindexable first 2 bins */
2070#define fastbin_index(sz) ((((unsigned int)(sz)) >> 3) - 2)
f65fd747 2071
fa8d436c
UD
2072/* The maximum fastbin request size we support */
2073#define MAX_FAST_SIZE 80
f65fd747 2074
fa8d436c 2075#define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1)
f65fd747
UD
2076
2077/*
fa8d436c
UD
2078 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
2079 that triggers automatic consolidation of possibly-surrounding
2080 fastbin chunks. This is a heuristic, so the exact value should not
2081 matter too much. It is defined at half the default trim threshold as a
2082 compromise heuristic to only attempt consolidation if it is likely
2083 to lead to trimming. However, it is not dynamically tunable, since
a9177ff5 2084 consolidation reduces fragmentation surrounding large chunks even
fa8d436c 2085 if trimming is not used.
f65fd747
UD
2086*/
2087
fa8d436c 2088#define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
f65fd747
UD
2089
2090/*
a9177ff5 2091 Since the lowest 2 bits in max_fast don't matter in size comparisons,
fa8d436c 2092 they are used as flags.
f65fd747
UD
2093*/
2094
fa8d436c
UD
2095/*
2096 FASTCHUNKS_BIT held in max_fast indicates that there are probably
2097 some fastbin chunks. It is set true on entering a chunk into any
2098 fastbin, and cleared only in malloc_consolidate.
f65fd747 2099
fa8d436c
UD
2100 The truth value is inverted so that have_fastchunks will be true
2101 upon startup (since statics are zero-filled), simplifying
2102 initialization checks.
2103*/
f65fd747 2104
fa8d436c 2105#define FASTCHUNKS_BIT (1U)
f65fd747 2106
fa8d436c
UD
2107#define have_fastchunks(M) (((M)->max_fast & FASTCHUNKS_BIT) == 0)
2108#define clear_fastchunks(M) ((M)->max_fast |= FASTCHUNKS_BIT)
2109#define set_fastchunks(M) ((M)->max_fast &= ~FASTCHUNKS_BIT)
f65fd747
UD
2110
2111/*
fa8d436c
UD
2112 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
2113 regions. Otherwise, contiguity is exploited in merging together,
2114 when possible, results from consecutive MORECORE calls.
f65fd747 2115
fa8d436c
UD
2116 The initial value comes from MORECORE_CONTIGUOUS, but is
2117 changed dynamically if mmap is ever used as an sbrk substitute.
f65fd747
UD
2118*/
2119
fa8d436c 2120#define NONCONTIGUOUS_BIT (2U)
f65fd747 2121
fa8d436c
UD
2122#define contiguous(M) (((M)->max_fast & NONCONTIGUOUS_BIT) == 0)
2123#define noncontiguous(M) (((M)->max_fast & NONCONTIGUOUS_BIT) != 0)
2124#define set_noncontiguous(M) ((M)->max_fast |= NONCONTIGUOUS_BIT)
2125#define set_contiguous(M) ((M)->max_fast &= ~NONCONTIGUOUS_BIT)
f65fd747 2126
a9177ff5
RM
2127/*
2128 Set value of max_fast.
fa8d436c
UD
2129 Use impossibly small value if 0.
2130 Precondition: there are no existing fastbin chunks.
2131 Setting the value clears fastchunk bit but preserves noncontiguous bit.
f65fd747
UD
2132*/
2133
fa8d436c
UD
2134#define set_max_fast(M, s) \
2135 (M)->max_fast = (((s) == 0)? SMALLBIN_WIDTH: request2size(s)) | \
2136 FASTCHUNKS_BIT | \
2137 ((M)->max_fast & NONCONTIGUOUS_BIT)
f65fd747 2138
f65fd747
UD
2139
2140/*
fa8d436c 2141 ----------- Internal state representation and initialization -----------
f65fd747
UD
2142*/
2143
fa8d436c
UD
2144struct malloc_state {
2145 /* Serialize access. */
2146 mutex_t mutex;
f65fd747 2147
fa8d436c
UD
2148 /* Statistics for locking. Only used if THREAD_STATS is defined. */
2149 long stat_lock_direct, stat_lock_loop, stat_lock_wait;
2150 long pad0_[1]; /* try to give the mutex its own cacheline */
f65fd747 2151
fa8d436c
UD
2152 /* The maximum chunk size to be eligible for fastbin */
2153 INTERNAL_SIZE_T max_fast; /* low 2 bits used as flags */
f65fd747 2154
fa8d436c
UD
2155 /* Fastbins */
2156 mfastbinptr fastbins[NFASTBINS];
f65fd747 2157
fa8d436c
UD
2158 /* Base of the topmost chunk -- not otherwise kept in a bin */
2159 mchunkptr top;
f65fd747 2160
fa8d436c
UD
2161 /* The remainder from the most recent split of a small request */
2162 mchunkptr last_remainder;
f65fd747 2163
fa8d436c
UD
2164 /* Normal bins packed as described above */
2165 mchunkptr bins[NBINS * 2];
f65fd747 2166
fa8d436c
UD
2167 /* Bitmap of bins */
2168 unsigned int binmap[BINMAPSIZE];
f65fd747 2169
fa8d436c
UD
2170 /* Linked list */
2171 struct malloc_state *next;
f65fd747 2172
fa8d436c
UD
2173 /* Memory allocated from the system in this arena. */
2174 INTERNAL_SIZE_T system_mem;
2175 INTERNAL_SIZE_T max_system_mem;
2176};
f65fd747 2177
fa8d436c
UD
2178struct malloc_par {
2179 /* Tunable parameters */
2180 unsigned long trim_threshold;
2181 INTERNAL_SIZE_T top_pad;
2182 INTERNAL_SIZE_T mmap_threshold;
2183
2184 /* Memory map support */
2185 int n_mmaps;
2186 int n_mmaps_max;
2187 int max_n_mmaps;
2188
2189 /* Cache malloc_getpagesize */
a9177ff5 2190 unsigned int pagesize;
fa8d436c
UD
2191
2192 /* Statistics */
2193 INTERNAL_SIZE_T mmapped_mem;
2194 /*INTERNAL_SIZE_T sbrked_mem;*/
2195 /*INTERNAL_SIZE_T max_sbrked_mem;*/
2196 INTERNAL_SIZE_T max_mmapped_mem;
2197 INTERNAL_SIZE_T max_total_mem; /* only kept for NO_THREADS */
2198
2199 /* First address handed out by MORECORE/sbrk. */
2200 char* sbrk_base;
2201};
f65fd747 2202
fa8d436c
UD
2203/* There are several instances of this struct ("arenas") in this
2204 malloc. If you are adapting this malloc in a way that does NOT use
2205 a static or mmapped malloc_state, you MUST explicitly zero-fill it
2206 before using. This malloc relies on the property that malloc_state
2207 is initialized to all zeroes (as is true of C statics). */
f65fd747 2208
fa8d436c 2209static struct malloc_state main_arena;
f65fd747 2210
fa8d436c 2211/* There is only one instance of the malloc parameters. */
f65fd747 2212
fa8d436c 2213static struct malloc_par mp_;
f65fd747 2214
fa8d436c
UD
2215/*
2216 Initialize a malloc_state struct.
f65fd747 2217
fa8d436c
UD
2218 This is called only from within malloc_consolidate, which needs
2219 be called in the same contexts anyway. It is never called directly
2220 outside of malloc_consolidate because some optimizing compilers try
2221 to inline it at all call points, which turns out not to be an
2222 optimization at all. (Inlining it in malloc_consolidate is fine though.)
2223*/
f65fd747 2224
fa8d436c
UD
2225#if __STD_C
2226static void malloc_init_state(mstate av)
2227#else
2228static void malloc_init_state(av) mstate av;
2229#endif
2230{
2231 int i;
2232 mbinptr bin;
a9177ff5 2233
fa8d436c 2234 /* Establish circular links for normal bins */
a9177ff5 2235 for (i = 1; i < NBINS; ++i) {
fa8d436c
UD
2236 bin = bin_at(av,i);
2237 bin->fd = bin->bk = bin;
2238 }
f65fd747 2239
fa8d436c
UD
2240#if MORECORE_CONTIGUOUS
2241 if (av != &main_arena)
2242#endif
2243 set_noncontiguous(av);
f65fd747 2244
fa8d436c 2245 set_max_fast(av, DEFAULT_MXFAST);
f65fd747 2246
fa8d436c
UD
2247 av->top = initial_top(av);
2248}
e9b3e3c5 2249
a9177ff5 2250/*
fa8d436c
UD
2251 Other internal utilities operating on mstates
2252*/
f65fd747 2253
fa8d436c
UD
2254#if __STD_C
2255static Void_t* sYSMALLOc(INTERNAL_SIZE_T, mstate);
2256static int sYSTRIm(size_t, mstate);
2257static void malloc_consolidate(mstate);
2258static Void_t** iALLOc(mstate, size_t, size_t*, int, Void_t**);
831372e7 2259#else
fa8d436c
UD
2260static Void_t* sYSMALLOc();
2261static int sYSTRIm();
2262static void malloc_consolidate();
2263static Void_t** iALLOc();
831372e7 2264#endif
7e3be507 2265
fa8d436c
UD
2266/* ------------------- Support for multiple arenas -------------------- */
2267#include "arena.c"
f65fd747 2268
fa8d436c
UD
2269/*
2270 Debugging support
f65fd747 2271
fa8d436c
UD
2272 These routines make a number of assertions about the states
2273 of data structures that should be true at all times. If any
2274 are not true, it's very likely that a user program has somehow
2275 trashed memory. (It's also possible that there is a coding error
2276 in malloc. In which case, please report it!)
2277*/
ee74a442 2278
fa8d436c 2279#if ! MALLOC_DEBUG
d8f00d46 2280
fa8d436c
UD
2281#define check_chunk(A,P)
2282#define check_free_chunk(A,P)
2283#define check_inuse_chunk(A,P)
2284#define check_remalloced_chunk(A,P,N)
2285#define check_malloced_chunk(A,P,N)
2286#define check_malloc_state(A)
d8f00d46 2287
fa8d436c 2288#else
ca34d7a7 2289
fa8d436c
UD
2290#define check_chunk(A,P) do_check_chunk(A,P)
2291#define check_free_chunk(A,P) do_check_free_chunk(A,P)
2292#define check_inuse_chunk(A,P) do_check_inuse_chunk(A,P)
2293#define check_remalloced_chunk(A,P,N) do_check_remalloced_chunk(A,P,N)
2294#define check_malloced_chunk(A,P,N) do_check_malloced_chunk(A,P,N)
2295#define check_malloc_state(A) do_check_malloc_state(A)
ca34d7a7 2296
fa8d436c
UD
2297/*
2298 Properties of all chunks
2299*/
ca34d7a7 2300
fa8d436c
UD
2301#if __STD_C
2302static void do_check_chunk(mstate av, mchunkptr p)
2303#else
2304static void do_check_chunk(av, p) mstate av; mchunkptr p;
ca34d7a7 2305#endif
ca34d7a7 2306{
fa8d436c
UD
2307 unsigned long sz = chunksize(p);
2308 /* min and max possible addresses assuming contiguous allocation */
2309 char* max_address = (char*)(av->top) + chunksize(av->top);
2310 char* min_address = max_address - av->system_mem;
2311
2312 if (!chunk_is_mmapped(p)) {
a9177ff5 2313
fa8d436c
UD
2314 /* Has legal address ... */
2315 if (p != av->top) {
2316 if (contiguous(av)) {
2317 assert(((char*)p) >= min_address);
2318 assert(((char*)p + sz) <= ((char*)(av->top)));
2319 }
2320 }
2321 else {
2322 /* top size is always at least MINSIZE */
2323 assert((unsigned long)(sz) >= MINSIZE);
2324 /* top predecessor always marked inuse */
2325 assert(prev_inuse(p));
2326 }
a9177ff5 2327
ca34d7a7 2328 }
fa8d436c
UD
2329 else {
2330#if HAVE_MMAP
2331 /* address is outside main heap */
2332 if (contiguous(av) && av->top != initial_top(av)) {
2333 assert(((char*)p) < min_address || ((char*)p) > max_address);
2334 }
2335 /* chunk is page-aligned */
2336 assert(((p->prev_size + sz) & (mp_.pagesize-1)) == 0);
2337 /* mem is aligned */
2338 assert(aligned_OK(chunk2mem(p)));
2339#else
2340 /* force an appropriate assert violation if debug set */
2341 assert(!chunk_is_mmapped(p));
eb406346 2342#endif
eb406346 2343 }
eb406346
UD
2344}
2345
fa8d436c
UD
2346/*
2347 Properties of free chunks
2348*/
ee74a442 2349
fa8d436c
UD
2350#if __STD_C
2351static void do_check_free_chunk(mstate av, mchunkptr p)
2352#else
2353static void do_check_free_chunk(av, p) mstate av; mchunkptr p;
10dc2a90 2354#endif
67c94753 2355{
fa8d436c
UD
2356 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
2357 mchunkptr next = chunk_at_offset(p, sz);
67c94753 2358
fa8d436c 2359 do_check_chunk(av, p);
67c94753 2360
fa8d436c
UD
2361 /* Chunk must claim to be free ... */
2362 assert(!inuse(p));
2363 assert (!chunk_is_mmapped(p));
67c94753 2364
fa8d436c
UD
2365 /* Unless a special marker, must have OK fields */
2366 if ((unsigned long)(sz) >= MINSIZE)
2367 {
2368 assert((sz & MALLOC_ALIGN_MASK) == 0);
2369 assert(aligned_OK(chunk2mem(p)));
2370 /* ... matching footer field */
2371 assert(next->prev_size == sz);
2372 /* ... and is fully consolidated */
2373 assert(prev_inuse(p));
2374 assert (next == av->top || inuse(next));
2375
2376 /* ... and has minimally sane links */
2377 assert(p->fd->bk == p);
2378 assert(p->bk->fd == p);
2379 }
2380 else /* markers are always of size SIZE_SZ */
2381 assert(sz == SIZE_SZ);
67c94753 2382}
67c94753 2383
fa8d436c
UD
2384/*
2385 Properties of inuse chunks
2386*/
2387
2388#if __STD_C
2389static void do_check_inuse_chunk(mstate av, mchunkptr p)
f65fd747 2390#else
fa8d436c 2391static void do_check_inuse_chunk(av, p) mstate av; mchunkptr p;
f65fd747
UD
2392#endif
2393{
fa8d436c 2394 mchunkptr next;
f65fd747 2395
fa8d436c 2396 do_check_chunk(av, p);
f65fd747 2397
fa8d436c
UD
2398 if (chunk_is_mmapped(p))
2399 return; /* mmapped chunks have no next/prev */
ca34d7a7 2400
fa8d436c
UD
2401 /* Check whether it claims to be in use ... */
2402 assert(inuse(p));
10dc2a90 2403
fa8d436c 2404 next = next_chunk(p);
10dc2a90 2405
fa8d436c
UD
2406 /* ... and is surrounded by OK chunks.
2407 Since more things can be checked with free chunks than inuse ones,
2408 if an inuse chunk borders them and debug is on, it's worth doing them.
2409 */
2410 if (!prev_inuse(p)) {
2411 /* Note that we cannot even look at prev unless it is not inuse */
2412 mchunkptr prv = prev_chunk(p);
2413 assert(next_chunk(prv) == p);
2414 do_check_free_chunk(av, prv);
2415 }
2416
2417 if (next == av->top) {
2418 assert(prev_inuse(next));
2419 assert(chunksize(next) >= MINSIZE);
2420 }
2421 else if (!inuse(next))
2422 do_check_free_chunk(av, next);
10dc2a90
UD
2423}
2424
fa8d436c
UD
2425/*
2426 Properties of chunks recycled from fastbins
2427*/
2428
10dc2a90 2429#if __STD_C
fa8d436c 2430static void do_check_remalloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
10dc2a90 2431#else
fa8d436c
UD
2432static void do_check_remalloced_chunk(av, p, s)
2433mstate av; mchunkptr p; INTERNAL_SIZE_T s;
a2b08ee5 2434#endif
10dc2a90 2435{
fa8d436c
UD
2436 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
2437
2438 if (!chunk_is_mmapped(p)) {
2439 assert(av == arena_for_chunk(p));
2440 if (chunk_non_main_arena(p))
2441 assert(av != &main_arena);
2442 else
2443 assert(av == &main_arena);
2444 }
2445
2446 do_check_inuse_chunk(av, p);
2447
2448 /* Legal size ... */
2449 assert((sz & MALLOC_ALIGN_MASK) == 0);
2450 assert((unsigned long)(sz) >= MINSIZE);
2451 /* ... and alignment */
2452 assert(aligned_OK(chunk2mem(p)));
2453 /* chunk is less than MINSIZE more than request */
2454 assert((long)(sz) - (long)(s) >= 0);
2455 assert((long)(sz) - (long)(s + MINSIZE) < 0);
10dc2a90
UD
2456}
2457
fa8d436c
UD
2458/*
2459 Properties of nonrecycled chunks at the point they are malloced
2460*/
2461
10dc2a90 2462#if __STD_C
fa8d436c 2463static void do_check_malloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s)
10dc2a90 2464#else
fa8d436c
UD
2465static void do_check_malloced_chunk(av, p, s)
2466mstate av; mchunkptr p; INTERNAL_SIZE_T s;
a2b08ee5 2467#endif
10dc2a90 2468{
fa8d436c
UD
2469 /* same as recycled case ... */
2470 do_check_remalloced_chunk(av, p, s);
10dc2a90 2471
fa8d436c
UD
2472 /*
2473 ... plus, must obey implementation invariant that prev_inuse is
2474 always true of any allocated chunk; i.e., that each allocated
2475 chunk borders either a previously allocated and still in-use
2476 chunk, or the base of its memory arena. This is ensured
2477 by making all allocations from the the `lowest' part of any found
2478 chunk. This does not necessarily hold however for chunks
2479 recycled via fastbins.
2480 */
10dc2a90 2481
fa8d436c
UD
2482 assert(prev_inuse(p));
2483}
10dc2a90 2484
f65fd747 2485
fa8d436c
UD
2486/*
2487 Properties of malloc_state.
f65fd747 2488
fa8d436c
UD
2489 This may be useful for debugging malloc, as well as detecting user
2490 programmer errors that somehow write into malloc_state.
f65fd747 2491
fa8d436c
UD
2492 If you are extending or experimenting with this malloc, you can
2493 probably figure out how to hack this routine to print out or
2494 display chunk addresses, sizes, bins, and other instrumentation.
2495*/
f65fd747 2496
fa8d436c
UD
2497static void do_check_malloc_state(mstate av)
2498{
2499 int i;
2500 mchunkptr p;
2501 mchunkptr q;
2502 mbinptr b;
2503 unsigned int binbit;
2504 int empty;
2505 unsigned int idx;
2506 INTERNAL_SIZE_T size;
2507 unsigned long total = 0;
2508 int max_fast_bin;
f65fd747 2509
fa8d436c
UD
2510 /* internal size_t must be no wider than pointer type */
2511 assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*));
f65fd747 2512
fa8d436c
UD
2513 /* alignment is a power of 2 */
2514 assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0);
f65fd747 2515
fa8d436c
UD
2516 /* cannot run remaining checks until fully initialized */
2517 if (av->top == 0 || av->top == initial_top(av))
2518 return;
f65fd747 2519
fa8d436c
UD
2520 /* pagesize is a power of 2 */
2521 assert((mp_.pagesize & (mp_.pagesize-1)) == 0);
f65fd747 2522
fa8d436c
UD
2523 /* A contiguous main_arena is consistent with sbrk_base. */
2524 if (av == &main_arena && contiguous(av))
2525 assert((char*)mp_.sbrk_base + av->system_mem ==
2526 (char*)av->top + chunksize(av->top));
2527
2528 /* properties of fastbins */
2529
2530 /* max_fast is in allowed range */
2531 assert((av->max_fast & ~1) <= request2size(MAX_FAST_SIZE));
2532
2533 max_fast_bin = fastbin_index(av->max_fast);
2534
2535 for (i = 0; i < NFASTBINS; ++i) {
2536 p = av->fastbins[i];
2537
2538 /* all bins past max_fast are empty */
2539 if (i > max_fast_bin)
2540 assert(p == 0);
2541
2542 while (p != 0) {
2543 /* each chunk claims to be inuse */
2544 do_check_inuse_chunk(av, p);
2545 total += chunksize(p);
2546 /* chunk belongs in this bin */
2547 assert(fastbin_index(chunksize(p)) == i);
2548 p = p->fd;
2549 }
2550 }
2551
2552 if (total != 0)
2553 assert(have_fastchunks(av));
2554 else if (!have_fastchunks(av))
2555 assert(total == 0);
2556
2557 /* check normal bins */
2558 for (i = 1; i < NBINS; ++i) {
2559 b = bin_at(av,i);
2560
2561 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2562 if (i >= 2) {
2563 binbit = get_binmap(av,i);
2564 empty = last(b) == b;
2565 if (!binbit)
2566 assert(empty);
2567 else if (!empty)
2568 assert(binbit);
2569 }
2570
2571 for (p = last(b); p != b; p = p->bk) {
2572 /* each chunk claims to be free */
2573 do_check_free_chunk(av, p);
2574 size = chunksize(p);
2575 total += size;
2576 if (i >= 2) {
2577 /* chunk belongs in bin */
2578 idx = bin_index(size);
2579 assert(idx == i);
2580 /* lists are sorted */
a9177ff5 2581 assert(p->bk == b ||
fa8d436c
UD
2582 (unsigned long)chunksize(p->bk) >= (unsigned long)chunksize(p));
2583 }
2584 /* chunk is followed by a legal chain of inuse chunks */
2585 for (q = next_chunk(p);
a9177ff5 2586 (q != av->top && inuse(q) &&
fa8d436c
UD
2587 (unsigned long)(chunksize(q)) >= MINSIZE);
2588 q = next_chunk(q))
2589 do_check_inuse_chunk(av, q);
2590 }
2591 }
f65fd747 2592
fa8d436c
UD
2593 /* top chunk is OK */
2594 check_chunk(av, av->top);
2595
2596 /* sanity checks for statistics */
2597
2598#ifdef NO_THREADS
2599 assert(total <= (unsigned long)(mp_.max_total_mem));
2600 assert(mp_.n_mmaps >= 0);
f65fd747 2601#endif
fa8d436c
UD
2602 assert(mp_.n_mmaps <= mp_.n_mmaps_max);
2603 assert(mp_.n_mmaps <= mp_.max_n_mmaps);
2604
2605 assert((unsigned long)(av->system_mem) <=
2606 (unsigned long)(av->max_system_mem));
f65fd747 2607
fa8d436c
UD
2608 assert((unsigned long)(mp_.mmapped_mem) <=
2609 (unsigned long)(mp_.max_mmapped_mem));
2610
2611#ifdef NO_THREADS
2612 assert((unsigned long)(mp_.max_total_mem) >=
2613 (unsigned long)(mp_.mmapped_mem) + (unsigned long)(av->system_mem));
dfd2257a 2614#endif
fa8d436c
UD
2615}
2616#endif
2617
2618
2619/* ----------------- Support for debugging hooks -------------------- */
2620#include "hooks.c"
2621
2622
2623/* ----------- Routines dealing with system allocation -------------- */
2624
2625/*
2626 sysmalloc handles malloc cases requiring more memory from the system.
2627 On entry, it is assumed that av->top does not have enough
2628 space to service request for nb bytes, thus requiring that av->top
2629 be extended or replaced.
2630*/
2631
f65fd747 2632#if __STD_C
fa8d436c 2633static Void_t* sYSMALLOc(INTERNAL_SIZE_T nb, mstate av)
f65fd747 2634#else
fa8d436c 2635static Void_t* sYSMALLOc(nb, av) INTERNAL_SIZE_T nb; mstate av;
f65fd747
UD
2636#endif
2637{
fa8d436c
UD
2638 mchunkptr old_top; /* incoming value of av->top */
2639 INTERNAL_SIZE_T old_size; /* its size */
2640 char* old_end; /* its end address */
f65fd747 2641
fa8d436c
UD
2642 long size; /* arg to first MORECORE or mmap call */
2643 char* brk; /* return value from MORECORE */
f65fd747 2644
fa8d436c
UD
2645 long correction; /* arg to 2nd MORECORE call */
2646 char* snd_brk; /* 2nd return val */
f65fd747 2647
fa8d436c
UD
2648 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2649 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2650 char* aligned_brk; /* aligned offset into brk */
f65fd747 2651
fa8d436c
UD
2652 mchunkptr p; /* the allocated/returned chunk */
2653 mchunkptr remainder; /* remainder from allocation */
2654 unsigned long remainder_size; /* its size */
2655
2656 unsigned long sum; /* for updating stats */
2657
2658 size_t pagemask = mp_.pagesize - 1;
2659
2660
2661#if HAVE_MMAP
2662
2663 /*
2664 If have mmap, and the request size meets the mmap threshold, and
2665 the system supports mmap, and there are few enough currently
2666 allocated mmapped regions, try to directly map this request
2667 rather than expanding top.
2668 */
f65fd747 2669
fa8d436c
UD
2670 if ((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) &&
2671 (mp_.n_mmaps < mp_.n_mmaps_max)) {
f65fd747 2672
fa8d436c
UD
2673 char* mm; /* return value from mmap call*/
2674
2675 /*
2676 Round up size to nearest page. For mmapped chunks, the overhead
2677 is one SIZE_SZ unit larger than for normal chunks, because there
2678 is no following chunk whose prev_size field could be used.
2679 */
2680 size = (nb + SIZE_SZ + MALLOC_ALIGN_MASK + pagemask) & ~pagemask;
2681
2682 /* Don't try if size wraps around 0 */
2683 if ((unsigned long)(size) > (unsigned long)(nb)) {
2684
2685 mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE));
a9177ff5 2686
fa8d436c 2687 if (mm != MAP_FAILED) {
a9177ff5 2688
fa8d436c
UD
2689 /*
2690 The offset to the start of the mmapped region is stored
2691 in the prev_size field of the chunk. This allows us to adjust
a9177ff5 2692 returned start address to meet alignment requirements here
fa8d436c
UD
2693 and in memalign(), and still be able to compute proper
2694 address argument for later munmap in free() and realloc().
2695 */
a9177ff5 2696
fa8d436c
UD
2697 front_misalign = (INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK;
2698 if (front_misalign > 0) {
2699 correction = MALLOC_ALIGNMENT - front_misalign;
2700 p = (mchunkptr)(mm + correction);
2701 p->prev_size = correction;
2702 set_head(p, (size - correction) |IS_MMAPPED);
2703 }
2704 else {
2705 p = (mchunkptr)mm;
2706 set_head(p, size|IS_MMAPPED);
2707 }
a9177ff5 2708
fa8d436c 2709 /* update statistics */
a9177ff5
RM
2710
2711 if (++mp_.n_mmaps > mp_.max_n_mmaps)
fa8d436c 2712 mp_.max_n_mmaps = mp_.n_mmaps;
a9177ff5 2713
fa8d436c 2714 sum = mp_.mmapped_mem += size;
a9177ff5 2715 if (sum > (unsigned long)(mp_.max_mmapped_mem))
fa8d436c 2716 mp_.max_mmapped_mem = sum;
8a4b65b4 2717#ifdef NO_THREADS
fa8d436c 2718 sum += av->system_mem;
a9177ff5 2719 if (sum > (unsigned long)(mp_.max_total_mem))
fa8d436c 2720 mp_.max_total_mem = sum;
8a4b65b4 2721#endif
fa8d436c
UD
2722
2723 check_chunk(av, p);
a9177ff5 2724
fa8d436c
UD
2725 return chunk2mem(p);
2726 }
2727 }
2728 }
2729#endif
2730
2731 /* Record incoming configuration of top */
2732
2733 old_top = av->top;
2734 old_size = chunksize(old_top);
2735 old_end = (char*)(chunk_at_offset(old_top, old_size));
2736
a9177ff5 2737 brk = snd_brk = (char*)(MORECORE_FAILURE);
fa8d436c 2738
a9177ff5 2739 /*
fa8d436c
UD
2740 If not the first time through, we require old_size to be
2741 at least MINSIZE and to have prev_inuse set.
2742 */
2743
a9177ff5 2744 assert((old_top == initial_top(av) && old_size == 0) ||
fa8d436c
UD
2745 ((unsigned long) (old_size) >= MINSIZE &&
2746 prev_inuse(old_top) &&
2747 ((unsigned long)old_end & pagemask) == 0));
2748
2749 /* Precondition: not enough current space to satisfy nb request */
2750 assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE));
2751
2752 /* Precondition: all fastbins are consolidated */
2753 assert(!have_fastchunks(av));
2754
2755
2756 if (av != &main_arena) {
2757
2758 heap_info *old_heap, *heap;
2759 size_t old_heap_size;
2760
2761 /* First try to extend the current heap. */
2762 old_heap = heap_for_ptr(old_top);
2763 old_heap_size = old_heap->size;
2764 if (grow_heap(old_heap, MINSIZE + nb - old_size) == 0) {
2765 av->system_mem += old_heap->size - old_heap_size;
2766 arena_mem += old_heap->size - old_heap_size;
2767#if 0
2768 if(mmapped_mem + arena_mem + sbrked_mem > max_total_mem)
2769 max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
2770#endif
2771 set_head(old_top, (((char *)old_heap + old_heap->size) - (char *)old_top)
2772 | PREV_INUSE);
e6ac0e78
UD
2773 }
2774 else if ((heap = new_heap(nb + (MINSIZE + sizeof(*heap)), mp_.top_pad))) {
2775 /* Use a newly allocated heap. */
2776 heap->ar_ptr = av;
2777 heap->prev = old_heap;
2778 av->system_mem += heap->size;
2779 arena_mem += heap->size;
fa8d436c 2780#if 0
e6ac0e78
UD
2781 if((unsigned long)(mmapped_mem + arena_mem + sbrked_mem) > max_total_mem)
2782 max_total_mem = mmapped_mem + arena_mem + sbrked_mem;
fa8d436c 2783#endif
fa8d436c
UD
2784 /* Set up the new top. */
2785 top(av) = chunk_at_offset(heap, sizeof(*heap));
2786 set_head(top(av), (heap->size - sizeof(*heap)) | PREV_INUSE);
2787
2788 /* Setup fencepost and free the old top chunk. */
2789 /* The fencepost takes at least MINSIZE bytes, because it might
2790 become the top chunk again later. Note that a footer is set
2791 up, too, although the chunk is marked in use. */
2792 old_size -= MINSIZE;
2793 set_head(chunk_at_offset(old_top, old_size + 2*SIZE_SZ), 0|PREV_INUSE);
2794 if (old_size >= MINSIZE) {
2795 set_head(chunk_at_offset(old_top, old_size), (2*SIZE_SZ)|PREV_INUSE);
2796 set_foot(chunk_at_offset(old_top, old_size), (2*SIZE_SZ));
2797 set_head(old_top, old_size|PREV_INUSE|NON_MAIN_ARENA);
2798 _int_free(av, chunk2mem(old_top));
2799 } else {
2800 set_head(old_top, (old_size + 2*SIZE_SZ)|PREV_INUSE);
2801 set_foot(old_top, (old_size + 2*SIZE_SZ));
2802 }
2803 }
2804
2805 } else { /* av == main_arena */
2806
2807
2808 /* Request enough space for nb + pad + overhead */
2809
2810 size = nb + mp_.top_pad + MINSIZE;
2811
2812 /*
2813 If contiguous, we can subtract out existing space that we hope to
2814 combine with new space. We add it back later only if
2815 we don't actually get contiguous space.
2816 */
2817
2818 if (contiguous(av))
2819 size -= old_size;
2820
2821 /*
2822 Round to a multiple of page size.
2823 If MORECORE is not contiguous, this ensures that we only call it
2824 with whole-page arguments. And if MORECORE is contiguous and
2825 this is not first time through, this preserves page-alignment of
2826 previous calls. Otherwise, we correct to page-align below.
2827 */
2828
2829 size = (size + pagemask) & ~pagemask;
2830
2831 /*
2832 Don't try to call MORECORE if argument is so big as to appear
2833 negative. Note that since mmap takes size_t arg, it may succeed
2834 below even if we cannot call MORECORE.
2835 */
2836
a9177ff5 2837 if (size > 0)
fa8d436c
UD
2838 brk = (char*)(MORECORE(size));
2839
2840 if (brk != (char*)(MORECORE_FAILURE)) {
2841 /* Call the `morecore' hook if necessary. */
2842 if (__after_morecore_hook)
2843 (*__after_morecore_hook) ();
2844 } else {
2845 /*
2846 If have mmap, try using it as a backup when MORECORE fails or
2847 cannot be used. This is worth doing on systems that have "holes" in
2848 address space, so sbrk cannot extend to give contiguous space, but
2849 space is available elsewhere. Note that we ignore mmap max count
2850 and threshold limits, since the space will not be used as a
2851 segregated mmap region.
2852 */
2853
2854#if HAVE_MMAP
2855 /* Cannot merge with old top, so add its size back in */
2856 if (contiguous(av))
2857 size = (size + old_size + pagemask) & ~pagemask;
2858
2859 /* If we are relying on mmap as backup, then use larger units */
2860 if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE))
2861 size = MMAP_AS_MORECORE_SIZE;
2862
2863 /* Don't try if size wraps around 0 */
2864 if ((unsigned long)(size) > (unsigned long)(nb)) {
2865
75bfdfc7 2866 char *mbrk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE));
a9177ff5 2867
75bfdfc7 2868 if (mbrk != MAP_FAILED) {
a9177ff5 2869
fa8d436c 2870 /* We do not need, and cannot use, another sbrk call to find end */
75bfdfc7 2871 brk = mbrk;
fa8d436c 2872 snd_brk = brk + size;
a9177ff5
RM
2873
2874 /*
2875 Record that we no longer have a contiguous sbrk region.
fa8d436c
UD
2876 After the first time mmap is used as backup, we do not
2877 ever rely on contiguous space since this could incorrectly
2878 bridge regions.
2879 */
2880 set_noncontiguous(av);
2881 }
2882 }
2883#endif
2884 }
2885
2886 if (brk != (char*)(MORECORE_FAILURE)) {
2887 if (mp_.sbrk_base == 0)
2888 mp_.sbrk_base = brk;
2889 av->system_mem += size;
2890
2891 /*
2892 If MORECORE extends previous space, we can likewise extend top size.
2893 */
a9177ff5 2894
fa8d436c
UD
2895 if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE))
2896 set_head(old_top, (size + old_size) | PREV_INUSE);
2897
2898 else if (old_size && brk < old_end) {
2899 /* Oops! Someone else killed our space.. Can't touch anything. */
2900 assert(0);
2901 }
2902
2903 /*
2904 Otherwise, make adjustments:
a9177ff5 2905
fa8d436c
UD
2906 * If the first time through or noncontiguous, we need to call sbrk
2907 just to find out where the end of memory lies.
2908
2909 * We need to ensure that all returned chunks from malloc will meet
2910 MALLOC_ALIGNMENT
2911
2912 * If there was an intervening foreign sbrk, we need to adjust sbrk
2913 request size to account for fact that we will not be able to
2914 combine new space with existing space in old_top.
2915
2916 * Almost all systems internally allocate whole pages at a time, in
2917 which case we might as well use the whole last page of request.
2918 So we allocate enough more memory to hit a page boundary now,
2919 which in turn causes future contiguous calls to page-align.
2920 */
a9177ff5 2921
fa8d436c
UD
2922 else {
2923 /* Count foreign sbrk as system_mem. */
2924 if (old_size)
2925 av->system_mem += brk - old_end;
2926 front_misalign = 0;
2927 end_misalign = 0;
2928 correction = 0;
2929 aligned_brk = brk;
a9177ff5 2930
fa8d436c 2931 /* handle contiguous cases */
a9177ff5
RM
2932 if (contiguous(av)) {
2933
fa8d436c
UD
2934 /* Guarantee alignment of first new chunk made from this space */
2935
2936 front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;
2937 if (front_misalign > 0) {
2938
2939 /*
2940 Skip over some bytes to arrive at an aligned position.
2941 We don't need to specially mark these wasted front bytes.
2942 They will never be accessed anyway because
2943 prev_inuse of av->top (and any chunk created from its start)
2944 is always true after initialization.
2945 */
2946
2947 correction = MALLOC_ALIGNMENT - front_misalign;
2948 aligned_brk += correction;
2949 }
a9177ff5 2950
fa8d436c
UD
2951 /*
2952 If this isn't adjacent to existing space, then we will not
2953 be able to merge with old_top space, so must add to 2nd request.
2954 */
a9177ff5 2955
fa8d436c 2956 correction += old_size;
a9177ff5 2957
fa8d436c
UD
2958 /* Extend the end address to hit a page boundary */
2959 end_misalign = (INTERNAL_SIZE_T)(brk + size + correction);
2960 correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign;
a9177ff5 2961
fa8d436c
UD
2962 assert(correction >= 0);
2963 snd_brk = (char*)(MORECORE(correction));
a9177ff5 2964
fa8d436c
UD
2965 /*
2966 If can't allocate correction, try to at least find out current
2967 brk. It might be enough to proceed without failing.
a9177ff5 2968
fa8d436c
UD
2969 Note that if second sbrk did NOT fail, we assume that space
2970 is contiguous with first sbrk. This is a safe assumption unless
2971 program is multithreaded but doesn't use locks and a foreign sbrk
2972 occurred between our first and second calls.
2973 */
a9177ff5 2974
fa8d436c
UD
2975 if (snd_brk == (char*)(MORECORE_FAILURE)) {
2976 correction = 0;
2977 snd_brk = (char*)(MORECORE(0));
2978 } else
2979 /* Call the `morecore' hook if necessary. */
2980 if (__after_morecore_hook)
2981 (*__after_morecore_hook) ();
2982 }
a9177ff5 2983
fa8d436c 2984 /* handle non-contiguous cases */
a9177ff5 2985 else {
fa8d436c
UD
2986 /* MORECORE/mmap must correctly align */
2987 assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0);
a9177ff5 2988
fa8d436c
UD
2989 /* Find out current end of memory */
2990 if (snd_brk == (char*)(MORECORE_FAILURE)) {
2991 snd_brk = (char*)(MORECORE(0));
2992 }
2993 }
a9177ff5 2994
fa8d436c
UD
2995 /* Adjust top based on results of second sbrk */
2996 if (snd_brk != (char*)(MORECORE_FAILURE)) {
2997 av->top = (mchunkptr)aligned_brk;
2998 set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2999 av->system_mem += correction;
a9177ff5 3000
fa8d436c
UD
3001 /*
3002 If not the first time through, we either have a
3003 gap due to foreign sbrk or a non-contiguous region. Insert a
3004 double fencepost at old_top to prevent consolidation with space
3005 we don't own. These fenceposts are artificial chunks that are
3006 marked as inuse and are in any case too small to use. We need
3007 two to make sizes and alignments work out.
3008 */
a9177ff5 3009
fa8d436c 3010 if (old_size != 0) {
a9177ff5 3011 /*
fa8d436c
UD
3012 Shrink old_top to insert fenceposts, keeping size a
3013 multiple of MALLOC_ALIGNMENT. We know there is at least
3014 enough space in old_top to do this.
3015 */
3016 old_size = (old_size - 4*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
3017 set_head(old_top, old_size | PREV_INUSE);
a9177ff5 3018
fa8d436c
UD
3019 /*
3020 Note that the following assignments completely overwrite
3021 old_top when old_size was previously MINSIZE. This is
3022 intentional. We need the fencepost, even if old_top otherwise gets
3023 lost.
3024 */
3025 chunk_at_offset(old_top, old_size )->size =
3026 (2*SIZE_SZ)|PREV_INUSE;
3027
3028 chunk_at_offset(old_top, old_size + 2*SIZE_SZ)->size =
3029 (2*SIZE_SZ)|PREV_INUSE;
3030
3031 /* If possible, release the rest. */
3032 if (old_size >= MINSIZE) {
3033 _int_free(av, chunk2mem(old_top));
3034 }
3035
3036 }
3037 }
3038 }
a9177ff5 3039
fa8d436c
UD
3040 /* Update statistics */
3041#ifdef NO_THREADS
3042 sum = av->system_mem + mp_.mmapped_mem;
3043 if (sum > (unsigned long)(mp_.max_total_mem))
3044 mp_.max_total_mem = sum;
3045#endif
3046
3047 }
3048
3049 } /* if (av != &main_arena) */
3050
3051 if ((unsigned long)av->system_mem > (unsigned long)(av->max_system_mem))
3052 av->max_system_mem = av->system_mem;
3053 check_malloc_state(av);
a9177ff5 3054
fa8d436c
UD
3055 /* finally, do the allocation */
3056 p = av->top;
3057 size = chunksize(p);
3058
3059 /* check that one of the above allocation paths succeeded */
3060 if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
3061 remainder_size = size - nb;
3062 remainder = chunk_at_offset(p, nb);
3063 av->top = remainder;
3064 set_head(p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
3065 set_head(remainder, remainder_size | PREV_INUSE);
3066 check_malloced_chunk(av, p, nb);
3067 return chunk2mem(p);
3068 }
3069
3070 /* catch all failure paths */
3071 MALLOC_FAILURE_ACTION;
3072 return 0;
3073}
3074
3075
3076/*
3077 sYSTRIm is an inverse of sorts to sYSMALLOc. It gives memory back
3078 to the system (via negative arguments to sbrk) if there is unused
3079 memory at the `high' end of the malloc pool. It is called
3080 automatically by free() when top space exceeds the trim
3081 threshold. It is also called by the public malloc_trim routine. It
3082 returns 1 if it actually released any memory, else 0.
3083*/
3084
3085#if __STD_C
3086static int sYSTRIm(size_t pad, mstate av)
3087#else
3088static int sYSTRIm(pad, av) size_t pad; mstate av;
3089#endif
3090{
3091 long top_size; /* Amount of top-most memory */
3092 long extra; /* Amount to release */
3093 long released; /* Amount actually released */
3094 char* current_brk; /* address returned by pre-check sbrk call */
3095 char* new_brk; /* address returned by post-check sbrk call */
3096 size_t pagesz;
3097
3098 pagesz = mp_.pagesize;
3099 top_size = chunksize(av->top);
a9177ff5 3100
fa8d436c
UD
3101 /* Release in pagesize units, keeping at least one page */
3102 extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
a9177ff5 3103
fa8d436c 3104 if (extra > 0) {
a9177ff5 3105
fa8d436c
UD
3106 /*
3107 Only proceed if end of memory is where we last set it.
3108 This avoids problems if there were foreign sbrk calls.
3109 */
3110 current_brk = (char*)(MORECORE(0));
3111 if (current_brk == (char*)(av->top) + top_size) {
a9177ff5 3112
fa8d436c
UD
3113 /*
3114 Attempt to release memory. We ignore MORECORE return value,
3115 and instead call again to find out where new end of memory is.
3116 This avoids problems if first call releases less than we asked,
3117 of if failure somehow altered brk value. (We could still
3118 encounter problems if it altered brk in some very bad way,
3119 but the only thing we can do is adjust anyway, which will cause
3120 some downstream failure.)
3121 */
a9177ff5 3122
fa8d436c
UD
3123 MORECORE(-extra);
3124 /* Call the `morecore' hook if necessary. */
3125 if (__after_morecore_hook)
3126 (*__after_morecore_hook) ();
3127 new_brk = (char*)(MORECORE(0));
a9177ff5 3128
fa8d436c
UD
3129 if (new_brk != (char*)MORECORE_FAILURE) {
3130 released = (long)(current_brk - new_brk);
a9177ff5 3131
fa8d436c
UD
3132 if (released != 0) {
3133 /* Success. Adjust top. */
3134 av->system_mem -= released;
3135 set_head(av->top, (top_size - released) | PREV_INUSE);
3136 check_malloc_state(av);
3137 return 1;
3138 }
3139 }
3140 }
3141 }
3142 return 0;
f65fd747
UD
3143}
3144
fa8d436c
UD
3145#ifdef HAVE_MMAP
3146
431c33c0
UD
3147static void
3148internal_function
f65fd747 3149#if __STD_C
431c33c0 3150munmap_chunk(mchunkptr p)
f65fd747 3151#else
431c33c0 3152munmap_chunk(p) mchunkptr p;
f65fd747
UD
3153#endif
3154{
3155 INTERNAL_SIZE_T size = chunksize(p);
3156 int ret;
3157
3158 assert (chunk_is_mmapped(p));
fa8d436c
UD
3159#if 0
3160 assert(! ((char*)p >= mp_.sbrk_base && (char*)p < mp_.sbrk_base + mp_.sbrked_mem));
3161 assert((mp_.n_mmaps > 0));
3162#endif
3163 assert(((p->prev_size + size) & (mp_.pagesize-1)) == 0);
f65fd747 3164
fa8d436c
UD
3165 mp_.n_mmaps--;
3166 mp_.mmapped_mem -= (size + p->prev_size);
f65fd747
UD
3167
3168 ret = munmap((char *)p - p->prev_size, size + p->prev_size);
3169
3170 /* munmap returns non-zero on failure */
3171 assert(ret == 0);
3172}
3173
3174#if HAVE_MREMAP
3175
431c33c0
UD
3176static mchunkptr
3177internal_function
f65fd747 3178#if __STD_C
431c33c0 3179mremap_chunk(mchunkptr p, size_t new_size)
f65fd747 3180#else
431c33c0 3181mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
f65fd747
UD
3182#endif
3183{
fa8d436c 3184 size_t page_mask = mp_.pagesize - 1;
f65fd747
UD
3185 INTERNAL_SIZE_T offset = p->prev_size;
3186 INTERNAL_SIZE_T size = chunksize(p);
3187 char *cp;
3188
3189 assert (chunk_is_mmapped(p));
fa8d436c
UD
3190#if 0
3191 assert(! ((char*)p >= mp_.sbrk_base && (char*)p < mp_.sbrk_base + mp_.sbrked_mem));
3192 assert((mp_.n_mmaps > 0));
3193#endif
3194 assert(((size + offset) & (mp_.pagesize-1)) == 0);
f65fd747
UD
3195
3196 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
3197 new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
3198
3199 cp = (char *)mremap((char *)p - offset, size + offset, new_size,
3200 MREMAP_MAYMOVE);
3201
431c33c0 3202 if (cp == MAP_FAILED) return 0;
f65fd747
UD
3203
3204 p = (mchunkptr)(cp + offset);
3205
3206 assert(aligned_OK(chunk2mem(p)));
3207
3208 assert((p->prev_size == offset));
3209 set_head(p, (new_size - offset)|IS_MMAPPED);
3210
fa8d436c
UD
3211 mp_.mmapped_mem -= size + offset;
3212 mp_.mmapped_mem += new_size;
3213 if ((unsigned long)mp_.mmapped_mem > (unsigned long)mp_.max_mmapped_mem)
3214 mp_.max_mmapped_mem = mp_.mmapped_mem;
8a4b65b4 3215#ifdef NO_THREADS
fa8d436c
UD
3216 if ((unsigned long)(mp_.mmapped_mem + arena_mem + main_arena.system_mem) >
3217 mp_.max_total_mem)
3218 mp_.max_total_mem = mp_.mmapped_mem + arena_mem + main_arena.system_mem;
8a4b65b4 3219#endif
f65fd747
UD
3220 return p;
3221}
3222
3223#endif /* HAVE_MREMAP */
3224
3225#endif /* HAVE_MMAP */
3226
fa8d436c 3227/*------------------------ Public wrappers. --------------------------------*/
f65fd747 3228
fa8d436c
UD
3229Void_t*
3230public_mALLOc(size_t bytes)
3231{
3232 mstate ar_ptr;
3233 Void_t *victim;
f65fd747 3234
fa8d436c
UD
3235 __malloc_ptr_t (*hook) __MALLOC_P ((size_t, __const __malloc_ptr_t)) =
3236 __malloc_hook;
3237 if (hook != NULL)
3238 return (*hook)(bytes, RETURN_ADDRESS (0));
f65fd747 3239
fa8d436c
UD
3240 arena_get(ar_ptr, bytes);
3241 if(!ar_ptr)
f65fd747 3242 return 0;
fa8d436c
UD
3243 victim = _int_malloc(ar_ptr, bytes);
3244 if(!victim) {
3245 /* Maybe the failure is due to running out of mmapped areas. */
3246 if(ar_ptr != &main_arena) {
3247 (void)mutex_unlock(&ar_ptr->mutex);
3248 (void)mutex_lock(&main_arena.mutex);
3249 victim = _int_malloc(&main_arena, bytes);
3250 (void)mutex_unlock(&main_arena.mutex);
3251 } else {
3252#if USE_ARENAS
3253 /* ... or sbrk() has failed and there is still a chance to mmap() */
3254 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
3255 (void)mutex_unlock(&main_arena.mutex);
3256 if(ar_ptr) {
3257 victim = _int_malloc(ar_ptr, bytes);
3258 (void)mutex_unlock(&ar_ptr->mutex);
3259 }
3260#endif
60f0e64b 3261 }
fa8d436c
UD
3262 } else
3263 (void)mutex_unlock(&ar_ptr->mutex);
3264 assert(!victim || chunk_is_mmapped(mem2chunk(victim)) ||
3265 ar_ptr == arena_for_chunk(mem2chunk(victim)));
3266 return victim;
f65fd747
UD
3267}
3268
fa8d436c
UD
3269void
3270public_fREe(Void_t* mem)
f65fd747 3271{
fa8d436c
UD
3272 mstate ar_ptr;
3273 mchunkptr p; /* chunk corresponding to mem */
3274
3275 void (*hook) __MALLOC_P ((__malloc_ptr_t, __const __malloc_ptr_t)) =
3276 __free_hook;
3277 if (hook != NULL) {
3278 (*hook)(mem, RETURN_ADDRESS (0));
3279 return;
f65fd747 3280 }
f65fd747 3281
fa8d436c
UD
3282 if (mem == 0) /* free(0) has no effect */
3283 return;
f65fd747 3284
fa8d436c 3285 p = mem2chunk(mem);
f65fd747 3286
fa8d436c
UD
3287#if HAVE_MMAP
3288 if (chunk_is_mmapped(p)) /* release mmapped memory. */
3289 {
3290 munmap_chunk(p);
3291 return;
8a4b65b4 3292 }
f65fd747 3293#endif
f65fd747 3294
fa8d436c
UD
3295 ar_ptr = arena_for_chunk(p);
3296#if THREAD_STATS
3297 if(!mutex_trylock(&ar_ptr->mutex))
3298 ++(ar_ptr->stat_lock_direct);
3299 else {
3300 (void)mutex_lock(&ar_ptr->mutex);
3301 ++(ar_ptr->stat_lock_wait);
f65fd747 3302 }
f65fd747 3303#else
fa8d436c 3304 (void)mutex_lock(&ar_ptr->mutex);
f65fd747 3305#endif
fa8d436c
UD
3306 _int_free(ar_ptr, mem);
3307 (void)mutex_unlock(&ar_ptr->mutex);
f65fd747
UD
3308}
3309
fa8d436c
UD
3310Void_t*
3311public_rEALLOc(Void_t* oldmem, size_t bytes)
f65fd747 3312{
fa8d436c
UD
3313 mstate ar_ptr;
3314 INTERNAL_SIZE_T nb; /* padded request size */
f65fd747 3315
fa8d436c
UD
3316 mchunkptr oldp; /* chunk corresponding to oldmem */
3317 INTERNAL_SIZE_T oldsize; /* its size */
8a4b65b4 3318
fa8d436c 3319 Void_t* newp; /* chunk to return */
f65fd747 3320
fa8d436c
UD
3321 __malloc_ptr_t (*hook) __MALLOC_P ((__malloc_ptr_t, size_t,
3322 __const __malloc_ptr_t)) =
3323 __realloc_hook;
3324 if (hook != NULL)
3325 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
f65fd747 3326
fa8d436c
UD
3327#if REALLOC_ZERO_BYTES_FREES
3328 if (bytes == 0 && oldmem != NULL) { public_fREe(oldmem); return 0; }
f65fd747 3329#endif
f65fd747 3330
fa8d436c
UD
3331 /* realloc of null is supposed to be same as malloc */
3332 if (oldmem == 0) return public_mALLOc(bytes);
f65fd747 3333
fa8d436c
UD
3334 oldp = mem2chunk(oldmem);
3335 oldsize = chunksize(oldp);
f65fd747 3336
fa8d436c 3337 checked_request2size(bytes, nb);
f65fd747 3338
fa8d436c
UD
3339#if HAVE_MMAP
3340 if (chunk_is_mmapped(oldp))
3341 {
3342 Void_t* newmem;
f65fd747 3343
fa8d436c
UD
3344#if HAVE_MREMAP
3345 newp = mremap_chunk(oldp, nb);
3346 if(newp) return chunk2mem(newp);
f65fd747 3347#endif
fa8d436c
UD
3348 /* Note the extra SIZE_SZ overhead. */
3349 if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
3350 /* Must alloc, copy, free. */
3351 newmem = public_mALLOc(bytes);
3352 if (newmem == 0) return 0; /* propagate failure */
3353 MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
3354 munmap_chunk(oldp);
3355 return newmem;
3356 }
dfd2257a 3357#endif
fa8d436c
UD
3358
3359 ar_ptr = arena_for_chunk(oldp);
3360#if THREAD_STATS
3361 if(!mutex_trylock(&ar_ptr->mutex))
3362 ++(ar_ptr->stat_lock_direct);
3363 else {
3364 (void)mutex_lock(&ar_ptr->mutex);
3365 ++(ar_ptr->stat_lock_wait);
3366 }
f65fd747 3367#else
fa8d436c 3368 (void)mutex_lock(&ar_ptr->mutex);
f65fd747 3369#endif
f65fd747 3370
fa8d436c
UD
3371#ifndef NO_THREADS
3372 /* As in malloc(), remember this arena for the next allocation. */
3373 tsd_setspecific(arena_key, (Void_t *)ar_ptr);
f65fd747
UD
3374#endif
3375
fa8d436c 3376 newp = _int_realloc(ar_ptr, oldmem, bytes);
f65fd747 3377
fa8d436c
UD
3378 (void)mutex_unlock(&ar_ptr->mutex);
3379 assert(!newp || chunk_is_mmapped(mem2chunk(newp)) ||
3380 ar_ptr == arena_for_chunk(mem2chunk(newp)));
3381 return newp;
3382}
f65fd747 3383
fa8d436c
UD
3384Void_t*
3385public_mEMALIGn(size_t alignment, size_t bytes)
3386{
3387 mstate ar_ptr;
3388 Void_t *p;
f65fd747 3389
fa8d436c
UD
3390 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t,
3391 __const __malloc_ptr_t)) =
3392 __memalign_hook;
3393 if (hook != NULL)
3394 return (*hook)(alignment, bytes, RETURN_ADDRESS (0));
f65fd747 3395
fa8d436c
UD
3396 /* If need less alignment than we give anyway, just relay to malloc */
3397 if (alignment <= MALLOC_ALIGNMENT) return public_mALLOc(bytes);
1228ed5c 3398
fa8d436c
UD
3399 /* Otherwise, ensure that it is at least a minimum chunk size */
3400 if (alignment < MINSIZE) alignment = MINSIZE;
f65fd747 3401
fa8d436c
UD
3402 arena_get(ar_ptr, bytes + alignment + MINSIZE);
3403 if(!ar_ptr)
3404 return 0;
3405 p = _int_memalign(ar_ptr, alignment, bytes);
3406 (void)mutex_unlock(&ar_ptr->mutex);
3407 if(!p) {
3408 /* Maybe the failure is due to running out of mmapped areas. */
3409 if(ar_ptr != &main_arena) {
3410 (void)mutex_lock(&main_arena.mutex);
3411 p = _int_memalign(&main_arena, alignment, bytes);
3412 (void)mutex_unlock(&main_arena.mutex);
f65fd747 3413 } else {
e9b3e3c5 3414#if USE_ARENAS
fa8d436c
UD
3415 /* ... or sbrk() has failed and there is still a chance to mmap() */
3416 ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);
3417 if(ar_ptr) {
3418 p = _int_memalign(ar_ptr, alignment, bytes);
3419 (void)mutex_unlock(&ar_ptr->mutex);
3420 }
e9b3e3c5 3421#endif
f65fd747
UD
3422 }
3423 }
fa8d436c
UD
3424 assert(!p || chunk_is_mmapped(mem2chunk(p)) ||
3425 ar_ptr == arena_for_chunk(mem2chunk(p)));
3426 return p;
f65fd747
UD
3427}
3428
fa8d436c
UD
3429Void_t*
3430public_vALLOc(size_t bytes)
3431{
3432 mstate ar_ptr;
3433 Void_t *p;
f65fd747 3434
fa8d436c
UD
3435 if(__malloc_initialized < 0)
3436 ptmalloc_init ();
3437 arena_get(ar_ptr, bytes + mp_.pagesize + MINSIZE);
3438 if(!ar_ptr)
3439 return 0;
3440 p = _int_valloc(ar_ptr, bytes);
3441 (void)mutex_unlock(&ar_ptr->mutex);
3442 return p;
3443}
f65fd747 3444
fa8d436c
UD
3445Void_t*
3446public_pVALLOc(size_t bytes)
3447{
3448 mstate ar_ptr;
3449 Void_t *p;
f65fd747 3450
fa8d436c
UD
3451 if(__malloc_initialized < 0)
3452 ptmalloc_init ();
3453 arena_get(ar_ptr, bytes + 2*mp_.pagesize + MINSIZE);
3454 p = _int_pvalloc(ar_ptr, bytes);
3455 (void)mutex_unlock(&ar_ptr->mutex);
3456 return p;
3457}
f65fd747 3458
fa8d436c
UD
3459Void_t*
3460public_cALLOc(size_t n, size_t elem_size)
f65fd747 3461{
fa8d436c
UD
3462 mstate av;
3463 mchunkptr oldtop, p;
0950889b 3464 INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
fa8d436c
UD
3465 Void_t* mem;
3466 unsigned long clearsize;
3467 unsigned long nclears;
3468 INTERNAL_SIZE_T* d;
6c6bb055 3469 __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, __const __malloc_ptr_t)) =
fa8d436c 3470 __malloc_hook;
0950889b
UD
3471
3472 /* size_t is unsigned so the behavior on overflow is defined. */
3473 bytes = n * elem_size;
d9af917d
UD
3474#define HALF_INTERNAL_SIZE_T \
3475 (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
3476 if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) {
0be405c2 3477 if (elem_size != 0 && bytes / elem_size != n) {
d9af917d
UD
3478 MALLOC_FAILURE_ACTION;
3479 return 0;
3480 }
0950889b
UD
3481 }
3482
6c6bb055 3483 if (hook != NULL) {
0950889b 3484 sz = bytes;
fa8d436c
UD
3485 mem = (*hook)(sz, RETURN_ADDRESS (0));
3486 if(mem == 0)
3487 return 0;
3488#ifdef HAVE_MEMCPY
3489 return memset(mem, 0, sz);
a2b08ee5 3490#else
fa8d436c
UD
3491 while(sz > 0) ((char*)mem)[--sz] = 0; /* rather inefficient */
3492 return mem;
a2b08ee5 3493#endif
10dc2a90 3494 }
10dc2a90 3495
0950889b 3496 sz = bytes;
fa8d436c
UD
3497
3498 arena_get(av, sz);
3499 if(!av)
f65fd747 3500 return 0;
fa8d436c
UD
3501
3502 /* Check if we hand out the top chunk, in which case there may be no
3503 need to clear. */
3504#if MORECORE_CLEARS
3505 oldtop = top(av);
3506 oldtopsize = chunksize(top(av));
3507#if MORECORE_CLEARS < 2
3508 /* Only newly allocated memory is guaranteed to be cleared. */
3509 if (av == &main_arena &&
3510 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *)oldtop)
3511 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *)oldtop);
3512#endif
3513#endif
3514 mem = _int_malloc(av, sz);
3515
3516 /* Only clearing follows, so we can unlock early. */
3517 (void)mutex_unlock(&av->mutex);
3518
3519 assert(!mem || chunk_is_mmapped(mem2chunk(mem)) ||
3520 av == arena_for_chunk(mem2chunk(mem)));
3521
3522 if (mem == 0) {
7799b7b3 3523 /* Maybe the failure is due to running out of mmapped areas. */
fa8d436c 3524 if(av != &main_arena) {
7799b7b3 3525 (void)mutex_lock(&main_arena.mutex);
fa8d436c 3526 mem = _int_malloc(&main_arena, sz);
7799b7b3 3527 (void)mutex_unlock(&main_arena.mutex);
e9b3e3c5
UD
3528 } else {
3529#if USE_ARENAS
3530 /* ... or sbrk() has failed and there is still a chance to mmap() */
fa8d436c
UD
3531 (void)mutex_lock(&main_arena.mutex);
3532 av = arena_get2(av->next ? av : 0, sz);
e9b3e3c5 3533 (void)mutex_unlock(&main_arena.mutex);
fa8d436c
UD
3534 if(av) {
3535 mem = _int_malloc(av, sz);
3536 (void)mutex_unlock(&av->mutex);
e9b3e3c5
UD
3537 }
3538#endif
7799b7b3 3539 }
fa8d436c
UD
3540 if (mem == 0) return 0;
3541 }
3542 p = mem2chunk(mem);
f65fd747 3543
fa8d436c
UD
3544 /* Two optional cases in which clearing not necessary */
3545#if HAVE_MMAP
3546 if (chunk_is_mmapped(p))
3547 return mem;
f65fd747 3548#endif
f65fd747 3549
fa8d436c 3550 csz = chunksize(p);
f65fd747 3551
fa8d436c
UD
3552#if MORECORE_CLEARS
3553 if (p == oldtop && csz > oldtopsize) {
3554 /* clear only the bytes from non-freshly-sbrked memory */
3555 csz = oldtopsize;
f65fd747 3556 }
fa8d436c 3557#endif
f65fd747 3558
fa8d436c
UD
3559 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3560 contents have an odd number of INTERNAL_SIZE_T-sized words;
3561 minimally 3. */
3562 d = (INTERNAL_SIZE_T*)mem;
3563 clearsize = csz - SIZE_SZ;
3564 nclears = clearsize / sizeof(INTERNAL_SIZE_T);
3565 assert(nclears >= 3);
f65fd747 3566
fa8d436c
UD
3567 if (nclears > 9)
3568 MALLOC_ZERO(d, clearsize);
f65fd747 3569
fa8d436c
UD
3570 else {
3571 *(d+0) = 0;
3572 *(d+1) = 0;
3573 *(d+2) = 0;
3574 if (nclears > 4) {
3575 *(d+3) = 0;
3576 *(d+4) = 0;
3577 if (nclears > 6) {
3578 *(d+5) = 0;
3579 *(d+6) = 0;
3580 if (nclears > 8) {
3581 *(d+7) = 0;
3582 *(d+8) = 0;
3583 }
f65fd747
UD
3584 }
3585 }
f65fd747
UD
3586 }
3587
fa8d436c
UD
3588 return mem;
3589}
f65fd747 3590
fa8d436c
UD
3591Void_t**
3592public_iCALLOc(size_t n, size_t elem_size, Void_t** chunks)
3593{
3594 mstate ar_ptr;
3595 Void_t** m;
f65fd747 3596
fa8d436c
UD
3597 arena_get(ar_ptr, n*elem_size);
3598 if(!ar_ptr)
3599 return 0;
f65fd747 3600
fa8d436c
UD
3601 m = _int_icalloc(ar_ptr, n, elem_size, chunks);
3602 (void)mutex_unlock(&ar_ptr->mutex);
3603 return m;
3604}
f65fd747 3605
fa8d436c
UD
3606Void_t**
3607public_iCOMALLOc(size_t n, size_t sizes[], Void_t** chunks)
3608{
3609 mstate ar_ptr;
3610 Void_t** m;
f65fd747 3611
fa8d436c
UD
3612 arena_get(ar_ptr, 0);
3613 if(!ar_ptr)
3614 return 0;
f65fd747 3615
fa8d436c
UD
3616 m = _int_icomalloc(ar_ptr, n, sizes, chunks);
3617 (void)mutex_unlock(&ar_ptr->mutex);
3618 return m;
3619}
f65fd747 3620
fa8d436c 3621#ifndef _LIBC
f65fd747 3622
fa8d436c
UD
3623void
3624public_cFREe(Void_t* m)
3625{
3626 public_fREe(m);
3627}
f65fd747 3628
fa8d436c 3629#endif /* _LIBC */
f65fd747 3630
fa8d436c
UD
3631int
3632public_mTRIm(size_t s)
3633{
3634 int result;
f65fd747 3635
fa8d436c
UD
3636 (void)mutex_lock(&main_arena.mutex);
3637 result = mTRIm(s);
3638 (void)mutex_unlock(&main_arena.mutex);
3639 return result;
3640}
f65fd747 3641
fa8d436c
UD
3642size_t
3643public_mUSABLe(Void_t* m)
3644{
3645 size_t result;
f65fd747 3646
fa8d436c
UD
3647 result = mUSABLe(m);
3648 return result;
3649}
f65fd747 3650
fa8d436c
UD
3651void
3652public_mSTATs()
3653{
3654 mSTATs();
3655}
f65fd747 3656
fa8d436c
UD
3657struct mallinfo public_mALLINFo()
3658{
3659 struct mallinfo m;
f65fd747 3660
fa8d436c
UD
3661 (void)mutex_lock(&main_arena.mutex);
3662 m = mALLINFo(&main_arena);
3663 (void)mutex_unlock(&main_arena.mutex);
3664 return m;
f65fd747
UD
3665}
3666
fa8d436c
UD
3667int
3668public_mALLOPt(int p, int v)
3669{
3670 int result;
3671 result = mALLOPt(p, v);
3672 return result;
3673}
f65fd747
UD
3674
3675/*
fa8d436c 3676 ------------------------------ malloc ------------------------------
f65fd747
UD
3677*/
3678
fa8d436c
UD
3679Void_t*
3680_int_malloc(mstate av, size_t bytes)
f65fd747 3681{
fa8d436c
UD
3682 INTERNAL_SIZE_T nb; /* normalized request size */
3683 unsigned int idx; /* associated bin index */
3684 mbinptr bin; /* associated bin */
3685 mfastbinptr* fb; /* associated fastbin */
f65fd747 3686
fa8d436c
UD
3687 mchunkptr victim; /* inspected/selected chunk */
3688 INTERNAL_SIZE_T size; /* its size */
3689 int victim_index; /* its bin index */
f65fd747 3690
fa8d436c
UD
3691 mchunkptr remainder; /* remainder from a split */
3692 unsigned long remainder_size; /* its size */
8a4b65b4 3693
fa8d436c
UD
3694 unsigned int block; /* bit map traverser */
3695 unsigned int bit; /* bit map traverser */
3696 unsigned int map; /* current word of binmap */
8a4b65b4 3697
fa8d436c
UD
3698 mchunkptr fwd; /* misc temp for linking */
3699 mchunkptr bck; /* misc temp for linking */
8a4b65b4 3700
fa8d436c
UD
3701 /*
3702 Convert request size to internal form by adding SIZE_SZ bytes
3703 overhead plus possibly more to obtain necessary alignment and/or
3704 to obtain a size of at least MINSIZE, the smallest allocatable
3705 size. Also, checked_request2size traps (returning 0) request sizes
3706 that are so large that they wrap around zero when padded and
3707 aligned.
3708 */
f65fd747 3709
fa8d436c 3710 checked_request2size(bytes, nb);
f65fd747 3711
fa8d436c
UD
3712 /*
3713 If the size qualifies as a fastbin, first check corresponding bin.
3714 This code is safe to execute even if av is not yet initialized, so we
3715 can try it without checking, which saves some time on this fast path.
3716 */
f65fd747 3717
a9177ff5 3718 if ((unsigned long)(nb) <= (unsigned long)(av->max_fast)) {
fa8d436c
UD
3719 fb = &(av->fastbins[(fastbin_index(nb))]);
3720 if ( (victim = *fb) != 0) {
3721 *fb = victim->fd;
3722 check_remalloced_chunk(av, victim, nb);
3723 return chunk2mem(victim);
3724 }
f65fd747
UD
3725 }
3726
fa8d436c
UD
3727 /*
3728 If a small request, check regular bin. Since these "smallbins"
3729 hold one size each, no searching within bins is necessary.
3730 (For a large request, we need to wait until unsorted chunks are
3731 processed to find best fit. But for small ones, fits are exact
3732 anyway, so we can check now, which is faster.)
3733 */
f65fd747 3734
fa8d436c
UD
3735 if (in_smallbin_range(nb)) {
3736 idx = smallbin_index(nb);
3737 bin = bin_at(av,idx);
7799b7b3 3738
fa8d436c
UD
3739 if ( (victim = last(bin)) != bin) {
3740 if (victim == 0) /* initialization check */
3741 malloc_consolidate(av);
3742 else {
3743 bck = victim->bk;
3744 set_inuse_bit_at_offset(victim, nb);
3745 bin->bk = bck;
3746 bck->fd = bin;
3747
3748 if (av != &main_arena)
3749 victim->size |= NON_MAIN_ARENA;
3750 check_malloced_chunk(av, victim, nb);
3751 return chunk2mem(victim);
3752 }
3753 }
f65fd747
UD
3754 }
3755
a9177ff5 3756 /*
fa8d436c
UD
3757 If this is a large request, consolidate fastbins before continuing.
3758 While it might look excessive to kill all fastbins before
3759 even seeing if there is space available, this avoids
3760 fragmentation problems normally associated with fastbins.
3761 Also, in practice, programs tend to have runs of either small or
a9177ff5 3762 large requests, but less often mixtures, so consolidation is not
fa8d436c
UD
3763 invoked all that often in most programs. And the programs that
3764 it is called frequently in otherwise tend to fragment.
3765 */
7799b7b3 3766
fa8d436c
UD
3767 else {
3768 idx = largebin_index(nb);
a9177ff5 3769 if (have_fastchunks(av))
fa8d436c 3770 malloc_consolidate(av);
7799b7b3 3771 }
f65fd747 3772
fa8d436c
UD
3773 /*
3774 Process recently freed or remaindered chunks, taking one only if
3775 it is exact fit, or, if this a small request, the chunk is remainder from
3776 the most recent non-exact fit. Place other traversed chunks in
3777 bins. Note that this step is the only place in any routine where
3778 chunks are placed in bins.
3779
3780 The outer loop here is needed because we might not realize until
3781 near the end of malloc that we should have consolidated, so must
3782 do so and retry. This happens at most once, and only when we would
3783 otherwise need to expand memory to service a "small" request.
3784 */
a9177ff5
RM
3785
3786 for(;;) {
3787
fa8d436c
UD
3788 while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
3789 bck = victim->bk;
3790 size = chunksize(victim);
3791
a9177ff5 3792 /*
fa8d436c
UD
3793 If a small request, try to use last remainder if it is the
3794 only chunk in unsorted bin. This helps promote locality for
3795 runs of consecutive small requests. This is the only
3796 exception to best-fit, and applies only when there is
3797 no exact fit for a small chunk.
3798 */
3799
a9177ff5 3800 if (in_smallbin_range(nb) &&
fa8d436c
UD
3801 bck == unsorted_chunks(av) &&
3802 victim == av->last_remainder &&
3803 (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
3804
3805 /* split and reattach remainder */
3806 remainder_size = size - nb;
3807 remainder = chunk_at_offset(victim, nb);
3808 unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
a9177ff5 3809 av->last_remainder = remainder;
fa8d436c 3810 remainder->bk = remainder->fd = unsorted_chunks(av);
a9177ff5 3811
fa8d436c
UD
3812 set_head(victim, nb | PREV_INUSE |
3813 (av != &main_arena ? NON_MAIN_ARENA : 0));
3814 set_head(remainder, remainder_size | PREV_INUSE);
3815 set_foot(remainder, remainder_size);
a9177ff5 3816
fa8d436c
UD
3817 check_malloced_chunk(av, victim, nb);
3818 return chunk2mem(victim);
3819 }
f65fd747 3820
fa8d436c
UD
3821 /* remove from unsorted list */
3822 unsorted_chunks(av)->bk = bck;
3823 bck->fd = unsorted_chunks(av);
a9177ff5 3824
fa8d436c 3825 /* Take now instead of binning if exact fit */
a9177ff5 3826
fa8d436c
UD
3827 if (size == nb) {
3828 set_inuse_bit_at_offset(victim, size);
3829 if (av != &main_arena)
3830 victim->size |= NON_MAIN_ARENA;
3831 check_malloced_chunk(av, victim, nb);
3832 return chunk2mem(victim);
3833 }
a9177ff5 3834
fa8d436c 3835 /* place chunk in bin */
a9177ff5 3836
fa8d436c
UD
3837 if (in_smallbin_range(size)) {
3838 victim_index = smallbin_index(size);
3839 bck = bin_at(av, victim_index);
3840 fwd = bck->fd;
3841 }
3842 else {
3843 victim_index = largebin_index(size);
3844 bck = bin_at(av, victim_index);
3845 fwd = bck->fd;
3846
3847 /* maintain large bins in sorted order */
3848 if (fwd != bck) {
3849 /* Or with inuse bit to speed comparisons */
3850 size |= PREV_INUSE;
3851 /* if smaller than smallest, bypass loop below */
3852 assert((bck->bk->size & NON_MAIN_ARENA) == 0);
3853 if ((unsigned long)(size) <= (unsigned long)(bck->bk->size)) {
3854 fwd = bck;
3855 bck = bck->bk;
3856 }
3857 else {
3858 assert((fwd->size & NON_MAIN_ARENA) == 0);
3859 while ((unsigned long)(size) < (unsigned long)(fwd->size)) {
3860 fwd = fwd->fd;
3861 assert((fwd->size & NON_MAIN_ARENA) == 0);
3862 }
3863 bck = fwd->bk;
3864 }
3865 }
3866 }
a9177ff5 3867
fa8d436c
UD
3868 mark_bin(av, victim_index);
3869 victim->bk = bck;
3870 victim->fd = fwd;
3871 fwd->bk = victim;
3872 bck->fd = victim;
3873 }
a9177ff5 3874
fa8d436c
UD
3875 /*
3876 If a large request, scan through the chunks of current bin in
3877 sorted order to find smallest that fits. This is the only step
3878 where an unbounded number of chunks might be scanned without doing
3879 anything useful with them. However the lists tend to be short.
3880 */
a9177ff5 3881
fa8d436c
UD
3882 if (!in_smallbin_range(nb)) {
3883 bin = bin_at(av, idx);
f65fd747 3884
fa8d436c
UD
3885 /* skip scan if empty or largest chunk is too small */
3886 if ((victim = last(bin)) != bin &&
3887 (unsigned long)(first(bin)->size) >= (unsigned long)(nb)) {
f65fd747 3888
a9177ff5 3889 while (((unsigned long)(size = chunksize(victim)) <
fa8d436c
UD
3890 (unsigned long)(nb)))
3891 victim = victim->bk;
f65fd747 3892
fa8d436c
UD
3893 remainder_size = size - nb;
3894 unlink(victim, bck, fwd);
a9177ff5 3895
fa8d436c
UD
3896 /* Exhaust */
3897 if (remainder_size < MINSIZE) {
3898 set_inuse_bit_at_offset(victim, size);
3899 if (av != &main_arena)
3900 victim->size |= NON_MAIN_ARENA;
3901 check_malloced_chunk(av, victim, nb);
3902 return chunk2mem(victim);
3903 }
3904 /* Split */
3905 else {
3906 remainder = chunk_at_offset(victim, nb);
3907 unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
3908 remainder->bk = remainder->fd = unsorted_chunks(av);
3909 set_head(victim, nb | PREV_INUSE |
3910 (av != &main_arena ? NON_MAIN_ARENA : 0));
3911 set_head(remainder, remainder_size | PREV_INUSE);
3912 set_foot(remainder, remainder_size);
3913 check_malloced_chunk(av, victim, nb);
3914 return chunk2mem(victim);
a9177ff5 3915 }
fa8d436c 3916 }
a9177ff5 3917 }
f65fd747 3918
fa8d436c
UD
3919 /*
3920 Search for a chunk by scanning bins, starting with next largest
3921 bin. This search is strictly by best-fit; i.e., the smallest
3922 (with ties going to approximately the least recently used) chunk
3923 that fits is selected.
a9177ff5 3924
fa8d436c
UD
3925 The bitmap avoids needing to check that most blocks are nonempty.
3926 The particular case of skipping all bins during warm-up phases
3927 when no chunks have been returned yet is faster than it might look.
3928 */
a9177ff5 3929
fa8d436c
UD
3930 ++idx;
3931 bin = bin_at(av,idx);
3932 block = idx2block(idx);
3933 map = av->binmap[block];
3934 bit = idx2bit(idx);
a9177ff5 3935
fa8d436c
UD
3936 for (;;) {
3937
3938 /* Skip rest of block if there are no more set bits in this block. */
3939 if (bit > map || bit == 0) {
3940 do {
3941 if (++block >= BINMAPSIZE) /* out of bins */
3942 goto use_top;
3943 } while ( (map = av->binmap[block]) == 0);
3944
3945 bin = bin_at(av, (block << BINMAPSHIFT));
3946 bit = 1;
3947 }
a9177ff5 3948
fa8d436c
UD
3949 /* Advance to bin with set bit. There must be one. */
3950 while ((bit & map) == 0) {
3951 bin = next_bin(bin);
3952 bit <<= 1;
3953 assert(bit != 0);
3954 }
a9177ff5 3955
fa8d436c
UD
3956 /* Inspect the bin. It is likely to be non-empty */
3957 victim = last(bin);
a9177ff5 3958
fa8d436c
UD
3959 /* If a false alarm (empty bin), clear the bit. */
3960 if (victim == bin) {
3961 av->binmap[block] = map &= ~bit; /* Write through */
3962 bin = next_bin(bin);
3963 bit <<= 1;
3964 }
a9177ff5 3965
fa8d436c
UD
3966 else {
3967 size = chunksize(victim);
3968
3969 /* We know the first chunk in this bin is big enough to use. */
3970 assert((unsigned long)(size) >= (unsigned long)(nb));
3971
3972 remainder_size = size - nb;
a9177ff5 3973
fa8d436c
UD
3974 /* unlink */
3975 bck = victim->bk;
3976 bin->bk = bck;
3977 bck->fd = bin;
a9177ff5 3978
fa8d436c
UD
3979 /* Exhaust */
3980 if (remainder_size < MINSIZE) {
3981 set_inuse_bit_at_offset(victim, size);
3982 if (av != &main_arena)
3983 victim->size |= NON_MAIN_ARENA;
3984 check_malloced_chunk(av, victim, nb);
3985 return chunk2mem(victim);
3986 }
a9177ff5 3987
fa8d436c
UD
3988 /* Split */
3989 else {
3990 remainder = chunk_at_offset(victim, nb);
a9177ff5 3991
fa8d436c
UD
3992 unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
3993 remainder->bk = remainder->fd = unsorted_chunks(av);
3994 /* advertise as last remainder */
a9177ff5
RM
3995 if (in_smallbin_range(nb))
3996 av->last_remainder = remainder;
3997
fa8d436c
UD
3998 set_head(victim, nb | PREV_INUSE |
3999 (av != &main_arena ? NON_MAIN_ARENA : 0));
4000 set_head(remainder, remainder_size | PREV_INUSE);
4001 set_foot(remainder, remainder_size);
4002 check_malloced_chunk(av, victim, nb);
4003 return chunk2mem(victim);
4004 }
4005 }
4006 }
f65fd747 4007
a9177ff5 4008 use_top:
fa8d436c
UD
4009 /*
4010 If large enough, split off the chunk bordering the end of memory
4011 (held in av->top). Note that this is in accord with the best-fit
4012 search rule. In effect, av->top is treated as larger (and thus
4013 less well fitting) than any other available chunk since it can
4014 be extended to be as large as necessary (up to system
4015 limitations).
4016
4017 We require that av->top always exists (i.e., has size >=
4018 MINSIZE) after initialization, so if it would otherwise be
4019 exhuasted by current request, it is replenished. (The main
4020 reason for ensuring it exists is that we may need MINSIZE space
4021 to put in fenceposts in sysmalloc.)
4022 */
f65fd747 4023
fa8d436c
UD
4024 victim = av->top;
4025 size = chunksize(victim);
a9177ff5 4026
fa8d436c
UD
4027 if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
4028 remainder_size = size - nb;
4029 remainder = chunk_at_offset(victim, nb);
4030 av->top = remainder;
4031 set_head(victim, nb | PREV_INUSE |
4032 (av != &main_arena ? NON_MAIN_ARENA : 0));
4033 set_head(remainder, remainder_size | PREV_INUSE);
f65fd747 4034
fa8d436c
UD
4035 check_malloced_chunk(av, victim, nb);
4036 return chunk2mem(victim);
4037 }
f65fd747 4038
fa8d436c
UD
4039 /*
4040 If there is space available in fastbins, consolidate and retry,
4041 to possibly avoid expanding memory. This can occur only if nb is
4042 in smallbin range so we didn't consolidate upon entry.
4043 */
f65fd747 4044
fa8d436c
UD
4045 else if (have_fastchunks(av)) {
4046 assert(in_smallbin_range(nb));
4047 malloc_consolidate(av);
4048 idx = smallbin_index(nb); /* restore original bin index */
4049 }
f65fd747 4050
a9177ff5
RM
4051 /*
4052 Otherwise, relay to handle system-dependent cases
fa8d436c 4053 */
a9177ff5
RM
4054 else
4055 return sYSMALLOc(nb, av);
fa8d436c
UD
4056 }
4057}
f65fd747 4058
fa8d436c
UD
4059/*
4060 ------------------------------ free ------------------------------
f65fd747
UD
4061*/
4062
fa8d436c
UD
4063void
4064_int_free(mstate av, Void_t* mem)
f65fd747 4065{
fa8d436c
UD
4066 mchunkptr p; /* chunk corresponding to mem */
4067 INTERNAL_SIZE_T size; /* its size */
4068 mfastbinptr* fb; /* associated fastbin */
4069 mchunkptr nextchunk; /* next contiguous chunk */
4070 INTERNAL_SIZE_T nextsize; /* its size */
4071 int nextinuse; /* true if nextchunk is used */
4072 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
4073 mchunkptr bck; /* misc temp for linking */
4074 mchunkptr fwd; /* misc temp for linking */
4075
4076
4077 /* free(0) has no effect */
4078 if (mem != 0) {
4079 p = mem2chunk(mem);
4080 size = chunksize(p);
f65fd747 4081
fa8d436c 4082 check_inuse_chunk(av, p);
f65fd747 4083
fa8d436c
UD
4084 /*
4085 If eligible, place chunk on a fastbin so it can be found
4086 and used quickly in malloc.
4087 */
f65fd747 4088
fa8d436c 4089 if ((unsigned long)(size) <= (unsigned long)(av->max_fast)
f65fd747 4090
fa8d436c 4091#if TRIM_FASTBINS
a9177ff5 4092 /*
fa8d436c
UD
4093 If TRIM_FASTBINS set, don't place chunks
4094 bordering top into fastbins
4095 */
4096 && (chunk_at_offset(p, size) != av->top)
f65fd747 4097#endif
fa8d436c 4098 ) {
f65fd747 4099
fa8d436c
UD
4100 set_fastchunks(av);
4101 fb = &(av->fastbins[fastbin_index(size)]);
4102 p->fd = *fb;
4103 *fb = p;
4104 }
f65fd747 4105
fa8d436c
UD
4106 /*
4107 Consolidate other non-mmapped chunks as they arrive.
4108 */
f65fd747 4109
fa8d436c
UD
4110 else if (!chunk_is_mmapped(p)) {
4111 nextchunk = chunk_at_offset(p, size);
4112 nextsize = chunksize(nextchunk);
4113 assert(nextsize > 0);
4114
4115 /* consolidate backward */
4116 if (!prev_inuse(p)) {
4117 prevsize = p->prev_size;
4118 size += prevsize;
4119 p = chunk_at_offset(p, -((long) prevsize));
4120 unlink(p, bck, fwd);
4121 }
f65fd747 4122
fa8d436c
UD
4123 if (nextchunk != av->top) {
4124 /* get and clear inuse bit */
4125 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4126
4127 /* consolidate forward */
4128 if (!nextinuse) {
4129 unlink(nextchunk, bck, fwd);
4130 size += nextsize;
4131 } else
4132 clear_inuse_bit_at_offset(nextchunk, 0);
4133
4134 /*
4135 Place the chunk in unsorted chunk list. Chunks are
4136 not placed into regular bins until after they have
4137 been given one chance to be used in malloc.
4138 */
4139
4140 bck = unsorted_chunks(av);
4141 fwd = bck->fd;
4142 p->bk = bck;
4143 p->fd = fwd;
4144 bck->fd = p;
4145 fwd->bk = p;
4146
4147 set_head(p, size | PREV_INUSE);
4148 set_foot(p, size);
a9177ff5 4149
fa8d436c
UD
4150 check_free_chunk(av, p);
4151 }
10dc2a90 4152
fa8d436c
UD
4153 /*
4154 If the chunk borders the current high end of memory,
4155 consolidate into top
4156 */
f65fd747 4157
fa8d436c
UD
4158 else {
4159 size += nextsize;
4160 set_head(p, size | PREV_INUSE);
4161 av->top = p;
4162 check_chunk(av, p);
4163 }
8a4b65b4 4164
fa8d436c
UD
4165 /*
4166 If freeing a large space, consolidate possibly-surrounding
4167 chunks. Then, if the total unused topmost memory exceeds trim
4168 threshold, ask malloc_trim to reduce top.
4169
4170 Unless max_fast is 0, we don't know if there are fastbins
4171 bordering top, so we cannot tell for sure whether threshold
4172 has been reached unless fastbins are consolidated. But we
4173 don't want to consolidate on each free. As a compromise,
4174 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4175 is reached.
4176 */
4177
a9177ff5
RM
4178 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4179 if (have_fastchunks(av))
fa8d436c
UD
4180 malloc_consolidate(av);
4181
4182 if (av == &main_arena) {
a9177ff5
RM
4183#ifndef MORECORE_CANNOT_TRIM
4184 if ((unsigned long)(chunksize(av->top)) >=
fa8d436c
UD
4185 (unsigned long)(mp_.trim_threshold))
4186 sYSTRIm(mp_.top_pad, av);
4187#endif
4188 } else {
4189 /* Always try heap_trim(), even if the top chunk is not
4190 large, because the corresponding heap might go away. */
4191 heap_info *heap = heap_for_ptr(top(av));
4192
4193 assert(heap->ar_ptr == av);
4194 heap_trim(heap, mp_.top_pad);
4195 }
4196 }
f65fd747 4197
fa8d436c
UD
4198 }
4199 /*
4200 If the chunk was allocated via mmap, release via munmap(). Note
4201 that if HAVE_MMAP is false but chunk_is_mmapped is true, then
4202 user must have overwritten memory. There's nothing we can do to
4203 catch this error unless MALLOC_DEBUG is set, in which case
4204 check_inuse_chunk (above) will have triggered error.
4205 */
10dc2a90 4206
fa8d436c
UD
4207 else {
4208#if HAVE_MMAP
4209 int ret;
4210 INTERNAL_SIZE_T offset = p->prev_size;
4211 mp_.n_mmaps--;
4212 mp_.mmapped_mem -= (size + offset);
4213 ret = munmap((char*)p - offset, size + offset);
4214 /* munmap returns non-zero on failure */
4215 assert(ret == 0);
4216#endif
4217 }
4218 }
10dc2a90
UD
4219}
4220
fa8d436c
UD
4221/*
4222 ------------------------- malloc_consolidate -------------------------
4223
4224 malloc_consolidate is a specialized version of free() that tears
4225 down chunks held in fastbins. Free itself cannot be used for this
4226 purpose since, among other things, it might place chunks back onto
4227 fastbins. So, instead, we need to use a minor variant of the same
4228 code.
a9177ff5 4229
fa8d436c
UD
4230 Also, because this routine needs to be called the first time through
4231 malloc anyway, it turns out to be the perfect place to trigger
4232 initialization code.
4233*/
4234
10dc2a90 4235#if __STD_C
fa8d436c 4236static void malloc_consolidate(mstate av)
10dc2a90 4237#else
fa8d436c 4238static void malloc_consolidate(av) mstate av;
10dc2a90
UD
4239#endif
4240{
fa8d436c
UD
4241 mfastbinptr* fb; /* current fastbin being consolidated */
4242 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4243 mchunkptr p; /* current chunk being consolidated */
4244 mchunkptr nextp; /* next chunk to consolidate */
4245 mchunkptr unsorted_bin; /* bin header */
4246 mchunkptr first_unsorted; /* chunk to link to */
4247
4248 /* These have same use as in free() */
4249 mchunkptr nextchunk;
4250 INTERNAL_SIZE_T size;
4251 INTERNAL_SIZE_T nextsize;
4252 INTERNAL_SIZE_T prevsize;
4253 int nextinuse;
4254 mchunkptr bck;
4255 mchunkptr fwd;
10dc2a90 4256
fa8d436c
UD
4257 /*
4258 If max_fast is 0, we know that av hasn't
4259 yet been initialized, in which case do so below
4260 */
10dc2a90 4261
fa8d436c
UD
4262 if (av->max_fast != 0) {
4263 clear_fastchunks(av);
10dc2a90 4264
fa8d436c 4265 unsorted_bin = unsorted_chunks(av);
10dc2a90 4266
fa8d436c
UD
4267 /*
4268 Remove each chunk from fast bin and consolidate it, placing it
4269 then in unsorted bin. Among other reasons for doing this,
4270 placing in unsorted bin avoids needing to calculate actual bins
4271 until malloc is sure that chunks aren't immediately going to be
4272 reused anyway.
4273 */
a9177ff5 4274
fa8d436c
UD
4275 maxfb = &(av->fastbins[fastbin_index(av->max_fast)]);
4276 fb = &(av->fastbins[0]);
4277 do {
4278 if ( (p = *fb) != 0) {
4279 *fb = 0;
a9177ff5 4280
fa8d436c
UD
4281 do {
4282 check_inuse_chunk(av, p);
4283 nextp = p->fd;
a9177ff5 4284
fa8d436c
UD
4285 /* Slightly streamlined version of consolidation code in free() */
4286 size = p->size & ~(PREV_INUSE|NON_MAIN_ARENA);
4287 nextchunk = chunk_at_offset(p, size);
4288 nextsize = chunksize(nextchunk);
a9177ff5 4289
fa8d436c
UD
4290 if (!prev_inuse(p)) {
4291 prevsize = p->prev_size;
4292 size += prevsize;
4293 p = chunk_at_offset(p, -((long) prevsize));
4294 unlink(p, bck, fwd);
4295 }
a9177ff5 4296
fa8d436c
UD
4297 if (nextchunk != av->top) {
4298 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
a9177ff5 4299
fa8d436c
UD
4300 if (!nextinuse) {
4301 size += nextsize;
4302 unlink(nextchunk, bck, fwd);
4303 } else
4304 clear_inuse_bit_at_offset(nextchunk, 0);
a9177ff5 4305
fa8d436c
UD
4306 first_unsorted = unsorted_bin->fd;
4307 unsorted_bin->fd = p;
4308 first_unsorted->bk = p;
a9177ff5 4309
fa8d436c
UD
4310 set_head(p, size | PREV_INUSE);
4311 p->bk = unsorted_bin;
4312 p->fd = first_unsorted;
4313 set_foot(p, size);
4314 }
a9177ff5 4315
fa8d436c
UD
4316 else {
4317 size += nextsize;
4318 set_head(p, size | PREV_INUSE);
4319 av->top = p;
4320 }
a9177ff5 4321
fa8d436c 4322 } while ( (p = nextp) != 0);
a9177ff5 4323
fa8d436c
UD
4324 }
4325 } while (fb++ != maxfb);
4326 }
4327 else {
4328 malloc_init_state(av);
4329 check_malloc_state(av);
4330 }
4331}
10dc2a90 4332
fa8d436c
UD
4333/*
4334 ------------------------------ realloc ------------------------------
4335*/
f65fd747 4336
fa8d436c
UD
4337Void_t*
4338_int_realloc(mstate av, Void_t* oldmem, size_t bytes)
4339{
4340 INTERNAL_SIZE_T nb; /* padded request size */
f65fd747 4341
fa8d436c
UD
4342 mchunkptr oldp; /* chunk corresponding to oldmem */
4343 INTERNAL_SIZE_T oldsize; /* its size */
f65fd747 4344
fa8d436c
UD
4345 mchunkptr newp; /* chunk to return */
4346 INTERNAL_SIZE_T newsize; /* its size */
4347 Void_t* newmem; /* corresponding user mem */
f65fd747 4348
fa8d436c 4349 mchunkptr next; /* next contiguous chunk after oldp */
f65fd747 4350
fa8d436c
UD
4351 mchunkptr remainder; /* extra space at end of newp */
4352 unsigned long remainder_size; /* its size */
f65fd747 4353
fa8d436c
UD
4354 mchunkptr bck; /* misc temp for linking */
4355 mchunkptr fwd; /* misc temp for linking */
2ed5fd9a 4356
fa8d436c
UD
4357 unsigned long copysize; /* bytes to copy */
4358 unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
a9177ff5 4359 INTERNAL_SIZE_T* s; /* copy source */
fa8d436c 4360 INTERNAL_SIZE_T* d; /* copy destination */
f65fd747 4361
f65fd747 4362
fa8d436c
UD
4363#if REALLOC_ZERO_BYTES_FREES
4364 if (bytes == 0) {
4365 _int_free(av, oldmem);
4366 return 0;
4367 }
4368#endif
f65fd747 4369
fa8d436c
UD
4370 /* realloc of null is supposed to be same as malloc */
4371 if (oldmem == 0) return _int_malloc(av, bytes);
f65fd747 4372
fa8d436c 4373 checked_request2size(bytes, nb);
f65fd747 4374
fa8d436c
UD
4375 oldp = mem2chunk(oldmem);
4376 oldsize = chunksize(oldp);
f65fd747 4377
fa8d436c 4378 check_inuse_chunk(av, oldp);
f65fd747 4379
fa8d436c 4380 if (!chunk_is_mmapped(oldp)) {
f65fd747 4381
fa8d436c
UD
4382 if ((unsigned long)(oldsize) >= (unsigned long)(nb)) {
4383 /* already big enough; split below */
4384 newp = oldp;
4385 newsize = oldsize;
7799b7b3 4386 }
f65fd747 4387
fa8d436c
UD
4388 else {
4389 next = chunk_at_offset(oldp, oldsize);
4390
4391 /* Try to expand forward into top */
4392 if (next == av->top &&
4393 (unsigned long)(newsize = oldsize + chunksize(next)) >=
4394 (unsigned long)(nb + MINSIZE)) {
4395 set_head_size(oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4396 av->top = chunk_at_offset(oldp, nb);
4397 set_head(av->top, (newsize - nb) | PREV_INUSE);
4398 check_inuse_chunk(av, oldp);
4399 return chunk2mem(oldp);
4400 }
a9177ff5 4401
fa8d436c 4402 /* Try to expand forward into next chunk; split off remainder below */
a9177ff5 4403 else if (next != av->top &&
fa8d436c
UD
4404 !inuse(next) &&
4405 (unsigned long)(newsize = oldsize + chunksize(next)) >=
4406 (unsigned long)(nb)) {
4407 newp = oldp;
4408 unlink(next, bck, fwd);
4409 }
f65fd747 4410
fa8d436c
UD
4411 /* allocate, copy, free */
4412 else {
4413 newmem = _int_malloc(av, nb - MALLOC_ALIGN_MASK);
4414 if (newmem == 0)
4415 return 0; /* propagate failure */
a9177ff5 4416
fa8d436c
UD
4417 newp = mem2chunk(newmem);
4418 newsize = chunksize(newp);
a9177ff5 4419
fa8d436c
UD
4420 /*
4421 Avoid copy if newp is next chunk after oldp.
4422 */
4423 if (newp == next) {
4424 newsize += oldsize;
4425 newp = oldp;
4426 }
4427 else {
4428 /*
4429 Unroll copy of <= 36 bytes (72 if 8byte sizes)
4430 We know that contents have an odd number of
4431 INTERNAL_SIZE_T-sized words; minimally 3.
4432 */
a9177ff5 4433
fa8d436c
UD
4434 copysize = oldsize - SIZE_SZ;
4435 s = (INTERNAL_SIZE_T*)(oldmem);
4436 d = (INTERNAL_SIZE_T*)(newmem);
4437 ncopies = copysize / sizeof(INTERNAL_SIZE_T);
4438 assert(ncopies >= 3);
a9177ff5 4439
fa8d436c
UD
4440 if (ncopies > 9)
4441 MALLOC_COPY(d, s, copysize);
a9177ff5 4442
fa8d436c
UD
4443 else {
4444 *(d+0) = *(s+0);
4445 *(d+1) = *(s+1);
4446 *(d+2) = *(s+2);
4447 if (ncopies > 4) {
4448 *(d+3) = *(s+3);
4449 *(d+4) = *(s+4);
4450 if (ncopies > 6) {
4451 *(d+5) = *(s+5);
4452 *(d+6) = *(s+6);
4453 if (ncopies > 8) {
4454 *(d+7) = *(s+7);
4455 *(d+8) = *(s+8);
4456 }
4457 }
4458 }
4459 }
a9177ff5 4460
fa8d436c
UD
4461 _int_free(av, oldmem);
4462 check_inuse_chunk(av, newp);
4463 return chunk2mem(newp);
4464 }
4465 }
f65fd747
UD
4466 }
4467
fa8d436c 4468 /* If possible, free extra space in old or extended chunk */
f65fd747 4469
fa8d436c 4470 assert((unsigned long)(newsize) >= (unsigned long)(nb));
f65fd747 4471
f65fd747 4472 remainder_size = newsize - nb;
f65fd747 4473
fa8d436c
UD
4474 if (remainder_size < MINSIZE) { /* not enough extra to split off */
4475 set_head_size(newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4476 set_inuse_bit_at_offset(newp, newsize);
4477 }
4478 else { /* split remainder */
4479 remainder = chunk_at_offset(newp, nb);
4480 set_head_size(newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4481 set_head(remainder, remainder_size | PREV_INUSE |
4482 (av != &main_arena ? NON_MAIN_ARENA : 0));
4483 /* Mark remainder as inuse so free() won't complain */
4484 set_inuse_bit_at_offset(remainder, remainder_size);
a9177ff5 4485 _int_free(av, chunk2mem(remainder));
fa8d436c 4486 }
f65fd747 4487
fa8d436c
UD
4488 check_inuse_chunk(av, newp);
4489 return chunk2mem(newp);
4490 }
f65fd747 4491
fa8d436c
UD
4492 /*
4493 Handle mmap cases
4494 */
f65fd747 4495
fa8d436c
UD
4496 else {
4497#if HAVE_MMAP
f65fd747 4498
fa8d436c
UD
4499#if HAVE_MREMAP
4500 INTERNAL_SIZE_T offset = oldp->prev_size;
4501 size_t pagemask = mp_.pagesize - 1;
4502 char *cp;
4503 unsigned long sum;
a9177ff5 4504
fa8d436c
UD
4505 /* Note the extra SIZE_SZ overhead */
4506 newsize = (nb + offset + SIZE_SZ + pagemask) & ~pagemask;
4507
4508 /* don't need to remap if still within same page */
a9177ff5 4509 if (oldsize == newsize - offset)
fa8d436c
UD
4510 return oldmem;
4511
4512 cp = (char*)mremap((char*)oldp - offset, oldsize + offset, newsize, 1);
a9177ff5 4513
fa8d436c
UD
4514 if (cp != MAP_FAILED) {
4515
4516 newp = (mchunkptr)(cp + offset);
4517 set_head(newp, (newsize - offset)|IS_MMAPPED);
a9177ff5 4518
fa8d436c
UD
4519 assert(aligned_OK(chunk2mem(newp)));
4520 assert((newp->prev_size == offset));
a9177ff5 4521
fa8d436c
UD
4522 /* update statistics */
4523 sum = mp_.mmapped_mem += newsize - oldsize;
a9177ff5 4524 if (sum > (unsigned long)(mp_.max_mmapped_mem))
fa8d436c
UD
4525 mp_.max_mmapped_mem = sum;
4526#ifdef NO_THREADS
4527 sum += main_arena.system_mem;
a9177ff5 4528 if (sum > (unsigned long)(mp_.max_total_mem))
fa8d436c
UD
4529 mp_.max_total_mem = sum;
4530#endif
a9177ff5 4531
fa8d436c
UD
4532 return chunk2mem(newp);
4533 }
f65fd747 4534#endif
10dc2a90 4535
fa8d436c 4536 /* Note the extra SIZE_SZ overhead. */
a9177ff5 4537 if ((unsigned long)(oldsize) >= (unsigned long)(nb + SIZE_SZ))
fa8d436c
UD
4538 newmem = oldmem; /* do nothing */
4539 else {
4540 /* Must alloc, copy, free. */
4541 newmem = _int_malloc(av, nb - MALLOC_ALIGN_MASK);
4542 if (newmem != 0) {
4543 MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
4544 _int_free(av, oldmem);
4545 }
4546 }
4547 return newmem;
10dc2a90 4548
a9177ff5 4549#else
fa8d436c
UD
4550 /* If !HAVE_MMAP, but chunk_is_mmapped, user must have overwritten mem */
4551 check_malloc_state(av);
4552 MALLOC_FAILURE_ACTION;
4553 return 0;
a2b08ee5 4554#endif
10dc2a90 4555 }
fa8d436c
UD
4556}
4557
4558/*
4559 ------------------------------ memalign ------------------------------
4560*/
4561
4562Void_t*
4563_int_memalign(mstate av, size_t alignment, size_t bytes)
4564{
4565 INTERNAL_SIZE_T nb; /* padded request size */
4566 char* m; /* memory returned by malloc call */
4567 mchunkptr p; /* corresponding chunk */
4568 char* brk; /* alignment point within p */
4569 mchunkptr newp; /* chunk to return */
4570 INTERNAL_SIZE_T newsize; /* its size */
4571 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4572 mchunkptr remainder; /* spare room at end to split off */
4573 unsigned long remainder_size; /* its size */
4574 INTERNAL_SIZE_T size;
f65fd747
UD
4575
4576 /* If need less alignment than we give anyway, just relay to malloc */
4577
fa8d436c 4578 if (alignment <= MALLOC_ALIGNMENT) return _int_malloc(av, bytes);
f65fd747
UD
4579
4580 /* Otherwise, ensure that it is at least a minimum chunk size */
4581
4582 if (alignment < MINSIZE) alignment = MINSIZE;
4583
fa8d436c
UD
4584 /* Make sure alignment is power of 2 (in case MINSIZE is not). */
4585 if ((alignment & (alignment - 1)) != 0) {
4586 size_t a = MALLOC_ALIGNMENT * 2;
4587 while ((unsigned long)a < (unsigned long)alignment) a <<= 1;
4588 alignment = a;
7799b7b3 4589 }
f65fd747 4590
fa8d436c
UD
4591 checked_request2size(bytes, nb);
4592
4593 /*
4594 Strategy: find a spot within that chunk that meets the alignment
4595 request, and then possibly free the leading and trailing space.
4596 */
4597
4598
4599 /* Call malloc with worst case padding to hit alignment. */
4600
4601 m = (char*)(_int_malloc(av, nb + alignment + MINSIZE));
4602
4603 if (m == 0) return 0; /* propagate failure */
4604
4605 p = mem2chunk(m);
4606
4607 if ((((unsigned long)(m)) % alignment) != 0) { /* misaligned */
4608
f65fd747 4609 /*
fa8d436c
UD
4610 Find an aligned spot inside chunk. Since we need to give back
4611 leading space in a chunk of at least MINSIZE, if the first
4612 calculation places us at a spot with less than MINSIZE leader,
4613 we can move to the next aligned spot -- we've allocated enough
4614 total room so that this is always possible.
f65fd747
UD
4615 */
4616
fa8d436c
UD
4617 brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) &
4618 -((signed long) alignment));
4619 if ((unsigned long)(brk - (char*)(p)) < MINSIZE)
4620 brk += alignment;
f65fd747 4621
fa8d436c 4622 newp = (mchunkptr)brk;
f65fd747
UD
4623 leadsize = brk - (char*)(p);
4624 newsize = chunksize(p) - leadsize;
4625
fa8d436c
UD
4626 /* For mmapped chunks, just adjust offset */
4627 if (chunk_is_mmapped(p)) {
f65fd747
UD
4628 newp->prev_size = p->prev_size + leadsize;
4629 set_head(newp, newsize|IS_MMAPPED);
fa8d436c 4630 return chunk2mem(newp);
f65fd747 4631 }
f65fd747 4632
fa8d436c
UD
4633 /* Otherwise, give back leader, use the rest */
4634 set_head(newp, newsize | PREV_INUSE |
4635 (av != &main_arena ? NON_MAIN_ARENA : 0));
f65fd747 4636 set_inuse_bit_at_offset(newp, newsize);
fa8d436c
UD
4637 set_head_size(p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4638 _int_free(av, chunk2mem(p));
f65fd747
UD
4639 p = newp;
4640
fa8d436c
UD
4641 assert (newsize >= nb &&
4642 (((unsigned long)(chunk2mem(p))) % alignment) == 0);
f65fd747
UD
4643 }
4644
4645 /* Also give back spare room at the end */
fa8d436c
UD
4646 if (!chunk_is_mmapped(p)) {
4647 size = chunksize(p);
4648 if ((unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
4649 remainder_size = size - nb;
4650 remainder = chunk_at_offset(p, nb);
4651 set_head(remainder, remainder_size | PREV_INUSE |
4652 (av != &main_arena ? NON_MAIN_ARENA : 0));
4653 set_head_size(p, nb);
4654 _int_free(av, chunk2mem(remainder));
4655 }
f65fd747
UD
4656 }
4657
fa8d436c
UD
4658 check_inuse_chunk(av, p);
4659 return chunk2mem(p);
f65fd747
UD
4660}
4661
fa8d436c
UD
4662#if 0
4663/*
4664 ------------------------------ calloc ------------------------------
4665*/
4666
4667#if __STD_C
4668Void_t* cALLOc(size_t n_elements, size_t elem_size)
4669#else
4670Void_t* cALLOc(n_elements, elem_size) size_t n_elements; size_t elem_size;
4671#endif
4672{
4673 mchunkptr p;
4674 unsigned long clearsize;
4675 unsigned long nclears;
4676 INTERNAL_SIZE_T* d;
4677
4678 Void_t* mem = mALLOc(n_elements * elem_size);
4679
4680 if (mem != 0) {
4681 p = mem2chunk(mem);
4682
4683#if MMAP_CLEARS
4684 if (!chunk_is_mmapped(p)) /* don't need to clear mmapped space */
4685#endif
a9177ff5 4686 {
fa8d436c
UD
4687 /*
4688 Unroll clear of <= 36 bytes (72 if 8byte sizes)
4689 We know that contents have an odd number of
4690 INTERNAL_SIZE_T-sized words; minimally 3.
4691 */
4692
4693 d = (INTERNAL_SIZE_T*)mem;
4694 clearsize = chunksize(p) - SIZE_SZ;
4695 nclears = clearsize / sizeof(INTERNAL_SIZE_T);
4696 assert(nclears >= 3);
f65fd747 4697
fa8d436c
UD
4698 if (nclears > 9)
4699 MALLOC_ZERO(d, clearsize);
4700
4701 else {
4702 *(d+0) = 0;
4703 *(d+1) = 0;
4704 *(d+2) = 0;
4705 if (nclears > 4) {
4706 *(d+3) = 0;
4707 *(d+4) = 0;
4708 if (nclears > 6) {
4709 *(d+5) = 0;
4710 *(d+6) = 0;
4711 if (nclears > 8) {
4712 *(d+7) = 0;
4713 *(d+8) = 0;
4714 }
4715 }
4716 }
4717 }
4718 }
4719 }
4720 return mem;
4721}
4722#endif /* 0 */
f65fd747
UD
4723
4724/*
fa8d436c 4725 ------------------------- independent_calloc -------------------------
f65fd747
UD
4726*/
4727
fa8d436c 4728Void_t**
f65fd747 4729#if __STD_C
fa8d436c 4730_int_icalloc(mstate av, size_t n_elements, size_t elem_size, Void_t* chunks[])
f65fd747 4731#else
fa8d436c
UD
4732_int_icalloc(av, n_elements, elem_size, chunks)
4733mstate av; size_t n_elements; size_t elem_size; Void_t* chunks[];
f65fd747
UD
4734#endif
4735{
fa8d436c
UD
4736 size_t sz = elem_size; /* serves as 1-element array */
4737 /* opts arg of 3 means all elements are same size, and should be cleared */
4738 return iALLOc(av, n_elements, &sz, 3, chunks);
f65fd747
UD
4739}
4740
4741/*
fa8d436c 4742 ------------------------- independent_comalloc -------------------------
f65fd747
UD
4743*/
4744
fa8d436c 4745Void_t**
f65fd747 4746#if __STD_C
fa8d436c 4747_int_icomalloc(mstate av, size_t n_elements, size_t sizes[], Void_t* chunks[])
f65fd747 4748#else
fa8d436c
UD
4749_int_icomalloc(av, n_elements, sizes, chunks)
4750mstate av; size_t n_elements; size_t sizes[]; Void_t* chunks[];
f65fd747
UD
4751#endif
4752{
fa8d436c 4753 return iALLOc(av, n_elements, sizes, 0, chunks);
f65fd747
UD
4754}
4755
f65fd747 4756
fa8d436c
UD
4757/*
4758 ------------------------------ ialloc ------------------------------
4759 ialloc provides common support for independent_X routines, handling all of
4760 the combinations that can result.
f65fd747 4761
fa8d436c
UD
4762 The opts arg has:
4763 bit 0 set if all elements are same size (using sizes[0])
4764 bit 1 set if elements should be zeroed
f65fd747
UD
4765*/
4766
fa8d436c
UD
4767
4768static Void_t**
f65fd747 4769#if __STD_C
fa8d436c 4770iALLOc(mstate av, size_t n_elements, size_t* sizes, int opts, Void_t* chunks[])
f65fd747 4771#else
fa8d436c
UD
4772iALLOc(av, n_elements, sizes, opts, chunks)
4773mstate av; size_t n_elements; size_t* sizes; int opts; Void_t* chunks[];
f65fd747
UD
4774#endif
4775{
fa8d436c
UD
4776 INTERNAL_SIZE_T element_size; /* chunksize of each element, if all same */
4777 INTERNAL_SIZE_T contents_size; /* total size of elements */
4778 INTERNAL_SIZE_T array_size; /* request size of pointer array */
4779 Void_t* mem; /* malloced aggregate space */
4780 mchunkptr p; /* corresponding chunk */
4781 INTERNAL_SIZE_T remainder_size; /* remaining bytes while splitting */
4782 Void_t** marray; /* either "chunks" or malloced ptr array */
4783 mchunkptr array_chunk; /* chunk for malloced ptr array */
4784 int mmx; /* to disable mmap */
a9177ff5 4785 INTERNAL_SIZE_T size;
fa8d436c
UD
4786 INTERNAL_SIZE_T size_flags;
4787 size_t i;
4788
4789 /* Ensure initialization/consolidation */
4790 if (have_fastchunks(av)) malloc_consolidate(av);
4791
4792 /* compute array length, if needed */
4793 if (chunks != 0) {
4794 if (n_elements == 0)
4795 return chunks; /* nothing to do */
4796 marray = chunks;
4797 array_size = 0;
4798 }
4799 else {
4800 /* if empty req, must still return chunk representing empty array */
a9177ff5 4801 if (n_elements == 0)
fa8d436c
UD
4802 return (Void_t**) _int_malloc(av, 0);
4803 marray = 0;
4804 array_size = request2size(n_elements * (sizeof(Void_t*)));
4805 }
f65fd747 4806
fa8d436c
UD
4807 /* compute total element size */
4808 if (opts & 0x1) { /* all-same-size */
4809 element_size = request2size(*sizes);
4810 contents_size = n_elements * element_size;
4811 }
4812 else { /* add up all the sizes */
4813 element_size = 0;
4814 contents_size = 0;
a9177ff5
RM
4815 for (i = 0; i != n_elements; ++i)
4816 contents_size += request2size(sizes[i]);
10dc2a90 4817 }
f65fd747 4818
fa8d436c
UD
4819 /* subtract out alignment bytes from total to minimize overallocation */
4820 size = contents_size + array_size - MALLOC_ALIGN_MASK;
a9177ff5
RM
4821
4822 /*
fa8d436c
UD
4823 Allocate the aggregate chunk.
4824 But first disable mmap so malloc won't use it, since
4825 we would not be able to later free/realloc space internal
4826 to a segregated mmap region.
4827 */
4828 mmx = mp_.n_mmaps_max; /* disable mmap */
4829 mp_.n_mmaps_max = 0;
4830 mem = _int_malloc(av, size);
4831 mp_.n_mmaps_max = mmx; /* reset mmap */
a9177ff5 4832 if (mem == 0)
f65fd747
UD
4833 return 0;
4834
fa8d436c 4835 p = mem2chunk(mem);
a9177ff5 4836 assert(!chunk_is_mmapped(p));
fa8d436c 4837 remainder_size = chunksize(p);
f65fd747 4838
fa8d436c
UD
4839 if (opts & 0x2) { /* optionally clear the elements */
4840 MALLOC_ZERO(mem, remainder_size - SIZE_SZ - array_size);
7799b7b3 4841 }
f65fd747 4842
fa8d436c 4843 size_flags = PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0);
f65fd747 4844
fa8d436c
UD
4845 /* If not provided, allocate the pointer array as final part of chunk */
4846 if (marray == 0) {
4847 array_chunk = chunk_at_offset(p, contents_size);
4848 marray = (Void_t**) (chunk2mem(array_chunk));
4849 set_head(array_chunk, (remainder_size - contents_size) | size_flags);
4850 remainder_size = contents_size;
4851 }
f65fd747 4852
fa8d436c
UD
4853 /* split out elements */
4854 for (i = 0; ; ++i) {
4855 marray[i] = chunk2mem(p);
4856 if (i != n_elements-1) {
a9177ff5 4857 if (element_size != 0)
fa8d436c
UD
4858 size = element_size;
4859 else
a9177ff5 4860 size = request2size(sizes[i]);
fa8d436c
UD
4861 remainder_size -= size;
4862 set_head(p, size | size_flags);
4863 p = chunk_at_offset(p, size);
4864 }
4865 else { /* the final element absorbs any overallocation slop */
4866 set_head(p, remainder_size | size_flags);
4867 break;
4868 }
4869 }
f65fd747 4870
fa8d436c
UD
4871#if MALLOC_DEBUG
4872 if (marray != chunks) {
4873 /* final element must have exactly exhausted chunk */
a9177ff5 4874 if (element_size != 0)
fa8d436c
UD
4875 assert(remainder_size == element_size);
4876 else
4877 assert(remainder_size == request2size(sizes[i]));
4878 check_inuse_chunk(av, mem2chunk(marray));
7799b7b3 4879 }
fa8d436c
UD
4880
4881 for (i = 0; i != n_elements; ++i)
4882 check_inuse_chunk(av, mem2chunk(marray[i]));
f65fd747
UD
4883#endif
4884
fa8d436c 4885 return marray;
f65fd747
UD
4886}
4887
f65fd747 4888
fa8d436c
UD
4889/*
4890 ------------------------------ valloc ------------------------------
f65fd747
UD
4891*/
4892
fa8d436c 4893Void_t*
f65fd747 4894#if __STD_C
fa8d436c 4895_int_valloc(mstate av, size_t bytes)
f65fd747 4896#else
fa8d436c 4897_int_valloc(av, bytes) mstate av; size_t bytes;
f65fd747
UD
4898#endif
4899{
fa8d436c
UD
4900 /* Ensure initialization/consolidation */
4901 if (have_fastchunks(av)) malloc_consolidate(av);
4902 return _int_memalign(av, mp_.pagesize, bytes);
f65fd747 4903}
f65fd747
UD
4904
4905/*
fa8d436c 4906 ------------------------------ pvalloc ------------------------------
f65fd747
UD
4907*/
4908
fa8d436c
UD
4909
4910Void_t*
f65fd747 4911#if __STD_C
fa8d436c 4912_int_pvalloc(mstate av, size_t bytes)
f65fd747 4913#else
fa8d436c 4914_int_pvalloc(av, bytes) mstate av, size_t bytes;
f65fd747
UD
4915#endif
4916{
fa8d436c 4917 size_t pagesz;
f65fd747 4918
fa8d436c
UD
4919 /* Ensure initialization/consolidation */
4920 if (have_fastchunks(av)) malloc_consolidate(av);
4921 pagesz = mp_.pagesize;
4922 return _int_memalign(av, pagesz, (bytes + pagesz - 1) & ~(pagesz - 1));
f65fd747 4923}
a9177ff5 4924
f65fd747 4925
fa8d436c
UD
4926/*
4927 ------------------------------ malloc_trim ------------------------------
4928*/
8a4b65b4 4929
f65fd747 4930#if __STD_C
fa8d436c 4931int mTRIm(size_t pad)
f65fd747 4932#else
fa8d436c 4933int mTRIm(pad) size_t pad;
f65fd747
UD
4934#endif
4935{
fa8d436c 4936 mstate av = &main_arena; /* already locked */
f65fd747 4937
fa8d436c
UD
4938 /* Ensure initialization/consolidation */
4939 malloc_consolidate(av);
8a4b65b4 4940
a9177ff5 4941#ifndef MORECORE_CANNOT_TRIM
fa8d436c 4942 return sYSTRIm(pad, av);
8a4b65b4 4943#else
fa8d436c 4944 return 0;
f65fd747 4945#endif
f65fd747
UD
4946}
4947
f65fd747
UD
4948
4949/*
fa8d436c 4950 ------------------------- malloc_usable_size -------------------------
f65fd747
UD
4951*/
4952
4953#if __STD_C
fa8d436c 4954size_t mUSABLe(Void_t* mem)
f65fd747 4955#else
fa8d436c 4956size_t mUSABLe(mem) Void_t* mem;
f65fd747
UD
4957#endif
4958{
4959 mchunkptr p;
fa8d436c 4960 if (mem != 0) {
f65fd747 4961 p = mem2chunk(mem);
fa8d436c
UD
4962 if (chunk_is_mmapped(p))
4963 return chunksize(p) - 2*SIZE_SZ;
4964 else if (inuse(p))
f65fd747 4965 return chunksize(p) - SIZE_SZ;
f65fd747 4966 }
fa8d436c 4967 return 0;
f65fd747
UD
4968}
4969
fa8d436c
UD
4970/*
4971 ------------------------------ mallinfo ------------------------------
4972*/
f65fd747 4973
fa8d436c 4974struct mallinfo mALLINFo(mstate av)
f65fd747 4975{
fa8d436c
UD
4976 struct mallinfo mi;
4977 int i;
f65fd747
UD
4978 mbinptr b;
4979 mchunkptr p;
f65fd747 4980 INTERNAL_SIZE_T avail;
fa8d436c
UD
4981 INTERNAL_SIZE_T fastavail;
4982 int nblocks;
4983 int nfastblocks;
f65fd747 4984
fa8d436c
UD
4985 /* Ensure initialization */
4986 if (av->top == 0) malloc_consolidate(av);
8a4b65b4 4987
fa8d436c 4988 check_malloc_state(av);
8a4b65b4 4989
fa8d436c
UD
4990 /* Account for top */
4991 avail = chunksize(av->top);
4992 nblocks = 1; /* top always exists */
f65fd747 4993
fa8d436c
UD
4994 /* traverse fastbins */
4995 nfastblocks = 0;
4996 fastavail = 0;
4997
4998 for (i = 0; i < NFASTBINS; ++i) {
4999 for (p = av->fastbins[i]; p != 0; p = p->fd) {
5000 ++nfastblocks;
5001 fastavail += chunksize(p);
5002 }
5003 }
5004
5005 avail += fastavail;
f65fd747 5006
fa8d436c
UD
5007 /* traverse regular bins */
5008 for (i = 1; i < NBINS; ++i) {
5009 b = bin_at(av, i);
5010 for (p = last(b); p != b; p = p->bk) {
5011 ++nblocks;
5012 avail += chunksize(p);
5013 }
5014 }
f65fd747 5015
fa8d436c
UD
5016 mi.smblks = nfastblocks;
5017 mi.ordblks = nblocks;
5018 mi.fordblks = avail;
5019 mi.uordblks = av->system_mem - avail;
5020 mi.arena = av->system_mem;
5021 mi.hblks = mp_.n_mmaps;
5022 mi.hblkhd = mp_.mmapped_mem;
5023 mi.fsmblks = fastavail;
5024 mi.keepcost = chunksize(av->top);
5025 mi.usmblks = mp_.max_total_mem;
5026 return mi;
5027}
f65fd747 5028
fa8d436c
UD
5029/*
5030 ------------------------------ malloc_stats ------------------------------
f65fd747
UD
5031*/
5032
fa8d436c 5033void mSTATs()
f65fd747 5034{
8a4b65b4 5035 int i;
fa8d436c 5036 mstate ar_ptr;
8a4b65b4 5037 struct mallinfo mi;
fa8d436c 5038 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
8a4b65b4
UD
5039#if THREAD_STATS
5040 long stat_lock_direct = 0, stat_lock_loop = 0, stat_lock_wait = 0;
5041#endif
5042
fa8d436c
UD
5043 for (i=0, ar_ptr = &main_arena;; i++) {
5044 (void)mutex_lock(&ar_ptr->mutex);
5045 mi = mALLINFo(ar_ptr);
8a4b65b4
UD
5046 fprintf(stderr, "Arena %d:\n", i);
5047 fprintf(stderr, "system bytes = %10u\n", (unsigned int)mi.arena);
5048 fprintf(stderr, "in use bytes = %10u\n", (unsigned int)mi.uordblks);
fa8d436c
UD
5049#if MALLOC_DEBUG > 1
5050 if (i > 0)
5051 dump_heap(heap_for_ptr(top(ar_ptr)));
5052#endif
8a4b65b4
UD
5053 system_b += mi.arena;
5054 in_use_b += mi.uordblks;
5055#if THREAD_STATS
5056 stat_lock_direct += ar_ptr->stat_lock_direct;
5057 stat_lock_loop += ar_ptr->stat_lock_loop;
5058 stat_lock_wait += ar_ptr->stat_lock_wait;
5059#endif
fa8d436c 5060 (void)mutex_unlock(&ar_ptr->mutex);
7e3be507
UD
5061 ar_ptr = ar_ptr->next;
5062 if(ar_ptr == &main_arena) break;
8a4b65b4 5063 }
7799b7b3 5064#if HAVE_MMAP
8a4b65b4 5065 fprintf(stderr, "Total (incl. mmap):\n");
7799b7b3
UD
5066#else
5067 fprintf(stderr, "Total:\n");
5068#endif
8a4b65b4
UD
5069 fprintf(stderr, "system bytes = %10u\n", system_b);
5070 fprintf(stderr, "in use bytes = %10u\n", in_use_b);
5071#ifdef NO_THREADS
fa8d436c 5072 fprintf(stderr, "max system bytes = %10u\n", (unsigned int)mp_.max_total_mem);
8a4b65b4 5073#endif
f65fd747 5074#if HAVE_MMAP
fa8d436c
UD
5075 fprintf(stderr, "max mmap regions = %10u\n", (unsigned int)mp_.max_n_mmaps);
5076 fprintf(stderr, "max mmap bytes = %10lu\n",
5077 (unsigned long)mp_.max_mmapped_mem);
f65fd747
UD
5078#endif
5079#if THREAD_STATS
8a4b65b4 5080 fprintf(stderr, "heaps created = %10d\n", stat_n_heaps);
f65fd747
UD
5081 fprintf(stderr, "locked directly = %10ld\n", stat_lock_direct);
5082 fprintf(stderr, "locked in loop = %10ld\n", stat_lock_loop);
8a4b65b4
UD
5083 fprintf(stderr, "locked waiting = %10ld\n", stat_lock_wait);
5084 fprintf(stderr, "locked total = %10ld\n",
5085 stat_lock_direct + stat_lock_loop + stat_lock_wait);
f65fd747
UD
5086#endif
5087}
5088
f65fd747
UD
5089
5090/*
fa8d436c 5091 ------------------------------ mallopt ------------------------------
f65fd747
UD
5092*/
5093
5094#if __STD_C
5095int mALLOPt(int param_number, int value)
5096#else
5097int mALLOPt(param_number, value) int param_number; int value;
5098#endif
5099{
fa8d436c
UD
5100 mstate av = &main_arena;
5101 int res = 1;
f65fd747 5102
fa8d436c
UD
5103 (void)mutex_lock(&av->mutex);
5104 /* Ensure initialization/consolidation */
5105 malloc_consolidate(av);
2f6d1f1b 5106
fa8d436c
UD
5107 switch(param_number) {
5108 case M_MXFAST:
5109 if (value >= 0 && value <= MAX_FAST_SIZE) {
5110 set_max_fast(av, value);
5111 }
5112 else
5113 res = 0;
5114 break;
2f6d1f1b 5115
fa8d436c
UD
5116 case M_TRIM_THRESHOLD:
5117 mp_.trim_threshold = value;
5118 break;
2f6d1f1b 5119
fa8d436c
UD
5120 case M_TOP_PAD:
5121 mp_.top_pad = value;
5122 break;
2f6d1f1b 5123
fa8d436c
UD
5124 case M_MMAP_THRESHOLD:
5125#if USE_ARENAS
5126 /* Forbid setting the threshold too high. */
5127 if((unsigned long)value > HEAP_MAX_SIZE/2)
5128 res = 0;
5129 else
2f6d1f1b 5130#endif
fa8d436c
UD
5131 mp_.mmap_threshold = value;
5132 break;
2f6d1f1b 5133
fa8d436c
UD
5134 case M_MMAP_MAX:
5135#if !HAVE_MMAP
5136 if (value != 0)
5137 res = 0;
5138 else
9a51759b 5139#endif
fa8d436c
UD
5140 mp_.n_mmaps_max = value;
5141 break;
10dc2a90 5142
fa8d436c
UD
5143 case M_CHECK_ACTION:
5144 check_action = value;
5145 break;
b22fc5f5 5146 }
fa8d436c
UD
5147 (void)mutex_unlock(&av->mutex);
5148 return res;
b22fc5f5
UD
5149}
5150
10dc2a90 5151
a9177ff5 5152/*
fa8d436c
UD
5153 -------------------- Alternative MORECORE functions --------------------
5154*/
10dc2a90 5155
b22fc5f5 5156
fa8d436c
UD
5157/*
5158 General Requirements for MORECORE.
b22fc5f5 5159
fa8d436c 5160 The MORECORE function must have the following properties:
b22fc5f5 5161
fa8d436c 5162 If MORECORE_CONTIGUOUS is false:
10dc2a90 5163
fa8d436c
UD
5164 * MORECORE must allocate in multiples of pagesize. It will
5165 only be called with arguments that are multiples of pagesize.
10dc2a90 5166
a9177ff5 5167 * MORECORE(0) must return an address that is at least
fa8d436c 5168 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
10dc2a90 5169
fa8d436c 5170 else (i.e. If MORECORE_CONTIGUOUS is true):
10dc2a90 5171
fa8d436c
UD
5172 * Consecutive calls to MORECORE with positive arguments
5173 return increasing addresses, indicating that space has been
5174 contiguously extended.
10dc2a90 5175
fa8d436c
UD
5176 * MORECORE need not allocate in multiples of pagesize.
5177 Calls to MORECORE need not have args of multiples of pagesize.
10dc2a90 5178
fa8d436c 5179 * MORECORE need not page-align.
10dc2a90 5180
fa8d436c 5181 In either case:
10dc2a90 5182
fa8d436c
UD
5183 * MORECORE may allocate more memory than requested. (Or even less,
5184 but this will generally result in a malloc failure.)
10dc2a90 5185
fa8d436c
UD
5186 * MORECORE must not allocate memory when given argument zero, but
5187 instead return one past the end address of memory from previous
5188 nonzero call. This malloc does NOT call MORECORE(0)
5189 until at least one call with positive arguments is made, so
5190 the initial value returned is not important.
10dc2a90 5191
fa8d436c
UD
5192 * Even though consecutive calls to MORECORE need not return contiguous
5193 addresses, it must be OK for malloc'ed chunks to span multiple
5194 regions in those cases where they do happen to be contiguous.
10dc2a90 5195
fa8d436c
UD
5196 * MORECORE need not handle negative arguments -- it may instead
5197 just return MORECORE_FAILURE when given negative arguments.
5198 Negative arguments are always multiples of pagesize. MORECORE
5199 must not misinterpret negative args as large positive unsigned
5200 args. You can suppress all such calls from even occurring by defining
5201 MORECORE_CANNOT_TRIM,
10dc2a90 5202
fa8d436c
UD
5203 There is some variation across systems about the type of the
5204 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
5205 actually be size_t, because sbrk supports negative args, so it is
5206 normally the signed type of the same width as size_t (sometimes
5207 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
5208 matter though. Internally, we use "long" as arguments, which should
5209 work across all reasonable possibilities.
ee74a442 5210
fa8d436c
UD
5211 Additionally, if MORECORE ever returns failure for a positive
5212 request, and HAVE_MMAP is true, then mmap is used as a noncontiguous
5213 system allocator. This is a useful backup strategy for systems with
5214 holes in address spaces -- in this case sbrk cannot contiguously
5215 expand the heap, but mmap may be able to map noncontiguous space.
7e3be507 5216
fa8d436c
UD
5217 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
5218 a function that always returns MORECORE_FAILURE.
2e65ca2b 5219
fa8d436c
UD
5220 If you are using this malloc with something other than sbrk (or its
5221 emulation) to supply memory regions, you probably want to set
5222 MORECORE_CONTIGUOUS as false. As an example, here is a custom
5223 allocator kindly contributed for pre-OSX macOS. It uses virtually
5224 but not necessarily physically contiguous non-paged memory (locked
5225 in, present and won't get swapped out). You can use it by
5226 uncommenting this section, adding some #includes, and setting up the
5227 appropriate defines above:
7e3be507 5228
fa8d436c
UD
5229 #define MORECORE osMoreCore
5230 #define MORECORE_CONTIGUOUS 0
7e3be507 5231
fa8d436c
UD
5232 There is also a shutdown routine that should somehow be called for
5233 cleanup upon program exit.
7e3be507 5234
fa8d436c
UD
5235 #define MAX_POOL_ENTRIES 100
5236 #define MINIMUM_MORECORE_SIZE (64 * 1024)
5237 static int next_os_pool;
5238 void *our_os_pools[MAX_POOL_ENTRIES];
7e3be507 5239
fa8d436c
UD
5240 void *osMoreCore(int size)
5241 {
5242 void *ptr = 0;
5243 static void *sbrk_top = 0;
ca34d7a7 5244
fa8d436c
UD
5245 if (size > 0)
5246 {
5247 if (size < MINIMUM_MORECORE_SIZE)
5248 size = MINIMUM_MORECORE_SIZE;
5249 if (CurrentExecutionLevel() == kTaskLevel)
5250 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
5251 if (ptr == 0)
5252 {
5253 return (void *) MORECORE_FAILURE;
5254 }
5255 // save ptrs so they can be freed during cleanup
5256 our_os_pools[next_os_pool] = ptr;
5257 next_os_pool++;
5258 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
5259 sbrk_top = (char *) ptr + size;
5260 return ptr;
5261 }
5262 else if (size < 0)
5263 {
5264 // we don't currently support shrink behavior
5265 return (void *) MORECORE_FAILURE;
5266 }
5267 else
5268 {
5269 return sbrk_top;
431c33c0 5270 }
ca34d7a7 5271 }
ca34d7a7 5272
fa8d436c
UD
5273 // cleanup any allocated memory pools
5274 // called as last thing before shutting down driver
ca34d7a7 5275
fa8d436c 5276 void osCleanupMem(void)
ca34d7a7 5277 {
fa8d436c 5278 void **ptr;
ca34d7a7 5279
fa8d436c
UD
5280 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
5281 if (*ptr)
5282 {
5283 PoolDeallocate(*ptr);
5284 *ptr = 0;
5285 }
5286 }
ee74a442 5287
fa8d436c 5288*/
f65fd747 5289
7e3be507
UD
5290
5291#ifdef _LIBC
b2bffca2 5292# include <sys/param.h>
fa8d436c 5293
a204dbb2
UD
5294/* We need a wrapper function for one of the additions of POSIX. */
5295int
5296__posix_memalign (void **memptr, size_t alignment, size_t size)
5297{
5298 void *mem;
5299
5300 /* Test whether the SIZE argument is valid. It must be a power of
5301 two multiple of sizeof (void *). */
b2bffca2 5302 if (alignment % sizeof (void *) != 0 || !powerof2 (alignment) != 0)
a204dbb2
UD
5303 return EINVAL;
5304
5305 mem = __libc_memalign (alignment, size);
5306
fa8d436c
UD
5307 if (mem != NULL) {
5308 *memptr = mem;
5309 return 0;
5310 }
a204dbb2
UD
5311
5312 return ENOMEM;
5313}
5314weak_alias (__posix_memalign, posix_memalign)
5315
7e3be507
UD
5316weak_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5317weak_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5318weak_alias (__libc_free, __free) weak_alias (__libc_free, free)
5319weak_alias (__libc_malloc, __malloc) weak_alias (__libc_malloc, malloc)
5320weak_alias (__libc_memalign, __memalign) weak_alias (__libc_memalign, memalign)
5321weak_alias (__libc_realloc, __realloc) weak_alias (__libc_realloc, realloc)
5322weak_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5323weak_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5324weak_alias (__libc_mallinfo, __mallinfo) weak_alias (__libc_mallinfo, mallinfo)
5325weak_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5326
5327weak_alias (__malloc_stats, malloc_stats)
5328weak_alias (__malloc_usable_size, malloc_usable_size)
5329weak_alias (__malloc_trim, malloc_trim)
2f6d1f1b
UD
5330weak_alias (__malloc_get_state, malloc_get_state)
5331weak_alias (__malloc_set_state, malloc_set_state)
7e3be507 5332
fa8d436c 5333#endif /* _LIBC */
f65fd747 5334
fa8d436c 5335/* ------------------------------------------------------------
f65fd747
UD
5336History:
5337
fa8d436c 5338[see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
f65fd747
UD
5339
5340*/
fa8d436c
UD
5341/*
5342 * Local variables:
5343 * c-basic-offset: 2
5344 * End:
5345 */