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