malloc.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  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. __UCLIBC_MUTEX_INIT(__malloc_lock, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP);
  15. /*
  16. There is exactly one instance of this struct in this malloc.
  17. If you are adapting this malloc in a way that does NOT use a static
  18. malloc_state, you MUST explicitly zero-fill it before using. This
  19. malloc relies on the property that malloc_state is initialized to
  20. all zeroes (as is true of C statics).
  21. */
  22. struct malloc_state __malloc_state; /* never directly referenced */
  23. /* forward declaration */
  24. static int __malloc_largebin_index(unsigned int sz);
  25. #ifdef __UCLIBC_MALLOC_DEBUGGING__
  26. /*
  27. Debugging support
  28. Because freed chunks may be overwritten with bookkeeping fields, this
  29. malloc will often die when freed memory is overwritten by user
  30. programs. This can be very effective (albeit in an annoying way)
  31. in helping track down dangling pointers.
  32. If you compile with __UCLIBC_MALLOC_DEBUGGING__, a number of assertion checks are
  33. enabled that will catch more memory errors. You probably won't be
  34. able to make much sense of the actual assertion errors, but they
  35. should help you locate incorrectly overwritten memory. The
  36. checking is fairly extensive, and will slow down execution
  37. noticeably. Calling malloc_stats or mallinfo with __UCLIBC_MALLOC_DEBUGGING__ set will
  38. attempt to check every non-mmapped allocated and free chunk in the
  39. course of computing the summmaries. (By nature, mmapped regions
  40. cannot be checked very much automatically.)
  41. Setting __UCLIBC_MALLOC_DEBUGGING__ may also be helpful if you are trying to modify
  42. this code. The assertions in the check routines spell out in more
  43. detail the assumptions and invariants underlying the algorithms.
  44. Setting __UCLIBC_MALLOC_DEBUGGING__ does NOT provide an automated mechanism for checking
  45. that all accesses to malloced memory stay within their
  46. bounds. However, there are several add-ons and adaptations of this
  47. or other mallocs available that do this.
  48. */
  49. /* Properties of all chunks */
  50. void __do_check_chunk(mchunkptr p)
  51. {
  52. mstate av = get_malloc_state();
  53. #ifdef __DOASSERTS__
  54. /* min and max possible addresses assuming contiguous allocation */
  55. char* max_address = (char*)(av->top) + chunksize(av->top);
  56. char* min_address = max_address - av->sbrked_mem;
  57. unsigned long sz = chunksize(p);
  58. #endif
  59. if (!chunk_is_mmapped(p)) {
  60. /* Has legal address ... */
  61. if (p != av->top) {
  62. if (contiguous(av)) {
  63. assert(((char*)p) >= min_address);
  64. assert(((char*)p + sz) <= ((char*)(av->top)));
  65. }
  66. }
  67. else {
  68. /* top size is always at least MINSIZE */
  69. assert((unsigned long)(sz) >= MINSIZE);
  70. /* top predecessor always marked inuse */
  71. assert(prev_inuse(p));
  72. }
  73. }
  74. else {
  75. /* address is outside main heap */
  76. if (contiguous(av) && av->top != initial_top(av)) {
  77. assert(((char*)p) < min_address || ((char*)p) > max_address);
  78. }
  79. /* chunk is page-aligned */
  80. assert(((p->prev_size + sz) & (av->pagesize-1)) == 0);
  81. /* mem is aligned */
  82. assert(aligned_OK(chunk2mem(p)));
  83. }
  84. }
  85. /* Properties of free chunks */
  86. void __do_check_free_chunk(mchunkptr p)
  87. {
  88. size_t sz = p->size & ~PREV_INUSE;
  89. #ifdef __DOASSERTS__
  90. mstate av = get_malloc_state();
  91. mchunkptr next = chunk_at_offset(p, sz);
  92. #endif
  93. __do_check_chunk(p);
  94. /* Chunk must claim to be free ... */
  95. assert(!inuse(p));
  96. assert (!chunk_is_mmapped(p));
  97. /* Unless a special marker, must have OK fields */
  98. if ((unsigned long)(sz) >= MINSIZE)
  99. {
  100. assert((sz & MALLOC_ALIGN_MASK) == 0);
  101. assert(aligned_OK(chunk2mem(p)));
  102. /* ... matching footer field */
  103. assert(next->prev_size == sz);
  104. /* ... and is fully consolidated */
  105. assert(prev_inuse(p));
  106. assert (next == av->top || inuse(next));
  107. /* ... and has minimally sane links */
  108. assert(p->fd->bk == p);
  109. assert(p->bk->fd == p);
  110. }
  111. else /* markers are always of size (sizeof(size_t)) */
  112. assert(sz == (sizeof(size_t)));
  113. }
  114. /* Properties of inuse chunks */
  115. void __do_check_inuse_chunk(mchunkptr p)
  116. {
  117. mstate av = get_malloc_state();
  118. mchunkptr next;
  119. __do_check_chunk(p);
  120. if (chunk_is_mmapped(p))
  121. return; /* mmapped chunks have no next/prev */
  122. /* Check whether it claims to be in use ... */
  123. assert(inuse(p));
  124. next = next_chunk(p);
  125. /* ... and is surrounded by OK chunks.
  126. Since more things can be checked with free chunks than inuse ones,
  127. if an inuse chunk borders them and debug is on, it's worth doing them.
  128. */
  129. if (!prev_inuse(p)) {
  130. /* Note that we cannot even look at prev unless it is not inuse */
  131. mchunkptr prv = prev_chunk(p);
  132. assert(next_chunk(prv) == p);
  133. __do_check_free_chunk(prv);
  134. }
  135. if (next == av->top) {
  136. assert(prev_inuse(next));
  137. assert(chunksize(next) >= MINSIZE);
  138. }
  139. else if (!inuse(next))
  140. __do_check_free_chunk(next);
  141. }
  142. /* Properties of chunks recycled from fastbins */
  143. void __do_check_remalloced_chunk(mchunkptr p, size_t s)
  144. {
  145. #ifdef __DOASSERTS__
  146. size_t sz = p->size & ~PREV_INUSE;
  147. #endif
  148. __do_check_inuse_chunk(p);
  149. /* Legal size ... */
  150. assert((sz & MALLOC_ALIGN_MASK) == 0);
  151. assert((unsigned long)(sz) >= MINSIZE);
  152. /* ... and alignment */
  153. assert(aligned_OK(chunk2mem(p)));
  154. /* chunk is less than MINSIZE more than request */
  155. assert((long)(sz) - (long)(s) >= 0);
  156. assert((long)(sz) - (long)(s + MINSIZE) < 0);
  157. }
  158. /* Properties of nonrecycled chunks at the point they are malloced */
  159. void __do_check_malloced_chunk(mchunkptr p, size_t s)
  160. {
  161. /* same as recycled case ... */
  162. __do_check_remalloced_chunk(p, s);
  163. /*
  164. ... plus, must obey implementation invariant that prev_inuse is
  165. always true of any allocated chunk; i.e., that each allocated
  166. chunk borders either a previously allocated and still in-use
  167. chunk, or the base of its memory arena. This is ensured
  168. by making all allocations from the the `lowest' part of any found
  169. chunk. This does not necessarily hold however for chunks
  170. recycled via fastbins.
  171. */
  172. assert(prev_inuse(p));
  173. }
  174. /*
  175. Properties of malloc_state.
  176. This may be useful for debugging malloc, as well as detecting user
  177. programmer errors that somehow write into malloc_state.
  178. If you are extending or experimenting with this malloc, you can
  179. probably figure out how to hack this routine to print out or
  180. display chunk addresses, sizes, bins, and other instrumentation.
  181. */
  182. void __do_check_malloc_state(void)
  183. {
  184. mstate av = get_malloc_state();
  185. int i;
  186. mchunkptr p;
  187. mchunkptr q;
  188. mbinptr b;
  189. unsigned int binbit;
  190. int empty;
  191. unsigned int idx;
  192. size_t size;
  193. unsigned long total = 0;
  194. int max_fast_bin;
  195. /* internal size_t must be no wider than pointer type */
  196. assert(sizeof(size_t) <= sizeof(char*));
  197. /* alignment is a power of 2 */
  198. assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0);
  199. /* cannot run remaining checks until fully initialized */
  200. if (av->top == 0 || av->top == initial_top(av))
  201. return;
  202. /* pagesize is a power of 2 */
  203. assert((av->pagesize & (av->pagesize-1)) == 0);
  204. /* properties of fastbins */
  205. /* max_fast is in allowed range */
  206. assert(get_max_fast(av) <= request2size(MAX_FAST_SIZE));
  207. max_fast_bin = fastbin_index(av->max_fast);
  208. for (i = 0; i < NFASTBINS; ++i) {
  209. p = av->fastbins[i];
  210. /* all bins past max_fast are empty */
  211. if (i > max_fast_bin)
  212. assert(p == 0);
  213. while (p != 0) {
  214. CHECK_PTR(p);
  215. /* each chunk claims to be inuse */
  216. __do_check_inuse_chunk(p);
  217. total += chunksize(p);
  218. /* chunk belongs in this bin */
  219. assert(fastbin_index(chunksize(p)) == i);
  220. p = REVEAL_PTR(&p->fd, p->fd);
  221. }
  222. }
  223. if (total != 0)
  224. assert(have_fastchunks(av));
  225. else if (!have_fastchunks(av))
  226. assert(total == 0);
  227. /* check normal bins */
  228. for (i = 1; i < NBINS; ++i) {
  229. b = bin_at(av,i);
  230. /* binmap is accurate (except for bin 1 == unsorted_chunks) */
  231. if (i >= 2) {
  232. binbit = get_binmap(av,i);
  233. empty = last(b) == b;
  234. if (!binbit)
  235. assert(empty);
  236. else if (!empty)
  237. assert(binbit);
  238. }
  239. for (p = last(b); p != b; p = p->bk) {
  240. /* each chunk claims to be free */
  241. __do_check_free_chunk(p);
  242. size = chunksize(p);
  243. total += size;
  244. if (i >= 2) {
  245. /* chunk belongs in bin */
  246. idx = bin_index(size);
  247. assert(idx == i);
  248. /* lists are sorted */
  249. if ((unsigned long) size >= (unsigned long)(FIRST_SORTED_BIN_SIZE)) {
  250. assert(p->bk == b ||
  251. (unsigned long)chunksize(p->bk) >=
  252. (unsigned long)chunksize(p));
  253. }
  254. }
  255. /* chunk is followed by a legal chain of inuse chunks */
  256. for (q = next_chunk(p);
  257. (q != av->top && inuse(q) &&
  258. (unsigned long)(chunksize(q)) >= MINSIZE);
  259. q = next_chunk(q))
  260. __do_check_inuse_chunk(q);
  261. }
  262. }
  263. /* top chunk is OK */
  264. __do_check_chunk(av->top);
  265. /* sanity checks for statistics */
  266. assert(total <= (unsigned long)(av->max_total_mem));
  267. assert(av->n_mmaps >= 0);
  268. assert(av->n_mmaps <= av->max_n_mmaps);
  269. assert((unsigned long)(av->sbrked_mem) <=
  270. (unsigned long)(av->max_sbrked_mem));
  271. assert((unsigned long)(av->mmapped_mem) <=
  272. (unsigned long)(av->max_mmapped_mem));
  273. assert((unsigned long)(av->max_total_mem) >=
  274. (unsigned long)(av->mmapped_mem) + (unsigned long)(av->sbrked_mem));
  275. }
  276. #endif
  277. /* ----------- Routines dealing with system allocation -------------- */
  278. /*
  279. sysmalloc handles malloc cases requiring more memory from the system.
  280. On entry, it is assumed that av->top does not have enough
  281. space to service request for nb bytes, thus requiring that av->top
  282. be extended or replaced.
  283. */
  284. static void* __malloc_alloc(size_t nb, mstate av)
  285. {
  286. mchunkptr old_top; /* incoming value of av->top */
  287. size_t old_size; /* its size */
  288. char* old_end; /* its end address */
  289. long size; /* arg to first MORECORE or mmap call */
  290. char* fst_brk; /* return value from MORECORE */
  291. long correction; /* arg to 2nd MORECORE call */
  292. char* snd_brk; /* 2nd return val */
  293. size_t front_misalign; /* unusable bytes at front of new space */
  294. size_t end_misalign; /* partial page left at end of new space */
  295. char* aligned_brk; /* aligned offset into brk */
  296. mchunkptr p; /* the allocated/returned chunk */
  297. mchunkptr remainder; /* remainder from allocation */
  298. unsigned long remainder_size; /* its size */
  299. unsigned long sum; /* for updating stats */
  300. size_t pagemask = av->pagesize - 1;
  301. /*
  302. If there is space available in fastbins, consolidate and retry
  303. malloc from scratch rather than getting memory from system. This
  304. can occur only if nb is in smallbin range so we didn't consolidate
  305. upon entry to malloc. It is much easier to handle this case here
  306. than in malloc proper.
  307. */
  308. if (have_fastchunks(av)) {
  309. assert(in_smallbin_range(nb));
  310. __malloc_consolidate(av);
  311. return malloc(nb - MALLOC_ALIGN_MASK);
  312. }
  313. /*
  314. If have mmap, and the request size meets the mmap threshold, and
  315. the system supports mmap, and there are few enough currently
  316. allocated mmapped regions, try to directly map this request
  317. rather than expanding top.
  318. */
  319. if ((unsigned long)(nb) >= (unsigned long)(av->mmap_threshold) &&
  320. (av->n_mmaps < av->n_mmaps_max)) {
  321. char* mm; /* return value from mmap call*/
  322. /*
  323. Round up size to nearest page. For mmapped chunks, the overhead
  324. is one (sizeof(size_t)) unit larger than for normal chunks, because there
  325. is no following chunk whose prev_size field could be used.
  326. */
  327. size = (nb + (sizeof(size_t)) + MALLOC_ALIGN_MASK + pagemask) & ~pagemask;
  328. /* Don't try if size wraps around 0 */
  329. if ((unsigned long)(size) > (unsigned long)(nb)) {
  330. mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE));
  331. if (mm != (char*)(MORECORE_FAILURE)) {
  332. /*
  333. The offset to the start of the mmapped region is stored
  334. in the prev_size field of the chunk. This allows us to adjust
  335. returned start address to meet alignment requirements here
  336. and in memalign(), and still be able to compute proper
  337. address argument for later munmap in free() and realloc().
  338. */
  339. front_misalign = (size_t)chunk2mem(mm) & MALLOC_ALIGN_MASK;
  340. if (front_misalign > 0) {
  341. correction = MALLOC_ALIGNMENT - front_misalign;
  342. p = (mchunkptr)(mm + correction);
  343. p->prev_size = correction;
  344. set_head(p, (size - correction) |IS_MMAPPED);
  345. }
  346. else {
  347. p = (mchunkptr)mm;
  348. p->prev_size = 0;
  349. set_head(p, size|IS_MMAPPED);
  350. }
  351. /* update statistics */
  352. if (++av->n_mmaps > av->max_n_mmaps)
  353. av->max_n_mmaps = av->n_mmaps;
  354. sum = av->mmapped_mem += size;
  355. if (sum > (unsigned long)(av->max_mmapped_mem))
  356. av->max_mmapped_mem = sum;
  357. sum += av->sbrked_mem;
  358. if (sum > (unsigned long)(av->max_total_mem))
  359. av->max_total_mem = sum;
  360. check_chunk(p);
  361. return chunk2mem(p);
  362. }
  363. }
  364. }
  365. /* Record incoming configuration of top */
  366. old_top = av->top;
  367. old_size = chunksize(old_top);
  368. old_end = (char*)(chunk_at_offset(old_top, old_size));
  369. fst_brk = snd_brk = (char*)(MORECORE_FAILURE);
  370. /* If not the first time through, we require old_size to
  371. * be at least MINSIZE and to have prev_inuse set. */
  372. assert((old_top == initial_top(av) && old_size == 0) ||
  373. ((unsigned long) (old_size) >= MINSIZE &&
  374. prev_inuse(old_top)));
  375. /* Precondition: not enough current space to satisfy nb request */
  376. assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE));
  377. /* Precondition: all fastbins are consolidated */
  378. assert(!have_fastchunks(av));
  379. /* Request enough space for nb + pad + overhead */
  380. size = nb + av->top_pad + MINSIZE;
  381. /*
  382. If contiguous, we can subtract out existing space that we hope to
  383. combine with new space. We add it back later only if
  384. we don't actually get contiguous space.
  385. */
  386. if (contiguous(av))
  387. size -= old_size;
  388. /*
  389. Round to a multiple of page size.
  390. If MORECORE is not contiguous, this ensures that we only call it
  391. with whole-page arguments. And if MORECORE is contiguous and
  392. this is not first time through, this preserves page-alignment of
  393. previous calls. Otherwise, we correct to page-align below.
  394. */
  395. size = (size + pagemask) & ~pagemask;
  396. /*
  397. Don't try to call MORECORE if argument is so big as to appear
  398. negative. Note that since mmap takes size_t arg, it may succeed
  399. below even if we cannot call MORECORE.
  400. */
  401. if (size > 0)
  402. fst_brk = (char*)(MORECORE(size));
  403. /*
  404. If have mmap, try using it as a backup when MORECORE fails or
  405. cannot be used. This is worth doing on systems that have "holes" in
  406. address space, so sbrk cannot extend to give contiguous space, but
  407. space is available elsewhere. Note that we ignore mmap max count
  408. and threshold limits, since the space will not be used as a
  409. segregated mmap region.
  410. */
  411. if (fst_brk == (char*)(MORECORE_FAILURE)) {
  412. /* Cannot merge with old top, so add its size back in */
  413. if (contiguous(av))
  414. size = (size + old_size + pagemask) & ~pagemask;
  415. /* If we are relying on mmap as backup, then use larger units */
  416. if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE))
  417. size = MMAP_AS_MORECORE_SIZE;
  418. /* Don't try if size wraps around 0 */
  419. if ((unsigned long)(size) > (unsigned long)(nb)) {
  420. fst_brk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE));
  421. if (fst_brk != (char*)(MORECORE_FAILURE)) {
  422. /* We do not need, and cannot use, another sbrk call to find end */
  423. snd_brk = fst_brk + size;
  424. /* Record that we no longer have a contiguous sbrk region.
  425. After the first time mmap is used as backup, we do not
  426. ever rely on contiguous space since this could incorrectly
  427. bridge regions.
  428. */
  429. set_noncontiguous(av);
  430. }
  431. }
  432. }
  433. if (fst_brk != (char*)(MORECORE_FAILURE)) {
  434. av->sbrked_mem += size;
  435. /*
  436. If MORECORE extends previous space, we can likewise extend top size.
  437. */
  438. if (fst_brk == old_end && snd_brk == (char*)(MORECORE_FAILURE)) {
  439. set_head(old_top, (size + old_size) | PREV_INUSE);
  440. }
  441. /*
  442. Otherwise, make adjustments:
  443. * If the first time through or noncontiguous, we need to call sbrk
  444. just to find out where the end of memory lies.
  445. * We need to ensure that all returned chunks from malloc will meet
  446. MALLOC_ALIGNMENT
  447. * If there was an intervening foreign sbrk, we need to adjust sbrk
  448. request size to account for fact that we will not be able to
  449. combine new space with existing space in old_top.
  450. * Almost all systems internally allocate whole pages at a time, in
  451. which case we might as well use the whole last page of request.
  452. So we allocate enough more memory to hit a page boundary now,
  453. which in turn causes future contiguous calls to page-align.
  454. */
  455. else {
  456. front_misalign = 0;
  457. end_misalign = 0;
  458. correction = 0;
  459. aligned_brk = fst_brk;
  460. /*
  461. If MORECORE returns an address lower than we have seen before,
  462. we know it isn't really contiguous. This and some subsequent
  463. checks help cope with non-conforming MORECORE functions and
  464. the presence of "foreign" calls to MORECORE from outside of
  465. malloc or by other threads. We cannot guarantee to detect
  466. these in all cases, but cope with the ones we do detect.
  467. */
  468. if (contiguous(av) && old_size != 0 && fst_brk < old_end) {
  469. set_noncontiguous(av);
  470. }
  471. /* handle contiguous cases */
  472. if (contiguous(av)) {
  473. /* We can tolerate forward non-contiguities here (usually due
  474. to foreign calls) but treat them as part of our space for
  475. stats reporting. */
  476. if (old_size != 0)
  477. av->sbrked_mem += fst_brk - old_end;
  478. /* Guarantee alignment of first new chunk made from this space */
  479. front_misalign = (size_t)chunk2mem(fst_brk) & MALLOC_ALIGN_MASK;
  480. if (front_misalign > 0) {
  481. /*
  482. Skip over some bytes to arrive at an aligned position.
  483. We don't need to specially mark these wasted front bytes.
  484. They will never be accessed anyway because
  485. prev_inuse of av->top (and any chunk created from its start)
  486. is always true after initialization.
  487. */
  488. correction = MALLOC_ALIGNMENT - front_misalign;
  489. aligned_brk += correction;
  490. }
  491. /*
  492. If this isn't adjacent to existing space, then we will not
  493. be able to merge with old_top space, so must add to 2nd request.
  494. */
  495. correction += old_size;
  496. /* Extend the end address to hit a page boundary */
  497. end_misalign = (size_t)(fst_brk + size + correction);
  498. correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign;
  499. assert(correction >= 0);
  500. snd_brk = (char*)(MORECORE(correction));
  501. if (snd_brk == (char*)(MORECORE_FAILURE)) {
  502. /*
  503. If can't allocate correction, try to at least find out current
  504. brk. It might be enough to proceed without failing.
  505. */
  506. correction = 0;
  507. snd_brk = (char*)(MORECORE(0));
  508. }
  509. else if (snd_brk < fst_brk) {
  510. /*
  511. If the second call gives noncontiguous space even though
  512. it says it won't, the only course of action is to ignore
  513. results of second call, and conservatively estimate where
  514. the first call left us. Also set noncontiguous, so this
  515. won't happen again, leaving at most one hole.
  516. Note that this check is intrinsically incomplete. Because
  517. MORECORE is allowed to give more space than we ask for,
  518. there is no reliable way to detect a noncontiguity
  519. producing a forward gap for the second call.
  520. */
  521. snd_brk = fst_brk + size;
  522. correction = 0;
  523. set_noncontiguous(av);
  524. }
  525. }
  526. /* handle non-contiguous cases */
  527. else {
  528. /* MORECORE/mmap must correctly align */
  529. assert(aligned_OK(chunk2mem(fst_brk)));
  530. /* Find out current end of memory */
  531. if (snd_brk == (char*)(MORECORE_FAILURE)) {
  532. snd_brk = (char*)(MORECORE(0));
  533. av->sbrked_mem += snd_brk - fst_brk - size;
  534. }
  535. }
  536. /* Adjust top based on results of second sbrk */
  537. if (snd_brk != (char*)(MORECORE_FAILURE)) {
  538. av->top = (mchunkptr)aligned_brk;
  539. set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
  540. av->sbrked_mem += correction;
  541. /*
  542. If not the first time through, we either have a
  543. gap due to foreign sbrk or a non-contiguous region. Insert a
  544. double fencepost at old_top to prevent consolidation with space
  545. we don't own. These fenceposts are artificial chunks that are
  546. marked as inuse and are in any case too small to use. We need
  547. two to make sizes and alignments work out.
  548. */
  549. if (old_size != 0) {
  550. /* Shrink old_top to insert fenceposts, keeping size a
  551. multiple of MALLOC_ALIGNMENT. We know there is at least
  552. enough space in old_top to do this.
  553. */
  554. old_size = (old_size - 3*(sizeof(size_t))) & ~MALLOC_ALIGN_MASK;
  555. set_head(old_top, old_size | PREV_INUSE);
  556. /*
  557. Note that the following assignments completely overwrite
  558. old_top when old_size was previously MINSIZE. This is
  559. intentional. We need the fencepost, even if old_top otherwise gets
  560. lost.
  561. */
  562. chunk_at_offset(old_top, old_size )->size =
  563. (sizeof(size_t))|PREV_INUSE;
  564. chunk_at_offset(old_top, old_size + (sizeof(size_t)))->size =
  565. (sizeof(size_t))|PREV_INUSE;
  566. /* If possible, release the rest, suppressing trimming. */
  567. if (old_size >= MINSIZE) {
  568. size_t tt = av->trim_threshold;
  569. av->trim_threshold = (size_t)(-1);
  570. free(chunk2mem(old_top));
  571. av->trim_threshold = tt;
  572. }
  573. }
  574. }
  575. }
  576. /* Update statistics */
  577. sum = av->sbrked_mem;
  578. if (sum > (unsigned long)(av->max_sbrked_mem))
  579. av->max_sbrked_mem = sum;
  580. sum += av->mmapped_mem;
  581. if (sum > (unsigned long)(av->max_total_mem))
  582. av->max_total_mem = sum;
  583. check_malloc_state();
  584. /* finally, do the allocation */
  585. p = av->top;
  586. size = chunksize(p);
  587. /* check that one of the above allocation paths succeeded */
  588. if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
  589. remainder_size = size - nb;
  590. remainder = chunk_at_offset(p, nb);
  591. av->top = remainder;
  592. set_head(p, nb | PREV_INUSE);
  593. set_head(remainder, remainder_size | PREV_INUSE);
  594. check_malloced_chunk(p, nb);
  595. return chunk2mem(p);
  596. }
  597. }
  598. /* catch all failure paths */
  599. __set_errno(ENOMEM);
  600. return 0;
  601. }
  602. /*
  603. Compute index for size. We expect this to be inlined when
  604. compiled with optimization, else not, which works out well.
  605. */
  606. static int __malloc_largebin_index(unsigned int sz)
  607. {
  608. unsigned int x = sz >> SMALLBIN_WIDTH;
  609. unsigned int m; /* bit position of highest set bit of m */
  610. if (x >= 0x10000) return NBINS-1;
  611. /* On intel, use BSRL instruction to find highest bit */
  612. #if defined(__GNUC__) && defined(i386)
  613. __asm__("bsrl %1,%0\n\t"
  614. : "=r" (m)
  615. : "g" (x));
  616. #else
  617. {
  618. /*
  619. Based on branch-free nlz algorithm in chapter 5 of Henry
  620. S. Warren Jr's book "Hacker's Delight".
  621. */
  622. unsigned int n = ((x - 0x100) >> 16) & 8;
  623. x <<= n;
  624. m = ((x - 0x1000) >> 16) & 4;
  625. n += m;
  626. x <<= m;
  627. m = ((x - 0x4000) >> 16) & 2;
  628. n += m;
  629. x = (x << m) >> 14;
  630. m = 13 - n + (x & ~(x>>1));
  631. }
  632. #endif
  633. /* Use next 2 bits to create finer-granularity bins */
  634. return NSMALLBINS + (m << 2) + ((sz >> (m + 6)) & 3);
  635. }
  636. /* ----------------------------------------------------------------------
  637. *
  638. * PUBLIC STUFF
  639. *
  640. * ----------------------------------------------------------------------*/
  641. /* ------------------------------ malloc ------------------------------ */
  642. void* malloc(size_t bytes)
  643. {
  644. mstate av;
  645. size_t nb; /* normalized request size */
  646. unsigned int idx; /* associated bin index */
  647. mbinptr bin; /* associated bin */
  648. mfastbinptr* fb; /* associated fastbin */
  649. mchunkptr victim; /* inspected/selected chunk */
  650. size_t size; /* its size */
  651. int victim_index; /* its bin index */
  652. mchunkptr remainder; /* remainder from a split */
  653. unsigned long remainder_size; /* its size */
  654. unsigned int block; /* bit map traverser */
  655. unsigned int bit; /* bit map traverser */
  656. unsigned int map; /* current word of binmap */
  657. mchunkptr fwd; /* misc temp for linking */
  658. mchunkptr bck; /* misc temp for linking */
  659. void * sysmem;
  660. void * retval;
  661. /*
  662. Convert request size to internal form by adding (sizeof(size_t)) bytes
  663. overhead plus possibly more to obtain necessary alignment and/or
  664. to obtain a size of at least MINSIZE, the smallest allocatable
  665. size. Also, checked_request2size traps (returning 0) request sizes
  666. that are so large that they wrap around zero when padded and
  667. aligned.
  668. */
  669. checked_request2size(bytes, nb);
  670. __MALLOC_LOCK;
  671. av = get_malloc_state();
  672. /*
  673. Bypass search if no frees yet
  674. */
  675. if (!have_anychunks(av)) {
  676. if (av->max_fast == 0) /* initialization check */
  677. __malloc_consolidate(av);
  678. goto use_top;
  679. }
  680. /*
  681. If the size qualifies as a fastbin, first check corresponding bin.
  682. */
  683. if ((unsigned long)(nb) <= (unsigned long)(av->max_fast)) {
  684. fb = &(av->fastbins[(fastbin_index(nb))]);
  685. if ( (victim = *fb) != 0) {
  686. CHECK_PTR(victim);
  687. *fb = REVEAL_PTR(&victim->fd, victim->fd);
  688. check_remalloced_chunk(victim, nb);
  689. retval = chunk2mem(victim);
  690. goto DONE;
  691. }
  692. }
  693. /*
  694. If a small request, check regular bin. Since these "smallbins"
  695. hold one size each, no searching within bins is necessary.
  696. (For a large request, we need to wait until unsorted chunks are
  697. processed to find best fit. But for small ones, fits are exact
  698. anyway, so we can check now, which is faster.)
  699. */
  700. if (in_smallbin_range(nb)) {
  701. idx = smallbin_index(nb);
  702. bin = bin_at(av,idx);
  703. if ( (victim = last(bin)) != bin) {
  704. bck = victim->bk;
  705. set_inuse_bit_at_offset(victim, nb);
  706. bin->bk = bck;
  707. bck->fd = bin;
  708. check_malloced_chunk(victim, nb);
  709. retval = chunk2mem(victim);
  710. goto DONE;
  711. }
  712. }
  713. /* If this is a large request, consolidate fastbins before continuing.
  714. While it might look excessive to kill all fastbins before
  715. even seeing if there is space available, this avoids
  716. fragmentation problems normally associated with fastbins.
  717. Also, in practice, programs tend to have runs of either small or
  718. large requests, but less often mixtures, so consolidation is not
  719. invoked all that often in most programs. And the programs that
  720. it is called frequently in otherwise tend to fragment.
  721. */
  722. else {
  723. idx = __malloc_largebin_index(nb);
  724. if (have_fastchunks(av))
  725. __malloc_consolidate(av);
  726. }
  727. /*
  728. Process recently freed or remaindered chunks, taking one only if
  729. it is exact fit, or, if this a small request, the chunk is remainder from
  730. the most recent non-exact fit. Place other traversed chunks in
  731. bins. Note that this step is the only place in any routine where
  732. chunks are placed in bins.
  733. */
  734. while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
  735. bck = victim->bk;
  736. size = chunksize(victim);
  737. /* If a small request, try to use last remainder if it is the
  738. only chunk in unsorted bin. This helps promote locality for
  739. runs of consecutive small requests. This is the only
  740. exception to best-fit, and applies only when there is
  741. no exact fit for a small chunk.
  742. */
  743. if (in_smallbin_range(nb) &&
  744. bck == unsorted_chunks(av) &&
  745. victim == av->last_remainder &&
  746. (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
  747. /* split and reattach remainder */
  748. remainder_size = size - nb;
  749. remainder = chunk_at_offset(victim, nb);
  750. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  751. av->last_remainder = remainder;
  752. remainder->bk = remainder->fd = unsorted_chunks(av);
  753. set_head(victim, nb | PREV_INUSE);
  754. set_head(remainder, remainder_size | PREV_INUSE);
  755. set_foot(remainder, remainder_size);
  756. check_malloced_chunk(victim, nb);
  757. retval = chunk2mem(victim);
  758. goto DONE;
  759. }
  760. /* remove from unsorted list */
  761. unsorted_chunks(av)->bk = bck;
  762. bck->fd = unsorted_chunks(av);
  763. /* Take now instead of binning if exact fit */
  764. if (size == nb) {
  765. set_inuse_bit_at_offset(victim, size);
  766. check_malloced_chunk(victim, nb);
  767. retval = chunk2mem(victim);
  768. goto DONE;
  769. }
  770. /* place chunk in bin */
  771. if (in_smallbin_range(size)) {
  772. victim_index = smallbin_index(size);
  773. bck = bin_at(av, victim_index);
  774. fwd = bck->fd;
  775. }
  776. else {
  777. victim_index = __malloc_largebin_index(size);
  778. bck = bin_at(av, victim_index);
  779. fwd = bck->fd;
  780. if (fwd != bck) {
  781. /* if smaller than smallest, place first */
  782. if ((unsigned long)(size) < (unsigned long)(bck->bk->size)) {
  783. fwd = bck;
  784. bck = bck->bk;
  785. }
  786. else if ((unsigned long)(size) >=
  787. (unsigned long)(FIRST_SORTED_BIN_SIZE)) {
  788. /* maintain large bins in sorted order */
  789. size |= PREV_INUSE; /* Or with inuse bit to speed comparisons */
  790. while ((unsigned long)(size) < (unsigned long)(fwd->size))
  791. fwd = fwd->fd;
  792. bck = fwd->bk;
  793. }
  794. }
  795. }
  796. mark_bin(av, victim_index);
  797. victim->bk = bck;
  798. victim->fd = fwd;
  799. fwd->bk = victim;
  800. bck->fd = victim;
  801. }
  802. /*
  803. If a large request, scan through the chunks of current bin to
  804. find one that fits. (This will be the smallest that fits unless
  805. FIRST_SORTED_BIN_SIZE has been changed from default.) This is
  806. the only step where an unbounded number of chunks might be
  807. scanned without doing anything useful with them. However the
  808. lists tend to be short.
  809. */
  810. if (!in_smallbin_range(nb)) {
  811. bin = bin_at(av, idx);
  812. for (victim = last(bin); victim != bin; victim = victim->bk) {
  813. size = chunksize(victim);
  814. if ((unsigned long)(size) >= (unsigned long)(nb)) {
  815. remainder_size = size - nb;
  816. unlink(victim, bck, fwd);
  817. /* Exhaust */
  818. if (remainder_size < MINSIZE) {
  819. set_inuse_bit_at_offset(victim, size);
  820. check_malloced_chunk(victim, nb);
  821. retval = chunk2mem(victim);
  822. goto DONE;
  823. }
  824. /* Split */
  825. else {
  826. remainder = chunk_at_offset(victim, nb);
  827. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  828. remainder->bk = remainder->fd = unsorted_chunks(av);
  829. set_head(victim, nb | PREV_INUSE);
  830. set_head(remainder, remainder_size | PREV_INUSE);
  831. set_foot(remainder, remainder_size);
  832. check_malloced_chunk(victim, nb);
  833. retval = chunk2mem(victim);
  834. goto DONE;
  835. }
  836. }
  837. }
  838. }
  839. /*
  840. Search for a chunk by scanning bins, starting with next largest
  841. bin. This search is strictly by best-fit; i.e., the smallest
  842. (with ties going to approximately the least recently used) chunk
  843. that fits is selected.
  844. The bitmap avoids needing to check that most blocks are nonempty.
  845. */
  846. ++idx;
  847. bin = bin_at(av,idx);
  848. block = idx2block(idx);
  849. map = av->binmap[block];
  850. bit = idx2bit(idx);
  851. for (;;) {
  852. /* Skip rest of block if there are no more set bits in this block. */
  853. if (bit > map || bit == 0) {
  854. do {
  855. if (++block >= BINMAPSIZE) /* out of bins */
  856. goto use_top;
  857. } while ( (map = av->binmap[block]) == 0);
  858. bin = bin_at(av, (block << BINMAPSHIFT));
  859. bit = 1;
  860. }
  861. /* Advance to bin with set bit. There must be one. */
  862. while ((bit & map) == 0) {
  863. bin = next_bin(bin);
  864. bit <<= 1;
  865. assert(bit != 0);
  866. }
  867. /* Inspect the bin. It is likely to be non-empty */
  868. victim = last(bin);
  869. /* If a false alarm (empty bin), clear the bit. */
  870. if (victim == bin) {
  871. av->binmap[block] = map &= ~bit; /* Write through */
  872. bin = next_bin(bin);
  873. bit <<= 1;
  874. }
  875. else {
  876. size = chunksize(victim);
  877. /* We know the first chunk in this bin is big enough to use. */
  878. assert((unsigned long)(size) >= (unsigned long)(nb));
  879. remainder_size = size - nb;
  880. /* unlink */
  881. bck = victim->bk;
  882. bin->bk = bck;
  883. bck->fd = bin;
  884. /* Exhaust */
  885. if (remainder_size < MINSIZE) {
  886. set_inuse_bit_at_offset(victim, size);
  887. check_malloced_chunk(victim, nb);
  888. retval = chunk2mem(victim);
  889. goto DONE;
  890. }
  891. /* Split */
  892. else {
  893. remainder = chunk_at_offset(victim, nb);
  894. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  895. remainder->bk = remainder->fd = unsorted_chunks(av);
  896. /* advertise as last remainder */
  897. if (in_smallbin_range(nb))
  898. av->last_remainder = remainder;
  899. set_head(victim, nb | PREV_INUSE);
  900. set_head(remainder, remainder_size | PREV_INUSE);
  901. set_foot(remainder, remainder_size);
  902. check_malloced_chunk(victim, nb);
  903. retval = chunk2mem(victim);
  904. goto DONE;
  905. }
  906. }
  907. }
  908. use_top:
  909. /*
  910. If large enough, split off the chunk bordering the end of memory
  911. (held in av->top). Note that this is in accord with the best-fit
  912. search rule. In effect, av->top is treated as larger (and thus
  913. less well fitting) than any other available chunk since it can
  914. be extended to be as large as necessary (up to system
  915. limitations).
  916. We require that av->top always exists (i.e., has size >=
  917. MINSIZE) after initialization, so if it would otherwise be
  918. exhuasted by current request, it is replenished. (The main
  919. reason for ensuring it exists is that we may need MINSIZE space
  920. to put in fenceposts in sysmalloc.)
  921. */
  922. victim = av->top;
  923. size = chunksize(victim);
  924. if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
  925. remainder_size = size - nb;
  926. remainder = chunk_at_offset(victim, nb);
  927. av->top = remainder;
  928. set_head(victim, nb | PREV_INUSE);
  929. set_head(remainder, remainder_size | PREV_INUSE);
  930. check_malloced_chunk(victim, nb);
  931. retval = chunk2mem(victim);
  932. goto DONE;
  933. }
  934. /* If no space in top, relay to handle system-dependent cases */
  935. sysmem = __malloc_alloc(nb, av);
  936. retval = sysmem;
  937. DONE:
  938. __MALLOC_UNLOCK;
  939. return retval;
  940. }
  941. /* glibc compatibilty */
  942. weak_alias(malloc, __libc_malloc)