00001 #ifdef _RAKNET_SUPPORT_DL_MALLOC 00002 00003 /* 00004 Default header file for malloc-2.8.x, written by Doug Lea 00005 and released to the public domain, as explained at 00006 http://creativecommons.org/licenses/publicdomain. 00007 00008 last update: Wed May 27 14:25:17 2009 Doug Lea (dl at gee) 00009 00010 This header is for ANSI C/C++ only. You can set any of 00011 the following #defines before including: 00012 00013 * If USE_DL_PREFIX is defined, it is assumed that malloc.c 00014 was also compiled with this option, so all routines 00015 have names starting with "dl". 00016 00017 * If HAVE_USR_INCLUDE_MALLOC_H is defined, it is assumed that this 00018 file will be #included AFTER <malloc.h>. This is needed only if 00019 your system defines a struct mallinfo that is incompatible with the 00020 standard one declared here. Otherwise, you can include this file 00021 INSTEAD of your system system <malloc.h>. At least on ANSI, all 00022 declarations should be compatible with system versions 00023 00024 * If MSPACES is defined, declarations for mspace versions are included. 00025 */ 00026 00027 #ifndef MALLOC_280_H 00028 #define MALLOC_280_H 00029 00030 #include "rdlmalloc-options.h" 00031 00032 #ifdef __cplusplus 00033 extern "C" { 00034 #endif 00035 00036 #include <stddef.h> /* for size_t */ 00037 00038 #ifndef ONLY_MSPACES 00039 #define ONLY_MSPACES 0 /* define to a value */ 00040 #endif /* ONLY_MSPACES */ 00041 #ifndef NO_MALLINFO 00042 #define NO_MALLINFO 0 00043 #endif /* NO_MALLINFO */ 00044 00045 00046 #if !ONLY_MSPACES 00047 00048 #ifndef USE_DL_PREFIX 00049 #define rdlcalloc calloc 00050 #define rdlfree free 00051 #define rdlmalloc malloc 00052 #define rdlmemalign memalign 00053 #define rdlrealloc realloc 00054 #define rdlvalloc valloc 00055 #define rdlpvalloc pvalloc 00056 #define rdlmallinfo mallinfo 00057 #define rdlmallopt mallopt 00058 #define rdlmalloc_trim malloc_trim 00059 #define rdlmalloc_stats malloc_stats 00060 #define rdlmalloc_usable_size malloc_usable_size 00061 #define rdlmalloc_footprint malloc_footprint 00062 #define rdlindependent_calloc independent_calloc 00063 #define rdlindependent_comalloc independent_comalloc 00064 #endif /* USE_DL_PREFIX */ 00065 #if !NO_MALLINFO 00066 #ifndef HAVE_USR_INCLUDE_MALLOC_H 00067 #ifndef _MALLOC_H 00068 #ifndef MALLINFO_FIELD_TYPE 00069 #define MALLINFO_FIELD_TYPE size_t 00070 #endif /* MALLINFO_FIELD_TYPE */ 00071 #ifndef STRUCT_MALLINFO_DECLARED 00072 #define STRUCT_MALLINFO_DECLARED 1 00073 struct mallinfo { 00074 MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ 00075 MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ 00076 MALLINFO_FIELD_TYPE smblks; /* always 0 */ 00077 MALLINFO_FIELD_TYPE hblks; /* always 0 */ 00078 MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ 00079 MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ 00080 MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ 00081 MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ 00082 MALLINFO_FIELD_TYPE fordblks; /* total free space */ 00083 MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ 00084 }; 00085 #endif /* STRUCT_MALLINFO_DECLARED */ 00086 #endif /* _MALLOC_H */ 00087 #endif /* HAVE_USR_INCLUDE_MALLOC_H */ 00088 #endif /* !NO_MALLINFO */ 00089 00090 /* 00091 malloc(size_t n) 00092 Returns a pointer to a newly allocated chunk of at least n bytes, or 00093 null if no space is available, in which case errno is set to ENOMEM 00094 on ANSI C systems. 00095 00096 If n is zero, malloc returns a minimum-sized chunk. (The minimum 00097 size is 16 bytes on most 32bit systems, and 32 bytes on 64bit 00098 systems.) Note that size_t is an unsigned type, so calls with 00099 arguments that would be negative if signed are interpreted as 00100 requests for huge amounts of space, which will often fail. The 00101 maximum supported value of n differs across systems, but is in all 00102 cases less than the maximum representable value of a size_t. 00103 */ 00104 void* rdlmalloc(size_t); 00105 00106 /* 00107 free(void* p) 00108 Releases the chunk of memory pointed to by p, that had been previously 00109 allocated using malloc or a related routine such as realloc. 00110 It has no effect if p is null. If p was not malloced or already 00111 freed, free(p) will by default cuase the current program to abort. 00112 */ 00113 void rdlfree(void*); 00114 00115 /* 00116 calloc(size_t n_elements, size_t element_size); 00117 Returns a pointer to n_elements * element_size bytes, with all locations 00118 set to zero. 00119 */ 00120 void* rdlcalloc(size_t, size_t); 00121 00122 /* 00123 realloc(void* p, size_t n) 00124 Returns a pointer to a chunk of size n that contains the same data 00125 as does chunk p up to the minimum of (n, p's size) bytes, or null 00126 if no space is available. 00127 00128 The returned pointer may or may not be the same as p. The algorithm 00129 prefers extending p in most cases when possible, otherwise it 00130 employs the equivalent of a malloc-copy-free sequence. 00131 00132 If p is null, realloc is equivalent to malloc. 00133 00134 If space is not available, realloc returns null, errno is set (if on 00135 ANSI) and p is NOT freed. 00136 00137 if n is for fewer bytes than already held by p, the newly unused 00138 space is lopped off and freed if possible. realloc with a size 00139 argument of zero (re)allocates a minimum-sized chunk. 00140 00141 The old unix realloc convention of allowing the last-free'd chunk 00142 to be used as an argument to realloc is not supported. 00143 */ 00144 00145 void* rdlrealloc(void*, size_t); 00146 00147 /* 00148 memalign(size_t alignment, size_t n); 00149 Returns a pointer to a newly allocated chunk of n bytes, aligned 00150 in accord with the alignment argument. 00151 00152 The alignment argument should be a power of two. If the argument is 00153 not a power of two, the nearest greater power is used. 00154 8-byte alignment is guaranteed by normal malloc calls, so don't 00155 bother calling memalign with an argument of 8 or less. 00156 00157 Overreliance on memalign is a sure way to fragment space. 00158 */ 00159 void* rdlmemalign(size_t, size_t); 00160 00161 /* 00162 valloc(size_t n); 00163 Equivalent to memalign(pagesize, n), where pagesize is the page 00164 size of the system. If the pagesize is unknown, 4096 is used. 00165 */ 00166 void* rdlvalloc(size_t); 00167 00168 /* 00169 mallopt(int parameter_number, int parameter_value) 00170 Sets tunable parameters The format is to provide a 00171 (parameter-number, parameter-value) pair. mallopt then sets the 00172 corresponding parameter to the argument value if it can (i.e., so 00173 long as the value is meaningful), and returns 1 if successful else 00174 0. SVID/XPG/ANSI defines four standard param numbers for mallopt, 00175 normally defined in malloc.h. None of these are use in this malloc, 00176 so setting them has no effect. But this malloc also supports other 00177 options in mallopt: 00178 00179 Symbol param # default allowed param values 00180 M_TRIM_THRESHOLD -1 2*1024*1024 any (-1U disables trimming) 00181 M_GRANULARITY -2 page size any power of 2 >= page size 00182 M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) 00183 */ 00184 int rdlmallopt(int, int); 00185 00186 #define M_TRIM_THRESHOLD (-1) 00187 #define M_GRANULARITY (-2) 00188 #define M_MMAP_THRESHOLD (-3) 00189 00190 00191 /* 00192 malloc_footprint(); 00193 Returns the number of bytes obtained from the system. The total 00194 number of bytes allocated by malloc, realloc etc., is less than this 00195 value. Unlike mallinfo, this function returns only a precomputed 00196 result, so can be called frequently to monitor memory consumption. 00197 Even if locks are otherwise defined, this function does not use them, 00198 so results might not be up to date. 00199 */ 00200 size_t rdlmalloc_footprint(); 00201 00202 #if !NO_MALLINFO 00203 /* 00204 mallinfo() 00205 Returns (by copy) a struct containing various summary statistics: 00206 00207 arena: current total non-mmapped bytes allocated from system 00208 ordblks: the number of free chunks 00209 smblks: always zero. 00210 hblks: current number of mmapped regions 00211 hblkhd: total bytes held in mmapped regions 00212 usmblks: the maximum total allocated space. This will be greater 00213 than current total if trimming has occurred. 00214 fsmblks: always zero 00215 uordblks: current total allocated space (normal or mmapped) 00216 fordblks: total free space 00217 keepcost: the maximum number of bytes that could ideally be released 00218 back to system via malloc_trim. ("ideally" means that 00219 it ignores page restrictions etc.) 00220 00221 Because these fields are ints, but internal bookkeeping may 00222 be kept as longs, the reported values may wrap around zero and 00223 thus be inaccurate. 00224 */ 00225 00226 struct mallinfo rdlmallinfo(void); 00227 #endif /* NO_MALLINFO */ 00228 00229 /* 00230 independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); 00231 00232 independent_calloc is similar to calloc, but instead of returning a 00233 single cleared space, it returns an array of pointers to n_elements 00234 independent elements that can hold contents of size elem_size, each 00235 of which starts out cleared, and can be independently freed, 00236 realloc'ed etc. The elements are guaranteed to be adjacently 00237 allocated (this is not guaranteed to occur with multiple callocs or 00238 mallocs), which may also improve cache locality in some 00239 applications. 00240 00241 The "chunks" argument is optional (i.e., may be null, which is 00242 probably the most typical usage). If it is null, the returned array 00243 is itself dynamically allocated and should also be freed when it is 00244 no longer needed. Otherwise, the chunks array must be of at least 00245 n_elements in length. It is filled in with the pointers to the 00246 chunks. 00247 00248 In either case, independent_calloc returns this pointer array, or 00249 null if the allocation failed. If n_elements is zero and "chunks" 00250 is null, it returns a chunk representing an array with zero elements 00251 (which should be freed if not wanted). 00252 00253 Each element must be individually freed when it is no longer 00254 needed. If you'd like to instead be able to free all at once, you 00255 should instead use regular calloc and assign pointers into this 00256 space to represent elements. (In this case though, you cannot 00257 independently free elements.) 00258 00259 independent_calloc simplifies and speeds up implementations of many 00260 kinds of pools. It may also be useful when constructing large data 00261 structures that initially have a fixed number of fixed-sized nodes, 00262 but the number is not known at compile time, and some of the nodes 00263 may later need to be freed. For example: 00264 00265 struct Node { int item; struct Node* next; }; 00266 00267 struct Node* build_list() { 00268 struct Node** pool; 00269 int n = read_number_of_nodes_needed(); 00270 if (n <= 0) return 0; 00271 pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); 00272 if (pool == 0) die(); 00273 // organize into a linked list... 00274 struct Node* first = pool[0]; 00275 for (i = 0; i < n-1; ++i) 00276 pool[i]->next = pool[i+1]; 00277 free(pool); // Can now free the array (or not, if it is needed later) 00278 return first; 00279 } 00280 */ 00281 void** rdlindependent_calloc(size_t, size_t, void**); 00282 00283 /* 00284 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); 00285 00286 independent_comalloc allocates, all at once, a set of n_elements 00287 chunks with sizes indicated in the "sizes" array. It returns 00288 an array of pointers to these elements, each of which can be 00289 independently freed, realloc'ed etc. The elements are guaranteed to 00290 be adjacently allocated (this is not guaranteed to occur with 00291 multiple callocs or mallocs), which may also improve cache locality 00292 in some applications. 00293 00294 The "chunks" argument is optional (i.e., may be null). If it is null 00295 the returned array is itself dynamically allocated and should also 00296 be freed when it is no longer needed. Otherwise, the chunks array 00297 must be of at least n_elements in length. It is filled in with the 00298 pointers to the chunks. 00299 00300 In either case, independent_comalloc returns this pointer array, or 00301 null if the allocation failed. If n_elements is zero and chunks is 00302 null, it returns a chunk representing an array with zero elements 00303 (which should be freed if not wanted). 00304 00305 Each element must be individually freed when it is no longer 00306 needed. If you'd like to instead be able to free all at once, you 00307 should instead use a single regular malloc, and assign pointers at 00308 particular offsets in the aggregate space. (In this case though, you 00309 cannot independently free elements.) 00310 00311 independent_comallac differs from independent_calloc in that each 00312 element may have a different size, and also that it does not 00313 automatically clear elements. 00314 00315 independent_comalloc can be used to speed up allocation in cases 00316 where several structs or objects must always be allocated at the 00317 same time. For example: 00318 00319 struct Head { ... } 00320 struct Foot { ... } 00321 00322 void send_message(char* msg) { 00323 int msglen = strlen(msg); 00324 size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; 00325 void* chunks[3]; 00326 if (independent_comalloc(3, sizes, chunks) == 0) 00327 die(); 00328 struct Head* head = (struct Head*)(chunks[0]); 00329 char* body = (char*)(chunks[1]); 00330 struct Foot* foot = (struct Foot*)(chunks[2]); 00331 // ... 00332 } 00333 00334 In general though, independent_comalloc is worth using only for 00335 larger values of n_elements. For small values, you probably won't 00336 detect enough difference from series of malloc calls to bother. 00337 00338 Overuse of independent_comalloc can increase overall memory usage, 00339 since it cannot reuse existing noncontiguous small chunks that 00340 might be available for some of the elements. 00341 */ 00342 void** rdlindependent_comalloc(size_t, size_t*, void**); 00343 00344 00345 /* 00346 pvalloc(size_t n); 00347 Equivalent to valloc(minimum-page-that-holds(n)), that is, 00348 round up n to nearest pagesize. 00349 */ 00350 void* rdlpvalloc(size_t); 00351 00352 /* 00353 malloc_trim(size_t pad); 00354 00355 If possible, gives memory back to the system (via negative arguments 00356 to sbrk) if there is unused memory at the `high' end of the malloc 00357 pool or in unused MMAP segments. You can call this after freeing 00358 large blocks of memory to potentially reduce the system-level memory 00359 requirements of a program. However, it cannot guarantee to reduce 00360 memory. Under some allocation patterns, some large free blocks of 00361 memory will be locked between two used chunks, so they cannot be 00362 given back to the system. 00363 00364 The `pad' argument to malloc_trim represents the amount of free 00365 trailing space to leave untrimmed. If this argument is zero, only 00366 the minimum amount of memory to maintain internal data structures 00367 will be left. Non-zero arguments can be supplied to maintain enough 00368 trailing space to service future expected allocations without having 00369 to re-obtain memory from the system. 00370 00371 Malloc_trim returns 1 if it actually released any memory, else 0. 00372 */ 00373 int rdlmalloc_trim(size_t); 00374 00375 /* 00376 malloc_stats(); 00377 Prints on stderr the amount of space obtained from the system (both 00378 via sbrk and mmap), the maximum amount (which may be more than 00379 current if malloc_trim and/or munmap got called), and the current 00380 number of bytes allocated via malloc (or realloc, etc) but not yet 00381 freed. Note that this is the number of bytes allocated, not the 00382 number requested. It will be larger than the number requested 00383 because of alignment and bookkeeping overhead. Because it includes 00384 alignment wastage as being in use, this figure may be greater than 00385 zero even when no user-level chunks are allocated. 00386 00387 The reported current and maximum system memory can be inaccurate if 00388 a program makes other calls to system memory allocation functions 00389 (normally sbrk) outside of malloc. 00390 00391 malloc_stats prints only the most commonly interesting statistics. 00392 More information can be obtained by calling mallinfo. 00393 */ 00394 void rdlmalloc_stats(); 00395 00396 #endif /* !ONLY_MSPACES */ 00397 00398 /* 00399 malloc_usable_size(void* p); 00400 00401 Returns the number of bytes you can actually use in 00402 an allocated chunk, which may be more than you requested (although 00403 often not) due to alignment and minimum size constraints. 00404 You can use this many bytes without worrying about 00405 overwriting other allocated objects. This is not a particularly great 00406 programming practice. malloc_usable_size can be more useful in 00407 debugging and assertions, for example: 00408 00409 p = malloc(n); 00410 assert(malloc_usable_size(p) >= 256); 00411 */ 00412 size_t rdlmalloc_usable_size(void*); 00413 00414 00415 #if MSPACES 00416 00417 /* 00418 mspace is an opaque type representing an independent 00419 region of space that supports rak_mspace_malloc, etc. 00420 */ 00421 typedef void* mspace; 00422 00423 /* 00424 rak_create_mspace creates and returns a new independent space with the 00425 given initial capacity, or, if 0, the default granularity size. It 00426 returns null if there is no system memory available to create the 00427 space. If argument locked is non-zero, the space uses a separate 00428 lock to control access. The capacity of the space will grow 00429 dynamically as needed to service rak_mspace_malloc requests. You can 00430 control the sizes of incremental increases of this space by 00431 compiling with a different DEFAULT_GRANULARITY or dynamically 00432 setting with mallopt(M_GRANULARITY, value). 00433 */ 00434 mspace rak_create_mspace(size_t capacity, int locked); 00435 00436 /* 00437 rak_destroy_mspace destroys the given space, and attempts to return all 00438 of its memory back to the system, returning the total number of 00439 bytes freed. After destruction, the results of access to all memory 00440 used by the space become undefined. 00441 */ 00442 size_t rak_destroy_mspace(mspace msp); 00443 00444 /* 00445 rak_create_mspace_with_base uses the memory supplied as the initial base 00446 of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this 00447 space is used for bookkeeping, so the capacity must be at least this 00448 large. (Otherwise 0 is returned.) When this initial space is 00449 exhausted, additional memory will be obtained from the system. 00450 Destroying this space will deallocate all additionally allocated 00451 space (if possible) but not the initial base. 00452 */ 00453 mspace rak_create_mspace_with_base(void* base, size_t capacity, int locked); 00454 00455 /* 00456 rak_mspace_track_large_chunks controls whether requests for large chunks 00457 are allocated in their own untracked mmapped regions, separate from 00458 others in this mspace. By default large chunks are not tracked, 00459 which reduces fragmentation. However, such chunks are not 00460 necessarily released to the system upon rak_destroy_mspace. Enabling 00461 tracking by setting to true may increase fragmentation, but avoids 00462 leakage when relying on rak_destroy_mspace to release all memory 00463 allocated using this space. The function returns the previous 00464 setting. 00465 */ 00466 int rak_mspace_track_large_chunks(mspace msp, int enable); 00467 00468 /* 00469 rak_mspace_malloc behaves as malloc, but operates within 00470 the given space. 00471 */ 00472 void* rak_mspace_malloc(mspace msp, size_t bytes); 00473 00474 /* 00475 rak_mspace_free behaves as free, but operates within 00476 the given space. 00477 00478 If compiled with FOOTERS==1, rak_mspace_free is not actually needed. 00479 free may be called instead of rak_mspace_free because freed chunks from 00480 any space are handled by their originating spaces. 00481 */ 00482 void rak_mspace_free(mspace msp, void* mem); 00483 00484 /* 00485 rak_mspace_realloc behaves as realloc, but operates within 00486 the given space. 00487 00488 If compiled with FOOTERS==1, rak_mspace_realloc is not actually 00489 needed. realloc may be called instead of rak_mspace_realloc because 00490 realloced chunks from any space are handled by their originating 00491 spaces. 00492 */ 00493 void* rak_mspace_realloc(mspace msp, void* mem, size_t newsize); 00494 00495 /* 00496 rak_mspace_calloc behaves as calloc, but operates within 00497 the given space. 00498 */ 00499 void* rak_mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); 00500 00501 /* 00502 rak_mspace_memalign behaves as memalign, but operates within 00503 the given space. 00504 */ 00505 void* rak_mspace_memalign(mspace msp, size_t alignment, size_t bytes); 00506 00507 /* 00508 rak_mspace_independent_calloc behaves as independent_calloc, but 00509 operates within the given space. 00510 */ 00511 void** rak_mspace_independent_calloc(mspace msp, size_t n_elements, 00512 size_t elem_size, void* chunks[]); 00513 00514 /* 00515 rak_mspace_independent_comalloc behaves as independent_comalloc, but 00516 operates within the given space. 00517 */ 00518 void** rak_mspace_independent_comalloc(mspace msp, size_t n_elements, 00519 size_t sizes[], void* chunks[]); 00520 00521 /* 00522 rak_mspace_footprint() returns the number of bytes obtained from the 00523 system for this space. 00524 */ 00525 size_t rak_mspace_footprint(mspace msp); 00526 00527 00528 #if !NO_MALLINFO 00529 /* 00530 rak_mspace_mallinfo behaves as mallinfo, but reports properties of 00531 the given space. 00532 */ 00533 struct mallinfo rak_mspace_mallinfo(mspace msp); 00534 #endif /* NO_MALLINFO */ 00535 00536 /* 00537 malloc_usable_size(void* p) behaves the same as malloc_usable_size; 00538 */ 00539 size_t rak_mspace_usable_size(void* mem); 00540 00541 /* 00542 rak_mspace_malloc_stats behaves as malloc_stats, but reports 00543 properties of the given space. 00544 */ 00545 void rak_mspace_malloc_stats(mspace msp); 00546 00547 /* 00548 rak_mspace_trim behaves as malloc_trim, but 00549 operates within the given space. 00550 */ 00551 int rak_mspace_trim(mspace msp, size_t pad); 00552 00553 /* 00554 An alias for mallopt. 00555 */ 00556 int rak_mspace_mallopt(int, int); 00557 00558 #endif /* MSPACES */ 00559 00560 #ifdef __cplusplus 00561 }; /* end of extern "C" */ 00562 #endif 00563 00564 /* 00565 This is a version (aka rdlmalloc) of malloc/free/realloc written by 00566 Doug Lea and released to the public domain, as explained at 00567 http://creativecommons.org/licenses/publicdomain. Send questions, 00568 comments, complaints, performance data, etc to dl@cs.oswego.edu 00569 00570 * Version 2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee) 00571 00572 Note: There may be an updated version of this malloc obtainable at 00573 ftp://gee.cs.oswego.edu/pub/misc/malloc.c 00574 Check before installing! 00575 00576 * Quickstart 00577 00578 This library is all in one file to simplify the most common usage: 00579 ftp it, compile it (-O3), and link it into another program. All of 00580 the compile-time options default to reasonable values for use on 00581 most platforms. You might later want to step through various 00582 compile-time and dynamic tuning options. 00583 00584 For convenience, an include file for code using this malloc is at: 00585 ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.4.h 00586 You don't really need this .h file unless you call functions not 00587 defined in your system include files. The .h file contains only the 00588 excerpts from this file needed for using this malloc on ANSI C/C++ 00589 systems, so long as you haven't changed compile-time options about 00590 naming and tuning parameters. If you do, then you can create your 00591 own malloc.h that does include all settings by cutting at the point 00592 indicated below. Note that you may already by default be using a C 00593 library containing a malloc that is based on some version of this 00594 malloc (for example in linux). You might still want to use the one 00595 in this file to customize settings or to avoid overheads associated 00596 with library versions. 00597 00598 * Vital statistics: 00599 00600 Supported pointer/size_t representation: 4 or 8 bytes 00601 size_t MUST be an unsigned type of the same width as 00602 pointers. (If you are using an ancient system that declares 00603 size_t as a signed type, or need it to be a different width 00604 than pointers, you can use a previous release of this malloc 00605 (e.g. 2.7.2) supporting these.) 00606 00607 Alignment: 8 bytes (default) 00608 This suffices for nearly all current machines and C compilers. 00609 However, you can define MALLOC_ALIGNMENT to be wider than this 00610 if necessary (up to 128bytes), at the expense of using more space. 00611 00612 Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes) 00613 8 or 16 bytes (if 8byte sizes) 00614 Each malloced chunk has a hidden word of overhead holding size 00615 and status information, and additional cross-check word 00616 if FOOTERS is defined. 00617 00618 Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead) 00619 8-byte ptrs: 32 bytes (including overhead) 00620 00621 Even a request for zero bytes (i.e., malloc(0)) returns a 00622 pointer to something of the minimum allocatable size. 00623 The maximum overhead wastage (i.e., number of extra bytes 00624 allocated than were requested in malloc) is less than or equal 00625 to the minimum size, except for requests >= mmap_threshold that 00626 are serviced via mmap(), where the worst case wastage is about 00627 32 bytes plus the remainder from a system page (the minimal 00628 mmap unit); typically 4096 or 8192 bytes. 00629 00630 Security: static-safe; optionally more or less 00631 The "security" of malloc refers to the ability of malicious 00632 code to accentuate the effects of errors (for example, freeing 00633 space that is not currently malloc'ed or overwriting past the 00634 ends of chunks) in code that calls malloc. This malloc 00635 guarantees not to modify any memory locations below the base of 00636 heap, i.e., static variables, even in the presence of usage 00637 errors. The routines additionally detect most improper frees 00638 and reallocs. All this holds as long as the static bookkeeping 00639 for malloc itself is not corrupted by some other means. This 00640 is only one aspect of security -- these checks do not, and 00641 cannot, detect all possible programming errors. 00642 00643 If FOOTERS is defined nonzero, then each allocated chunk 00644 carries an additional check word to verify that it was malloced 00645 from its space. These check words are the same within each 00646 execution of a program using malloc, but differ across 00647 executions, so externally crafted fake chunks cannot be 00648 freed. This improves security by rejecting frees/reallocs that 00649 could corrupt heap memory, in addition to the checks preventing 00650 writes to statics that are always on. This may further improve 00651 security at the expense of time and space overhead. (Note that 00652 FOOTERS may also be worth using with MSPACES.) 00653 00654 By default detected errors cause the program to abort (calling 00655 "abort()"). You can override this to instead proceed past 00656 errors by defining PROCEED_ON_ERROR. In this case, a bad free 00657 has no effect, and a malloc that encounters a bad address 00658 caused by user overwrites will ignore the bad address by 00659 dropping pointers and indices to all known memory. This may 00660 be appropriate for programs that should continue if at all 00661 possible in the face of programming errors, although they may 00662 run out of memory because dropped memory is never reclaimed. 00663 00664 If you don't like either of these options, you can define 00665 CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything 00666 else. And if if you are sure that your program using malloc has 00667 no errors or vulnerabilities, you can define INSECURE to 1, 00668 which might (or might not) provide a small performance improvement. 00669 00670 Thread-safety: NOT thread-safe unless USE_LOCKS defined 00671 When USE_LOCKS is defined, each public call to malloc, free, 00672 etc is surrounded with either a pthread mutex or a win32 00673 spinlock (depending on DL_PLATFORM_WIN32). This is not especially fast, and 00674 can be a major bottleneck. It is designed only to provide 00675 minimal protection in concurrent environments, and to provide a 00676 basis for extensions. If you are using malloc in a concurrent 00677 program, consider instead using nedmalloc 00678 (http://www.nedprod.com/programs/portable/nedmalloc/) or 00679 ptmalloc (See http://www.malloc.de), which are derived 00680 from versions of this malloc. 00681 00682 System requirements: Any combination of MORECORE and/or MMAP/MUNMAP 00683 This malloc can use unix sbrk or any emulation (invoked using 00684 the CALL_MORECORE macro) and/or mmap/munmap or any emulation 00685 (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system 00686 memory. On most unix systems, it tends to work best if both 00687 MORECORE and MMAP are enabled. On Win32, it uses emulations 00688 based on VirtualAlloc. It also uses common C library functions 00689 like memset. 00690 00691 Compliance: I believe it is compliant with the Single Unix Specification 00692 (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably 00693 others as well. 00694 00695 * Overview of algorithms 00696 00697 This is not the fastest, most space-conserving, most portable, or 00698 most tunable malloc ever written. However it is among the fastest 00699 while also being among the most space-conserving, portable and 00700 tunable. Consistent balance across these factors results in a good 00701 general-purpose allocator for malloc-intensive programs. 00702 00703 In most ways, this malloc is a best-fit allocator. Generally, it 00704 chooses the best-fitting existing chunk for a request, with ties 00705 broken in approximately least-recently-used order. (This strategy 00706 normally maintains low fragmentation.) However, for requests less 00707 than 256bytes, it deviates from best-fit when there is not an 00708 exactly fitting available chunk by preferring to use space adjacent 00709 to that used for the previous small request, as well as by breaking 00710 ties in approximately most-recently-used order. (These enhance 00711 locality of series of small allocations.) And for very large requests 00712 (>= 256Kb by default), it relies on system memory mapping 00713 facilities, if supported. (This helps avoid carrying around and 00714 possibly fragmenting memory used only for large chunks.) 00715 00716 All operations (except malloc_stats and mallinfo) have execution 00717 times that are bounded by a constant factor of the number of bits in 00718 a size_t, not counting any clearing in calloc or copying in realloc, 00719 or actions surrounding MORECORE and MMAP that have times 00720 proportional to the number of non-contiguous regions returned by 00721 system allocation routines, which is often just 1. In real-time 00722 applications, you can optionally suppress segment traversals using 00723 NO_SEGMENT_TRAVERSAL, which assures bounded execution even when 00724 system allocators return non-contiguous spaces, at the typical 00725 expense of carrying around more memory and increased fragmentation. 00726 00727 The implementation is not very modular and seriously overuses 00728 macros. Perhaps someday all C compilers will do as good a job 00729 inlining modular code as can now be done by brute-force expansion, 00730 but now, enough of them seem not to. 00731 00732 Some compilers issue a lot of warnings about code that is 00733 dead/unreachable only on some platforms, and also about intentional 00734 uses of negation on unsigned types. All known cases of each can be 00735 ignored. 00736 00737 For a longer but out of date high-level description, see 00738 http://gee.cs.oswego.edu/dl/html/malloc.html 00739 00740 * MSPACES 00741 If MSPACES is defined, then in addition to malloc, free, etc., 00742 this file also defines rak_mspace_malloc, rak_mspace_free, etc. These 00743 are versions of malloc routines that take an "mspace" argument 00744 obtained using rak_create_mspace, to control all internal bookkeeping. 00745 If ONLY_MSPACES is defined, only these versions are compiled. 00746 So if you would like to use this allocator for only some allocations, 00747 and your system malloc for others, you can compile with 00748 ONLY_MSPACES and then do something like... 00749 static mspace mymspace = rak_create_mspace(0,0); // for example 00750 #define mymalloc(bytes) rak_mspace_malloc(mymspace, bytes) 00751 00752 (Note: If you only need one instance of an mspace, you can instead 00753 use "USE_DL_PREFIX" to relabel the global malloc.) 00754 00755 You can similarly create thread-local allocators by storing 00756 mspaces as thread-locals. For example: 00757 static __thread mspace tlms = 0; 00758 void* tlmalloc(size_t bytes) { 00759 if (tlms == 0) tlms = rak_create_mspace(0, 0); 00760 return rak_mspace_malloc(tlms, bytes); 00761 } 00762 void tlfree(void* mem) { rak_mspace_free(tlms, mem); } 00763 00764 Unless FOOTERS is defined, each mspace is completely independent. 00765 You cannot allocate from one and free to another (although 00766 conformance is only weakly checked, so usage errors are not always 00767 caught). If FOOTERS is defined, then each chunk carries around a tag 00768 indicating its originating mspace, and frees are directed to their 00769 originating spaces. 00770 00771 ------------------------- Compile-time options --------------------------- 00772 00773 Be careful in setting #define values for numerical constants of type 00774 size_t. On some systems, literal values are not automatically extended 00775 to size_t precision unless they are explicitly casted. You can also 00776 use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below. 00777 00778 DL_PLATFORM_WIN32 default: defined if _WIN32 defined 00779 Defining DL_PLATFORM_WIN32 sets up defaults for MS environment and compilers. 00780 Otherwise defaults are for unix. Beware that there seem to be some 00781 cases where this malloc might not be a pure drop-in replacement for 00782 Win32 malloc: Random-looking failures from Win32 GDI API's (eg; 00783 SetDIBits()) may be due to bugs in some video driver implementations 00784 when pixel buffers are malloc()ed, and the region spans more than 00785 one VirtualAlloc()ed region. Because rdlmalloc uses a small (64Kb) 00786 default granularity, pixel buffers may straddle virtual allocation 00787 regions more often than when using the Microsoft allocator. You can 00788 avoid this by using VirtualAlloc() and VirtualFree() for all pixel 00789 buffers rather than using malloc(). If this is not possible, 00790 recompile this malloc with a larger DEFAULT_GRANULARITY. 00791 00792 MALLOC_ALIGNMENT default: (size_t)8 00793 Controls the minimum alignment for malloc'ed chunks. It must be a 00794 power of two and at least 8, even on machines for which smaller 00795 alignments would suffice. It may be defined as larger than this 00796 though. Note however that code and data structures are optimized for 00797 the case of 8-byte alignment. 00798 00799 MSPACES default: 0 (false) 00800 If true, compile in support for independent allocation spaces. 00801 This is only supported if HAVE_MMAP is true. 00802 00803 ONLY_MSPACES default: 0 (false) 00804 If true, only compile in mspace versions, not regular versions. 00805 00806 USE_LOCKS default: 0 (false) 00807 Causes each call to each public routine to be surrounded with 00808 pthread or DL_PLATFORM_WIN32 mutex lock/unlock. (If set true, this can be 00809 overridden on a per-mspace basis for mspace versions.) If set to a 00810 non-zero value other than 1, locks are used, but their 00811 implementation is left out, so lock functions must be supplied manually, 00812 as described below. 00813 00814 USE_SPIN_LOCKS default: 1 iff USE_LOCKS and on x86 using gcc or MSC 00815 If true, uses custom spin locks for locking. This is currently 00816 supported only for x86 platforms using gcc or recent MS compilers. 00817 Otherwise, posix locks or win32 critical sections are used. 00818 00819 FOOTERS default: 0 00820 If true, provide extra checking and dispatching by placing 00821 information in the footers of allocated chunks. This adds 00822 space and time overhead. 00823 00824 INSECURE default: 0 00825 If true, omit checks for usage errors and heap space overwrites. 00826 00827 USE_DL_PREFIX default: NOT defined 00828 Causes compiler to prefix all public routines with the string 'dl'. 00829 This can be useful when you only want to use this malloc in one part 00830 of a program, using your regular system malloc elsewhere. 00831 00832 ABORT default: defined as abort() 00833 Defines how to abort on failed checks. On most systems, a failed 00834 check cannot die with an "assert" or even print an informative 00835 message, because the underlying print routines in turn call malloc, 00836 which will fail again. Generally, the best policy is to simply call 00837 abort(). It's not very useful to do more than this because many 00838 errors due to overwriting will show up as address faults (null, odd 00839 addresses etc) rather than malloc-triggered checks, so will also 00840 abort. Also, most compilers know that abort() does not return, so 00841 can better optimize code conditionally calling it. 00842 00843 PROCEED_ON_ERROR default: defined as 0 (false) 00844 Controls whether detected bad addresses cause them to bypassed 00845 rather than aborting. If set, detected bad arguments to free and 00846 realloc are ignored. And all bookkeeping information is zeroed out 00847 upon a detected overwrite of freed heap space, thus losing the 00848 ability to ever return it from malloc again, but enabling the 00849 application to proceed. If PROCEED_ON_ERROR is defined, the 00850 static variable malloc_corruption_error_count is compiled in 00851 and can be examined to see if errors have occurred. This option 00852 generates slower code than the default abort policy. 00853 00854 DEBUG default: NOT defined 00855 The DEBUG setting is mainly intended for people trying to modify 00856 this code or diagnose problems when porting to new platforms. 00857 However, it may also be able to better isolate user errors than just 00858 using runtime checks. The assertions in the check routines spell 00859 out in more detail the assumptions and invariants underlying the 00860 algorithms. The checking is fairly extensive, and will slow down 00861 execution noticeably. Calling malloc_stats or mallinfo with DEBUG 00862 set will attempt to check every non-mmapped allocated and free chunk 00863 in the course of computing the summaries. 00864 00865 ABORT_ON_ASSERT_FAILURE default: defined as 1 (true) 00866 Debugging assertion failures can be nearly impossible if your 00867 version of the assert macro causes malloc to be called, which will 00868 lead to a cascade of further failures, blowing the runtime stack. 00869 ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(), 00870 which will usually make debugging easier. 00871 00872 MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32 00873 The action to take before "return 0" when malloc fails to be able to 00874 return memory because there is none available. 00875 00876 HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES 00877 True if this system supports sbrk or an emulation of it. 00878 00879 MORECORE default: sbrk 00880 The name of the sbrk-style system routine to call to obtain more 00881 memory. See below for guidance on writing custom MORECORE 00882 functions. The type of the argument to sbrk/MORECORE varies across 00883 systems. It cannot be size_t, because it supports negative 00884 arguments, so it is normally the signed type of the same width as 00885 size_t (sometimes declared as "intptr_t"). It doesn't much matter 00886 though. Internally, we only call it with arguments less than half 00887 the max value of a size_t, which should work across all reasonable 00888 possibilities, although sometimes generating compiler warnings. 00889 00890 MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE 00891 If true, take advantage of fact that consecutive calls to MORECORE 00892 with positive arguments always return contiguous increasing 00893 addresses. This is true of unix sbrk. It does not hurt too much to 00894 set it true anyway, since malloc copes with non-contiguities. 00895 Setting it false when definitely non-contiguous saves time 00896 and possibly wasted space it would take to discover this though. 00897 00898 MORECORE_CANNOT_TRIM default: NOT defined 00899 True if MORECORE cannot release space back to the system when given 00900 negative arguments. This is generally necessary only if you are 00901 using a hand-crafted MORECORE function that cannot handle negative 00902 arguments. 00903 00904 NO_SEGMENT_TRAVERSAL default: 0 00905 If non-zero, suppresses traversals of memory segments 00906 returned by either MORECORE or CALL_MMAP. This disables 00907 merging of segments that are contiguous, and selectively 00908 releasing them to the OS if unused, but bounds execution times. 00909 00910 HAVE_MMAP default: 1 (true) 00911 True if this system supports mmap or an emulation of it. If so, and 00912 HAVE_MORECORE is not true, MMAP is used for all system 00913 allocation. If set and HAVE_MORECORE is true as well, MMAP is 00914 primarily used to directly allocate very large blocks. It is also 00915 used as a backup strategy in cases where MORECORE fails to provide 00916 space from system. Note: A single call to MUNMAP is assumed to be 00917 able to unmap memory that may have be allocated using multiple calls 00918 to MMAP, so long as they are adjacent. 00919 00920 HAVE_MREMAP default: 1 on linux, else 0 00921 If true realloc() uses mremap() to re-allocate large blocks and 00922 extend or shrink allocation spaces. 00923 00924 MMAP_CLEARS default: 1 except on WINCE. 00925 True if mmap clears memory so calloc doesn't need to. This is true 00926 for standard unix mmap using /dev/zero and on DL_PLATFORM_WIN32 except for WINCE. 00927 00928 USE_BUILTIN_FFS default: 0 (i.e., not used) 00929 Causes malloc to use the builtin ffs() function to compute indices. 00930 Some compilers may recognize and intrinsify ffs to be faster than the 00931 supplied C version. Also, the case of x86 using gcc is special-cased 00932 to an asm instruction, so is already as fast as it can be, and so 00933 this setting has no effect. Similarly for Win32 under recent MS compilers. 00934 (On most x86s, the asm version is only slightly faster than the C version.) 00935 00936 malloc_getpagesize default: derive from system includes, or 4096. 00937 The system page size. To the extent possible, this malloc manages 00938 memory from the system in page-size units. This may be (and 00939 usually is) a function rather than a constant. This is ignored 00940 if DL_PLATFORM_WIN32, where page size is determined using getSystemInfo during 00941 initialization. 00942 00943 USE_DEV_RANDOM default: 0 (i.e., not used) 00944 Causes malloc to use /dev/random to initialize secure magic seed for 00945 stamping footers. Otherwise, the current time is used. 00946 00947 NO_MALLINFO default: 0 00948 If defined, don't compile "mallinfo". This can be a simple way 00949 of dealing with mismatches between system declarations and 00950 those in this file. 00951 00952 MALLINFO_FIELD_TYPE default: size_t 00953 The type of the fields in the mallinfo struct. This was originally 00954 defined as "int" in SVID etc, but is more usefully defined as 00955 size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set 00956 00957 REALLOC_ZERO_BYTES_FREES default: not defined 00958 This should be set if a call to realloc with zero bytes should 00959 be the same as a call to free. Some people think it should. Otherwise, 00960 since this malloc returns a unique pointer for malloc(0), so does 00961 realloc(p, 0). 00962 00963 LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H 00964 LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H 00965 LACKS_STDLIB_H default: NOT defined unless on DL_PLATFORM_WIN32 00966 Define these if your system does not have these header files. 00967 You might need to manually insert some of the declarations they provide. 00968 00969 DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS, 00970 system_info.dwAllocationGranularity in DL_PLATFORM_WIN32, 00971 otherwise 64K. 00972 Also settable using mallopt(M_GRANULARITY, x) 00973 The unit for allocating and deallocating memory from the system. On 00974 most systems with contiguous MORECORE, there is no reason to 00975 make this more than a page. However, systems with MMAP tend to 00976 either require or encourage larger granularities. You can increase 00977 this value to prevent system allocation functions to be called so 00978 often, especially if they are slow. The value must be at least one 00979 page and must be a power of two. Setting to 0 causes initialization 00980 to either page size or win32 region size. (Note: In previous 00981 versions of malloc, the equivalent of this option was called 00982 "TOP_PAD") 00983 00984 DEFAULT_TRIM_THRESHOLD default: 2MB 00985 Also settable using mallopt(M_TRIM_THRESHOLD, x) 00986 The maximum amount of unused top-most memory to keep before 00987 releasing via malloc_trim in free(). Automatic trimming is mainly 00988 useful in long-lived programs using contiguous MORECORE. Because 00989 trimming via sbrk can be slow on some systems, and can sometimes be 00990 wasteful (in cases where programs immediately afterward allocate 00991 more large chunks) the value should be high enough so that your 00992 overall system performance would improve by releasing this much 00993 memory. As a rough guide, you might set to a value close to the 00994 average size of a process (program) running on your system. 00995 Releasing this much memory would allow such a process to run in 00996 memory. Generally, it is worth tuning trim thresholds when a 00997 program undergoes phases where several large chunks are allocated 00998 and released in ways that can reuse each other's storage, perhaps 00999 mixed with phases where there are no such chunks at all. The trim 01000 value must be greater than page size to have any useful effect. To 01001 disable trimming completely, you can set to MAX_SIZE_T. Note that the trick 01002 some people use of mallocing a huge space and then freeing it at 01003 program startup, in an attempt to reserve system memory, doesn't 01004 have the intended effect under automatic trimming, since that memory 01005 will immediately be returned to the system. 01006 01007 DEFAULT_MMAP_THRESHOLD default: 256K 01008 Also settable using mallopt(M_MMAP_THRESHOLD, x) 01009 The request size threshold for using MMAP to directly service a 01010 request. Requests of at least this size that cannot be allocated 01011 using already-existing space will be serviced via mmap. (If enough 01012 normal freed space already exists it is used instead.) Using mmap 01013 segregates relatively large chunks of memory so that they can be 01014 individually obtained and released from the host system. A request 01015 serviced through mmap is never reused by any other request (at least 01016 not directly; the system may just so happen to remap successive 01017 requests to the same locations). Segregating space in this way has 01018 the benefits that: Mmapped space can always be individually released 01019 back to the system, which helps keep the system level memory demands 01020 of a long-lived program low. Also, mapped memory doesn't become 01021 `locked' between other chunks, as can happen with normally allocated 01022 chunks, which means that even trimming via malloc_trim would not 01023 release them. However, it has the disadvantage that the space 01024 cannot be reclaimed, consolidated, and then used to service later 01025 requests, as happens with normal chunks. The advantages of mmap 01026 nearly always outweigh disadvantages for "large" chunks, but the 01027 value of "large" may vary across systems. The default is an 01028 empirically derived value that works well in most systems. You can 01029 disable mmap by setting to MAX_SIZE_T. 01030 01031 MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP 01032 The number of consolidated frees between checks to release 01033 unused segments when freeing. When using non-contiguous segments, 01034 especially with multiple mspaces, checking only for topmost space 01035 doesn't always suffice to trigger trimming. To compensate for this, 01036 free() will, with a period of MAX_RELEASE_CHECK_RATE (or the 01037 current number of segments, if greater) try to release unused 01038 segments to the OS when freeing chunks that result in 01039 consolidation. The best value for this parameter is a compromise 01040 between slowing down frees with relatively costly checks that 01041 rarely trigger versus holding on to unused memory. To effectively 01042 disable, set to MAX_SIZE_T. This may lead to a very slight speed 01043 improvement at the expense of carrying around more memory. 01044 */ 01045 01046 /* Version identifier to allow people to support multiple versions */ 01047 #ifndef DLMALLOC_VERSION 01048 #define DLMALLOC_VERSION 20804 01049 #endif /* DLMALLOC_VERSION */ 01050 01051 #include "rdlmalloc-options.h" 01052 01053 #ifndef WIN32 01054 #if defined(_XBOX) || defined(X360) 01055 #else 01056 #if defined(_WIN32) 01057 #define DL_PLATFORM_WIN32 1 01058 #endif /* _WIN32 */ 01059 #ifdef _WIN32_WCE 01060 #define LACKS_FCNTL_H 01061 #define DL_PLATFORM_WIN32 1 01062 #endif /* _WIN32_WCE */ 01063 #endif 01064 #else 01065 #define DL_PLATFORM_WIN32 1 01066 #endif /* DL_PLATFORM_WIN32 */ 01067 01068 #if defined(_XBOX) || defined(X360) 01069 01070 #endif 01071 01072 #if defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) 01073 01074 #endif 01075 01076 01077 #ifdef DL_PLATFORM_WIN32 01078 #define WIN32_LEAN_AND_MEAN 01079 #include <windows.h> 01080 #define HAVE_MMAP 1 01081 #define HAVE_MORECORE 0 01082 #define LACKS_UNISTD_H 01083 #define LACKS_SYS_PARAM_H 01084 #define LACKS_SYS_MMAN_H 01085 #define LACKS_STRING_H 01086 #define LACKS_STRINGS_H 01087 #define LACKS_SYS_TYPES_H 01088 #define LACKS_ERRNO_H 01089 #ifndef MALLOC_FAILURE_ACTION 01090 #define MALLOC_FAILURE_ACTION 01091 #endif /* MALLOC_FAILURE_ACTION */ 01092 #ifdef _WIN32_WCE /* WINCE reportedly does not clear */ 01093 #define MMAP_CLEARS 0 01094 #else 01095 #define MMAP_CLEARS 1 01096 #endif /* _WIN32_WCE */ 01097 #endif /* DL_PLATFORM_WIN32 */ 01098 01099 #if defined(DARWIN) || defined(_DARWIN) 01100 /* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ 01101 #ifndef HAVE_MORECORE 01102 #define HAVE_MORECORE 0 01103 #define HAVE_MMAP 1 01104 /* OSX allocators provide 16 byte alignment */ 01105 #ifndef MALLOC_ALIGNMENT 01106 #define MALLOC_ALIGNMENT ((size_t)16U) 01107 #endif 01108 #endif /* HAVE_MORECORE */ 01109 #endif /* DARWIN */ 01110 01111 #ifndef LACKS_SYS_TYPES_H 01112 #include <sys/types.h> /* For size_t */ 01113 #endif /* LACKS_SYS_TYPES_H */ 01114 01115 #if (defined(__GNUC__) && ((defined(__i386__) || defined(__x86_64__)))) || (defined(_MSC_VER) && _MSC_VER>=1310) 01116 #define SPIN_LOCKS_AVAILABLE 1 01117 #else 01118 #define SPIN_LOCKS_AVAILABLE 0 01119 #endif 01120 01121 /* The maximum possible size_t value has all bits set */ 01122 #define MAX_SIZE_T (~(size_t)0) 01123 01124 #ifndef ONLY_MSPACES 01125 #define ONLY_MSPACES 0 /* define to a value */ 01126 #else 01127 #define ONLY_MSPACES 1 01128 #endif /* ONLY_MSPACES */ 01129 #ifndef MSPACES 01130 #if ONLY_MSPACES 01131 #define MSPACES 1 01132 #else /* ONLY_MSPACES */ 01133 #define MSPACES 0 01134 #endif /* ONLY_MSPACES */ 01135 #endif /* MSPACES */ 01136 #ifndef MALLOC_ALIGNMENT 01137 #define MALLOC_ALIGNMENT ((size_t)8U) 01138 #endif /* MALLOC_ALIGNMENT */ 01139 #ifndef FOOTERS 01140 #define FOOTERS 0 01141 #endif /* FOOTERS */ 01142 #ifndef ABORT 01143 #define ABORT abort() 01144 #endif /* ABORT */ 01145 #ifndef ABORT_ON_ASSERT_FAILURE 01146 #define ABORT_ON_ASSERT_FAILURE 1 01147 #endif /* ABORT_ON_ASSERT_FAILURE */ 01148 #ifndef PROCEED_ON_ERROR 01149 #define PROCEED_ON_ERROR 0 01150 #endif /* PROCEED_ON_ERROR */ 01151 #ifndef USE_LOCKS 01152 #define USE_LOCKS 0 01153 #endif /* USE_LOCKS */ 01154 #ifndef USE_SPIN_LOCKS 01155 #if USE_LOCKS && SPIN_LOCKS_AVAILABLE 01156 #define USE_SPIN_LOCKS 1 01157 #else 01158 #define USE_SPIN_LOCKS 0 01159 #endif /* USE_LOCKS && SPIN_LOCKS_AVAILABLE. */ 01160 #endif /* USE_SPIN_LOCKS */ 01161 #ifndef INSECURE 01162 #define INSECURE 0 01163 #endif /* INSECURE */ 01164 #ifndef HAVE_MMAP 01165 #define HAVE_MMAP 1 01166 #endif /* HAVE_MMAP */ 01167 #ifndef MMAP_CLEARS 01168 #define MMAP_CLEARS 1 01169 #endif /* MMAP_CLEARS */ 01170 #ifndef HAVE_MREMAP 01171 #ifdef linux 01172 #define HAVE_MREMAP 1 01173 #else /* linux */ 01174 #define HAVE_MREMAP 0 01175 #endif /* linux */ 01176 #endif /* HAVE_MREMAP */ 01177 #ifndef MALLOC_FAILURE_ACTION 01178 #define MALLOC_FAILURE_ACTION errno = ENOMEM; 01179 #endif /* MALLOC_FAILURE_ACTION */ 01180 #ifndef HAVE_MORECORE 01181 #if ONLY_MSPACES 01182 #define HAVE_MORECORE 0 01183 #else /* ONLY_MSPACES */ 01184 #define HAVE_MORECORE 1 01185 #endif /* ONLY_MSPACES */ 01186 #endif /* HAVE_MORECORE */ 01187 #if !HAVE_MORECORE 01188 #define MORECORE_CONTIGUOUS 0 01189 #else /* !HAVE_MORECORE */ 01190 #define MORECORE_DEFAULT sbrk 01191 #ifndef MORECORE_CONTIGUOUS 01192 #define MORECORE_CONTIGUOUS 1 01193 #endif /* MORECORE_CONTIGUOUS */ 01194 #endif /* HAVE_MORECORE */ 01195 #ifndef DEFAULT_GRANULARITY 01196 #if (MORECORE_CONTIGUOUS || defined(DL_PLATFORM_WIN32)) 01197 #define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ 01198 #else /* MORECORE_CONTIGUOUS */ 01199 #define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) 01200 #endif /* MORECORE_CONTIGUOUS */ 01201 #endif /* DEFAULT_GRANULARITY */ 01202 #ifndef DEFAULT_TRIM_THRESHOLD 01203 #ifndef MORECORE_CANNOT_TRIM 01204 #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) 01205 #else /* MORECORE_CANNOT_TRIM */ 01206 #define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T 01207 #endif /* MORECORE_CANNOT_TRIM */ 01208 #endif /* DEFAULT_TRIM_THRESHOLD */ 01209 #ifndef DEFAULT_MMAP_THRESHOLD 01210 #if HAVE_MMAP 01211 #define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) 01212 #else /* HAVE_MMAP */ 01213 #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T 01214 #endif /* HAVE_MMAP */ 01215 #endif /* DEFAULT_MMAP_THRESHOLD */ 01216 #ifndef MAX_RELEASE_CHECK_RATE 01217 #if HAVE_MMAP 01218 #define MAX_RELEASE_CHECK_RATE 4095 01219 #else 01220 #define MAX_RELEASE_CHECK_RATE MAX_SIZE_T 01221 #endif /* HAVE_MMAP */ 01222 #endif /* MAX_RELEASE_CHECK_RATE */ 01223 #ifndef USE_BUILTIN_FFS 01224 #define USE_BUILTIN_FFS 0 01225 #endif /* USE_BUILTIN_FFS */ 01226 #ifndef USE_DEV_RANDOM 01227 #define USE_DEV_RANDOM 0 01228 #endif /* USE_DEV_RANDOM */ 01229 #ifndef NO_MALLINFO 01230 #define NO_MALLINFO 0 01231 #endif /* NO_MALLINFO */ 01232 #ifndef MALLINFO_FIELD_TYPE 01233 #define MALLINFO_FIELD_TYPE size_t 01234 #endif /* MALLINFO_FIELD_TYPE */ 01235 #ifndef NO_SEGMENT_TRAVERSAL 01236 #define NO_SEGMENT_TRAVERSAL 0 01237 #endif /* NO_SEGMENT_TRAVERSAL */ 01238 01239 /* 01240 mallopt tuning options. SVID/XPG defines four standard parameter 01241 numbers for mallopt, normally defined in malloc.h. None of these 01242 are used in this malloc, so setting them has no effect. But this 01243 malloc does support the following options. 01244 */ 01245 01246 #define M_TRIM_THRESHOLD (-1) 01247 #define M_GRANULARITY (-2) 01248 #define M_MMAP_THRESHOLD (-3) 01249 01250 /* ------------------------ Mallinfo declarations ------------------------ */ 01251 01252 #if !NO_MALLINFO 01253 /* 01254 This version of malloc supports the standard SVID/XPG mallinfo 01255 routine that returns a struct containing usage properties and 01256 statistics. It should work on any system that has a 01257 /usr/include/malloc.h defining struct mallinfo. The main 01258 declaration needed is the mallinfo struct that is returned (by-copy) 01259 by mallinfo(). The malloinfo struct contains a bunch of fields that 01260 are not even meaningful in this version of malloc. These fields are 01261 are instead filled by mallinfo() with other numbers that might be of 01262 interest. 01263 01264 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a 01265 /usr/include/malloc.h file that includes a declaration of struct 01266 mallinfo. If so, it is included; else a compliant version is 01267 declared below. These must be precisely the same for mallinfo() to 01268 work. The original SVID version of this struct, defined on most 01269 systems with mallinfo, declares all fields as ints. But some others 01270 define as unsigned long. If your system defines the fields using a 01271 type of different width than listed here, you MUST #include your 01272 system version and #define HAVE_USR_INCLUDE_MALLOC_H. 01273 */ 01274 01275 /* #define HAVE_USR_INCLUDE_MALLOC_H */ 01276 01277 #ifdef HAVE_USR_INCLUDE_MALLOC_H 01278 #include "/usr/include/malloc.h" 01279 #else /* HAVE_USR_INCLUDE_MALLOC_H */ 01280 #ifndef STRUCT_MALLINFO_DECLARED 01281 #define STRUCT_MALLINFO_DECLARED 1 01282 struct mallinfo { 01283 MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ 01284 MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ 01285 MALLINFO_FIELD_TYPE smblks; /* always 0 */ 01286 MALLINFO_FIELD_TYPE hblks; /* always 0 */ 01287 MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ 01288 MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ 01289 MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ 01290 MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ 01291 MALLINFO_FIELD_TYPE fordblks; /* total free space */ 01292 MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ 01293 }; 01294 #endif /* STRUCT_MALLINFO_DECLARED */ 01295 #endif /* HAVE_USR_INCLUDE_MALLOC_H */ 01296 #endif /* NO_MALLINFO */ 01297 01298 /* 01299 Try to persuade compilers to inline. The most critical functions for 01300 inlining are defined as macros, so these aren't used for them. 01301 */ 01302 01303 #ifndef FORCEINLINE 01304 #if defined(__GNUC__) 01305 #define FORCEINLINE __inline __attribute__ ((always_inline)) 01306 #elif defined(_MSC_VER) 01307 #define FORCEINLINE __forceinline 01308 #endif 01309 #endif 01310 #ifndef NOINLINE 01311 #if defined(__GNUC__) 01312 #define NOINLINE __attribute__ ((noinline)) 01313 #elif defined(_MSC_VER) 01314 #define NOINLINE __declspec(noinline) 01315 #else 01316 #define NOINLINE 01317 #endif 01318 #endif 01319 01320 #ifdef __cplusplus 01321 extern "C" { 01322 #ifndef FORCEINLINE 01323 #define FORCEINLINE inline 01324 #endif 01325 #endif /* __cplusplus */ 01326 #ifndef FORCEINLINE 01327 #define FORCEINLINE 01328 #endif 01329 01330 #if !ONLY_MSPACES 01331 01332 /* ------------------- Declarations of public routines ------------------- */ 01333 01334 #ifndef USE_DL_PREFIX 01335 #define rdlcalloc calloc 01336 #define rdlfree free 01337 #define rdlmalloc malloc 01338 #define rdlmemalign memalign 01339 #define rdlrealloc realloc 01340 #define rdlvalloc valloc 01341 #define rdlpvalloc pvalloc 01342 #define rdlmallinfo mallinfo 01343 #define rdlmallopt mallopt 01344 #define rdlmalloc_trim malloc_trim 01345 #define rdlmalloc_stats malloc_stats 01346 #define rdlmalloc_usable_size malloc_usable_size 01347 #define rdlmalloc_footprint malloc_footprint 01348 #define dlmalloc_max_footprint malloc_max_footprint 01349 #define rdlindependent_calloc independent_calloc 01350 #define rdlindependent_comalloc independent_comalloc 01351 #endif /* USE_DL_PREFIX */ 01352 01353 01354 /* 01355 malloc(size_t n) 01356 Returns a pointer to a newly allocated chunk of at least n bytes, or 01357 null if no space is available, in which case errno is set to ENOMEM 01358 on ANSI C systems. 01359 01360 If n is zero, malloc returns a minimum-sized chunk. (The minimum 01361 size is 16 bytes on most 32bit systems, and 32 bytes on 64bit 01362 systems.) Note that size_t is an unsigned type, so calls with 01363 arguments that would be negative if signed are interpreted as 01364 requests for huge amounts of space, which will often fail. The 01365 maximum supported value of n differs across systems, but is in all 01366 cases less than the maximum representable value of a size_t. 01367 */ 01368 void* rdlmalloc(size_t); 01369 01370 /* 01371 free(void* p) 01372 Releases the chunk of memory pointed to by p, that had been previously 01373 allocated using malloc or a related routine such as realloc. 01374 It has no effect if p is null. If p was not malloced or already 01375 freed, free(p) will by default cause the current program to abort. 01376 */ 01377 void rdlfree(void*); 01378 01379 /* 01380 calloc(size_t n_elements, size_t element_size); 01381 Returns a pointer to n_elements * element_size bytes, with all locations 01382 set to zero. 01383 */ 01384 void* rdlcalloc(size_t, size_t); 01385 01386 /* 01387 realloc(void* p, size_t n) 01388 Returns a pointer to a chunk of size n that contains the same data 01389 as does chunk p up to the minimum of (n, p's size) bytes, or null 01390 if no space is available. 01391 01392 The returned pointer may or may not be the same as p. The algorithm 01393 prefers extending p in most cases when possible, otherwise it 01394 employs the equivalent of a malloc-copy-free sequence. 01395 01396 If p is null, realloc is equivalent to malloc. 01397 01398 If space is not available, realloc returns null, errno is set (if on 01399 ANSI) and p is NOT freed. 01400 01401 if n is for fewer bytes than already held by p, the newly unused 01402 space is lopped off and freed if possible. realloc with a size 01403 argument of zero (re)allocates a minimum-sized chunk. 01404 01405 The old unix realloc convention of allowing the last-free'd chunk 01406 to be used as an argument to realloc is not supported. 01407 */ 01408 01409 void* rdlrealloc(void*, size_t); 01410 01411 /* 01412 memalign(size_t alignment, size_t n); 01413 Returns a pointer to a newly allocated chunk of n bytes, aligned 01414 in accord with the alignment argument. 01415 01416 The alignment argument should be a power of two. If the argument is 01417 not a power of two, the nearest greater power is used. 01418 8-byte alignment is guaranteed by normal malloc calls, so don't 01419 bother calling memalign with an argument of 8 or less. 01420 01421 Overreliance on memalign is a sure way to fragment space. 01422 */ 01423 void* rdlmemalign(size_t, size_t); 01424 01425 /* 01426 valloc(size_t n); 01427 Equivalent to memalign(pagesize, n), where pagesize is the page 01428 size of the system. If the pagesize is unknown, 4096 is used. 01429 */ 01430 void* rdlvalloc(size_t); 01431 01432 /* 01433 mallopt(int parameter_number, int parameter_value) 01434 Sets tunable parameters The format is to provide a 01435 (parameter-number, parameter-value) pair. mallopt then sets the 01436 corresponding parameter to the argument value if it can (i.e., so 01437 long as the value is meaningful), and returns 1 if successful else 01438 0. To workaround the fact that mallopt is specified to use int, 01439 not size_t parameters, the value -1 is specially treated as the 01440 maximum unsigned size_t value. 01441 01442 SVID/XPG/ANSI defines four standard param numbers for mallopt, 01443 normally defined in malloc.h. None of these are use in this malloc, 01444 so setting them has no effect. But this malloc also supports other 01445 options in mallopt. See below for details. Briefly, supported 01446 parameters are as follows (listed defaults are for "typical" 01447 configurations). 01448 01449 Symbol param # default allowed param values 01450 M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables) 01451 M_GRANULARITY -2 page size any power of 2 >= page size 01452 M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) 01453 */ 01454 int rdlmallopt(int, int); 01455 01456 /* 01457 malloc_footprint(); 01458 Returns the number of bytes obtained from the system. The total 01459 number of bytes allocated by malloc, realloc etc., is less than this 01460 value. Unlike mallinfo, this function returns only a precomputed 01461 result, so can be called frequently to monitor memory consumption. 01462 Even if locks are otherwise defined, this function does not use them, 01463 so results might not be up to date. 01464 */ 01465 size_t rdlmalloc_footprint(void); 01466 01467 /* 01468 malloc_max_footprint(); 01469 Returns the maximum number of bytes obtained from the system. This 01470 value will be greater than current footprint if deallocated space 01471 has been reclaimed by the system. The peak number of bytes allocated 01472 by malloc, realloc etc., is less than this value. Unlike mallinfo, 01473 this function returns only a precomputed result, so can be called 01474 frequently to monitor memory consumption. Even if locks are 01475 otherwise defined, this function does not use them, so results might 01476 not be up to date. 01477 */ 01478 size_t dlmalloc_max_footprint(void); 01479 01480 #if !NO_MALLINFO 01481 /* 01482 mallinfo() 01483 Returns (by copy) a struct containing various summary statistics: 01484 01485 arena: current total non-mmapped bytes allocated from system 01486 ordblks: the number of free chunks 01487 smblks: always zero. 01488 hblks: current number of mmapped regions 01489 hblkhd: total bytes held in mmapped regions 01490 usmblks: the maximum total allocated space. This will be greater 01491 than current total if trimming has occurred. 01492 fsmblks: always zero 01493 uordblks: current total allocated space (normal or mmapped) 01494 fordblks: total free space 01495 keepcost: the maximum number of bytes that could ideally be released 01496 back to system via malloc_trim. ("ideally" means that 01497 it ignores page restrictions etc.) 01498 01499 Because these fields are ints, but internal bookkeeping may 01500 be kept as longs, the reported values may wrap around zero and 01501 thus be inaccurate. 01502 */ 01503 struct mallinfo rdlmallinfo(void); 01504 #endif /* NO_MALLINFO */ 01505 01506 /* 01507 independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); 01508 01509 independent_calloc is similar to calloc, but instead of returning a 01510 single cleared space, it returns an array of pointers to n_elements 01511 independent elements that can hold contents of size elem_size, each 01512 of which starts out cleared, and can be independently freed, 01513 realloc'ed etc. The elements are guaranteed to be adjacently 01514 allocated (this is not guaranteed to occur with multiple callocs or 01515 mallocs), which may also improve cache locality in some 01516 applications. 01517 01518 The "chunks" argument is optional (i.e., may be null, which is 01519 probably the most typical usage). If it is null, the returned array 01520 is itself dynamically allocated and should also be freed when it is 01521 no longer needed. Otherwise, the chunks array must be of at least 01522 n_elements in length. It is filled in with the pointers to the 01523 chunks. 01524 01525 In either case, independent_calloc returns this pointer array, or 01526 null if the allocation failed. If n_elements is zero and "chunks" 01527 is null, it returns a chunk representing an array with zero elements 01528 (which should be freed if not wanted). 01529 01530 Each element must be individually freed when it is no longer 01531 needed. If you'd like to instead be able to free all at once, you 01532 should instead use regular calloc and assign pointers into this 01533 space to represent elements. (In this case though, you cannot 01534 independently free elements.) 01535 01536 independent_calloc simplifies and speeds up implementations of many 01537 kinds of pools. It may also be useful when constructing large data 01538 structures that initially have a fixed number of fixed-sized nodes, 01539 but the number is not known at compile time, and some of the nodes 01540 may later need to be freed. For example: 01541 01542 struct Node { int item; struct Node* next; }; 01543 01544 struct Node* build_list() { 01545 struct Node** pool; 01546 int n = read_number_of_nodes_needed(); 01547 if (n <= 0) return 0; 01548 pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); 01549 if (pool == 0) die(); 01550 // organize into a linked list... 01551 struct Node* first = pool[0]; 01552 for (i = 0; i < n-1; ++i) 01553 pool[i]->next = pool[i+1]; 01554 free(pool); // Can now free the array (or not, if it is needed later) 01555 return first; 01556 } 01557 */ 01558 void** rdlindependent_calloc(size_t, size_t, void**); 01559 01560 /* 01561 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); 01562 01563 independent_comalloc allocates, all at once, a set of n_elements 01564 chunks with sizes indicated in the "sizes" array. It returns 01565 an array of pointers to these elements, each of which can be 01566 independently freed, realloc'ed etc. The elements are guaranteed to 01567 be adjacently allocated (this is not guaranteed to occur with 01568 multiple callocs or mallocs), which may also improve cache locality 01569 in some applications. 01570 01571 The "chunks" argument is optional (i.e., may be null). If it is null 01572 the returned array is itself dynamically allocated and should also 01573 be freed when it is no longer needed. Otherwise, the chunks array 01574 must be of at least n_elements in length. It is filled in with the 01575 pointers to the chunks. 01576 01577 In either case, independent_comalloc returns this pointer array, or 01578 null if the allocation failed. If n_elements is zero and chunks is 01579 null, it returns a chunk representing an array with zero elements 01580 (which should be freed if not wanted). 01581 01582 Each element must be individually freed when it is no longer 01583 needed. If you'd like to instead be able to free all at once, you 01584 should instead use a single regular malloc, and assign pointers at 01585 particular offsets in the aggregate space. (In this case though, you 01586 cannot independently free elements.) 01587 01588 independent_comallac differs from independent_calloc in that each 01589 element may have a different size, and also that it does not 01590 automatically clear elements. 01591 01592 independent_comalloc can be used to speed up allocation in cases 01593 where several structs or objects must always be allocated at the 01594 same time. For example: 01595 01596 struct Head { ... } 01597 struct Foot { ... } 01598 01599 void send_message(char* msg) { 01600 int msglen = strlen(msg); 01601 size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; 01602 void* chunks[3]; 01603 if (independent_comalloc(3, sizes, chunks) == 0) 01604 die(); 01605 struct Head* head = (struct Head*)(chunks[0]); 01606 char* body = (char*)(chunks[1]); 01607 struct Foot* foot = (struct Foot*)(chunks[2]); 01608 // ... 01609 } 01610 01611 In general though, independent_comalloc is worth using only for 01612 larger values of n_elements. For small values, you probably won't 01613 detect enough difference from series of malloc calls to bother. 01614 01615 Overuse of independent_comalloc can increase overall memory usage, 01616 since it cannot reuse existing noncontiguous small chunks that 01617 might be available for some of the elements. 01618 */ 01619 void** rdlindependent_comalloc(size_t, size_t*, void**); 01620 01621 01622 /* 01623 pvalloc(size_t n); 01624 Equivalent to valloc(minimum-page-that-holds(n)), that is, 01625 round up n to nearest pagesize. 01626 */ 01627 void* rdlpvalloc(size_t); 01628 01629 /* 01630 malloc_trim(size_t pad); 01631 01632 If possible, gives memory back to the system (via negative arguments 01633 to sbrk) if there is unused memory at the `high' end of the malloc 01634 pool or in unused MMAP segments. You can call this after freeing 01635 large blocks of memory to potentially reduce the system-level memory 01636 requirements of a program. However, it cannot guarantee to reduce 01637 memory. Under some allocation patterns, some large free blocks of 01638 memory will be locked between two used chunks, so they cannot be 01639 given back to the system. 01640 01641 The `pad' argument to malloc_trim represents the amount of free 01642 trailing space to leave untrimmed. If this argument is zero, only 01643 the minimum amount of memory to maintain internal data structures 01644 will be left. Non-zero arguments can be supplied to maintain enough 01645 trailing space to service future expected allocations without having 01646 to re-obtain memory from the system. 01647 01648 Malloc_trim returns 1 if it actually released any memory, else 0. 01649 */ 01650 int rdlmalloc_trim(size_t); 01651 01652 /* 01653 malloc_stats(); 01654 Prints on stderr the amount of space obtained from the system (both 01655 via sbrk and mmap), the maximum amount (which may be more than 01656 current if malloc_trim and/or munmap got called), and the current 01657 number of bytes allocated via malloc (or realloc, etc) but not yet 01658 freed. Note that this is the number of bytes allocated, not the 01659 number requested. It will be larger than the number requested 01660 because of alignment and bookkeeping overhead. Because it includes 01661 alignment wastage as being in use, this figure may be greater than 01662 zero even when no user-level chunks are allocated. 01663 01664 The reported current and maximum system memory can be inaccurate if 01665 a program makes other calls to system memory allocation functions 01666 (normally sbrk) outside of malloc. 01667 01668 malloc_stats prints only the most commonly interesting statistics. 01669 More information can be obtained by calling mallinfo. 01670 */ 01671 void rdlmalloc_stats(void); 01672 01673 #endif /* ONLY_MSPACES */ 01674 01675 /* 01676 malloc_usable_size(void* p); 01677 01678 Returns the number of bytes you can actually use in 01679 an allocated chunk, which may be more than you requested (although 01680 often not) due to alignment and minimum size constraints. 01681 You can use this many bytes without worrying about 01682 overwriting other allocated objects. This is not a particularly great 01683 programming practice. malloc_usable_size can be more useful in 01684 debugging and assertions, for example: 01685 01686 p = malloc(n); 01687 assert(malloc_usable_size(p) >= 256); 01688 */ 01689 size_t rdlmalloc_usable_size(void*); 01690 01691 01692 #if MSPACES 01693 01694 /* 01695 mspace is an opaque type representing an independent 01696 region of space that supports rak_mspace_malloc, etc. 01697 */ 01698 typedef void* mspace; 01699 01700 /* 01701 rak_create_mspace creates and returns a new independent space with the 01702 given initial capacity, or, if 0, the default granularity size. It 01703 returns null if there is no system memory available to create the 01704 space. If argument locked is non-zero, the space uses a separate 01705 lock to control access. The capacity of the space will grow 01706 dynamically as needed to service rak_mspace_malloc requests. You can 01707 control the sizes of incremental increases of this space by 01708 compiling with a different DEFAULT_GRANULARITY or dynamically 01709 setting with mallopt(M_GRANULARITY, value). 01710 */ 01711 mspace rak_create_mspace(size_t capacity, int locked); 01712 01713 /* 01714 rak_destroy_mspace destroys the given space, and attempts to return all 01715 of its memory back to the system, returning the total number of 01716 bytes freed. After destruction, the results of access to all memory 01717 used by the space become undefined. 01718 */ 01719 size_t rak_destroy_mspace(mspace msp); 01720 01721 /* 01722 rak_create_mspace_with_base uses the memory supplied as the initial base 01723 of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this 01724 space is used for bookkeeping, so the capacity must be at least this 01725 large. (Otherwise 0 is returned.) When this initial space is 01726 exhausted, additional memory will be obtained from the system. 01727 Destroying this space will deallocate all additionally allocated 01728 space (if possible) but not the initial base. 01729 */ 01730 mspace rak_create_mspace_with_base(void* base, size_t capacity, int locked); 01731 01732 /* 01733 rak_mspace_track_large_chunks controls whether requests for large chunks 01734 are allocated in their own untracked mmapped regions, separate from 01735 others in this mspace. By default large chunks are not tracked, 01736 which reduces fragmentation. However, such chunks are not 01737 necessarily released to the system upon rak_destroy_mspace. Enabling 01738 tracking by setting to true may increase fragmentation, but avoids 01739 leakage when relying on rak_destroy_mspace to release all memory 01740 allocated using this space. The function returns the previous 01741 setting. 01742 */ 01743 int rak_mspace_track_large_chunks(mspace msp, int enable); 01744 01745 01746 /* 01747 rak_mspace_malloc behaves as malloc, but operates within 01748 the given space. 01749 */ 01750 void* rak_mspace_malloc(mspace msp, size_t bytes); 01751 01752 /* 01753 rak_mspace_free behaves as free, but operates within 01754 the given space. 01755 01756 If compiled with FOOTERS==1, rak_mspace_free is not actually needed. 01757 free may be called instead of rak_mspace_free because freed chunks from 01758 any space are handled by their originating spaces. 01759 */ 01760 void rak_mspace_free(mspace msp, void* mem); 01761 01762 /* 01763 rak_mspace_realloc behaves as realloc, but operates within 01764 the given space. 01765 01766 If compiled with FOOTERS==1, rak_mspace_realloc is not actually 01767 needed. realloc may be called instead of rak_mspace_realloc because 01768 realloced chunks from any space are handled by their originating 01769 spaces. 01770 */ 01771 void* rak_mspace_realloc(mspace msp, void* mem, size_t newsize); 01772 01773 /* 01774 rak_mspace_calloc behaves as calloc, but operates within 01775 the given space. 01776 */ 01777 void* rak_mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); 01778 01779 /* 01780 rak_mspace_memalign behaves as memalign, but operates within 01781 the given space. 01782 */ 01783 void* rak_mspace_memalign(mspace msp, size_t alignment, size_t bytes); 01784 01785 /* 01786 rak_mspace_independent_calloc behaves as independent_calloc, but 01787 operates within the given space. 01788 */ 01789 void** rak_mspace_independent_calloc(mspace msp, size_t n_elements, 01790 size_t elem_size, void* chunks[]); 01791 01792 /* 01793 rak_mspace_independent_comalloc behaves as independent_comalloc, but 01794 operates within the given space. 01795 */ 01796 void** rak_mspace_independent_comalloc(mspace msp, size_t n_elements, 01797 size_t sizes[], void* chunks[]); 01798 01799 /* 01800 rak_mspace_footprint() returns the number of bytes obtained from the 01801 system for this space. 01802 */ 01803 size_t rak_mspace_footprint(mspace msp); 01804 01805 /* 01806 mspace_max_footprint() returns the peak number of bytes obtained from the 01807 system for this space. 01808 */ 01809 size_t mspace_max_footprint(mspace msp); 01810 01811 01812 #if !NO_MALLINFO 01813 /* 01814 rak_mspace_mallinfo behaves as mallinfo, but reports properties of 01815 the given space. 01816 */ 01817 struct mallinfo rak_mspace_mallinfo(mspace msp); 01818 #endif /* NO_MALLINFO */ 01819 01820 /* 01821 malloc_usable_size(void* p) behaves the same as malloc_usable_size; 01822 */ 01823 size_t rak_mspace_usable_size(void* mem); 01824 01825 /* 01826 rak_mspace_malloc_stats behaves as malloc_stats, but reports 01827 properties of the given space. 01828 */ 01829 void rak_mspace_malloc_stats(mspace msp); 01830 01831 /* 01832 rak_mspace_trim behaves as malloc_trim, but 01833 operates within the given space. 01834 */ 01835 int rak_mspace_trim(mspace msp, size_t pad); 01836 01837 /* 01838 An alias for mallopt. 01839 */ 01840 int rak_mspace_mallopt(int, int); 01841 01842 #endif /* MSPACES */ 01843 01844 #ifdef __cplusplus 01845 }; /* end of extern "C" */ 01846 #endif /* __cplusplus */ 01847 01848 /* 01849 ======================================================================== 01850 To make a fully customizable malloc.h header file, cut everything 01851 above this line, put into file malloc.h, edit to suit, and #include it 01852 on the next line, as well as in programs that use this malloc. 01853 ======================================================================== 01854 */ 01855 01856 /* #include "malloc.h" */ 01857 01858 /*------------------------------ internal #includes ---------------------- */ 01859 01860 #ifdef DL_PLATFORM_WIN32 01861 #pragma warning( disable : 4146 ) /* no "unsigned" warnings */ 01862 #endif /* DL_PLATFORM_WIN32 */ 01863 01864 #include <stdio.h> /* for printing in malloc_stats */ 01865 01866 #ifndef LACKS_ERRNO_H 01867 #include <errno.h> /* for MALLOC_FAILURE_ACTION */ 01868 #endif /* LACKS_ERRNO_H */ 01869 01870 #if FOOTERS || DEBUG 01871 #include <time.h> /* for magic initialization */ 01872 #endif /* FOOTERS */ 01873 01874 #ifndef LACKS_STDLIB_H 01875 #include <stdlib.h> /* for abort() */ 01876 #endif /* LACKS_STDLIB_H */ 01877 01878 #ifdef DEBUG 01879 #if ABORT_ON_ASSERT_FAILURE 01880 #undef assert 01881 #define assert(x) if(!(x)) ABORT 01882 #else /* ABORT_ON_ASSERT_FAILURE */ 01883 #include <assert.h> 01884 #endif /* ABORT_ON_ASSERT_FAILURE */ 01885 #else /* DEBUG */ 01886 #ifndef assert 01887 #define assert(x) 01888 #endif 01889 #define DEBUG 0 01890 #endif /* DEBUG */ 01891 01892 #ifndef LACKS_STRING_H 01893 #include <string.h> /* for memset etc */ 01894 #endif /* LACKS_STRING_H */ 01895 01896 #if USE_BUILTIN_FFS 01897 #ifndef LACKS_STRINGS_H 01898 #include <strings.h> /* for ffs */ 01899 #endif /* LACKS_STRINGS_H */ 01900 #endif /* USE_BUILTIN_FFS */ 01901 01902 #if HAVE_MMAP 01903 #ifndef LACKS_SYS_MMAN_H 01904 /* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */ 01905 #if (defined(linux) && !defined(__USE_GNU)) 01906 #define __USE_GNU 1 01907 #include <sys/mman.h> /* for mmap */ 01908 #undef __USE_GNU 01909 #else 01910 #include <sys/mman.h> /* for mmap */ 01911 #endif /* linux */ 01912 #endif /* LACKS_SYS_MMAN_H */ 01913 #ifndef LACKS_FCNTL_H 01914 #include <fcntl.h> 01915 #endif /* LACKS_FCNTL_H */ 01916 #endif /* HAVE_MMAP */ 01917 01918 #ifndef LACKS_UNISTD_H 01919 #include <unistd.h> /* for sbrk, sysconf */ 01920 #else /* LACKS_UNISTD_H */ 01921 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) 01922 extern void* sbrk(ptrdiff_t); 01923 #endif /* FreeBSD etc */ 01924 #endif /* LACKS_UNISTD_H */ 01925 01926 /* Declarations for locking */ 01927 #if USE_LOCKS 01928 #if defined(_XBOX) || defined(X360) 01929 01930 #elif !defined(DL_PLATFORM_WIN32) 01931 #include <pthread.h> 01932 #if defined (__SVR4) && defined (__sun) /* solaris */ 01933 #include <thread.h> 01934 #endif /* solaris */ 01935 #else 01936 #ifndef _M_AMD64 01937 /* These are already defined on AMD64 builds */ 01938 #ifdef __cplusplus 01939 extern "C" { 01940 #endif /* __cplusplus */ 01941 LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp); 01942 LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value); 01943 #ifdef __cplusplus 01944 } 01945 #endif /* __cplusplus */ 01946 #endif /* _M_AMD64 */ 01947 #pragma intrinsic (_InterlockedCompareExchange) 01948 #pragma intrinsic (_InterlockedExchange) 01949 #define interlockedcompareexchange _InterlockedCompareExchange 01950 #define interlockedexchange _InterlockedExchange 01951 #endif /* Win32 */ 01952 #endif /* USE_LOCKS */ 01953 01954 /* Declarations for bit scanning on win32 */ 01955 #if defined(_MSC_VER) && _MSC_VER>=1300 && defined(DL_PLATFORM_WIN32) 01956 #ifndef BitScanForward /* Try to avoid pulling in WinNT.h */ 01957 #ifdef __cplusplus 01958 extern "C" { 01959 #endif /* __cplusplus */ 01960 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); 01961 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); 01962 #ifdef __cplusplus 01963 } 01964 #endif /* __cplusplus */ 01965 01966 #define BitScanForward _BitScanForward 01967 #define BitScanReverse _BitScanReverse 01968 #pragma intrinsic(_BitScanForward) 01969 #pragma intrinsic(_BitScanReverse) 01970 #endif /* BitScanForward */ 01971 #endif /* defined(_MSC_VER) && _MSC_VER>=1300 */ 01972 01973 #ifndef DL_PLATFORM_WIN32 01974 #ifndef malloc_getpagesize 01975 # ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ 01976 # ifndef _SC_PAGE_SIZE 01977 # define _SC_PAGE_SIZE _SC_PAGESIZE 01978 # endif 01979 # endif 01980 # ifdef _SC_PAGE_SIZE 01981 # define malloc_getpagesize sysconf(_SC_PAGE_SIZE) 01982 # else 01983 # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) 01984 extern size_t getpagesize(); 01985 # define malloc_getpagesize getpagesize() 01986 # else 01987 # ifdef DL_PLATFORM_WIN32 /* use supplied emulation of getpagesize */ 01988 # define malloc_getpagesize getpagesize() 01989 # else 01990 # ifndef LACKS_SYS_PARAM_H 01991 # include <sys/param.h> 01992 # endif 01993 # ifdef EXEC_PAGESIZE 01994 # define malloc_getpagesize EXEC_PAGESIZE 01995 # else 01996 # ifdef NBPG 01997 # ifndef CLSIZE 01998 # define malloc_getpagesize NBPG 01999 # else 02000 # define malloc_getpagesize (NBPG * CLSIZE) 02001 # endif 02002 # else 02003 # ifdef NBPC 02004 # define malloc_getpagesize NBPC 02005 # else 02006 # ifdef PAGESIZE 02007 # define malloc_getpagesize PAGESIZE 02008 # else /* just guess */ 02009 # define malloc_getpagesize ((size_t)4096U) 02010 # endif 02011 # endif 02012 # endif 02013 # endif 02014 # endif 02015 # endif 02016 # endif 02017 #endif 02018 #endif 02019 02020 02021 02022 /* ------------------- size_t and alignment properties -------------------- */ 02023 02024 /* The byte and bit size of a size_t */ 02025 #define SIZE_T_SIZE (sizeof(size_t)) 02026 #define SIZE_T_BITSIZE (sizeof(size_t) << 3) 02027 02028 /* Some constants coerced to size_t */ 02029 /* Annoying but necessary to avoid errors on some platforms */ 02030 #define SIZE_T_ZERO ((size_t)0) 02031 #define SIZE_T_ONE ((size_t)1) 02032 #define SIZE_T_TWO ((size_t)2) 02033 #define SIZE_T_FOUR ((size_t)4) 02034 #define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1) 02035 #define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2) 02036 #define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES) 02037 #define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) 02038 02039 /* The bit mask value corresponding to MALLOC_ALIGNMENT */ 02040 #define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) 02041 02042 /* True if address a has acceptable alignment */ 02043 #define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) 02044 02045 /* the number of bytes to offset an address to align it */ 02046 #define align_offset(A)\ 02047 ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\ 02048 ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) 02049 02050 /* -------------------------- MMAP preliminaries ------------------------- */ 02051 02052 /* 02053 If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and 02054 checks to fail so compiler optimizer can delete code rather than 02055 using so many "#if"s. 02056 */ 02057 02058 02059 /* MORECORE and MMAP must return MFAIL on failure */ 02060 #define MFAIL ((void*)(MAX_SIZE_T)) 02061 #define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ 02062 02063 #if HAVE_MMAP 02064 02065 #if defined(_XBOX) || defined(X360) 02066 02067 #elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) 02068 02069 #elif !defined(DL_PLATFORM_WIN32) 02070 #define RAK_MUNMAP_DEFAULT(a, s) munmap((a), (s)) 02071 #define MMAP_PROT (PROT_READ|PROT_WRITE) 02072 #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) 02073 #define MAP_ANONYMOUS MAP_ANON 02074 #endif /* MAP_ANON */ 02075 #ifdef MAP_ANONYMOUS 02076 #define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) 02077 #define RAK_MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) 02078 #else /* MAP_ANONYMOUS */ 02079 /* 02080 Nearly all versions of mmap support MAP_ANONYMOUS, so the following 02081 is unlikely to be needed, but is supplied just in case. 02082 */ 02083 #define MMAP_FLAGS (MAP_PRIVATE) 02084 static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ 02085 #define RAK_MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \ 02086 (dev_zero_fd = open("/dev/zero", O_RDWR), \ 02087 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ 02088 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) 02089 #endif /* MAP_ANONYMOUS */ 02090 02091 #define RAK_DIRECT_MMAP_DEFAULT(s) RAK_MMAP_DEFAULT(s) 02092 02093 #else /* DL_PLATFORM_WIN32 */ 02094 02095 /* Win32 MMAP via VirtualAlloc */ 02096 static FORCEINLINE void* win32mmap(size_t size) { 02097 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); 02098 return (ptr != 0)? ptr: MFAIL; 02099 } 02100 02101 /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ 02102 static FORCEINLINE void* win32direct_mmap(size_t size) { 02103 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, 02104 PAGE_READWRITE); 02105 return (ptr != 0)? ptr: MFAIL; 02106 } 02107 02108 /* This function supports releasing coalesed segments */ 02109 static FORCEINLINE int win32munmap(void* ptr, size_t size) { 02110 MEMORY_BASIC_INFORMATION minfo; 02111 char* cptr = (char*)ptr; 02112 while (size) { 02113 if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) 02114 return -1; 02115 if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || 02116 minfo.State != MEM_COMMIT || minfo.RegionSize > size) 02117 return -1; 02118 if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) 02119 return -1; 02120 cptr += minfo.RegionSize; 02121 size -= minfo.RegionSize; 02122 } 02123 return 0; 02124 } 02125 02126 #define RAK_MMAP_DEFAULT(s) win32mmap(s) 02127 #define RAK_MUNMAP_DEFAULT(a, s) win32munmap((a), (s)) 02128 #define RAK_DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s) 02129 #endif /* DL_PLATFORM_WIN32 */ 02130 #endif /* HAVE_MMAP */ 02131 02132 #if HAVE_MREMAP 02133 #ifndef DL_PLATFORM_WIN32 02134 #define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) 02135 #endif /* DL_PLATFORM_WIN32 */ 02136 #endif /* HAVE_MREMAP */ 02137 02138 02142 #if HAVE_MORECORE 02143 #ifdef MORECORE 02144 #define CALL_MORECORE(S) MORECORE(S) 02145 #else /* MORECORE */ 02146 #define CALL_MORECORE(S) MORECORE_DEFAULT(S) 02147 #endif /* MORECORE */ 02148 #else /* HAVE_MORECORE */ 02149 #define CALL_MORECORE(S) MFAIL 02150 #endif /* HAVE_MORECORE */ 02151 02155 #if HAVE_MMAP 02156 #define USE_MMAP_BIT (SIZE_T_ONE) 02157 02158 #ifdef MMAP 02159 #define CALL_MMAP(s) MMAP(s) 02160 #else /* MMAP */ 02161 #define CALL_MMAP(s) RAK_MMAP_DEFAULT(s) 02162 #endif /* MMAP */ 02163 #ifdef MUNMAP 02164 #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) 02165 #else /* MUNMAP */ 02166 #define CALL_MUNMAP(a, s) RAK_MUNMAP_DEFAULT((a), (s)) 02167 #endif /* MUNMAP */ 02168 #ifdef DIRECT_MMAP 02169 #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) 02170 #else /* DIRECT_MMAP */ 02171 #define CALL_DIRECT_MMAP(s) RAK_DIRECT_MMAP_DEFAULT(s) 02172 #endif /* DIRECT_MMAP */ 02173 #else /* HAVE_MMAP */ 02174 #define USE_MMAP_BIT (SIZE_T_ZERO) 02175 02176 #define MMAP(s) MFAIL 02177 #define MUNMAP(a, s) (-1) 02178 #define DIRECT_MMAP(s) MFAIL 02179 #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) 02180 #define CALL_MMAP(s) MMAP(s) 02181 #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) 02182 #endif /* HAVE_MMAP */ 02183 02187 #if HAVE_MMAP && HAVE_MREMAP 02188 #ifdef MREMAP 02189 #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv)) 02190 #else /* MREMAP */ 02191 #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv)) 02192 #endif /* MREMAP */ 02193 #else /* HAVE_MMAP && HAVE_MREMAP */ 02194 #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL 02195 #endif /* HAVE_MMAP && HAVE_MREMAP */ 02196 02197 /* mstate bit set if continguous morecore disabled or failed */ 02198 #define USE_NONCONTIGUOUS_BIT (4U) 02199 02200 /* segment bit set in rak_create_mspace_with_base */ 02201 #define EXTERN_BIT (8U) 02202 02203 02204 #endif /* MALLOC_280_H */ 02205 02206 #endif // _RAKNET_SUPPORT_DL_MALLOC