malloc.c 34 KB

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