Counter Strike : Global Offensive Source Code
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.

5652 lines
194 KiB

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