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