malloc.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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. 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. #if !defined(__MALLOC_GLIBC_COMPAT__)
  661. if (!bytes) {
  662. __set_errno(ENOMEM);
  663. return NULL;
  664. }
  665. #endif
  666. __MALLOC_LOCK;
  667. av = get_malloc_state();
  668. /*
  669. Convert request size to internal form by adding (sizeof(size_t)) bytes
  670. overhead plus possibly more to obtain necessary alignment and/or
  671. to obtain a size of at least MINSIZE, the smallest allocatable
  672. size. Also, checked_request2size traps (returning 0) request sizes
  673. that are so large that they wrap around zero when padded and
  674. aligned.
  675. */
  676. checked_request2size(bytes, nb);
  677. /*
  678. Bypass search if no frees yet
  679. */
  680. if (!have_anychunks(av)) {
  681. if (av->max_fast == 0) /* initialization check */
  682. __malloc_consolidate(av);
  683. goto use_top;
  684. }
  685. /*
  686. If the size qualifies as a fastbin, first check corresponding bin.
  687. */
  688. if ((unsigned long)(nb) <= (unsigned long)(av->max_fast)) {
  689. fb = &(av->fastbins[(fastbin_index(nb))]);
  690. if ( (victim = *fb) != 0) {
  691. *fb = victim->fd;
  692. check_remalloced_chunk(victim, nb);
  693. retval = chunk2mem(victim);
  694. goto DONE;
  695. }
  696. }
  697. /*
  698. If a small request, check regular bin. Since these "smallbins"
  699. hold one size each, no searching within bins is necessary.
  700. (For a large request, we need to wait until unsorted chunks are
  701. processed to find best fit. But for small ones, fits are exact
  702. anyway, so we can check now, which is faster.)
  703. */
  704. if (in_smallbin_range(nb)) {
  705. idx = smallbin_index(nb);
  706. bin = bin_at(av,idx);
  707. if ( (victim = last(bin)) != bin) {
  708. bck = victim->bk;
  709. set_inuse_bit_at_offset(victim, nb);
  710. bin->bk = bck;
  711. bck->fd = bin;
  712. check_malloced_chunk(victim, nb);
  713. retval = chunk2mem(victim);
  714. goto DONE;
  715. }
  716. }
  717. /* If this is a large request, consolidate fastbins before continuing.
  718. While it might look excessive to kill all fastbins before
  719. even seeing if there is space available, this avoids
  720. fragmentation problems normally associated with fastbins.
  721. Also, in practice, programs tend to have runs of either small or
  722. large requests, but less often mixtures, so consolidation is not
  723. invoked all that often in most programs. And the programs that
  724. it is called frequently in otherwise tend to fragment.
  725. */
  726. else {
  727. idx = __malloc_largebin_index(nb);
  728. if (have_fastchunks(av))
  729. __malloc_consolidate(av);
  730. }
  731. /*
  732. Process recently freed or remaindered chunks, taking one only if
  733. it is exact fit, or, if this a small request, the chunk is remainder from
  734. the most recent non-exact fit. Place other traversed chunks in
  735. bins. Note that this step is the only place in any routine where
  736. chunks are placed in bins.
  737. */
  738. while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
  739. bck = victim->bk;
  740. size = chunksize(victim);
  741. /* If a small request, try to use last remainder if it is the
  742. only chunk in unsorted bin. This helps promote locality for
  743. runs of consecutive small requests. This is the only
  744. exception to best-fit, and applies only when there is
  745. no exact fit for a small chunk.
  746. */
  747. if (in_smallbin_range(nb) &&
  748. bck == unsorted_chunks(av) &&
  749. victim == av->last_remainder &&
  750. (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) {
  751. /* split and reattach remainder */
  752. remainder_size = size - nb;
  753. remainder = chunk_at_offset(victim, nb);
  754. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  755. av->last_remainder = remainder;
  756. remainder->bk = remainder->fd = unsorted_chunks(av);
  757. set_head(victim, nb | PREV_INUSE);
  758. set_head(remainder, remainder_size | PREV_INUSE);
  759. set_foot(remainder, remainder_size);
  760. check_malloced_chunk(victim, nb);
  761. retval = chunk2mem(victim);
  762. goto DONE;
  763. }
  764. /* remove from unsorted list */
  765. unsorted_chunks(av)->bk = bck;
  766. bck->fd = unsorted_chunks(av);
  767. /* Take now instead of binning if exact fit */
  768. if (size == nb) {
  769. set_inuse_bit_at_offset(victim, size);
  770. check_malloced_chunk(victim, nb);
  771. retval = chunk2mem(victim);
  772. goto DONE;
  773. }
  774. /* place chunk in bin */
  775. if (in_smallbin_range(size)) {
  776. victim_index = smallbin_index(size);
  777. bck = bin_at(av, victim_index);
  778. fwd = bck->fd;
  779. }
  780. else {
  781. victim_index = __malloc_largebin_index(size);
  782. bck = bin_at(av, victim_index);
  783. fwd = bck->fd;
  784. if (fwd != bck) {
  785. /* if smaller than smallest, place first */
  786. if ((unsigned long)(size) < (unsigned long)(bck->bk->size)) {
  787. fwd = bck;
  788. bck = bck->bk;
  789. }
  790. else if ((unsigned long)(size) >=
  791. (unsigned long)(FIRST_SORTED_BIN_SIZE)) {
  792. /* maintain large bins in sorted order */
  793. size |= PREV_INUSE; /* Or with inuse bit to speed comparisons */
  794. while ((unsigned long)(size) < (unsigned long)(fwd->size))
  795. fwd = fwd->fd;
  796. bck = fwd->bk;
  797. }
  798. }
  799. }
  800. mark_bin(av, victim_index);
  801. victim->bk = bck;
  802. victim->fd = fwd;
  803. fwd->bk = victim;
  804. bck->fd = victim;
  805. }
  806. /*
  807. If a large request, scan through the chunks of current bin to
  808. find one that fits. (This will be the smallest that fits unless
  809. FIRST_SORTED_BIN_SIZE has been changed from default.) This is
  810. the only step where an unbounded number of chunks might be
  811. scanned without doing anything useful with them. However the
  812. lists tend to be short.
  813. */
  814. if (!in_smallbin_range(nb)) {
  815. bin = bin_at(av, idx);
  816. for (victim = last(bin); victim != bin; victim = victim->bk) {
  817. size = chunksize(victim);
  818. if ((unsigned long)(size) >= (unsigned long)(nb)) {
  819. remainder_size = size - nb;
  820. unlink(victim, bck, fwd);
  821. /* Exhaust */
  822. if (remainder_size < MINSIZE) {
  823. set_inuse_bit_at_offset(victim, size);
  824. check_malloced_chunk(victim, nb);
  825. retval = chunk2mem(victim);
  826. goto DONE;
  827. }
  828. /* Split */
  829. else {
  830. remainder = chunk_at_offset(victim, nb);
  831. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  832. remainder->bk = remainder->fd = unsorted_chunks(av);
  833. set_head(victim, nb | PREV_INUSE);
  834. set_head(remainder, remainder_size | PREV_INUSE);
  835. set_foot(remainder, remainder_size);
  836. check_malloced_chunk(victim, nb);
  837. retval = chunk2mem(victim);
  838. goto DONE;
  839. }
  840. }
  841. }
  842. }
  843. /*
  844. Search for a chunk by scanning bins, starting with next largest
  845. bin. This search is strictly by best-fit; i.e., the smallest
  846. (with ties going to approximately the least recently used) chunk
  847. that fits is selected.
  848. The bitmap avoids needing to check that most blocks are nonempty.
  849. */
  850. ++idx;
  851. bin = bin_at(av,idx);
  852. block = idx2block(idx);
  853. map = av->binmap[block];
  854. bit = idx2bit(idx);
  855. for (;;) {
  856. /* Skip rest of block if there are no more set bits in this block. */
  857. if (bit > map || bit == 0) {
  858. do {
  859. if (++block >= BINMAPSIZE) /* out of bins */
  860. goto use_top;
  861. } while ( (map = av->binmap[block]) == 0);
  862. bin = bin_at(av, (block << BINMAPSHIFT));
  863. bit = 1;
  864. }
  865. /* Advance to bin with set bit. There must be one. */
  866. while ((bit & map) == 0) {
  867. bin = next_bin(bin);
  868. bit <<= 1;
  869. assert(bit != 0);
  870. }
  871. /* Inspect the bin. It is likely to be non-empty */
  872. victim = last(bin);
  873. /* If a false alarm (empty bin), clear the bit. */
  874. if (victim == bin) {
  875. av->binmap[block] = map &= ~bit; /* Write through */
  876. bin = next_bin(bin);
  877. bit <<= 1;
  878. }
  879. else {
  880. size = chunksize(victim);
  881. /* We know the first chunk in this bin is big enough to use. */
  882. assert((unsigned long)(size) >= (unsigned long)(nb));
  883. remainder_size = size - nb;
  884. /* unlink */
  885. bck = victim->bk;
  886. bin->bk = bck;
  887. bck->fd = bin;
  888. /* Exhaust */
  889. if (remainder_size < MINSIZE) {
  890. set_inuse_bit_at_offset(victim, size);
  891. check_malloced_chunk(victim, nb);
  892. retval = chunk2mem(victim);
  893. goto DONE;
  894. }
  895. /* Split */
  896. else {
  897. remainder = chunk_at_offset(victim, nb);
  898. unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
  899. remainder->bk = remainder->fd = unsorted_chunks(av);
  900. /* advertise as last remainder */
  901. if (in_smallbin_range(nb))
  902. av->last_remainder = remainder;
  903. set_head(victim, nb | PREV_INUSE);
  904. set_head(remainder, remainder_size | PREV_INUSE);
  905. set_foot(remainder, remainder_size);
  906. check_malloced_chunk(victim, nb);
  907. retval = chunk2mem(victim);
  908. goto DONE;
  909. }
  910. }
  911. }
  912. use_top:
  913. /*
  914. If large enough, split off the chunk bordering the end of memory
  915. (held in av->top). Note that this is in accord with the best-fit
  916. search rule. In effect, av->top is treated as larger (and thus
  917. less well fitting) than any other available chunk since it can
  918. be extended to be as large as necessary (up to system
  919. limitations).
  920. We require that av->top always exists (i.e., has size >=
  921. MINSIZE) after initialization, so if it would otherwise be
  922. exhuasted by current request, it is replenished. (The main
  923. reason for ensuring it exists is that we may need MINSIZE space
  924. to put in fenceposts in sysmalloc.)
  925. */
  926. victim = av->top;
  927. size = chunksize(victim);
  928. if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
  929. remainder_size = size - nb;
  930. remainder = chunk_at_offset(victim, nb);
  931. av->top = remainder;
  932. set_head(victim, nb | PREV_INUSE);
  933. set_head(remainder, remainder_size | PREV_INUSE);
  934. check_malloced_chunk(victim, nb);
  935. retval = chunk2mem(victim);
  936. goto DONE;
  937. }
  938. /* If no space in top, relay to handle system-dependent cases */
  939. sysmem = __malloc_alloc(nb, av);
  940. retval = sysmem;
  941. DONE:
  942. __MALLOC_UNLOCK;
  943. return retval;
  944. }