malloc.c 34 KB

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