malloc.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. /*
  2. This is a version (aka dlmalloc) of malloc/free/realloc written by
  3. Doug Lea and released to the public domain. Use, modify, and
  4. redistribute this code without permission or acknowledgement in any
  5. way you wish. Send questions, comments, complaints, performance
  6. data, etc to dl@cs.oswego.edu
  7. VERSION 2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
  8. Note: There may be an updated version of this malloc obtainable at
  9. ftp://gee.cs.oswego.edu/pub/misc/malloc.c
  10. Check before installing!
  11. Hacked up for uClibc by Erik Andersen <andersen@codepoet.org>
  12. */
  13. #define sysconf __sysconf
  14. #include <features.h>
  15. #include <stddef.h>
  16. #include <unistd.h>
  17. #include <errno.h>
  18. #include <string.h>
  19. #include <malloc.h>
  20. #include <stdlib.h>
  21. #ifdef __UCLIBC_HAS_THREADS__
  22. # include <pthread.h>
  23. extern pthread_mutex_t __malloc_lock;
  24. #endif
  25. #define LOCK __pthread_mutex_lock(&__malloc_lock)
  26. #define UNLOCK __pthread_mutex_unlock(&__malloc_lock)
  27. /*
  28. MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.
  29. It must be a power of two at least 2 * (sizeof(size_t)), even on machines
  30. for which smaller alignments would suffice. It may be defined as
  31. larger than this though. Note however that code and data structures
  32. are optimized for the case of 8-byte alignment.
  33. */
  34. #ifndef MALLOC_ALIGNMENT
  35. #define MALLOC_ALIGNMENT (2 * (sizeof(size_t)))
  36. #endif
  37. /* The corresponding bit mask value */
  38. #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
  39. /*
  40. TRIM_FASTBINS controls whether free() of a very small chunk can
  41. immediately lead to trimming. Setting to true (1) can reduce memory
  42. footprint, but will almost always slow down programs that use a lot
  43. of small chunks.
  44. Define this only if you are willing to give up some speed to more
  45. aggressively reduce system-level memory footprint when releasing
  46. memory in programs that use many small chunks. You can get
  47. essentially the same effect by setting MXFAST to 0, but this can
  48. lead to even greater slowdowns in programs using many small chunks.
  49. TRIM_FASTBINS is an in-between compile-time option, that disables
  50. only those chunks bordering topmost memory from being placed in
  51. fastbins.
  52. */
  53. #ifndef TRIM_FASTBINS
  54. #define TRIM_FASTBINS 0
  55. #endif
  56. /*
  57. MORECORE-related declarations. By default, rely on sbrk
  58. */
  59. /*
  60. MORECORE is the name of the routine to call to obtain more memory
  61. from the system. See below for general guidance on writing
  62. alternative MORECORE functions, as well as a version for WIN32 and a
  63. sample version for pre-OSX macos.
  64. */
  65. #ifndef MORECORE
  66. #define MORECORE sbrk
  67. #endif
  68. /*
  69. MORECORE_FAILURE is the value returned upon failure of MORECORE
  70. as well as mmap. Since it cannot be an otherwise valid memory address,
  71. and must reflect values of standard sys calls, you probably ought not
  72. try to redefine it.
  73. */
  74. #ifndef MORECORE_FAILURE
  75. #define MORECORE_FAILURE (-1)
  76. #endif
  77. /*
  78. If MORECORE_CONTIGUOUS is true, take advantage of fact that
  79. consecutive calls to MORECORE with positive arguments always return
  80. contiguous increasing addresses. This is true of unix sbrk. Even
  81. if not defined, when regions happen to be contiguous, malloc will
  82. permit allocations spanning regions obtained from different
  83. calls. But defining this when applicable enables some stronger
  84. consistency checks and space efficiencies.
  85. */
  86. #ifndef MORECORE_CONTIGUOUS
  87. #define MORECORE_CONTIGUOUS 1
  88. #endif
  89. /*
  90. MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
  91. sbrk fails, and mmap is used as a backup (which is done only if
  92. HAVE_MMAP). The value must be a multiple of page size. This
  93. backup strategy generally applies only when systems have "holes" in
  94. address space, so sbrk cannot perform contiguous expansion, but
  95. there is still space available on system. On systems for which
  96. this is known to be useful (i.e. most linux kernels), this occurs
  97. only when programs allocate huge amounts of memory. Between this,
  98. and the fact that mmap regions tend to be limited, the size should
  99. be large, to avoid too many mmap calls and thus avoid running out
  100. of kernel resources.
  101. */
  102. #ifndef MMAP_AS_MORECORE_SIZE
  103. #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
  104. #endif
  105. /*
  106. The system page size. To the extent possible, this malloc manages
  107. memory from the system in page-size units. Note that this value is
  108. cached during initialization into a field of malloc_state. So even
  109. if malloc_getpagesize is a function, it is only called once.
  110. The following mechanics for getpagesize were adapted from bsd/gnu
  111. getpagesize.h. If none of the system-probes here apply, a value of
  112. 4096 is used, which should be OK: If they don't apply, then using
  113. the actual value probably doesn't impact performance.
  114. */
  115. #ifndef malloc_getpagesize
  116. # include <unistd.h>
  117. # define malloc_getpagesize sysconf(_SC_PAGESIZE)
  118. #else /* just guess */
  119. # define malloc_getpagesize (4096)
  120. #endif
  121. /* mallopt tuning options */
  122. /*
  123. M_MXFAST is the maximum request size used for "fastbins", special bins
  124. that hold returned chunks without consolidating their spaces. This
  125. enables future requests for chunks of the same size to be handled
  126. very quickly, but can increase fragmentation, and thus increase the
  127. overall memory footprint of a program.
  128. This malloc manages fastbins very conservatively yet still
  129. efficiently, so fragmentation is rarely a problem for values less
  130. than or equal to the default. The maximum supported value of MXFAST
  131. is 80. You wouldn't want it any higher than this anyway. Fastbins
  132. are designed especially for use with many small structs, objects or
  133. strings -- the default handles structs/objects/arrays with sizes up
  134. to 16 4byte fields, or small strings representing words, tokens,
  135. etc. Using fastbins for larger objects normally worsens
  136. fragmentation without improving speed.
  137. M_MXFAST is set in REQUEST size units. It is internally used in
  138. chunksize units, which adds padding and alignment. You can reduce
  139. M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
  140. algorithm to be a closer approximation of fifo-best-fit in all cases,
  141. not just for larger requests, but will generally cause it to be
  142. slower.
  143. */
  144. /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
  145. #ifndef M_MXFAST
  146. #define M_MXFAST 1
  147. #endif
  148. #ifndef DEFAULT_MXFAST
  149. #define DEFAULT_MXFAST 64
  150. #endif
  151. /*
  152. M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
  153. to keep before releasing via malloc_trim in free().
  154. Automatic trimming is mainly useful in long-lived programs.
  155. Because trimming via sbrk can be slow on some systems, and can
  156. sometimes be wasteful (in cases where programs immediately
  157. afterward allocate more large chunks) the value should be high
  158. enough so that your overall system performance would improve by
  159. releasing this much memory.
  160. The trim threshold and the mmap control parameters (see below)
  161. can be traded off with one another. Trimming and mmapping are
  162. two different ways of releasing unused memory back to the
  163. system. Between these two, it is often possible to keep
  164. system-level demands of a long-lived program down to a bare
  165. minimum. For example, in one test suite of sessions measuring
  166. the XF86 X server on Linux, using a trim threshold of 128K and a
  167. mmap threshold of 192K led to near-minimal long term resource
  168. consumption.
  169. If you are using this malloc in a long-lived program, it should
  170. pay to experiment with these values. As a rough guide, you
  171. might set to a value close to the average size of a process
  172. (program) running on your system. Releasing this much memory
  173. would allow such a process to run in memory. Generally, it's
  174. worth it to tune for trimming rather tham memory mapping when a
  175. program undergoes phases where several large chunks are
  176. allocated and released in ways that can reuse each other's
  177. storage, perhaps mixed with phases where there are no such
  178. chunks at all. And in well-behaved long-lived programs,
  179. controlling release of large blocks via trimming versus mapping
  180. is usually faster.
  181. However, in most programs, these parameters serve mainly as
  182. protection against the system-level effects of carrying around
  183. massive amounts of unneeded memory. Since frequent calls to
  184. sbrk, mmap, and munmap otherwise degrade performance, the default
  185. parameters are set to relatively high values that serve only as
  186. safeguards.
  187. The trim value must be greater than page size to have any useful
  188. effect. To disable trimming completely, you can set to
  189. (unsigned long)(-1)
  190. Trim settings interact with fastbin (MXFAST) settings: Unless
  191. TRIM_FASTBINS is defined, automatic trimming never takes place upon
  192. freeing a chunk with size less than or equal to MXFAST. Trimming is
  193. instead delayed until subsequent freeing of larger chunks. However,
  194. you can still force an attempted trim by calling malloc_trim.
  195. Also, trimming is not generally possible in cases where
  196. the main arena is obtained via mmap.
  197. Note that the trick some people use of mallocing a huge space and
  198. then freeing it at program startup, in an attempt to reserve system
  199. memory, doesn't have the intended effect under automatic trimming,
  200. since that memory will immediately be returned to the system.
  201. */
  202. #define M_TRIM_THRESHOLD -1
  203. #ifndef DEFAULT_TRIM_THRESHOLD
  204. #define DEFAULT_TRIM_THRESHOLD (256 * 1024)
  205. #endif
  206. /*
  207. M_TOP_PAD is the amount of extra `padding' space to allocate or
  208. retain whenever sbrk is called. It is used in two ways internally:
  209. * When sbrk is called to extend the top of the arena to satisfy
  210. a new malloc request, this much padding is added to the sbrk
  211. request.
  212. * When malloc_trim is called automatically from free(),
  213. it is used as the `pad' argument.
  214. In both cases, the actual amount of padding is rounded
  215. so that the end of the arena is always a system page boundary.
  216. The main reason for using padding is to avoid calling sbrk so
  217. often. Having even a small pad greatly reduces the likelihood
  218. that nearly every malloc request during program start-up (or
  219. after trimming) will invoke sbrk, which needlessly wastes
  220. time.
  221. Automatic rounding-up to page-size units is normally sufficient
  222. to avoid measurable overhead, so the default is 0. However, in
  223. systems where sbrk is relatively slow, it can pay to increase
  224. this value, at the expense of carrying around more memory than
  225. the program needs.
  226. */
  227. #define M_TOP_PAD -2
  228. #ifndef DEFAULT_TOP_PAD
  229. #define DEFAULT_TOP_PAD (0)
  230. #endif
  231. /*
  232. M_MMAP_THRESHOLD is the request size threshold for using mmap()
  233. to service a request. Requests of at least this size that cannot
  234. be allocated using already-existing space will be serviced via mmap.
  235. (If enough normal freed space already exists it is used instead.)
  236. Using mmap segregates relatively large chunks of memory so that
  237. they can be individually obtained and released from the host
  238. system. A request serviced through mmap is never reused by any
  239. other request (at least not directly; the system may just so
  240. happen to remap successive requests to the same locations).
  241. Segregating space in this way has the benefits that:
  242. 1. Mmapped space can ALWAYS be individually released back
  243. to the system, which helps keep the system level memory
  244. demands of a long-lived program low.
  245. 2. Mapped memory can never become `locked' between
  246. other chunks, as can happen with normally allocated chunks, which
  247. means that even trimming via malloc_trim would not release them.
  248. 3. On some systems with "holes" in address spaces, mmap can obtain
  249. memory that sbrk cannot.
  250. However, it has the disadvantages that:
  251. 1. The space cannot be reclaimed, consolidated, and then
  252. used to service later requests, as happens with normal chunks.
  253. 2. It can lead to more wastage because of mmap page alignment
  254. requirements
  255. 3. It causes malloc performance to be more dependent on host
  256. system memory management support routines which may vary in
  257. implementation quality and may impose arbitrary
  258. limitations. Generally, servicing a request via normal
  259. malloc steps is faster than going through a system's mmap.
  260. The advantages of mmap nearly always outweigh disadvantages for
  261. "large" chunks, but the value of "large" varies across systems. The
  262. default is an empirically derived value that works well in most
  263. systems.
  264. */
  265. #define M_MMAP_THRESHOLD -3
  266. #ifndef DEFAULT_MMAP_THRESHOLD
  267. #define DEFAULT_MMAP_THRESHOLD (256 * 1024)
  268. #endif
  269. /*
  270. M_MMAP_MAX is the maximum number of requests to simultaneously
  271. service using mmap. This parameter exists because
  272. . Some systems have a limited number of internal tables for
  273. use by mmap, and using more than a few of them may degrade
  274. performance.
  275. The default is set to a value that serves only as a safeguard.
  276. Setting to 0 disables use of mmap for servicing large requests. If
  277. HAVE_MMAP is not set, the default value is 0, and attempts to set it
  278. to non-zero values in mallopt will fail.
  279. */
  280. #define M_MMAP_MAX -4
  281. #ifndef DEFAULT_MMAP_MAX
  282. #define DEFAULT_MMAP_MAX (65536)
  283. #endif
  284. /* ------------------ MMAP support ------------------ */
  285. #include <fcntl.h>
  286. #include <sys/mman.h>
  287. #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
  288. #define MAP_ANONYMOUS MAP_ANON
  289. #endif
  290. #ifdef __ARCH_HAS_MMU__
  291. #define MMAP(addr, size, prot) \
  292. (mmap((addr), (size), (prot), MAP_PRIVATE|MAP_ANONYMOUS, 0, 0))
  293. #else
  294. #define MMAP(addr, size, prot) \
  295. (mmap((addr), (size), (prot), MAP_SHARED|MAP_ANONYMOUS, 0, 0))
  296. #endif
  297. /* ----------------------- Chunk representations ----------------------- */
  298. /*
  299. This struct declaration is misleading (but accurate and necessary).
  300. It declares a "view" into memory allowing access to necessary
  301. fields at known offsets from a given base. See explanation below.
  302. */
  303. struct malloc_chunk {
  304. size_t prev_size; /* Size of previous chunk (if free). */
  305. size_t size; /* Size in bytes, including overhead. */
  306. struct malloc_chunk* fd; /* double links -- used only if free. */
  307. struct malloc_chunk* bk;
  308. };
  309. typedef struct malloc_chunk* mchunkptr;
  310. /*
  311. malloc_chunk details:
  312. (The following includes lightly edited explanations by Colin Plumb.)
  313. Chunks of memory are maintained using a `boundary tag' method as
  314. described in e.g., Knuth or Standish. (See the paper by Paul
  315. Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
  316. survey of such techniques.) Sizes of free chunks are stored both
  317. in the front of each chunk and at the end. This makes
  318. consolidating fragmented chunks into bigger chunks very fast. The
  319. size fields also hold bits representing whether chunks are free or
  320. in use.
  321. An allocated chunk looks like this:
  322. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  323. | Size of previous chunk, if allocated | |
  324. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  325. | Size of chunk, in bytes |P|
  326. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  327. | User data starts here... .
  328. . .
  329. . (malloc_usable_space() bytes) .
  330. . |
  331. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  332. | Size of chunk |
  333. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  334. Where "chunk" is the front of the chunk for the purpose of most of
  335. the malloc code, but "mem" is the pointer that is returned to the
  336. user. "Nextchunk" is the beginning of the next contiguous chunk.
  337. Chunks always begin on even word boundries, so the mem portion
  338. (which is returned to the user) is also on an even word boundary, and
  339. thus at least double-word aligned.
  340. Free chunks are stored in circular doubly-linked lists, and look like this:
  341. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  342. | Size of previous chunk |
  343. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  344. `head:' | Size of chunk, in bytes |P|
  345. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  346. | Forward pointer to next chunk in list |
  347. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  348. | Back pointer to previous chunk in list |
  349. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  350. | Unused space (may be 0 bytes long) .
  351. . .
  352. . |
  353. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  354. `foot:' | Size of chunk, in bytes |
  355. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  356. The P (PREV_INUSE) bit, stored in the unused low-order bit of the
  357. chunk size (which is always a multiple of two words), is an in-use
  358. bit for the *previous* chunk. If that bit is *clear*, then the
  359. word before the current chunk size contains the previous chunk
  360. size, and can be used to find the front of the previous chunk.
  361. The very first chunk allocated always has this bit set,
  362. preventing access to non-existent (or non-owned) memory. If
  363. prev_inuse is set for any given chunk, then you CANNOT determine
  364. the size of the previous chunk, and might even get a memory
  365. addressing fault when trying to do so.
  366. Note that the `foot' of the current chunk is actually represented
  367. as the prev_size of the NEXT chunk. This makes it easier to
  368. deal with alignments etc but can be very confusing when trying
  369. to extend or adapt this code.
  370. The two exceptions to all this are
  371. 1. The special chunk `top' doesn't bother using the
  372. trailing size field since there is no next contiguous chunk
  373. that would have to index off it. After initialization, `top'
  374. is forced to always exist. If it would become less than
  375. MINSIZE bytes long, it is replenished.
  376. 2. Chunks allocated via mmap, which have the second-lowest-order
  377. bit (IS_MMAPPED) set in their size fields. Because they are
  378. allocated one-by-one, each must contain its own trailing size field.
  379. */
  380. /*
  381. ---------- Size and alignment checks and conversions ----------
  382. */
  383. /* conversion from malloc headers to user pointers, and back */
  384. #define chunk2mem(p) ((void*)((char*)(p) + 2*(sizeof(size_t))))
  385. #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*(sizeof(size_t))))
  386. /* The smallest possible chunk */
  387. #define MIN_CHUNK_SIZE (sizeof(struct malloc_chunk))
  388. /* The smallest size we can malloc is an aligned minimal chunk */
  389. #define MINSIZE \
  390. (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
  391. /* Check if m has acceptable alignment */
  392. #define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
  393. /* Check if a request is so large that it would wrap around zero when
  394. padded and aligned. To simplify some other code, the bound is made
  395. low enough so that adding MINSIZE will also not wrap around sero.
  396. */
  397. #define REQUEST_OUT_OF_RANGE(req) \
  398. ((unsigned long)(req) >= \
  399. (unsigned long)(size_t)(-2 * MINSIZE))
  400. /* pad request bytes into a usable size -- internal version */
  401. #define request2size(req) \
  402. (((req) + (sizeof(size_t)) + MALLOC_ALIGN_MASK < MINSIZE) ? \
  403. MINSIZE : \
  404. ((req) + (sizeof(size_t)) + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
  405. /* Same, except also perform argument check */
  406. #define checked_request2size(req, sz) \
  407. if (REQUEST_OUT_OF_RANGE(req)) { \
  408. errno = ENOMEM; \
  409. return 0; \
  410. } \
  411. (sz) = request2size(req);
  412. /*
  413. --------------- Physical chunk operations ---------------
  414. */
  415. /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
  416. #define PREV_INUSE 0x1
  417. /* extract inuse bit of previous chunk */
  418. #define prev_inuse(p) ((p)->size & PREV_INUSE)
  419. /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
  420. #define IS_MMAPPED 0x2
  421. /* check for mmap()'ed chunk */
  422. #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
  423. /* Bits to mask off when extracting size
  424. Note: IS_MMAPPED is intentionally not masked off from size field in
  425. macros for which mmapped chunks should never be seen. This should
  426. cause helpful core dumps to occur if it is tried by accident by
  427. people extending or adapting this malloc.
  428. */
  429. #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
  430. /* Get size, ignoring use bits */
  431. #define chunksize(p) ((p)->size & ~(SIZE_BITS))
  432. /* Ptr to next physical malloc_chunk. */
  433. #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
  434. /* Ptr to previous physical malloc_chunk */
  435. #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
  436. /* Treat space at ptr + offset as a chunk */
  437. #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
  438. /* extract p's inuse bit */
  439. #define inuse(p)\
  440. ((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
  441. /* set/clear chunk as being inuse without otherwise disturbing */
  442. #define set_inuse(p)\
  443. ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
  444. #define clear_inuse(p)\
  445. ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
  446. /* check/set/clear inuse bits in known places */
  447. #define inuse_bit_at_offset(p, s)\
  448. (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
  449. #define set_inuse_bit_at_offset(p, s)\
  450. (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
  451. #define clear_inuse_bit_at_offset(p, s)\
  452. (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
  453. /* Set size at head, without disturbing its use bit */
  454. #define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
  455. /* Set size/use field */
  456. #define set_head(p, s) ((p)->size = (s))
  457. /* Set size at footer (only when chunk is not in use) */
  458. #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
  459. /* -------------------- Internal data structures -------------------- */
  460. /*
  461. Bins
  462. An array of bin headers for free chunks. Each bin is doubly
  463. linked. The bins are approximately proportionally (log) spaced.
  464. There are a lot of these bins (128). This may look excessive, but
  465. works very well in practice. Most bins hold sizes that are
  466. unusual as malloc request sizes, but are more usual for fragments
  467. and consolidated sets of chunks, which is what these bins hold, so
  468. they can be found quickly. All procedures maintain the invariant
  469. that no consolidated chunk physically borders another one, so each
  470. chunk in a list is known to be preceeded and followed by either
  471. inuse chunks or the ends of memory.
  472. Chunks in bins are kept in size order, with ties going to the
  473. approximately least recently used chunk. Ordering isn't needed
  474. for the small bins, which all contain the same-sized chunks, but
  475. facilitates best-fit allocation for larger chunks. These lists
  476. are just sequential. Keeping them in order almost never requires
  477. enough traversal to warrant using fancier ordered data
  478. structures.
  479. Chunks of the same size are linked with the most
  480. recently freed at the front, and allocations are taken from the
  481. back. This results in LRU (FIFO) allocation order, which tends
  482. to give each chunk an equal opportunity to be consolidated with
  483. adjacent freed chunks, resulting in larger free chunks and less
  484. fragmentation.
  485. To simplify use in double-linked lists, each bin header acts
  486. as a malloc_chunk. This avoids special-casing for headers.
  487. But to conserve space and improve locality, we allocate
  488. only the fd/bk pointers of bins, and then use repositioning tricks
  489. to treat these as the fields of a malloc_chunk*.
  490. */
  491. typedef struct malloc_chunk* mbinptr;
  492. /* addressing -- note that bin_at(0) does not exist */
  493. #define bin_at(m, i) ((mbinptr)((char*)&((m)->bins[(i)<<1]) - ((sizeof(size_t))<<1)))
  494. /* analog of ++bin */
  495. #define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1)))
  496. /* Reminders about list directionality within bins */
  497. #define first(b) ((b)->fd)
  498. #define last(b) ((b)->bk)
  499. /* Take a chunk off a bin list */
  500. #define unlink(P, BK, FD) { \
  501. FD = P->fd; \
  502. BK = P->bk; \
  503. if (FD->bk != P || BK->fd != P) \
  504. abort(); \
  505. FD->bk = BK; \
  506. BK->fd = FD; \
  507. }
  508. /*
  509. Indexing
  510. Bins for sizes < 512 bytes contain chunks of all the same size, spaced
  511. 8 bytes apart. Larger bins are approximately logarithmically spaced:
  512. 64 bins of size 8
  513. 32 bins of size 64
  514. 16 bins of size 512
  515. 8 bins of size 4096
  516. 4 bins of size 32768
  517. 2 bins of size 262144
  518. 1 bin of size what's left
  519. The bins top out around 1MB because we expect to service large
  520. requests via mmap.
  521. */
  522. #define NBINS 96
  523. #define NSMALLBINS 32
  524. #define SMALLBIN_WIDTH 8
  525. #define MIN_LARGE_SIZE 256
  526. #define in_smallbin_range(sz) \
  527. ((unsigned long)(sz) < (unsigned long)MIN_LARGE_SIZE)
  528. #define smallbin_index(sz) (((unsigned)(sz)) >> 3)
  529. #define bin_index(sz) \
  530. ((in_smallbin_range(sz)) ? smallbin_index(sz) : __malloc_largebin_index(sz))
  531. /*
  532. FIRST_SORTED_BIN_SIZE is the chunk size corresponding to the
  533. first bin that is maintained in sorted order. This must
  534. be the smallest size corresponding to a given bin.
  535. Normally, this should be MIN_LARGE_SIZE. But you can weaken
  536. best fit guarantees to sometimes speed up malloc by increasing value.
  537. Doing this means that malloc may choose a chunk that is
  538. non-best-fitting by up to the width of the bin.
  539. Some useful cutoff values:
  540. 512 - all bins sorted
  541. 2560 - leaves bins <= 64 bytes wide unsorted
  542. 12288 - leaves bins <= 512 bytes wide unsorted
  543. 65536 - leaves bins <= 4096 bytes wide unsorted
  544. 262144 - leaves bins <= 32768 bytes wide unsorted
  545. -1 - no bins sorted (not recommended!)
  546. */
  547. #define FIRST_SORTED_BIN_SIZE MIN_LARGE_SIZE
  548. /* #define FIRST_SORTED_BIN_SIZE 65536 */
  549. /*
  550. Unsorted chunks
  551. All remainders from chunk splits, as well as all returned chunks,
  552. are first placed in the "unsorted" bin. They are then placed
  553. in regular bins after malloc gives them ONE chance to be used before
  554. binning. So, basically, the unsorted_chunks list acts as a queue,
  555. with chunks being placed on it in free (and __malloc_consolidate),
  556. and taken off (to be either used or placed in bins) in malloc.
  557. */
  558. /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
  559. #define unsorted_chunks(M) (bin_at(M, 1))
  560. /*
  561. Top
  562. The top-most available chunk (i.e., the one bordering the end of
  563. available memory) is treated specially. It is never included in
  564. any bin, is used only if no other chunk is available, and is
  565. released back to the system if it is very large (see
  566. M_TRIM_THRESHOLD). Because top initially
  567. points to its own bin with initial zero size, thus forcing
  568. extension on the first malloc request, we avoid having any special
  569. code in malloc to check whether it even exists yet. But we still
  570. need to do so when getting memory from system, so we make
  571. initial_top treat the bin as a legal but unusable chunk during the
  572. interval between initialization and the first call to
  573. __malloc_alloc. (This is somewhat delicate, since it relies on
  574. the 2 preceding words to be zero during this interval as well.)
  575. */
  576. /* Conveniently, the unsorted bin can be used as dummy top on first call */
  577. #define initial_top(M) (unsorted_chunks(M))
  578. /*
  579. Binmap
  580. To help compensate for the large number of bins, a one-level index
  581. structure is used for bin-by-bin searching. `binmap' is a
  582. bitvector recording whether bins are definitely empty so they can
  583. be skipped over during during traversals. The bits are NOT always
  584. cleared as soon as bins are empty, but instead only
  585. when they are noticed to be empty during traversal in malloc.
  586. */
  587. /* Conservatively use 32 bits per map word, even if on 64bit system */
  588. #define BINMAPSHIFT 5
  589. #define BITSPERMAP (1U << BINMAPSHIFT)
  590. #define BINMAPSIZE (NBINS / BITSPERMAP)
  591. #define idx2block(i) ((i) >> BINMAPSHIFT)
  592. #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1))))
  593. #define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i))
  594. #define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i)))
  595. #define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i))
  596. /*
  597. Fastbins
  598. An array of lists holding recently freed small chunks. Fastbins
  599. are not doubly linked. It is faster to single-link them, and
  600. since chunks are never removed from the middles of these lists,
  601. double linking is not necessary. Also, unlike regular bins, they
  602. are not even processed in FIFO order (they use faster LIFO) since
  603. ordering doesn't much matter in the transient contexts in which
  604. fastbins are normally used.
  605. Chunks in fastbins keep their inuse bit set, so they cannot
  606. be consolidated with other free chunks. __malloc_consolidate
  607. releases all chunks in fastbins and consolidates them with
  608. other free chunks.
  609. */
  610. typedef struct malloc_chunk* mfastbinptr;
  611. /* offset 2 to use otherwise unindexable first 2 bins */
  612. #define fastbin_index(sz) ((((unsigned int)(sz)) >> 3) - 2)
  613. /* The maximum fastbin request size we support */
  614. #define MAX_FAST_SIZE 80
  615. #define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1)
  616. /*
  617. FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
  618. that triggers automatic consolidation of possibly-surrounding
  619. fastbin chunks. This is a heuristic, so the exact value should not
  620. matter too much. It is defined at half the default trim threshold as a
  621. compromise heuristic to only attempt consolidation if it is likely
  622. to lead to trimming. However, it is not dynamically tunable, since
  623. consolidation reduces fragmentation surrounding loarge chunks even
  624. if trimming is not used.
  625. */
  626. #define FASTBIN_CONSOLIDATION_THRESHOLD \
  627. ((unsigned long)(DEFAULT_TRIM_THRESHOLD) >> 1)
  628. /*
  629. Since the lowest 2 bits in max_fast don't matter in size comparisons,
  630. they are used as flags.
  631. */
  632. /*
  633. ANYCHUNKS_BIT held in max_fast indicates that there may be any
  634. freed chunks at all. It is set true when entering a chunk into any
  635. bin.
  636. */
  637. #define ANYCHUNKS_BIT (1U)
  638. #define have_anychunks(M) (((M)->max_fast & ANYCHUNKS_BIT))
  639. #define set_anychunks(M) ((M)->max_fast |= ANYCHUNKS_BIT)
  640. #define clear_anychunks(M) ((M)->max_fast &= ~ANYCHUNKS_BIT)
  641. /*
  642. FASTCHUNKS_BIT held in max_fast indicates that there are probably
  643. some fastbin chunks. It is set true on entering a chunk into any
  644. fastbin, and cleared only in __malloc_consolidate.
  645. */
  646. #define FASTCHUNKS_BIT (2U)
  647. #define have_fastchunks(M) (((M)->max_fast & FASTCHUNKS_BIT))
  648. #define set_fastchunks(M) ((M)->max_fast |= (FASTCHUNKS_BIT|ANYCHUNKS_BIT))
  649. #define clear_fastchunks(M) ((M)->max_fast &= ~(FASTCHUNKS_BIT))
  650. /* Set value of max_fast. Use impossibly small value if 0. */
  651. #define set_max_fast(M, s) \
  652. (M)->max_fast = (((s) == 0)? SMALLBIN_WIDTH: request2size(s)) | \
  653. ((M)->max_fast & (FASTCHUNKS_BIT|ANYCHUNKS_BIT))
  654. #define get_max_fast(M) \
  655. ((M)->max_fast & ~(FASTCHUNKS_BIT | ANYCHUNKS_BIT))
  656. /*
  657. morecore_properties is a status word holding dynamically discovered
  658. or controlled properties of the morecore function
  659. */
  660. #define MORECORE_CONTIGUOUS_BIT (1U)
  661. #define contiguous(M) \
  662. (((M)->morecore_properties & MORECORE_CONTIGUOUS_BIT))
  663. #define noncontiguous(M) \
  664. (((M)->morecore_properties & MORECORE_CONTIGUOUS_BIT) == 0)
  665. #define set_contiguous(M) \
  666. ((M)->morecore_properties |= MORECORE_CONTIGUOUS_BIT)
  667. #define set_noncontiguous(M) \
  668. ((M)->morecore_properties &= ~MORECORE_CONTIGUOUS_BIT)
  669. /*
  670. ----------- Internal state representation and initialization -----------
  671. */
  672. struct malloc_state {
  673. /* The maximum chunk size to be eligible for fastbin */
  674. size_t max_fast; /* low 2 bits used as flags */
  675. /* Fastbins */
  676. mfastbinptr fastbins[NFASTBINS];
  677. /* Base of the topmost chunk -- not otherwise kept in a bin */
  678. mchunkptr top;
  679. /* The remainder from the most recent split of a small request */
  680. mchunkptr last_remainder;
  681. /* Normal bins packed as described above */
  682. mchunkptr bins[NBINS * 2];
  683. /* Bitmap of bins. Trailing zero map handles cases of largest binned size */
  684. unsigned int binmap[BINMAPSIZE+1];
  685. /* Tunable parameters */
  686. unsigned long trim_threshold;
  687. size_t top_pad;
  688. size_t mmap_threshold;
  689. /* Memory map support */
  690. int n_mmaps;
  691. int n_mmaps_max;
  692. int max_n_mmaps;
  693. /* Cache malloc_getpagesize */
  694. unsigned int pagesize;
  695. /* Track properties of MORECORE */
  696. unsigned int morecore_properties;
  697. /* Statistics */
  698. size_t mmapped_mem;
  699. size_t sbrked_mem;
  700. size_t max_sbrked_mem;
  701. size_t max_mmapped_mem;
  702. size_t max_total_mem;
  703. };
  704. typedef struct malloc_state *mstate;
  705. /*
  706. There is exactly one instance of this struct in this malloc.
  707. If you are adapting this malloc in a way that does NOT use a static
  708. malloc_state, you MUST explicitly zero-fill it before using. This
  709. malloc relies on the property that malloc_state is initialized to
  710. all zeroes (as is true of C statics).
  711. */
  712. extern struct malloc_state __malloc_state; /* never directly referenced */
  713. /*
  714. All uses of av_ are via get_malloc_state().
  715. At most one "call" to get_malloc_state is made per invocation of
  716. the public versions of malloc and free, but other routines
  717. that in turn invoke malloc and/or free may call more then once.
  718. Also, it is called in check* routines if __MALLOC_DEBUGGING is set.
  719. */
  720. #define get_malloc_state() (&(__malloc_state))
  721. /* External internal utilities operating on mstates */
  722. void __malloc_consolidate(mstate);
  723. /* Debugging support */
  724. #if ! __MALLOC_DEBUGGING
  725. #define check_chunk(P)
  726. #define check_free_chunk(P)
  727. #define check_inuse_chunk(P)
  728. #define check_remalloced_chunk(P,N)
  729. #define check_malloced_chunk(P,N)
  730. #define check_malloc_state()
  731. #define assert(x) ((void)0)
  732. #else
  733. #define check_chunk(P) __do_check_chunk(P)
  734. #define check_free_chunk(P) __do_check_free_chunk(P)
  735. #define check_inuse_chunk(P) __do_check_inuse_chunk(P)
  736. #define check_remalloced_chunk(P,N) __do_check_remalloced_chunk(P,N)
  737. #define check_malloced_chunk(P,N) __do_check_malloced_chunk(P,N)
  738. #define check_malloc_state() __do_check_malloc_state()
  739. extern void __do_check_chunk(mchunkptr p);
  740. extern void __do_check_free_chunk(mchunkptr p);
  741. extern void __do_check_inuse_chunk(mchunkptr p);
  742. extern void __do_check_remalloced_chunk(mchunkptr p, size_t s);
  743. extern void __do_check_malloced_chunk(mchunkptr p, size_t s);
  744. extern void __do_check_malloc_state(void);
  745. #include <assert.h>
  746. #endif