malloc.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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. /* each chunk claims to be inuse */
  215. __do_check_inuse_chunk(p);
  216. total += chunksize(p);
  217. /* chunk belongs in this bin */
  218. assert(fastbin_index(chunksize(p)) == i);
  219. p = p->fd;
  220. }
  221. }
  222. if (total != 0)
  223. assert(have_fastchunks(av));
  224. else if (!have_fastchunks(av))
  225. assert(total == 0);
  226. /* check normal bins */
  227. for (i = 1; i < NBINS; ++i) {
  228. b = bin_at(av,i);
  229. /* binmap is accurate (except for bin 1 == unsorted_chunks) */
  230. if (i >= 2) {
  231. binbit = get_binmap(av,i);
  232. empty = last(b) == b;
  233. if (!binbit)
  234. assert(empty);
  235. else if (!empty)
  236. assert(binbit);
  237. }
  238. for (p = last(b); p != b; p = p->bk) {
  239. /* each chunk claims to be free */
  240. __do_check_free_chunk(p);
  241. size = chunksize(p);
  242. total += size;
  243. if (i >= 2) {
  244. /* chunk belongs in bin */
  245. idx = bin_index(size);
  246. assert(idx == i);
  247. /* lists are sorted */
  248. if ((unsigned long) size >= (unsigned long)(FIRST_SORTED_BIN_SIZE)) {
  249. assert(p->bk == b ||
  250. (unsigned long)chunksize(p->bk) >=
  251. (unsigned long)chunksize(p));
  252. }
  253. }
  254. /* chunk is followed by a legal chain of inuse chunks */
  255. for (q = next_chunk(p);
  256. (q != av->top && inuse(q) &&
  257. (unsigned long)(chunksize(q)) >= MINSIZE);
  258. q = next_chunk(q))
  259. __do_check_inuse_chunk(q);
  260. }
  261. }
  262. /* top chunk is OK */
  263. __do_check_chunk(av->top);
  264. /* sanity checks for statistics */
  265. assert(total <= (unsigned long)(av->max_total_mem));
  266. assert(av->n_mmaps >= 0);
  267. assert(av->n_mmaps <= av->max_n_mmaps);
  268. assert((unsigned long)(av->sbrked_mem) <=
  269. (unsigned long)(av->max_sbrked_mem));
  270. assert((unsigned long)(av->mmapped_mem) <=
  271. (unsigned long)(av->max_mmapped_mem));
  272. assert((unsigned long)(av->max_total_mem) >=
  273. (unsigned long)(av->mmapped_mem) + (unsigned long)(av->sbrked_mem));
  274. }
  275. #endif
  276. /* ----------- Routines dealing with system allocation -------------- */
  277. /*
  278. sysmalloc handles malloc cases requiring more memory from the system.
  279. On entry, it is assumed that av->top does not have enough
  280. space to service request for nb bytes, thus requiring that av->top
  281. be extended or replaced.
  282. */
  283. static void* __malloc_alloc(size_t nb, mstate av)
  284. {
  285. mchunkptr old_top; /* incoming value of av->top */
  286. size_t old_size; /* its size */
  287. char* old_end; /* its end address */
  288. long size; /* arg to first MORECORE or mmap call */
  289. char* fst_brk; /* return value from MORECORE */
  290. long correction; /* arg to 2nd MORECORE call */
  291. char* snd_brk; /* 2nd return val */
  292. size_t front_misalign; /* unusable bytes at front of new space */
  293. size_t end_misalign; /* partial page left at end of new space */
  294. char* aligned_brk; /* aligned offset into brk */
  295. mchunkptr p; /* the allocated/returned chunk */
  296. mchunkptr remainder; /* remainder from allocation */
  297. unsigned long remainder_size; /* its size */
  298. unsigned long sum; /* for updating stats */
  299. size_t pagemask = av->pagesize - 1;
  300. /*
  301. If there is space available in fastbins, consolidate and retry
  302. malloc from scratch rather than getting memory from system. This
  303. can occur only if nb is in smallbin range so we didn't consolidate
  304. upon entry to malloc. It is much easier to handle this case here
  305. than in malloc proper.
  306. */
  307. if (have_fastchunks(av)) {
  308. assert(in_smallbin_range(nb));
  309. __malloc_consolidate(av);
  310. return malloc(nb - MALLOC_ALIGN_MASK);
  311. }
  312. /*
  313. If have mmap, and the request size meets the mmap threshold, and
  314. the system supports mmap, and there are few enough currently
  315. allocated mmapped regions, try to directly map this request
  316. rather than expanding top.
  317. */
  318. if ((unsigned long)(nb) >= (unsigned long)(av->mmap_threshold) &&
  319. (av->n_mmaps < av->n_mmaps_max)) {
  320. char* mm; /* return value from mmap call*/
  321. /*
  322. Round up size to nearest page. For mmapped chunks, the overhead
  323. is one (sizeof(size_t)) unit larger than for normal chunks, because there
  324. is no following chunk whose prev_size field could be used.
  325. */
  326. size = (nb + (sizeof(size_t)) + MALLOC_ALIGN_MASK + pagemask) & ~pagemask;
  327. /* Don't try if size wraps around 0 */
  328. if ((unsigned long)(size) > (unsigned long)(nb)) {
  329. mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE));
  330. if (mm != (char*)(MORECORE_FAILURE)) {
  331. /*
  332. The offset to the start of the mmapped region is stored
  333. in the prev_size field of the chunk. This allows us to adjust
  334. returned start address to meet alignment requirements here
  335. and in memalign(), and still be able to compute proper
  336. address argument for later munmap in free() and realloc().
  337. */
  338. front_misalign = (size_t)chunk2mem(mm) & MALLOC_ALIGN_MASK;
  339. if (front_misalign > 0) {
  340. correction = MALLOC_ALIGNMENT - front_misalign;
  341. p = (mchunkptr)(mm + correction);
  342. p->prev_size = correction;
  343. set_head(p, (size - correction) |IS_MMAPPED);
  344. }
  345. else {
  346. p = (mchunkptr)mm;
  347. p->prev_size = 0;
  348. set_head(p, size|IS_MMAPPED);
  349. }
  350. /* update statistics */
  351. if (++av->n_mmaps > av->max_n_mmaps)
  352. av->max_n_mmaps = av->n_mmaps;
  353. sum = av->mmapped_mem += size;
  354. if (sum > (unsigned long)(av->max_mmapped_mem))
  355. av->max_mmapped_mem = sum;
  356. sum += av->sbrked_mem;
  357. if (sum > (unsigned long)(av->max_total_mem))
  358. av->max_total_mem = sum;
  359. check_chunk(p);
  360. return chunk2mem(p);
  361. }
  362. }
  363. }
  364. /* Record incoming configuration of top */
  365. old_top = av->top;
  366. old_size = chunksize(old_top);
  367. old_end = (char*)(chunk_at_offset(old_top, old_size));
  368. fst_brk = snd_brk = (char*)(MORECORE_FAILURE);
  369. /* If not the first time through, we require old_size to
  370. * be at least MINSIZE and to have prev_inuse set. */
  371. assert((old_top == initial_top(av) && old_size == 0) ||
  372. ((unsigned long) (old_size) >= MINSIZE &&
  373. prev_inuse(old_top)));
  374. /* Precondition: not enough current space to satisfy nb request */
  375. assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE));
  376. /* Precondition: all fastbins are consolidated */
  377. assert(!have_fastchunks(av));
  378. /* Request enough space for nb + pad + overhead */
  379. size = nb + av->top_pad + MINSIZE;
  380. /*
  381. If contiguous, we can subtract out existing space that we hope to
  382. combine with new space. We add it back later only if
  383. we don't actually get contiguous space.
  384. */
  385. if (contiguous(av))
  386. size -= old_size;
  387. /*
  388. Round to a multiple of page size.
  389. If MORECORE is not contiguous, this ensures that we only call it
  390. with whole-page arguments. And if MORECORE is contiguous and
  391. this is not first time through, this preserves page-alignment of
  392. previous calls. Otherwise, we correct to page-align below.
  393. */
  394. size = (size + pagemask) & ~pagemask;
  395. /*
  396. Don't try to call MORECORE if argument is so big as to appear
  397. negative. Note that since mmap takes size_t arg, it may succeed
  398. below even if we cannot call MORECORE.
  399. */
  400. if (size > 0)
  401. fst_brk = (char*)(MORECORE(size));
  402. /*
  403. If have mmap, try using it as a backup when MORECORE fails or
  404. cannot be used. This is worth doing on systems that have "holes" in
  405. address space, so sbrk cannot extend to give contiguous space, but
  406. space is available elsewhere. Note that we ignore mmap max count
  407. and threshold limits, since the space will not be used as a
  408. segregated mmap region.
  409. */
  410. if (fst_brk == (char*)(MORECORE_FAILURE)) {
  411. /* Cannot merge with old top, so add its size back in */
  412. if (contiguous(av))
  413. size = (size + old_size + pagemask) & ~pagemask;
  414. /* If we are relying on mmap as backup, then use larger units */
  415. if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE))
  416. size = MMAP_AS_MORECORE_SIZE;
  417. /* Don't try if size wraps around 0 */
  418. if ((unsigned long)(size) > (unsigned long)(nb)) {
  419. fst_brk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE));
  420. if (fst_brk != (char*)(MORECORE_FAILURE)) {
  421. /* We do not need, and cannot use, another sbrk call to find end */
  422. snd_brk = fst_brk + size;
  423. /* Record that we no longer have a contiguous sbrk region.
  424. After the first time mmap is used as backup, we do not
  425. ever rely on contiguous space since this could incorrectly
  426. bridge regions.
  427. */
  428. set_noncontiguous(av);
  429. }
  430. }
  431. }
  432. if (fst_brk != (char*)(MORECORE_FAILURE)) {
  433. av->sbrked_mem += size;
  434. /*
  435. If MORECORE extends previous space, we can likewise extend top size.
  436. */
  437. if (fst_brk == old_end && snd_brk == (char*)(MORECORE_FAILURE)) {
  438. set_head(old_top, (size + old_size) | PREV_INUSE);
  439. }
  440. /*
  441. Otherwise, make adjustments:
  442. * If the first time through or noncontiguous, we need to call sbrk
  443. just to find out where the end of memory lies.
  444. * We need to ensure that all returned chunks from malloc will meet
  445. MALLOC_ALIGNMENT
  446. * If there was an intervening foreign sbrk, we need to adjust sbrk
  447. request size to account for fact that we will not be able to
  448. combine new space with existing space in old_top.
  449. * Almost all systems internally allocate whole pages at a time, in
  450. which case we might as well use the whole last page of request.
  451. So we allocate enough more memory to hit a page boundary now,
  452. which in turn causes future contiguous calls to page-align.
  453. */
  454. else {
  455. front_misalign = 0;
  456. end_misalign = 0;
  457. correction = 0;
  458. aligned_brk = fst_brk;
  459. /*
  460. If MORECORE returns an address lower than we have seen before,
  461. we know it isn't really contiguous. This and some subsequent
  462. checks help cope with non-conforming MORECORE functions and
  463. the presence of "foreign" calls to MORECORE from outside of
  464. malloc or by other threads. We cannot guarantee to detect
  465. these in all cases, but cope with the ones we do detect.
  466. */
  467. if (contiguous(av) && old_size != 0 && fst_brk < old_end) {
  468. set_noncontiguous(av);
  469. }
  470. /* handle contiguous cases */
  471. if (contiguous(av)) {
  472. /* We can tolerate forward non-contiguities here (usually due
  473. to foreign calls) but treat them as part of our space for
  474. stats reporting. */
  475. if (old_size != 0)
  476. av->sbrked_mem += fst_brk - old_end;
  477. /* Guarantee alignment of first new chunk made from this space */
  478. front_misalign = (size_t)chunk2mem(fst_brk) & MALLOC_ALIGN_MASK;
  479. if (front_misalign > 0) {
  480. /*
  481. Skip over some bytes to arrive at an aligned position.
  482. We don't need to specially mark these wasted front bytes.
  483. They will never be accessed anyway because
  484. prev_inuse of av->top (and any chunk created from its start)
  485. is always true after initialization.
  486. */
  487. correction = MALLOC_ALIGNMENT - front_misalign;
  488. aligned_brk += correction;
  489. }
  490. /*
  491. If this isn't adjacent to existing space, then we will not
  492. be able to merge with old_top space, so must add to 2nd request.
  493. */
  494. correction += old_size;
  495. /* Extend the end address to hit a page boundary */
  496. end_misalign = (size_t)(fst_brk + size + correction);
  497. correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign;
  498. assert(correction >= 0);
  499. snd_brk = (char*)(MORECORE(correction));
  500. if (snd_brk == (char*)(MORECORE_FAILURE)) {
  501. /*
  502. If can't allocate correction, try to at least find out current
  503. brk. It might be enough to proceed without failing.
  504. */
  505. correction = 0;
  506. snd_brk = (char*)(MORECORE(0));
  507. }
  508. else if (snd_brk < fst_brk) {
  509. /*
  510. If the second call gives noncontiguous space even though
  511. it says it won't, the only course of action is to ignore
  512. results of second call, and conservatively estimate where
  513. the first call left us. Also set noncontiguous, so this
  514. won't happen again, leaving at most one hole.
  515. Note that this check is intrinsically incomplete. Because
  516. MORECORE is allowed to give more space than we ask for,
  517. there is no reliable way to detect a noncontiguity
  518. producing a forward gap for the second call.
  519. */
  520. snd_brk = fst_brk + size;
  521. correction = 0;
  522. set_noncontiguous(av);
  523. }
  524. }
  525. /* handle non-contiguous cases */
  526. else {
  527. /* MORECORE/mmap must correctly align */
  528. assert(aligned_OK(chunk2mem(fst_brk)));
  529. /* Find out current end of memory */
  530. if (snd_brk == (char*)(MORECORE_FAILURE)) {
  531. snd_brk = (char*)(MORECORE(0));
  532. av->sbrked_mem += snd_brk - fst_brk - size;
  533. }
  534. }
  535. /* Adjust top based on results of second sbrk */
  536. if (snd_brk != (char*)(MORECORE_FAILURE)) {
  537. av->top = (mchunkptr)aligned_brk;
  538. set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
  539. av->sbrked_mem += correction;
  540. /*
  541. If not the first time through, we either have a
  542. gap due to foreign sbrk or a non-contiguous region. Insert a
  543. double fencepost at old_top to prevent consolidation with space
  544. we don't own. These fenceposts are artificial chunks that are
  545. marked as inuse and are in any case too small to use. We need
  546. two to make sizes and alignments work out.
  547. */
  548. if (old_size != 0) {
  549. /* Shrink old_top to insert fenceposts, keeping size a
  550. multiple of MALLOC_ALIGNMENT. We know there is at least
  551. enough space in old_top to do this.
  552. */
  553. old_size = (old_size - 3*(sizeof(size_t))) & ~MALLOC_ALIGN_MASK;
  554. set_head(old_top, old_size | PREV_INUSE);
  555. /*
  556. Note that the following assignments completely overwrite
  557. old_top when old_size was previously MINSIZE. This is
  558. intentional. We need the fencepost, even if old_top otherwise gets
  559. lost.
  560. */
  561. chunk_at_offset(old_top, old_size )->size =
  562. (sizeof(size_t))|PREV_INUSE;
  563. chunk_at_offset(old_top, old_size + (sizeof(size_t)))->size =
  564. (sizeof(size_t))|PREV_INUSE;
  565. /* If possible, release the rest, suppressing trimming. */
  566. if (old_size >= MINSIZE) {
  567. size_t tt = av->trim_threshold;
  568. av->trim_threshold = (size_t)(-1);
  569. free(chunk2mem(old_top));
  570. av->trim_threshold = tt;
  571. }
  572. }
  573. }
  574. }
  575. /* Update statistics */
  576. sum = av->sbrked_mem;
  577. if (sum > (unsigned long)(av->max_sbrked_mem))
  578. av->max_sbrked_mem = sum;
  579. sum += av->mmapped_mem;
  580. if (sum > (unsigned long)(av->max_total_mem))
  581. av->max_total_mem = sum;
  582. check_malloc_state();
  583. /* finally, do the allocation */
  584. p = av->top;
  585. size = chunksize(p);
  586. /* check that one of the above allocation paths succeeded */
  587. if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
  588. remainder_size = size - nb;
  589. remainder = chunk_at_offset(p, nb);
  590. av->top = remainder;
  591. set_head(p, nb | PREV_INUSE);
  592. set_head(remainder, remainder_size | PREV_INUSE);
  593. check_malloced_chunk(p, nb);
  594. return chunk2mem(p);
  595. }
  596. }
  597. /* catch all failure paths */
  598. __set_errno(ENOMEM);
  599. return 0;
  600. }
  601. /*
  602. Compute index for size. We expect this to be inlined when
  603. compiled with optimization, else not, which works out well.
  604. */
  605. static int __malloc_largebin_index(unsigned int sz)
  606. {
  607. unsigned int x = sz >> SMALLBIN_WIDTH;
  608. unsigned int m; /* bit position of highest set bit of m */
  609. if (x >= 0x10000) return NBINS-1;
  610. /* On intel, use BSRL instruction to find highest bit */
  611. #if defined(__GNUC__) && defined(i386)
  612. __asm__("bsrl %1,%0\n\t"
  613. : "=r" (m)
  614. : "g" (x));
  615. #else
  616. {
  617. /*
  618. Based on branch-free nlz algorithm in chapter 5 of Henry
  619. S. Warren Jr's book "Hacker's Delight".
  620. */
  621. unsigned int n = ((x - 0x100) >> 16) & 8;
  622. x <<= n;
  623. m = ((x - 0x1000) >> 16) & 4;
  624. n += m;
  625. x <<= m;
  626. m = ((x - 0x4000) >> 16) & 2;
  627. n += m;
  628. x = (x << m) >> 14;
  629. m = 13 - n + (x & ~(x>>1));
  630. }
  631. #endif
  632. /* Use next 2 bits to create finer-granularity bins */
  633. return NSMALLBINS + (m << 2) + ((sz >> (m + 6)) & 3);
  634. }
  635. /* ----------------------------------------------------------------------
  636. *
  637. * PUBLIC STUFF
  638. *
  639. * ----------------------------------------------------------------------*/
  640. /* ------------------------------ malloc ------------------------------ */
  641. void* malloc(size_t bytes)
  642. {
  643. mstate av;
  644. size_t nb; /* normalized request size */
  645. unsigned int idx; /* associated bin index */
  646. mbinptr bin; /* associated bin */
  647. mfastbinptr* fb; /* associated fastbin */
  648. mchunkptr victim; /* inspected/selected chunk */
  649. size_t size; /* its size */
  650. int victim_index; /* its bin index */
  651. mchunkptr remainder; /* remainder from a split */
  652. unsigned long remainder_size; /* its size */
  653. unsigned int block; /* bit map traverser */
  654. unsigned int bit; /* bit map traverser */
  655. unsigned int map; /* current word of binmap */
  656. mchunkptr fwd; /* misc temp for linking */
  657. mchunkptr bck; /* misc temp for linking */
  658. void * sysmem;
  659. void * retval;
  660. /*
  661. Convert request size to internal form by adding (sizeof(size_t)) bytes
  662. overhead plus possibly more to obtain necessary alignment and/or
  663. to obtain a size of at least MINSIZE, the smallest allocatable
  664. size. Also, checked_request2size traps (returning 0) request sizes
  665. that are so large that they wrap around zero when padded and
  666. aligned.
  667. */
  668. checked_request2size(bytes, nb);
  669. __MALLOC_LOCK;
  670. av = get_malloc_state();
  671. /*
  672. Bypass search if no frees yet
  673. */
  674. if (!have_anychunks(av)) {
  675. if (av->max_fast == 0) /* initialization check */
  676. __malloc_consolidate(av);
  677. goto use_top;
  678. }
  679. /*
  680. If the size qualifies as a fastbin, first check corresponding bin.
  681. */
  682. if ((unsigned long)(nb) <= (unsigned long)(av->max_fast)) {
  683. fb = &(av->fastbins[(fastbin_index(nb))]);
  684. if ( (victim = *fb) != 0) {
  685. *fb = victim->fd;
  686. check_remalloced_chunk(victim, nb);
  687. retval = chunk2mem(victim);
  688. goto DONE;
  689. }
  690. }
  691. /*
  692. If a small request, check regular bin. Since these "smallbins"
  693. hold one size each, no searching within bins is necessary.
  694. (For a large request, we need to wait until unsorted chunks are
  695. processed to find best fit. But for small ones, fits are exact
  696. anyway, so we can check now, which is faster.)
  697. */
  698. if (in_smallbin_range(nb)) {
  699. idx = smallbin_index(nb);
  700. bin = bin_at(av,idx);
  701. if ( (victim = last(bin)) != bin) {
  702. bck = victim->bk;
  703. set_inuse_bit_at_offset(victim, nb);
  704. bin->bk = bck;
  705. bck->fd = bin;
  706. check_malloced_chunk(victim, nb);
  707. retval = chunk2mem(victim);
  708. goto DONE;
  709. }
  710. }
  711. /* If this is a large request, consolidate fastbins before continuing.
  712. While it might look excessive to kill all fastbins before
  713. even seeing if there is space available, this avoids
  714. fragmentation problems normally associated with fastbins.
  715. Also, in practice, programs tend to have runs of either small or
  716. large requests, but less often mixtures, so consolidation is not
  717. invoked all that often in most programs. And the programs that
  718. it is called frequently in otherwise tend to fragment.
  719. */
  720. else {
  721. idx = __malloc_largebin_index(nb);
  722. if (have_fastchunks(av))
  723. __malloc_consolidate(av);
  724. }
  725. /*
  726. Process recently freed or remaindered chunks, taking one only if
  727. it is exact fit, or, if this a small request, the chunk is remainder from
  728. the most recent non-exact fit. Place other traversed chunks in
  729. bins. Note that this step is the only place in any routine where
  730. chunks are placed in bins.
  731. */
  732. while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
  733. bck = victim->bk;
  734. size = chunksize(victim);
  735. /* If a small request, try to use last remainder if it is the
  736. only chunk in unsorted bin. This helps promote locality for
  737. runs of consecutive small requests. This is the only
  738. exception to best-fit, and applies only when there is
  739. no exact fit for a small chunk.
  740. */
  741. if (in_smallbin_range(nb) &&
  742. bck == unsorted_chunks(av) &&
  743. victim == av->last_remainder &&
  744. (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
  745. /* split and reattach remainder */
  746. remainder_size = size - nb;
  747. remainder = chunk_at_offset(victim, nb);
  748. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  749. av->last_remainder = remainder;
  750. remainder->bk = remainder->fd = unsorted_chunks(av);
  751. set_head(victim, nb | PREV_INUSE);
  752. set_head(remainder, remainder_size | PREV_INUSE);
  753. set_foot(remainder, remainder_size);
  754. check_malloced_chunk(victim, nb);
  755. retval = chunk2mem(victim);
  756. goto DONE;
  757. }
  758. /* remove from unsorted list */
  759. unsorted_chunks(av)->bk = bck;
  760. bck->fd = unsorted_chunks(av);
  761. /* Take now instead of binning if exact fit */
  762. if (size == nb) {
  763. set_inuse_bit_at_offset(victim, size);
  764. check_malloced_chunk(victim, nb);
  765. retval = chunk2mem(victim);
  766. goto DONE;
  767. }
  768. /* place chunk in bin */
  769. if (in_smallbin_range(size)) {
  770. victim_index = smallbin_index(size);
  771. bck = bin_at(av, victim_index);
  772. fwd = bck->fd;
  773. }
  774. else {
  775. victim_index = __malloc_largebin_index(size);
  776. bck = bin_at(av, victim_index);
  777. fwd = bck->fd;
  778. if (fwd != bck) {
  779. /* if smaller than smallest, place first */
  780. if ((unsigned long)(size) < (unsigned long)(bck->bk->size)) {
  781. fwd = bck;
  782. bck = bck->bk;
  783. }
  784. else if ((unsigned long)(size) >=
  785. (unsigned long)(FIRST_SORTED_BIN_SIZE)) {
  786. /* maintain large bins in sorted order */
  787. size |= PREV_INUSE; /* Or with inuse bit to speed comparisons */
  788. while ((unsigned long)(size) < (unsigned long)(fwd->size))
  789. fwd = fwd->fd;
  790. bck = fwd->bk;
  791. }
  792. }
  793. }
  794. mark_bin(av, victim_index);
  795. victim->bk = bck;
  796. victim->fd = fwd;
  797. fwd->bk = victim;
  798. bck->fd = victim;
  799. }
  800. /*
  801. If a large request, scan through the chunks of current bin to
  802. find one that fits. (This will be the smallest that fits unless
  803. FIRST_SORTED_BIN_SIZE has been changed from default.) This is
  804. the only step where an unbounded number of chunks might be
  805. scanned without doing anything useful with them. However the
  806. lists tend to be short.
  807. */
  808. if (!in_smallbin_range(nb)) {
  809. bin = bin_at(av, idx);
  810. for (victim = last(bin); victim != bin; victim = victim->bk) {
  811. size = chunksize(victim);
  812. if ((unsigned long)(size) >= (unsigned long)(nb)) {
  813. remainder_size = size - nb;
  814. unlink(victim, bck, fwd);
  815. /* Exhaust */
  816. if (remainder_size < MINSIZE) {
  817. set_inuse_bit_at_offset(victim, size);
  818. check_malloced_chunk(victim, nb);
  819. retval = chunk2mem(victim);
  820. goto DONE;
  821. }
  822. /* Split */
  823. else {
  824. remainder = chunk_at_offset(victim, nb);
  825. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  826. remainder->bk = remainder->fd = unsorted_chunks(av);
  827. set_head(victim, nb | PREV_INUSE);
  828. set_head(remainder, remainder_size | PREV_INUSE);
  829. set_foot(remainder, remainder_size);
  830. check_malloced_chunk(victim, nb);
  831. retval = chunk2mem(victim);
  832. goto DONE;
  833. }
  834. }
  835. }
  836. }
  837. /*
  838. Search for a chunk by scanning bins, starting with next largest
  839. bin. This search is strictly by best-fit; i.e., the smallest
  840. (with ties going to approximately the least recently used) chunk
  841. that fits is selected.
  842. The bitmap avoids needing to check that most blocks are nonempty.
  843. */
  844. ++idx;
  845. bin = bin_at(av,idx);
  846. block = idx2block(idx);
  847. map = av->binmap[block];
  848. bit = idx2bit(idx);
  849. for (;;) {
  850. /* Skip rest of block if there are no more set bits in this block. */
  851. if (bit > map || bit == 0) {
  852. do {
  853. if (++block >= BINMAPSIZE) /* out of bins */
  854. goto use_top;
  855. } while ( (map = av->binmap[block]) == 0);
  856. bin = bin_at(av, (block << BINMAPSHIFT));
  857. bit = 1;
  858. }
  859. /* Advance to bin with set bit. There must be one. */
  860. while ((bit & map) == 0) {
  861. bin = next_bin(bin);
  862. bit <<= 1;
  863. assert(bit != 0);
  864. }
  865. /* Inspect the bin. It is likely to be non-empty */
  866. victim = last(bin);
  867. /* If a false alarm (empty bin), clear the bit. */
  868. if (victim == bin) {
  869. av->binmap[block] = map &= ~bit; /* Write through */
  870. bin = next_bin(bin);
  871. bit <<= 1;
  872. }
  873. else {
  874. size = chunksize(victim);
  875. /* We know the first chunk in this bin is big enough to use. */
  876. assert((unsigned long)(size) >= (unsigned long)(nb));
  877. remainder_size = size - nb;
  878. /* unlink */
  879. bck = victim->bk;
  880. bin->bk = bck;
  881. bck->fd = bin;
  882. /* Exhaust */
  883. if (remainder_size < MINSIZE) {
  884. set_inuse_bit_at_offset(victim, size);
  885. check_malloced_chunk(victim, nb);
  886. retval = chunk2mem(victim);
  887. goto DONE;
  888. }
  889. /* Split */
  890. else {
  891. remainder = chunk_at_offset(victim, nb);
  892. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  893. remainder->bk = remainder->fd = unsorted_chunks(av);
  894. /* advertise as last remainder */
  895. if (in_smallbin_range(nb))
  896. av->last_remainder = remainder;
  897. set_head(victim, nb | PREV_INUSE);
  898. set_head(remainder, remainder_size | PREV_INUSE);
  899. set_foot(remainder, remainder_size);
  900. check_malloced_chunk(victim, nb);
  901. retval = chunk2mem(victim);
  902. goto DONE;
  903. }
  904. }
  905. }
  906. use_top:
  907. /*
  908. If large enough, split off the chunk bordering the end of memory
  909. (held in av->top). Note that this is in accord with the best-fit
  910. search rule. In effect, av->top is treated as larger (and thus
  911. less well fitting) than any other available chunk since it can
  912. be extended to be as large as necessary (up to system
  913. limitations).
  914. We require that av->top always exists (i.e., has size >=
  915. MINSIZE) after initialization, so if it would otherwise be
  916. exhuasted by current request, it is replenished. (The main
  917. reason for ensuring it exists is that we may need MINSIZE space
  918. to put in fenceposts in sysmalloc.)
  919. */
  920. victim = av->top;
  921. size = chunksize(victim);
  922. if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
  923. remainder_size = size - nb;
  924. remainder = chunk_at_offset(victim, nb);
  925. av->top = remainder;
  926. set_head(victim, nb | PREV_INUSE);
  927. set_head(remainder, remainder_size | PREV_INUSE);
  928. check_malloced_chunk(victim, nb);
  929. retval = chunk2mem(victim);
  930. goto DONE;
  931. }
  932. /* If no space in top, relay to handle system-dependent cases */
  933. sysmem = __malloc_alloc(nb, av);
  934. retval = sysmem;
  935. DONE:
  936. __MALLOC_UNLOCK;
  937. return retval;
  938. }