The R Project SVN R

Rev

Rev 26895 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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