malloc.c 34 KB

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