You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5703 lines
195 KiB

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