/src/3rdparty/ptmalloc/malloc.c

https://bitbucket.org/ultra_iter/qt-vtl · C · 5515 lines · 3106 code · 472 blank · 1937 comment · 780 complexity · f9c8fed20ed43f00f7d85790a1e327cf MD5 · raw file

Large files are truncated click here to view the full file

  1. /*
  2. $Id: malloc.c,v 1.4 2006/03/30 16:47:29 wg Exp $
  3. This version of malloc.c was adapted for ptmalloc3 by Wolfram Gloger
  4. <wg@malloc.de>. Therefore, some of the comments below do not apply
  5. for this modified version. However, it is the intention to keep
  6. differences to Doug Lea's original version minimal, hence the
  7. comments were mostly left unchanged.
  8. -----------------------------------------------------------------------
  9. This is a version (aka dlmalloc) of malloc/free/realloc written by
  10. Doug Lea and released to the public domain, as explained at
  11. http://creativecommons.org/licenses/publicdomain. Send questions,
  12. comments, complaints, performance data, etc to dl@cs.oswego.edu
  13. * Version pre-2.8.4 Wed Mar 29 19:46:29 2006 (dl at gee)
  14. Note: There may be an updated version of this malloc obtainable at
  15. ftp://gee.cs.oswego.edu/pub/misc/malloc.c
  16. Check before installing!
  17. * Quickstart
  18. This library is all in one file to simplify the most common usage:
  19. ftp it, compile it (-O3), and link it into another program. All of
  20. the compile-time options default to reasonable values for use on
  21. most platforms. You might later want to step through various
  22. compile-time and dynamic tuning options.
  23. For convenience, an include file for code using this malloc is at:
  24. ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
  25. You don't really need this .h file unless you call functions not
  26. defined in your system include files. The .h file contains only the
  27. excerpts from this file needed for using this malloc on ANSI C/C++
  28. systems, so long as you haven't changed compile-time options about
  29. naming and tuning parameters. If you do, then you can create your
  30. own malloc.h that does include all settings by cutting at the point
  31. indicated below. Note that you may already by default be using a C
  32. library containing a malloc that is based on some version of this
  33. malloc (for example in linux). You might still want to use the one
  34. in this file to customize settings or to avoid overheads associated
  35. with library versions.
  36. * Vital statistics:
  37. Supported pointer/size_t representation: 4 or 8 bytes
  38. size_t MUST be an unsigned type of the same width as
  39. pointers. (If you are using an ancient system that declares
  40. size_t as a signed type, or need it to be a different width
  41. than pointers, you can use a previous release of this malloc
  42. (e.g. 2.7.2) supporting these.)
  43. Alignment: 8 bytes (default)
  44. This suffices for nearly all current machines and C compilers.
  45. However, you can define MALLOC_ALIGNMENT to be wider than this
  46. if necessary (up to 128bytes), at the expense of using more space.
  47. Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
  48. 8 or 16 bytes (if 8byte sizes)
  49. Each malloced chunk has a hidden word of overhead holding size
  50. and status information, and additional cross-check word
  51. if FOOTERS is defined.
  52. Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
  53. 8-byte ptrs: 32 bytes (including overhead)
  54. Even a request for zero bytes (i.e., malloc(0)) returns a
  55. pointer to something of the minimum allocatable size.
  56. The maximum overhead wastage (i.e., number of extra bytes
  57. allocated than were requested in malloc) is less than or equal
  58. to the minimum size, except for requests >= mmap_threshold that
  59. are serviced via mmap(), where the worst case wastage is about
  60. 32 bytes plus the remainder from a system page (the minimal
  61. mmap unit); typically 4096 or 8192 bytes.
  62. Security: static-safe; optionally more or less
  63. The "security" of malloc refers to the ability of malicious
  64. code to accentuate the effects of errors (for example, freeing
  65. space that is not currently malloc'ed or overwriting past the
  66. ends of chunks) in code that calls malloc. This malloc
  67. guarantees not to modify any memory locations below the base of
  68. heap, i.e., static variables, even in the presence of usage
  69. errors. The routines additionally detect most improper frees
  70. and reallocs. All this holds as long as the static bookkeeping
  71. for malloc itself is not corrupted by some other means. This
  72. is only one aspect of security -- these checks do not, and
  73. cannot, detect all possible programming errors.
  74. If FOOTERS is defined nonzero, then each allocated chunk
  75. carries an additional check word to verify that it was malloced
  76. from its space. These check words are the same within each
  77. execution of a program using malloc, but differ across
  78. executions, so externally crafted fake chunks cannot be
  79. freed. This improves security by rejecting frees/reallocs that
  80. could corrupt heap memory, in addition to the checks preventing
  81. writes to statics that are always on. This may further improve
  82. security at the expense of time and space overhead. (Note that
  83. FOOTERS may also be worth using with MSPACES.)
  84. By default detected errors cause the program to abort (calling
  85. "abort()"). You can override this to instead proceed past
  86. errors by defining PROCEED_ON_ERROR. In this case, a bad free
  87. has no effect, and a malloc that encounters a bad address
  88. caused by user overwrites will ignore the bad address by
  89. dropping pointers and indices to all known memory. This may
  90. be appropriate for programs that should continue if at all
  91. possible in the face of programming errors, although they may
  92. run out of memory because dropped memory is never reclaimed.
  93. If you don't like either of these options, you can define
  94. CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
  95. else. And if if you are sure that your program using malloc has
  96. no errors or vulnerabilities, you can define INSECURE to 1,
  97. which might (or might not) provide a small performance improvement.
  98. Thread-safety: NOT thread-safe unless USE_LOCKS defined
  99. When USE_LOCKS is defined, each public call to malloc, free,
  100. etc is surrounded with either a pthread mutex or a win32
  101. spinlock (depending on WIN32). This is not especially fast, and
  102. can be a major bottleneck. It is designed only to provide
  103. minimal protection in concurrent environments, and to provide a
  104. basis for extensions. If you are using malloc in a concurrent
  105. program, consider instead using nedmalloc
  106. (http://www.nedprod.com/programs/portable/nedmalloc/) or
  107. ptmalloc (See http://www.malloc.de), which are derived
  108. from versions of this malloc.
  109. System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
  110. This malloc can use unix sbrk or any emulation (invoked using
  111. the CALL_MORECORE macro) and/or mmap/munmap or any emulation
  112. (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
  113. memory. On most unix systems, it tends to work best if both
  114. MORECORE and MMAP are enabled. On Win32, it uses emulations
  115. based on VirtualAlloc. It also uses common C library functions
  116. like memset.
  117. Compliance: I believe it is compliant with the Single Unix Specification
  118. (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
  119. others as well.
  120. * Overview of algorithms
  121. This is not the fastest, most space-conserving, most portable, or
  122. most tunable malloc ever written. However it is among the fastest
  123. while also being among the most space-conserving, portable and
  124. tunable. Consistent balance across these factors results in a good
  125. general-purpose allocator for malloc-intensive programs.
  126. In most ways, this malloc is a best-fit allocator. Generally, it
  127. chooses the best-fitting existing chunk for a request, with ties
  128. broken in approximately least-recently-used order. (This strategy
  129. normally maintains low fragmentation.) However, for requests less
  130. than 256bytes, it deviates from best-fit when there is not an
  131. exactly fitting available chunk by preferring to use space adjacent
  132. to that used for the previous small request, as well as by breaking
  133. ties in approximately most-recently-used order. (These enhance
  134. locality of series of small allocations.) And for very large requests
  135. (>= 256Kb by default), it relies on system memory mapping
  136. facilities, if supported. (This helps avoid carrying around and
  137. possibly fragmenting memory used only for large chunks.)
  138. All operations (except malloc_stats and mallinfo) have execution
  139. times that are bounded by a constant factor of the number of bits in
  140. a size_t, not counting any clearing in calloc or copying in realloc,
  141. or actions surrounding MORECORE and MMAP that have times
  142. proportional to the number of non-contiguous regions returned by
  143. system allocation routines, which is often just 1. In real-time
  144. applications, you can optionally suppress segment traversals using
  145. NO_SEGMENT_TRAVERSAL, which assures bounded execution even when
  146. system allocators return non-contiguous spaces, at the typical
  147. expense of carrying around more memory and increased fragmentation.
  148. The implementation is not very modular and seriously overuses
  149. macros. Perhaps someday all C compilers will do as good a job
  150. inlining modular code as can now be done by brute-force expansion,
  151. but now, enough of them seem not to.
  152. Some compilers issue a lot of warnings about code that is
  153. dead/unreachable only on some platforms, and also about intentional
  154. uses of negation on unsigned types. All known cases of each can be
  155. ignored.
  156. For a longer but out of date high-level description, see
  157. http://gee.cs.oswego.edu/dl/html/malloc.html
  158. * MSPACES
  159. If MSPACES is defined, then in addition to malloc, free, etc.,
  160. this file also defines mspace_malloc, mspace_free, etc. These
  161. are versions of malloc routines that take an "mspace" argument
  162. obtained using create_mspace, to control all internal bookkeeping.
  163. If ONLY_MSPACES is defined, only these versions are compiled.
  164. So if you would like to use this allocator for only some allocations,
  165. and your system malloc for others, you can compile with
  166. ONLY_MSPACES and then do something like...
  167. static mspace mymspace = create_mspace(0,0); // for example
  168. #define mymalloc(bytes) mspace_malloc(mymspace, bytes)
  169. (Note: If you only need one instance of an mspace, you can instead
  170. use "USE_DL_PREFIX" to relabel the global malloc.)
  171. You can similarly create thread-local allocators by storing
  172. mspaces as thread-locals. For example:
  173. static __thread mspace tlms = 0;
  174. void* tlmalloc(size_t bytes) {
  175. if (tlms == 0) tlms = create_mspace(0, 0);
  176. return mspace_malloc(tlms, bytes);
  177. }
  178. void tlfree(void* mem) { mspace_free(tlms, mem); }
  179. Unless FOOTERS is defined, each mspace is completely independent.
  180. You cannot allocate from one and free to another (although
  181. conformance is only weakly checked, so usage errors are not always
  182. caught). If FOOTERS is defined, then each chunk carries around a tag
  183. indicating its originating mspace, and frees are directed to their
  184. originating spaces.
  185. ------------------------- Compile-time options ---------------------------
  186. Be careful in setting #define values for numerical constants of type
  187. size_t. On some systems, literal values are not automatically extended
  188. to size_t precision unless they are explicitly casted. You can also
  189. use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.
  190. WIN32 default: defined if _WIN32 defined
  191. Defining WIN32 sets up defaults for MS environment and compilers.
  192. Otherwise defaults are for unix.
  193. MALLOC_ALIGNMENT default: (size_t)8
  194. Controls the minimum alignment for malloc'ed chunks. It must be a
  195. power of two and at least 8, even on machines for which smaller
  196. alignments would suffice. It may be defined as larger than this
  197. though. Note however that code and data structures are optimized for
  198. the case of 8-byte alignment.
  199. MSPACES default: 0 (false)
  200. If true, compile in support for independent allocation spaces.
  201. This is only supported if HAVE_MMAP is true.
  202. ONLY_MSPACES default: 0 (false)
  203. If true, only compile in mspace versions, not regular versions.
  204. USE_LOCKS default: 0 (false)
  205. Causes each call to each public routine to be surrounded with
  206. pthread or WIN32 mutex lock/unlock. (If set true, this can be
  207. overridden on a per-mspace basis for mspace versions.) If set to a
  208. non-zero value other than 1, locks are used, but their
  209. implementation is left out, so lock functions must be supplied manually.
  210. USE_SPIN_LOCKS default: 1 iff USE_LOCKS and on x86 using gcc or MSC
  211. If true, uses custom spin locks for locking. This is currently
  212. supported only for x86 platforms using gcc or recent MS compilers.
  213. Otherwise, posix locks or win32 critical sections are used.
  214. FOOTERS default: 0
  215. If true, provide extra checking and dispatching by placing
  216. information in the footers of allocated chunks. This adds
  217. space and time overhead.
  218. INSECURE default: 0
  219. If true, omit checks for usage errors and heap space overwrites.
  220. USE_DL_PREFIX default: NOT defined
  221. Causes compiler to prefix all public routines with the string 'dl'.
  222. This can be useful when you only want to use this malloc in one part
  223. of a program, using your regular system malloc elsewhere.
  224. ABORT default: defined as abort()
  225. Defines how to abort on failed checks. On most systems, a failed
  226. check cannot die with an "assert" or even print an informative
  227. message, because the underlying print routines in turn call malloc,
  228. which will fail again. Generally, the best policy is to simply call
  229. abort(). It's not very useful to do more than this because many
  230. errors due to overwriting will show up as address faults (null, odd
  231. addresses etc) rather than malloc-triggered checks, so will also
  232. abort. Also, most compilers know that abort() does not return, so
  233. can better optimize code conditionally calling it.
  234. PROCEED_ON_ERROR default: defined as 0 (false)
  235. Controls whether detected bad addresses cause them to bypassed
  236. rather than aborting. If set, detected bad arguments to free and
  237. realloc are ignored. And all bookkeeping information is zeroed out
  238. upon a detected overwrite of freed heap space, thus losing the
  239. ability to ever return it from malloc again, but enabling the
  240. application to proceed. If PROCEED_ON_ERROR is defined, the
  241. static variable malloc_corruption_error_count is compiled in
  242. and can be examined to see if errors have occurred. This option
  243. generates slower code than the default abort policy.
  244. DEBUG default: NOT defined
  245. The DEBUG setting is mainly intended for people trying to modify
  246. this code or diagnose problems when porting to new platforms.
  247. However, it may also be able to better isolate user errors than just
  248. using runtime checks. The assertions in the check routines spell
  249. out in more detail the assumptions and invariants underlying the
  250. algorithms. The checking is fairly extensive, and will slow down
  251. execution noticeably. Calling malloc_stats or mallinfo with DEBUG
  252. set will attempt to check every non-mmapped allocated and free chunk
  253. in the course of computing the summaries.
  254. ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
  255. Debugging assertion failures can be nearly impossible if your
  256. version of the assert macro causes malloc to be called, which will
  257. lead to a cascade of further failures, blowing the runtime stack.
  258. ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
  259. which will usually make debugging easier.
  260. MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
  261. The action to take before "return 0" when malloc fails to be able to
  262. return memory because there is none available.
  263. HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
  264. True if this system supports sbrk or an emulation of it.
  265. MORECORE default: sbrk
  266. The name of the sbrk-style system routine to call to obtain more
  267. memory. See below for guidance on writing custom MORECORE
  268. functions. The type of the argument to sbrk/MORECORE varies across
  269. systems. It cannot be size_t, because it supports negative
  270. arguments, so it is normally the signed type of the same width as
  271. size_t (sometimes declared as "intptr_t"). It doesn't much matter
  272. though. Internally, we only call it with arguments less than half
  273. the max value of a size_t, which should work across all reasonable
  274. possibilities, although sometimes generating compiler warnings. See
  275. near the end of this file for guidelines for creating a custom
  276. version of MORECORE.
  277. MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE
  278. If true, take advantage of fact that consecutive calls to MORECORE
  279. with positive arguments always return contiguous increasing
  280. addresses. This is true of unix sbrk. It does not hurt too much to
  281. set it true anyway, since malloc copes with non-contiguities.
  282. Setting it false when definitely non-contiguous saves time
  283. and possibly wasted space it would take to discover this though.
  284. MORECORE_CANNOT_TRIM default: NOT defined
  285. True if MORECORE cannot release space back to the system when given
  286. negative arguments. This is generally necessary only if you are
  287. using a hand-crafted MORECORE function that cannot handle negative
  288. arguments.
  289. NO_SEGMENT_TRAVERSAL default: 0
  290. If non-zero, suppresses traversals of memory segments
  291. returned by either MORECORE or CALL_MMAP. This disables
  292. merging of segments that are contiguous, and selectively
  293. releasing them to the OS if unused, but bounds execution times.
  294. HAVE_MMAP default: 1 (true)
  295. True if this system supports mmap or an emulation of it. If so, and
  296. HAVE_MORECORE is not true, MMAP is used for all system
  297. allocation. If set and HAVE_MORECORE is true as well, MMAP is
  298. primarily used to directly allocate very large blocks. It is also
  299. used as a backup strategy in cases where MORECORE fails to provide
  300. space from system. Note: A single call to MUNMAP is assumed to be
  301. able to unmap memory that may have be allocated using multiple calls
  302. to MMAP, so long as they are adjacent.
  303. HAVE_MREMAP default: 1 on linux, else 0
  304. If true realloc() uses mremap() to re-allocate large blocks and
  305. extend or shrink allocation spaces.
  306. MMAP_CLEARS default: 1 except on WINCE.
  307. True if mmap clears memory so calloc doesn't need to. This is true
  308. for standard unix mmap using /dev/zero and on WIN32 except for WINCE.
  309. USE_BUILTIN_FFS default: 0 (i.e., not used)
  310. Causes malloc to use the builtin ffs() function to compute indices.
  311. Some compilers may recognize and intrinsify ffs to be faster than the
  312. supplied C version. Also, the case of x86 using gcc is special-cased
  313. to an asm instruction, so is already as fast as it can be, and so
  314. this setting has no effect. Similarly for Win32 under recent MS compilers.
  315. (On most x86s, the asm version is only slightly faster than the C version.)
  316. malloc_getpagesize default: derive from system includes, or 4096.
  317. The system page size. To the extent possible, this malloc manages
  318. memory from the system in page-size units. This may be (and
  319. usually is) a function rather than a constant. This is ignored
  320. if WIN32, where page size is determined using getSystemInfo during
  321. initialization.
  322. USE_DEV_RANDOM default: 0 (i.e., not used)
  323. Causes malloc to use /dev/random to initialize secure magic seed for
  324. stamping footers. Otherwise, the current time is used.
  325. NO_MALLINFO default: 0
  326. If defined, don't compile "mallinfo". This can be a simple way
  327. of dealing with mismatches between system declarations and
  328. those in this file.
  329. MALLINFO_FIELD_TYPE default: size_t
  330. The type of the fields in the mallinfo struct. This was originally
  331. defined as "int" in SVID etc, but is more usefully defined as
  332. size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
  333. REALLOC_ZERO_BYTES_FREES default: not defined
  334. This should be set if a call to realloc with zero bytes should
  335. be the same as a call to free. Some people think it should. Otherwise,
  336. since this malloc returns a unique pointer for malloc(0), so does
  337. realloc(p, 0).
  338. LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
  339. LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
  340. LACKS_STDLIB_H default: NOT defined unless on WIN32
  341. Define these if your system does not have these header files.
  342. You might need to manually insert some of the declarations they provide.
  343. DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
  344. system_info.dwAllocationGranularity in WIN32,
  345. otherwise 64K.
  346. Also settable using mallopt(M_GRANULARITY, x)
  347. The unit for allocating and deallocating memory from the system. On
  348. most systems with contiguous MORECORE, there is no reason to
  349. make this more than a page. However, systems with MMAP tend to
  350. either require or encourage larger granularities. You can increase
  351. this value to prevent system allocation functions to be called so
  352. often, especially if they are slow. The value must be at least one
  353. page and must be a power of two. Setting to 0 causes initialization
  354. to either page size or win32 region size. (Note: In previous
  355. versions of malloc, the equivalent of this option was called
  356. "TOP_PAD")
  357. DEFAULT_TRIM_THRESHOLD default: 2MB
  358. Also settable using mallopt(M_TRIM_THRESHOLD, x)
  359. The maximum amount of unused top-most memory to keep before
  360. releasing via malloc_trim in free(). Automatic trimming is mainly
  361. useful in long-lived programs using contiguous MORECORE. Because
  362. trimming via sbrk can be slow on some systems, and can sometimes be
  363. wasteful (in cases where programs immediately afterward allocate
  364. more large chunks) the value should be high enough so that your
  365. overall system performance would improve by releasing this much
  366. memory. As a rough guide, you might set to a value close to the
  367. average size of a process (program) running on your system.
  368. Releasing this much memory would allow such a process to run in
  369. memory. Generally, it is worth tuning trim thresholds when a
  370. program undergoes phases where several large chunks are allocated
  371. and released in ways that can reuse each other's storage, perhaps
  372. mixed with phases where there are no such chunks at all. The trim
  373. value must be greater than page size to have any useful effect. To
  374. disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
  375. some people use of mallocing a huge space and then freeing it at
  376. program startup, in an attempt to reserve system memory, doesn't
  377. have the intended effect under automatic trimming, since that memory
  378. will immediately be returned to the system.
  379. DEFAULT_MMAP_THRESHOLD default: 256K
  380. Also settable using mallopt(M_MMAP_THRESHOLD, x)
  381. The request size threshold for using MMAP to directly service a
  382. request. Requests of at least this size that cannot be allocated
  383. using already-existing space will be serviced via mmap. (If enough
  384. normal freed space already exists it is used instead.) Using mmap
  385. segregates relatively large chunks of memory so that they can be
  386. individually obtained and released from the host system. A request
  387. serviced through mmap is never reused by any other request (at least
  388. not directly; the system may just so happen to remap successive
  389. requests to the same locations). Segregating space in this way has
  390. the benefits that: Mmapped space can always be individually released
  391. back to the system, which helps keep the system level memory demands
  392. of a long-lived program low. Also, mapped memory doesn't become
  393. `locked' between other chunks, as can happen with normally allocated
  394. chunks, which means that even trimming via malloc_trim would not
  395. release them. However, it has the disadvantage that the space
  396. cannot be reclaimed, consolidated, and then used to service later
  397. requests, as happens with normal chunks. The advantages of mmap
  398. nearly always outweigh disadvantages for "large" chunks, but the
  399. value of "large" may vary across systems. The default is an
  400. empirically derived value that works well in most systems. You can
  401. disable mmap by setting to MAX_SIZE_T.
  402. MAX_RELEASE_CHECK_RATE default: 255 unless not HAVE_MMAP
  403. The number of consolidated frees between checks to release
  404. unused segments when freeing. When using non-contiguous segments,
  405. especially with multiple mspaces, checking only for topmost space
  406. doesn't always suffice to trigger trimming. To compensate for this,
  407. free() will, with a period of MAX_RELEASE_CHECK_RATE (or the
  408. current number of segments, if greater) try to release unused
  409. segments to the OS when freeing chunks that result in
  410. consolidation. The best value for this parameter is a compromise
  411. between slowing down frees with relatively costly checks that
  412. rarely trigger versus holding on to unused memory. To effectively
  413. disable, set to MAX_SIZE_T. This may lead to a very slight speed
  414. improvement at the expense of carrying around more memory.
  415. */
  416. #ifndef WIN32
  417. #ifdef _WIN32
  418. #define WIN32 1
  419. #endif /* _WIN32 */
  420. #endif /* WIN32 */
  421. #ifdef WIN32
  422. #define WIN32_LEAN_AND_MEAN
  423. #include <windows.h>
  424. #define HAVE_MMAP 1
  425. #define HAVE_MORECORE 0
  426. #define LACKS_UNISTD_H
  427. #define LACKS_SYS_PARAM_H
  428. #define LACKS_SYS_MMAN_H
  429. #define LACKS_STRING_H
  430. #define LACKS_STRINGS_H
  431. #define LACKS_SYS_TYPES_H
  432. #define LACKS_ERRNO_H
  433. #define MALLOC_FAILURE_ACTION
  434. #ifdef _WIN32_WCE /* WINCE reportedly does not clear */
  435. #define MMAP_CLEARS 0
  436. #else
  437. #define MMAP_CLEARS 1
  438. #endif /* _WIN32_WCE */
  439. #endif /* WIN32 */
  440. #if defined(DARWIN) || defined(_DARWIN)
  441. /* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
  442. #ifndef HAVE_MORECORE
  443. #define HAVE_MORECORE 0
  444. #define HAVE_MMAP 1
  445. #endif /* HAVE_MORECORE */
  446. #endif /* DARWIN */
  447. #ifndef LACKS_SYS_TYPES_H
  448. #include <sys/types.h> /* For size_t */
  449. #endif /* LACKS_SYS_TYPES_H */
  450. /* The maximum possible size_t value has all bits set */
  451. #define MAX_SIZE_T (~(size_t)0)
  452. #ifndef ONLY_MSPACES
  453. #define ONLY_MSPACES 0
  454. #endif /* ONLY_MSPACES */
  455. #ifndef MSPACES
  456. #if ONLY_MSPACES
  457. #define MSPACES 1
  458. #else /* ONLY_MSPACES */
  459. #define MSPACES 0
  460. #endif /* ONLY_MSPACES */
  461. #endif /* MSPACES */
  462. #ifndef MALLOC_ALIGNMENT
  463. #define MALLOC_ALIGNMENT ((size_t)8U)
  464. #endif /* MALLOC_ALIGNMENT */
  465. #ifndef FOOTERS
  466. #define FOOTERS 0
  467. #endif /* FOOTERS */
  468. #ifndef ABORT
  469. #define ABORT abort()
  470. #endif /* ABORT */
  471. #ifndef ABORT_ON_ASSERT_FAILURE
  472. #define ABORT_ON_ASSERT_FAILURE 1
  473. #endif /* ABORT_ON_ASSERT_FAILURE */
  474. #ifndef PROCEED_ON_ERROR
  475. #define PROCEED_ON_ERROR 0
  476. #endif /* PROCEED_ON_ERROR */
  477. #ifndef USE_LOCKS
  478. #define USE_LOCKS 0
  479. #endif /* USE_LOCKS */
  480. #ifndef USE_SPIN_LOCKS
  481. #if USE_LOCKS && (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) || (defined(_MSC_VER) && _MSC_VER>=1310)
  482. #define USE_SPIN_LOCKS 1
  483. #else
  484. #define USE_SPIN_LOCKS 0
  485. #endif /* USE_LOCKS && ... */
  486. #endif /* USE_SPIN_LOCKS */
  487. #ifndef INSECURE
  488. #define INSECURE 0
  489. #endif /* INSECURE */
  490. #ifndef HAVE_MMAP
  491. #define HAVE_MMAP 1
  492. #endif /* HAVE_MMAP */
  493. #ifndef MMAP_CLEARS
  494. #define MMAP_CLEARS 1
  495. #endif /* MMAP_CLEARS */
  496. #ifndef HAVE_MREMAP
  497. #ifdef linux
  498. #define HAVE_MREMAP 1
  499. #else /* linux */
  500. #define HAVE_MREMAP 0
  501. #endif /* linux */
  502. #endif /* HAVE_MREMAP */
  503. #ifndef MALLOC_FAILURE_ACTION
  504. #define MALLOC_FAILURE_ACTION errno = ENOMEM;
  505. #endif /* MALLOC_FAILURE_ACTION */
  506. #ifndef HAVE_MORECORE
  507. #if ONLY_MSPACES
  508. #define HAVE_MORECORE 0
  509. #else /* ONLY_MSPACES */
  510. #define HAVE_MORECORE 1
  511. #endif /* ONLY_MSPACES */
  512. #endif /* HAVE_MORECORE */
  513. #if !HAVE_MORECORE
  514. #define MORECORE_CONTIGUOUS 0
  515. #else /* !HAVE_MORECORE */
  516. #ifndef MORECORE
  517. #define MORECORE sbrk
  518. #endif /* MORECORE */
  519. #ifndef MORECORE_CONTIGUOUS
  520. #define MORECORE_CONTIGUOUS 1
  521. #endif /* MORECORE_CONTIGUOUS */
  522. #endif /* HAVE_MORECORE */
  523. #ifndef DEFAULT_GRANULARITY
  524. #if MORECORE_CONTIGUOUS
  525. #define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
  526. #else /* MORECORE_CONTIGUOUS */
  527. #define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
  528. #endif /* MORECORE_CONTIGUOUS */
  529. #endif /* DEFAULT_GRANULARITY */
  530. #ifndef DEFAULT_TRIM_THRESHOLD
  531. #ifndef MORECORE_CANNOT_TRIM
  532. #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
  533. #else /* MORECORE_CANNOT_TRIM */
  534. #define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
  535. #endif /* MORECORE_CANNOT_TRIM */
  536. #endif /* DEFAULT_TRIM_THRESHOLD */
  537. #ifndef DEFAULT_MMAP_THRESHOLD
  538. #if HAVE_MMAP
  539. #define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
  540. #else /* HAVE_MMAP */
  541. #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
  542. #endif /* HAVE_MMAP */
  543. #endif /* DEFAULT_MMAP_THRESHOLD */
  544. #ifndef MAX_RELEASE_CHECK_RATE
  545. #if HAVE_MMAP
  546. #define MAX_RELEASE_CHECK_RATE 255
  547. #else
  548. #define MAX_RELEASE_CHECK_RATE MAX_SIZE_T
  549. #endif /* HAVE_MMAP */
  550. #endif /* MAX_RELEASE_CHECK_RATE */
  551. #ifndef USE_BUILTIN_FFS
  552. #define USE_BUILTIN_FFS 0
  553. #endif /* USE_BUILTIN_FFS */
  554. #ifndef USE_DEV_RANDOM
  555. #define USE_DEV_RANDOM 0
  556. #endif /* USE_DEV_RANDOM */
  557. #ifndef NO_MALLINFO
  558. #define NO_MALLINFO 0
  559. #endif /* NO_MALLINFO */
  560. #ifndef MALLINFO_FIELD_TYPE
  561. #define MALLINFO_FIELD_TYPE size_t
  562. #endif /* MALLINFO_FIELD_TYPE */
  563. #ifndef NO_SEGMENT_TRAVERSAL
  564. #define NO_SEGMENT_TRAVERSAL 0
  565. #endif /* NO_SEGMENT_TRAVERSAL */
  566. /*
  567. mallopt tuning options. SVID/XPG defines four standard parameter
  568. numbers for mallopt, normally defined in malloc.h. None of these
  569. are used in this malloc, so setting them has no effect. But this
  570. malloc does support the following options.
  571. */
  572. #define M_TRIM_THRESHOLD (-1)
  573. #define M_GRANULARITY (-2)
  574. #define M_MMAP_THRESHOLD (-3)
  575. /* ------------------------ Mallinfo declarations ------------------------ */
  576. #if !NO_MALLINFO
  577. /*
  578. This version of malloc supports the standard SVID/XPG mallinfo
  579. routine that returns a struct containing usage properties and
  580. statistics. It should work on any system that has a
  581. /usr/include/malloc.h defining struct mallinfo. The main
  582. declaration needed is the mallinfo struct that is returned (by-copy)
  583. by mallinfo(). The malloinfo struct contains a bunch of fields that
  584. are not even meaningful in this version of malloc. These fields are
  585. are instead filled by mallinfo() with other numbers that might be of
  586. interest.
  587. HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
  588. /usr/include/malloc.h file that includes a declaration of struct
  589. mallinfo. If so, it is included; else a compliant version is
  590. declared below. These must be precisely the same for mallinfo() to
  591. work. The original SVID version of this struct, defined on most
  592. systems with mallinfo, declares all fields as ints. But some others
  593. define as unsigned long. If your system defines the fields using a
  594. type of different width than listed here, you MUST #include your
  595. system version and #define HAVE_USR_INCLUDE_MALLOC_H.
  596. */
  597. /* #define HAVE_USR_INCLUDE_MALLOC_H */
  598. #ifdef HAVE_USR_INCLUDE_MALLOC_H
  599. #include "/usr/include/malloc.h"
  600. #else /* HAVE_USR_INCLUDE_MALLOC_H */
  601. struct mallinfo {
  602. MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
  603. MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
  604. MALLINFO_FIELD_TYPE smblks; /* always 0 */
  605. MALLINFO_FIELD_TYPE hblks; /* always 0 */
  606. MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
  607. MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
  608. MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
  609. MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
  610. MALLINFO_FIELD_TYPE fordblks; /* total free space */
  611. MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
  612. };
  613. #endif /* HAVE_USR_INCLUDE_MALLOC_H */
  614. #endif /* NO_MALLINFO */
  615. /*
  616. Try to persuade compilers to inline. The most critical functions for
  617. inlining are defined as macros, so these aren't used for them.
  618. */
  619. #ifndef FORCEINLINE
  620. #if defined(__GNUC__)
  621. #define FORCEINLINE __inline __attribute__ ((always_inline))
  622. #elif defined(_MSC_VER)
  623. #define FORCEINLINE __forceinline
  624. #endif
  625. #endif
  626. #ifndef NOINLINE
  627. #if defined(__GNUC__)
  628. #define NOINLINE __attribute__ ((noinline))
  629. #elif defined(_MSC_VER)
  630. #define NOINLINE __declspec(noinline)
  631. #else
  632. #define NOINLINE
  633. #endif
  634. #endif
  635. #ifdef __cplusplus
  636. extern "C" {
  637. #ifndef FORCEINLINE
  638. #define FORCEINLINE inline
  639. #endif
  640. #endif /* __cplusplus */
  641. #ifndef FORCEINLINE
  642. #define FORCEINLINE
  643. #endif
  644. #if !ONLY_MSPACES
  645. /* ------------------- Declarations of public routines ------------------- */
  646. #ifndef USE_DL_PREFIX
  647. #define dlcalloc calloc
  648. #define dlfree free
  649. #define dlmalloc malloc
  650. #define dlmemalign memalign
  651. #define dlrealloc realloc
  652. #define dlvalloc valloc
  653. #define dlpvalloc pvalloc
  654. #define dlmallinfo mallinfo
  655. #define dlmallopt mallopt
  656. #define dlmalloc_trim malloc_trim
  657. #define dlmalloc_stats malloc_stats
  658. #define dlmalloc_usable_size malloc_usable_size
  659. #define dlmalloc_footprint malloc_footprint
  660. #define dlmalloc_max_footprint malloc_max_footprint
  661. #define dlindependent_calloc independent_calloc
  662. #define dlindependent_comalloc independent_comalloc
  663. #endif /* USE_DL_PREFIX */
  664. /*
  665. malloc(size_t n)
  666. Returns a pointer to a newly allocated chunk of at least n bytes, or
  667. null if no space is available, in which case errno is set to ENOMEM
  668. on ANSI C systems.
  669. If n is zero, malloc returns a minimum-sized chunk. (The minimum
  670. size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
  671. systems.) Note that size_t is an unsigned type, so calls with
  672. arguments that would be negative if signed are interpreted as
  673. requests for huge amounts of space, which will often fail. The
  674. maximum supported value of n differs across systems, but is in all
  675. cases less than the maximum representable value of a size_t.
  676. */
  677. void* dlmalloc(size_t);
  678. /*
  679. free(void* p)
  680. Releases the chunk of memory pointed to by p, that had been previously
  681. allocated using malloc or a related routine such as realloc.
  682. It has no effect if p is null. If p was not malloced or already
  683. freed, free(p) will by default cause the current program to abort.
  684. */
  685. void dlfree(void*);
  686. /*
  687. calloc(size_t n_elements, size_t element_size);
  688. Returns a pointer to n_elements * element_size bytes, with all locations
  689. set to zero.
  690. */
  691. void* dlcalloc(size_t, size_t);
  692. /*
  693. realloc(void* p, size_t n)
  694. Returns a pointer to a chunk of size n that contains the same data
  695. as does chunk p up to the minimum of (n, p's size) bytes, or null
  696. if no space is available.
  697. The returned pointer may or may not be the same as p. The algorithm
  698. prefers extending p in most cases when possible, otherwise it
  699. employs the equivalent of a malloc-copy-free sequence.
  700. If p is null, realloc is equivalent to malloc.
  701. If space is not available, realloc returns null, errno is set (if on
  702. ANSI) and p is NOT freed.
  703. if n is for fewer bytes than already held by p, the newly unused
  704. space is lopped off and freed if possible. realloc with a size
  705. argument of zero (re)allocates a minimum-sized chunk.
  706. The old unix realloc convention of allowing the last-free'd chunk
  707. to be used as an argument to realloc is not supported.
  708. */
  709. void* dlrealloc(void*, size_t);
  710. /*
  711. memalign(size_t alignment, size_t n);
  712. Returns a pointer to a newly allocated chunk of n bytes, aligned
  713. in accord with the alignment argument.
  714. The alignment argument should be a power of two. If the argument is
  715. not a power of two, the nearest greater power is used.
  716. 8-byte alignment is guaranteed by normal malloc calls, so don't
  717. bother calling memalign with an argument of 8 or less.
  718. Overreliance on memalign is a sure way to fragment space.
  719. */
  720. void* dlmemalign(size_t, size_t);
  721. /*
  722. valloc(size_t n);
  723. Equivalent to memalign(pagesize, n), where pagesize is the page
  724. size of the system. If the pagesize is unknown, 4096 is used.
  725. */
  726. void* dlvalloc(size_t);
  727. /*
  728. mallopt(int parameter_number, int parameter_value)
  729. Sets tunable parameters The format is to provide a
  730. (parameter-number, parameter-value) pair. mallopt then sets the
  731. corresponding parameter to the argument value if it can (i.e., so
  732. long as the value is meaningful), and returns 1 if successful else
  733. 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
  734. normally defined in malloc.h. None of these are use in this malloc,
  735. so setting them has no effect. But this malloc also supports other
  736. options in mallopt. See below for details. Briefly, supported
  737. parameters are as follows (listed defaults are for "typical"
  738. configurations).
  739. Symbol param # default allowed param values
  740. M_TRIM_THRESHOLD -1 2*1024*1024 any (MAX_SIZE_T disables)
  741. M_GRANULARITY -2 page size any power of 2 >= page size
  742. M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
  743. */
  744. int dlmallopt(int, int);
  745. /*
  746. malloc_footprint();
  747. Returns the number of bytes obtained from the system. The total
  748. number of bytes allocated by malloc, realloc etc., is less than this
  749. value. Unlike mallinfo, this function returns only a precomputed
  750. result, so can be called frequently to monitor memory consumption.
  751. Even if locks are otherwise defined, this function does not use them,
  752. so results might not be up to date.
  753. */
  754. size_t dlmalloc_footprint(void);
  755. /*
  756. malloc_max_footprint();
  757. Returns the maximum number of bytes obtained from the system. This
  758. value will be greater than current footprint if deallocated space
  759. has been reclaimed by the system. The peak number of bytes allocated
  760. by malloc, realloc etc., is less than this value. Unlike mallinfo,
  761. this function returns only a precomputed result, so can be called
  762. frequently to monitor memory consumption. Even if locks are
  763. otherwise defined, this function does not use them, so results might
  764. not be up to date.
  765. */
  766. size_t dlmalloc_max_footprint(void);
  767. #if !NO_MALLINFO
  768. /*
  769. mallinfo()
  770. Returns (by copy) a struct containing various summary statistics:
  771. arena: current total non-mmapped bytes allocated from system
  772. ordblks: the number of free chunks
  773. smblks: always zero.
  774. hblks: current number of mmapped regions
  775. hblkhd: total bytes held in mmapped regions
  776. usmblks: the maximum total allocated space. This will be greater
  777. than current total if trimming has occurred.
  778. fsmblks: always zero
  779. uordblks: current total allocated space (normal or mmapped)
  780. fordblks: total free space
  781. keepcost: the maximum number of bytes that could ideally be released
  782. back to system via malloc_trim. ("ideally" means that
  783. it ignores page restrictions etc.)
  784. Because these fields are ints, but internal bookkeeping may
  785. be kept as longs, the reported values may wrap around zero and
  786. thus be inaccurate.
  787. */
  788. struct mallinfo dlmallinfo(void);
  789. #endif /* NO_MALLINFO */
  790. /*
  791. independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
  792. independent_calloc is similar to calloc, but instead of returning a
  793. single cleared space, it returns an array of pointers to n_elements
  794. independent elements that can hold contents of size elem_size, each
  795. of which starts out cleared, and can be independently freed,
  796. realloc'ed etc. The elements are guaranteed to be adjacently
  797. allocated (this is not guaranteed to occur with multiple callocs or
  798. mallocs), which may also improve cache locality in some
  799. applications.
  800. The "chunks" argument is optional (i.e., may be null, which is
  801. probably the most typical usage). If it is null, the returned array
  802. is itself dynamically allocated and should also be freed when it is
  803. no longer needed. Otherwise, the chunks array must be of at least
  804. n_elements in length. It is filled in with the pointers to the
  805. chunks.
  806. In either case, independent_calloc returns this pointer array, or
  807. null if the allocation failed. If n_elements is zero and "chunks"
  808. is null, it returns a chunk representing an array with zero elements
  809. (which should be freed if not wanted).
  810. Each element must be individually freed when it is no longer
  811. needed. If you'd like to instead be able to free all at once, you
  812. should instead use regular calloc and assign pointers into this
  813. space to represent elements. (In this case though, you cannot
  814. independently free elements.)
  815. independent_calloc simplifies and speeds up implementations of many
  816. kinds of pools. It may also be useful when constructing large data
  817. structures that initially have a fixed number of fixed-sized nodes,
  818. but the number is not known at compile time, and some of the nodes
  819. may later need to be freed. For example:
  820. struct Node { int item; struct Node* next; };
  821. struct Node* build_list() {
  822. struct Node** pool;
  823. int n = read_number_of_nodes_needed();
  824. if (n <= 0) return 0;
  825. pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
  826. if (pool == 0) die();
  827. // organize into a linked list...
  828. struct Node* first = pool[0];
  829. for (i = 0; i < n-1; ++i)
  830. pool[i]->next = pool[i+1];
  831. free(pool); // Can now free the array (or not, if it is needed later)
  832. return first;
  833. }
  834. */
  835. void** dlindependent_calloc(size_t, size_t, void**);
  836. /*
  837. independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
  838. independent_comalloc allocates, all at once, a set of n_elements
  839. chunks with sizes indicated in the "sizes" array. It returns
  840. an array of pointers to these elements, each of which can be
  841. independently freed, realloc'ed etc. The elements are guaranteed to
  842. be adjacently allocated (this is not guaranteed to occur with
  843. multiple callocs or mallocs), which may also improve cache locality
  844. in some applications.
  845. The "chunks" argument is optional (i.e., may be null). If it is null
  846. the returned array is itself dynamically allocated and should also
  847. be freed when it is no longer needed. Otherwise, the chunks array
  848. must be of at least n_elements in length. It is filled in with the
  849. pointers to the chunks.
  850. In either case, independent_comalloc returns this pointer array, or
  851. null if the allocation failed. If n_elements is zero and chunks is
  852. null, it returns a chunk representing an array with zero elements
  853. (which should be freed if not wanted).
  854. Each element must be individually freed when it is no longer
  855. needed. If you'd like to instead be able to free all at once, you
  856. should instead use a single regular malloc, and assign pointers at
  857. particular offsets in the aggregate space. (In this case though, you
  858. cannot independently free elements.)
  859. independent_comallac differs from independent_calloc in that each
  860. element may have a different size, and also that it does not
  861. automatically clear elements.
  862. independent_comalloc can be used to speed up allocation in cases
  863. where several structs or objects must always be allocated at the
  864. same time. For example:
  865. struct Head { ... }
  866. struct Foot { ... }
  867. void send_message(char* msg) {
  868. int msglen = strlen(msg);
  869. size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
  870. void* chunks[3];
  871. if (independent_comalloc(3, sizes, chunks) == 0)
  872. die();
  873. struct Head* head = (struct Head*)(chunks[0]);
  874. char* body = (char*)(chunks[1]);
  875. struct Foot* foot = (struct Foot*)(chunks[2]);
  876. // ...
  877. }
  878. In general though, independent_comalloc is worth using only for
  879. larger values of n_elements. For small values, you probably won't
  880. detect enough difference from series of malloc calls to bother.
  881. Overuse of independent_comalloc can increase overall memory usage,
  882. since it cannot reuse existing noncontiguous small chunks that
  883. might be available for some of the elements.
  884. */
  885. void** dlindependent_comalloc(size_t, size_t*, void**);
  886. /*
  887. pvalloc(size_t n);
  888. Equivalent to valloc(minimum-page-that-holds(n)), that is,
  889. round up n to nearest pagesize.
  890. */
  891. void* dlpvalloc(size_t);
  892. /*
  893. malloc_trim(size_t pad);
  894. If possible, gives memory back to the system (via negative arguments
  895. to sbrk) if there is unused memory at the `high' end of the malloc
  896. pool or in unused MMAP segments. You can call this after freeing
  897. large blocks of memory to potentially reduce the system-level memory
  898. requirements of a program. However, it cannot guarantee to reduce
  899. memory. Under some allocation patterns, some large free blocks of
  900. memory will be locked between two used chunks, so they cannot be
  901. given back to the system.
  902. The `pad' argument to malloc_trim represents the amount of free
  903. trailing space to leave untrimmed. If this argument is zero, only
  904. the minimum amount of memory to maintain internal data structures
  905. will be left. Non-zero arguments can be supplied to maintain enough
  906. trailing space to service future expected allocations without having
  907. to re-obtain memory from the system.
  908. Malloc_trim returns 1 if it actually released any memory, else 0.
  909. */
  910. int dlmalloc_trim(size_t);
  911. /*
  912. malloc_usable_size(void* p);
  913. Returns the number of bytes you can actually use in
  914. an allocated chunk, which may be more than you requested (although
  915. often not) due to alignment and minimum size constraints.
  916. You can use this many bytes without worrying about
  917. overwriting other allocated objects. This is not a particularly great
  918. programming practice. malloc_usable_size can be more useful in
  919. debugging and assertions, for example:
  920. p = malloc(n);
  921. assert(malloc_usable_size(p) >= 256);
  922. */
  923. size_t dlmalloc_usable_size(void*);
  924. /*
  925. malloc_stats();
  926. Prints on stderr the amount of space obtained from the system (both
  927. via sbrk and mmap), the maximum amount (which may be more than
  928. current if malloc_trim and/or munmap got called), and the current
  929. number of bytes allocated via malloc (or realloc, etc) but not yet
  930. freed. Note that this is the number of bytes allocated, not the
  931. number requested. It will be larger than the number requested
  932. because of alignment and bookkeeping overhead. Because it includes
  933. alignment wastage as being in use, this figure may be greater than
  934. zero even when no user-level chunks are allocated.
  935. The reported current and maximum system memory can be inaccurate if
  936. a program makes other calls to system memory allocation functions
  937. (normally sbrk) outside of malloc.
  938. malloc_stats prints only the most commonly interesting statistics.
  939. More information can be obtained by calling mallinfo.
  940. */
  941. void dlmalloc_stats(void);
  942. #endif /* ONLY_MSPACES */
  943. #if MSPACES
  944. /*
  945. mspace is an opaque type representing an independent
  946. region of space that supports mspace_malloc, etc.
  947. */
  948. typedef void* mspace;
  949. /*
  950. create_mspace creates and returns a new independent space with the
  951. given initial capacity, or, if 0, the default granularity size. It
  952. returns null if there is no system memory available to create the
  953. space. If argument locked is non-zero, the space uses a separate
  954. lock to control access. The capacity of the space will grow
  955. dynamically as needed to service mspace_malloc requests. You can
  956. control the sizes of incremental increases of this space by
  957. compiling with a different DEFAULT_GRANULARITY or dynamically
  958. setting with mallopt(M_GRANULARITY, value).
  959. */
  960. mspace create_mspace(size_t capacity, int locked);
  961. /*
  962. destroy_mspace destroys the given space, and attempts to return all
  963. of its memory back to the system, returning the total number of
  964. bytes freed. After destruction, the results of access to all memory
  965. used by the space become undefined.
  966. */
  967. size_t destroy_mspace(mspace msp);
  968. /*
  969. create_mspace_with_base uses the memory supplied as the initial base
  970. of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
  971. space is used for bookkeeping, so the capacity must be at least this
  972. large. (Otherwise 0 is returned.) When this initial space is
  973. exhausted, additional memory will be obtained from the system.
  974. Destroying this space will deallocate all additionally allocated
  975. space (if possible) but not the initial base.
  976. */
  977. mspace create_mspace_with_base(void* base, size_t capacity, int locked);
  978. /*
  979. mspace_malloc behaves as malloc, but operates within
  980. the given space.
  981. */
  982. void* mspace_malloc(mspace msp, size_t bytes);
  983. /*
  984. mspace_free behaves as free, but operates within
  985. the given space.
  986. If compiled with FOOTERS==1, mspace_free is not actually needed.
  987. free may be called instead of mspace_free because freed chunks from
  988. any space are handled by their originating spaces.
  989. */
  990. void mspace_free(mspace msp, void* mem);
  991. /*
  992. mspace_realloc behaves as realloc, but operates within
  993. the given space.
  994. If compiled with FOOTERS==1, mspace_realloc is not actually
  995. needed. realloc may be called instead of mspace_realloc because
  996. realloced chunks from any space are handled by their originating
  997. spaces.
  998. */
  999. void* mspace_realloc(mspace msp, void* mem, size_t newsize);
  1000. /*
  1001. mspace_calloc behaves as calloc, but operates within
  1002. the given space.
  1003. */
  1004. void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
  1005. /*
  1006. mspace_memalign behaves as memalign, but operates within
  1007. the given space.
  1008. */
  1009. void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
  1010. /*
  1011. mspace_independent_calloc behaves as independent_calloc, but
  1012. operates within the given space.
  1013. */
  1014. void** mspace_independent_calloc(mspace msp, size_t n_elements,
  1015. size_t elem_size, void* chunk