free.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. #include "malloc.h"
  14. /* ------------------------- __malloc_trim -------------------------
  15. __malloc_trim is an inverse of sorts to __malloc_alloc. It gives memory
  16. back to the system (via negative arguments to sbrk) if there is unused
  17. memory at the `high' end of the malloc pool. It is called automatically by
  18. free() when top space exceeds the trim threshold. It is also called by the
  19. public malloc_trim routine. It returns 1 if it actually released any
  20. memory, else 0.
  21. */
  22. static int __malloc_trim(size_t pad, mstate av)
  23. {
  24. long top_size; /* Amount of top-most memory */
  25. long extra; /* Amount to release */
  26. long released; /* Amount actually released */
  27. char* current_brk; /* address returned by pre-check sbrk call */
  28. char* new_brk; /* address returned by post-check sbrk call */
  29. size_t pagesz;
  30. pagesz = av->pagesize;
  31. top_size = chunksize(av->top);
  32. /* Release in pagesize units, keeping at least one page */
  33. extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
  34. if (extra > 0) {
  35. /*
  36. Only proceed if end of memory is where we last set it.
  37. This avoids problems if there were foreign sbrk calls.
  38. */
  39. current_brk = (char*)(MORECORE(0));
  40. if (current_brk == (char*)(av->top) + top_size) {
  41. /*
  42. Attempt to release memory. We ignore MORECORE return value,
  43. and instead call again to find out where new end of memory is.
  44. This avoids problems if first call releases less than we asked,
  45. of if failure somehow altered brk value. (We could still
  46. encounter problems if it altered brk in some very bad way,
  47. but the only thing we can do is adjust anyway, which will cause
  48. some downstream failure.)
  49. */
  50. MORECORE(-extra);
  51. new_brk = (char*)(MORECORE(0));
  52. if (new_brk != (char*)MORECORE_FAILURE) {
  53. released = (long)(current_brk - new_brk);
  54. if (released != 0) {
  55. /* Success. Adjust top. */
  56. av->sbrked_mem -= released;
  57. set_head(av->top, (top_size - released) | PREV_INUSE);
  58. check_malloc_state();
  59. return 1;
  60. }
  61. }
  62. }
  63. }
  64. return 0;
  65. }
  66. /* ------------------------- malloc_trim -------------------------
  67. malloc_trim(size_t pad);
  68. If possible, gives memory back to the system (via negative
  69. arguments to sbrk) if there is unused memory at the `high' end of
  70. the malloc pool. You can call this after freeing large blocks of
  71. memory to potentially reduce the system-level memory requirements
  72. of a program. However, it cannot guarantee to reduce memory. Under
  73. some allocation patterns, some large free blocks of memory will be
  74. locked between two used chunks, so they cannot be given back to
  75. the system.
  76. The `pad' argument to malloc_trim represents the amount of free
  77. trailing space to leave untrimmed. If this argument is zero,
  78. only the minimum amount of memory to maintain internal data
  79. structures will be left (one page or less). Non-zero arguments
  80. can be supplied to maintain enough trailing space to service
  81. future expected allocations without having to re-obtain memory
  82. from the system.
  83. Malloc_trim returns 1 if it actually released any memory, else 0.
  84. On systems that do not support "negative sbrks", it will always
  85. return 0.
  86. */
  87. int malloc_trim(size_t pad)
  88. {
  89. mstate av = get_malloc_state();
  90. __malloc_consolidate(av);
  91. return __malloc_trim(pad, av);
  92. }
  93. /*
  94. Initialize a malloc_state struct.
  95. This is called only from within __malloc_consolidate, which needs
  96. be called in the same contexts anyway. It is never called directly
  97. outside of __malloc_consolidate because some optimizing compilers try
  98. to inline it at all call points, which turns out not to be an
  99. optimization at all. (Inlining it in __malloc_consolidate is fine though.)
  100. */
  101. static void malloc_init_state(mstate av)
  102. {
  103. int i;
  104. mbinptr bin;
  105. /* Establish circular links for normal bins */
  106. for (i = 1; i < NBINS; ++i) {
  107. bin = bin_at(av,i);
  108. bin->fd = bin->bk = bin;
  109. }
  110. av->top_pad = DEFAULT_TOP_PAD;
  111. av->n_mmaps_max = DEFAULT_MMAP_MAX;
  112. av->mmap_threshold = DEFAULT_MMAP_THRESHOLD;
  113. av->trim_threshold = DEFAULT_TRIM_THRESHOLD;
  114. #if MORECORE_CONTIGUOUS
  115. set_contiguous(av);
  116. #else
  117. set_noncontiguous(av);
  118. #endif
  119. set_max_fast(av, DEFAULT_MXFAST);
  120. av->top = initial_top(av);
  121. av->pagesize = malloc_getpagesize;
  122. }
  123. /* ----------------------------------------------------------------------
  124. *
  125. * PUBLIC STUFF
  126. *
  127. * ----------------------------------------------------------------------*/
  128. /* ------------------------- __malloc_consolidate -------------------------
  129. __malloc_consolidate is a specialized version of free() that tears
  130. down chunks held in fastbins. Free itself cannot be used for this
  131. purpose since, among other things, it might place chunks back onto
  132. fastbins. So, instead, we need to use a minor variant of the same
  133. code.
  134. Also, because this routine needs to be called the first time through
  135. malloc anyway, it turns out to be the perfect place to trigger
  136. initialization code.
  137. */
  138. void __malloc_consolidate(mstate av)
  139. {
  140. mfastbinptr* fb; /* current fastbin being consolidated */
  141. mfastbinptr* maxfb; /* last fastbin (for loop control) */
  142. mchunkptr p; /* current chunk being consolidated */
  143. mchunkptr nextp; /* next chunk to consolidate */
  144. mchunkptr unsorted_bin; /* bin header */
  145. mchunkptr first_unsorted; /* chunk to link to */
  146. /* These have same use as in free() */
  147. mchunkptr nextchunk;
  148. size_t size;
  149. size_t nextsize;
  150. size_t prevsize;
  151. int nextinuse;
  152. mchunkptr bck;
  153. mchunkptr fwd;
  154. /*
  155. If max_fast is 0, we know that av hasn't
  156. yet been initialized, in which case do so below
  157. */
  158. if (av->max_fast != 0) {
  159. clear_fastchunks(av);
  160. unsorted_bin = unsorted_chunks(av);
  161. /*
  162. Remove each chunk from fast bin and consolidate it, placing it
  163. then in unsorted bin. Among other reasons for doing this,
  164. placing in unsorted bin avoids needing to calculate actual bins
  165. until malloc is sure that chunks aren't immediately going to be
  166. reused anyway.
  167. */
  168. maxfb = &(av->fastbins[fastbin_index(av->max_fast)]);
  169. fb = &(av->fastbins[0]);
  170. do {
  171. if ( (p = *fb) != 0) {
  172. *fb = 0;
  173. do {
  174. check_inuse_chunk(p);
  175. nextp = p->fd;
  176. /* Slightly streamlined version of consolidation code in free() */
  177. size = p->size & ~PREV_INUSE;
  178. nextchunk = chunk_at_offset(p, size);
  179. nextsize = chunksize(nextchunk);
  180. if (!prev_inuse(p)) {
  181. prevsize = p->prev_size;
  182. size += prevsize;
  183. p = chunk_at_offset(p, -((long) prevsize));
  184. unlink(p, bck, fwd);
  185. }
  186. if (nextchunk != av->top) {
  187. nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
  188. set_head(nextchunk, nextsize);
  189. if (!nextinuse) {
  190. size += nextsize;
  191. unlink(nextchunk, bck, fwd);
  192. }
  193. first_unsorted = unsorted_bin->fd;
  194. unsorted_bin->fd = p;
  195. first_unsorted->bk = p;
  196. set_head(p, size | PREV_INUSE);
  197. p->bk = unsorted_bin;
  198. p->fd = first_unsorted;
  199. set_foot(p, size);
  200. }
  201. else {
  202. size += nextsize;
  203. set_head(p, size | PREV_INUSE);
  204. av->top = p;
  205. }
  206. } while ( (p = nextp) != 0);
  207. }
  208. } while (fb++ != maxfb);
  209. }
  210. else {
  211. malloc_init_state(av);
  212. check_malloc_state();
  213. }
  214. }
  215. /* ------------------------------ free ------------------------------ */
  216. void free(void* mem)
  217. {
  218. mstate av;
  219. mchunkptr p; /* chunk corresponding to mem */
  220. size_t size; /* its size */
  221. mfastbinptr* fb; /* associated fastbin */
  222. mchunkptr nextchunk; /* next contiguous chunk */
  223. size_t nextsize; /* its size */
  224. int nextinuse; /* true if nextchunk is used */
  225. size_t prevsize; /* size of previous contiguous chunk */
  226. mchunkptr bck; /* misc temp for linking */
  227. mchunkptr fwd; /* misc temp for linking */
  228. /* free(0) has no effect */
  229. if (mem == NULL)
  230. return;
  231. LOCK;
  232. av = get_malloc_state();
  233. p = mem2chunk(mem);
  234. size = chunksize(p);
  235. check_inuse_chunk(p);
  236. /*
  237. If eligible, place chunk on a fastbin so it can be found
  238. and used quickly in malloc.
  239. */
  240. if ((unsigned long)(size) <= (unsigned long)(av->max_fast)
  241. #if TRIM_FASTBINS
  242. /* If TRIM_FASTBINS set, don't place chunks
  243. bordering top into fastbins */
  244. && (chunk_at_offset(p, size) != av->top)
  245. #endif
  246. ) {
  247. set_fastchunks(av);
  248. fb = &(av->fastbins[fastbin_index(size)]);
  249. p->fd = *fb;
  250. *fb = p;
  251. }
  252. /*
  253. Consolidate other non-mmapped chunks as they arrive.
  254. */
  255. else if (!chunk_is_mmapped(p)) {
  256. set_anychunks(av);
  257. nextchunk = chunk_at_offset(p, size);
  258. nextsize = chunksize(nextchunk);
  259. /* consolidate backward */
  260. if (!prev_inuse(p)) {
  261. prevsize = p->prev_size;
  262. size += prevsize;
  263. p = chunk_at_offset(p, -((long) prevsize));
  264. unlink(p, bck, fwd);
  265. }
  266. if (nextchunk != av->top) {
  267. /* get and clear inuse bit */
  268. nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
  269. set_head(nextchunk, nextsize);
  270. /* consolidate forward */
  271. if (!nextinuse) {
  272. unlink(nextchunk, bck, fwd);
  273. size += nextsize;
  274. }
  275. /*
  276. Place the chunk in unsorted chunk list. Chunks are
  277. not placed into regular bins until after they have
  278. been given one chance to be used in malloc.
  279. */
  280. bck = unsorted_chunks(av);
  281. fwd = bck->fd;
  282. p->bk = bck;
  283. p->fd = fwd;
  284. bck->fd = p;
  285. fwd->bk = p;
  286. set_head(p, size | PREV_INUSE);
  287. set_foot(p, size);
  288. check_free_chunk(p);
  289. }
  290. /*
  291. If the chunk borders the current high end of memory,
  292. consolidate into top
  293. */
  294. else {
  295. size += nextsize;
  296. set_head(p, size | PREV_INUSE);
  297. av->top = p;
  298. check_chunk(p);
  299. }
  300. /*
  301. If freeing a large space, consolidate possibly-surrounding
  302. chunks. Then, if the total unused topmost memory exceeds trim
  303. threshold, ask malloc_trim to reduce top.
  304. Unless max_fast is 0, we don't know if there are fastbins
  305. bordering top, so we cannot tell for sure whether threshold
  306. has been reached unless fastbins are consolidated. But we
  307. don't want to consolidate on each free. As a compromise,
  308. consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
  309. is reached.
  310. */
  311. if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
  312. if (have_fastchunks(av))
  313. __malloc_consolidate(av);
  314. if ((unsigned long)(chunksize(av->top)) >=
  315. (unsigned long)(av->trim_threshold))
  316. __malloc_trim(av->top_pad, av);
  317. }
  318. }
  319. /*
  320. If the chunk was allocated via mmap, release via munmap()
  321. Note that if HAVE_MMAP is false but chunk_is_mmapped is
  322. true, then user must have overwritten memory. There's nothing
  323. we can do to catch this error unless DEBUG is set, in which case
  324. check_inuse_chunk (above) will have triggered error.
  325. */
  326. else {
  327. int ret;
  328. size_t offset = p->prev_size;
  329. av->n_mmaps--;
  330. av->mmapped_mem -= (size + offset);
  331. ret = munmap((char*)p - offset, size + offset);
  332. /* munmap returns non-zero on failure */
  333. assert(ret == 0);
  334. }
  335. UNLOCK;
  336. }