The R Project SVN R

Rev

Rev 38427 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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