malloc.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /* malloc.c - C standard library routine.
  2. Copyright (c) 1989, 1993 Michael J. Haertel
  3. You may redistribute this library under the terms of the
  4. GNU Library General Public License (version 2 or any later
  5. version) as published by the Free Software Foundation.
  6. THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED
  7. WARRANTY. IN PARTICULAR, THE AUTHOR MAKES NO REPRESENTATION OR
  8. WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY OF THIS
  9. SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. */
  10. #define _GNU_SOURCE
  11. #include <features.h>
  12. #include <limits.h>
  13. #include <stddef.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <unistd.h>
  17. #include "malloc.h"
  18. #define MIN(x,y) ({ \
  19. const typeof(x) _x = (x); \
  20. const typeof(y) _y = (y); \
  21. (void) (&_x == &_y); \
  22. _x < _y ? _x : _y; })
  23. #ifdef __UCLIBC_HAS_THREADS__
  24. #include <pthread.h>
  25. static pthread_mutex_t malloclock = PTHREAD_MUTEX_INITIALIZER;
  26. # define LOCK pthread_mutex_lock(&malloclock)
  27. # define UNLOCK pthread_mutex_unlock(&malloclock);
  28. #else
  29. # define LOCK
  30. # define UNLOCK
  31. #endif
  32. static void * malloc_unlocked (size_t size);
  33. static void free_unlocked(void *ptr);
  34. static void * __default_morecore_init(long size);
  35. /* How to really get more memory. */
  36. static void *(*__morecore)(long) = __default_morecore_init;
  37. /* Pointer to the base of the first block. */
  38. static char *_heapbase;
  39. /* Block information table. */
  40. static union info *_heapinfo;
  41. /* Number of info entries. */
  42. static size_t heapsize;
  43. /* Search index in the info table. */
  44. static size_t _heapindex;
  45. /* Limit of valid info table indices. */
  46. static size_t _heaplimit;
  47. /* Count of large blocks allocated for each fragment size. */
  48. static size_t _fragblocks[BLOCKLOG];
  49. /* Free lists for each fragment size. */
  50. static struct list _fraghead[BLOCKLOG];
  51. /* Are we experienced? */
  52. static int initialized;
  53. /* Aligned allocation.
  54. * Called within the lock in initialize() and morecore(),
  55. * so no explicit locking needed... */
  56. static void * align(size_t size)
  57. {
  58. void *result;
  59. unsigned int adj;
  60. result = (*__morecore)(size);
  61. adj = (unsigned int) ((char *) result - (char *) NULL) % BLOCKSIZE;
  62. if (adj != 0) {
  63. (*__morecore)(adj = BLOCKSIZE - adj);
  64. result = (char *) result + adj;
  65. }
  66. return result;
  67. }
  68. /* Set everything up and remember that we have.
  69. * Called within the lock in malloc(), so no
  70. * explicit locking needed... */
  71. static int initialize(void)
  72. {
  73. heapsize = HEAP / BLOCKSIZE;
  74. _heapinfo = align(heapsize * sizeof (union info));
  75. if (!_heapinfo) {
  76. return 0;
  77. }
  78. memset(_heapinfo, 0, heapsize * sizeof (union info));
  79. _heapinfo[0].free.size = 0;
  80. _heapinfo[0].free.next = _heapinfo[0].free.prev = 0;
  81. _heapindex = 0;
  82. _heapbase = (char *) _heapinfo;
  83. initialized = 1;
  84. return 1;
  85. }
  86. /* Get neatly aligned memory, initializing or growing the
  87. * heap info table as necessary.
  88. * Called within a lock in malloc() and free(),
  89. * so no explicit locking needed... */
  90. static void * morecore(size_t size)
  91. {
  92. void *result;
  93. union info *newinfo, *oldinfo;
  94. size_t newsize;
  95. result = align(size);
  96. if (!result)
  97. return NULL;
  98. /* Check if we need to grow the info table. */
  99. if (BLOCK((char *) result + size) > heapsize) {
  100. newsize = heapsize;
  101. while (BLOCK((char *) result + size) > newsize)
  102. newsize *= 2;
  103. newinfo = align(newsize * sizeof (union info));
  104. if (!newinfo) {
  105. (*__morecore)(-size);
  106. return NULL;
  107. }
  108. memset(newinfo, 0, newsize * sizeof (union info));
  109. memcpy(newinfo, _heapinfo, heapsize * sizeof (union info));
  110. oldinfo = _heapinfo;
  111. newinfo[BLOCK(oldinfo)].busy.type = 0;
  112. newinfo[BLOCK(oldinfo)].busy.info.size
  113. = BLOCKIFY(heapsize * sizeof (union info));
  114. _heapinfo = newinfo;
  115. free_unlocked(oldinfo);
  116. heapsize = newsize;
  117. }
  118. _heaplimit = BLOCK((char *) result + size);
  119. return result;
  120. }
  121. /* Note that morecore has to take a signed argument so
  122. that negative values can return memory to the system. */
  123. static void * __default_morecore_init(long size)
  124. {
  125. void *result;
  126. result = sbrk(size);
  127. if (result == (void *) -1)
  128. return NULL;
  129. return result;
  130. }
  131. /* Allocate memory from the heap. */
  132. void * malloc (size_t size)
  133. {
  134. void * ptr;
  135. LOCK;
  136. ptr = malloc_unlocked(size);
  137. UNLOCK;
  138. return(ptr);
  139. }
  140. static void * malloc_unlocked (size_t size)
  141. {
  142. void *result;
  143. size_t log, block, blocks, i, lastblocks, start;
  144. struct list *next;
  145. #if 1
  146. /* Some programs will call malloc (0). Lets be strict and return NULL */
  147. if (size == 0)
  148. return NULL;
  149. #endif
  150. if (size < sizeof (struct list))
  151. size = sizeof (struct list);
  152. #if 1
  153. /* Some programs will call malloc (0). Lets be strict and return NULL */
  154. if (size == 0)
  155. return NULL;
  156. #endif
  157. if (size < sizeof (struct list))
  158. size = sizeof (struct list);
  159. if (!initialized && !initialize()) {
  160. return NULL;
  161. }
  162. /* Determine the allocation policy based on the request size. */
  163. if (size <= BLOCKSIZE / 2) {
  164. /* Small allocation to receive a fragment of a block. Determine
  165. the logarithm to base two of the fragment size. */
  166. --size;
  167. for (log = 1; (size >>= 1) != 0; ++log)
  168. ;
  169. /* Look in the fragment lists for a free fragment of the
  170. desired size. */
  171. if ((next = _fraghead[log].next) != 0) {
  172. /* There are free fragments of this size. Pop a fragment
  173. out of the fragment list and return it. Update the block's
  174. nfree and first counters. */
  175. result = next;
  176. next->prev->next = next->next;
  177. if (next->next)
  178. next->next->prev = next->prev;
  179. block = BLOCK(result);
  180. if (--_heapinfo[block].busy.info.frag.nfree)
  181. _heapinfo[block].busy.info.frag.first
  182. = (unsigned int) ((char *) next->next - (char *) NULL)
  183. % BLOCKSIZE >> log;
  184. } else {
  185. /* No free fragments of the desired size, so get a new block
  186. and break it into fragments, returning the first. */
  187. result = malloc_unlocked(BLOCKSIZE);
  188. if (!result) {
  189. return NULL;
  190. }
  191. ++_fragblocks[log];
  192. /* Link all fragments but the first into the free list. */
  193. next = (struct list *) ((char *) result + (1 << log));
  194. next->next = 0;
  195. next->prev = &_fraghead[log];
  196. _fraghead[log].next = next;
  197. for (i = 2; i < BLOCKSIZE >> log; ++i) {
  198. next = (struct list *) ((char *) result + (i << log));
  199. next->next = _fraghead[log].next;
  200. next->prev = &_fraghead[log];
  201. next->prev->next = next;
  202. next->next->prev = next;
  203. }
  204. /* Initialize the nfree and first counters for this block. */
  205. block = BLOCK(result);
  206. _heapinfo[block].busy.type = log;
  207. _heapinfo[block].busy.info.frag.nfree = i - 1;
  208. _heapinfo[block].busy.info.frag.first = i - 1;
  209. }
  210. } else {
  211. /* Large allocation to receive one or more blocks. Search
  212. the free list in a circle starting at the last place visited.
  213. If we loop completely around without finding a large enough
  214. space we will have to get more memory from the system. */
  215. blocks = BLOCKIFY(size);
  216. start = block = _heapindex;
  217. while (_heapinfo[block].free.size < blocks) {
  218. block = _heapinfo[block].free.next;
  219. if (block == start) {
  220. /* Need to get more from the system. Check to see if
  221. the new core will be contiguous with the final free
  222. block; if so we don't need to get as much. */
  223. block = _heapinfo[0].free.prev;
  224. lastblocks = _heapinfo[block].free.size;
  225. if (_heaplimit && block + lastblocks == _heaplimit
  226. && (*__morecore)(0) == ADDRESS(block + lastblocks)
  227. && morecore((blocks - lastblocks) * BLOCKSIZE)) {
  228. /* Note that morecore() can change the location of
  229. the final block if it moves the info table and the
  230. old one gets coalesced into the final block. */
  231. block = _heapinfo[0].free.prev;
  232. _heapinfo[block].free.size += blocks - lastblocks;
  233. continue;
  234. }
  235. result = morecore(blocks * BLOCKSIZE);
  236. if (!result) {
  237. return NULL;
  238. }
  239. block = BLOCK(result);
  240. _heapinfo[block].busy.type = 0;
  241. _heapinfo[block].busy.info.size = blocks;
  242. return result;
  243. }
  244. }
  245. /* At this point we have found a suitable free list entry.
  246. Figure out how to remove what we need from the list. */
  247. result = ADDRESS(block);
  248. if (_heapinfo[block].free.size > blocks) {
  249. /* The block we found has a bit left over, so relink the
  250. tail end back into the free list. */
  251. _heapinfo[block + blocks].free.size
  252. = _heapinfo[block].free.size - blocks;
  253. _heapinfo[block + blocks].free.next
  254. = _heapinfo[block].free.next;
  255. _heapinfo[block + blocks].free.prev
  256. = _heapinfo[block].free.prev;
  257. _heapinfo[_heapinfo[block].free.prev].free.next
  258. = _heapinfo[_heapinfo[block].free.next].free.prev
  259. = _heapindex = block + blocks;
  260. } else {
  261. /* The block exactly matches our requirements, so
  262. just remove it from the list. */
  263. _heapinfo[_heapinfo[block].free.next].free.prev
  264. = _heapinfo[block].free.prev;
  265. _heapinfo[_heapinfo[block].free.prev].free.next
  266. = _heapindex = _heapinfo[block].free.next;
  267. }
  268. _heapinfo[block].busy.type = 0;
  269. _heapinfo[block].busy.info.size = blocks;
  270. }
  271. return result;
  272. }
  273. /* Return memory to the heap. */
  274. void free(void *ptr)
  275. {
  276. LOCK;
  277. free_unlocked(ptr);
  278. UNLOCK;
  279. }
  280. static void free_unlocked(void *ptr)
  281. {
  282. int block, blocks, i, type;
  283. struct list *prev, *next;
  284. if (ptr == NULL)
  285. return;
  286. block = BLOCK(ptr);
  287. switch (type = _heapinfo[block].busy.type) {
  288. case 0:
  289. /* Find the free cluster previous to this one in the free list.
  290. Start searching at the last block referenced; this may benefit
  291. programs with locality of allocation. */
  292. i = _heapindex;
  293. if (i > block)
  294. while (i > block)
  295. i = _heapinfo[i].free.prev;
  296. else {
  297. do
  298. i = _heapinfo[i].free.next;
  299. while (i > 0 && i < block);
  300. i = _heapinfo[i].free.prev;
  301. }
  302. /* Determine how to link this block into the free list. */
  303. if (block == i + _heapinfo[i].free.size) {
  304. /* Coalesce this block with its predecessor. */
  305. _heapinfo[i].free.size += _heapinfo[block].busy.info.size;
  306. block = i;
  307. } else {
  308. /* Really link this block back into the free list. */
  309. _heapinfo[block].free.size = _heapinfo[block].busy.info.size;
  310. _heapinfo[block].free.next = _heapinfo[i].free.next;
  311. _heapinfo[block].free.prev = i;
  312. _heapinfo[i].free.next = block;
  313. _heapinfo[_heapinfo[block].free.next].free.prev = block;
  314. }
  315. /* Now that the block is linked in, see if we can coalesce it
  316. with its successor (by deleting its successor from the list
  317. and adding in its size). */
  318. if (block + _heapinfo[block].free.size == _heapinfo[block].free.next) {
  319. _heapinfo[block].free.size
  320. += _heapinfo[_heapinfo[block].free.next].free.size;
  321. _heapinfo[block].free.next
  322. = _heapinfo[_heapinfo[block].free.next].free.next;
  323. _heapinfo[_heapinfo[block].free.next].free.prev = block;
  324. }
  325. /* Now see if we can return stuff to the system. */
  326. blocks = _heapinfo[block].free.size;
  327. if (blocks >= FINAL_FREE_BLOCKS && block + blocks == _heaplimit
  328. && (*__morecore)(0) == ADDRESS(block + blocks)) {
  329. _heaplimit -= blocks;
  330. (*__morecore)(-blocks * BLOCKSIZE);
  331. _heapinfo[_heapinfo[block].free.prev].free.next
  332. = _heapinfo[block].free.next;
  333. _heapinfo[_heapinfo[block].free.next].free.prev
  334. = _heapinfo[block].free.prev;
  335. block = _heapinfo[block].free.prev;
  336. }
  337. /* Set the next search to begin at this block. */
  338. _heapindex = block;
  339. break;
  340. default:
  341. /* Get the address of the first free fragment in this block. */
  342. prev = (struct list *) ((char *) ADDRESS(block)
  343. + (_heapinfo[block].busy.info.frag.first
  344. << type));
  345. if (_heapinfo[block].busy.info.frag.nfree == (BLOCKSIZE >> type) - 1
  346. && _fragblocks[type] > 1) {
  347. /* If all fragments of this block are free, remove them
  348. from the fragment list and free the whole block. */
  349. --_fragblocks[type];
  350. for (next = prev, i = 1; i < BLOCKSIZE >> type; ++i)
  351. next = next->next;
  352. prev->prev->next = next;
  353. if (next)
  354. next->prev = prev->prev;
  355. _heapinfo[block].busy.type = 0;
  356. _heapinfo[block].busy.info.size = 1;
  357. free_unlocked(ADDRESS(block));
  358. } else if (_heapinfo[block].busy.info.frag.nfree) {
  359. /* If some fragments of this block are free, link this fragment
  360. into the fragment list after the first free fragment of
  361. this block. */
  362. next = ptr;
  363. next->next = prev->next;
  364. next->prev = prev;
  365. prev->next = next;
  366. if (next->next)
  367. next->next->prev = next;
  368. ++_heapinfo[block].busy.info.frag.nfree;
  369. } else {
  370. /* No fragments of this block are free, so link this fragment
  371. into the fragment list and announce that it is the first
  372. free fragment of this block. */
  373. prev = (struct list *) ptr;
  374. _heapinfo[block].busy.info.frag.nfree = 1;
  375. _heapinfo[block].busy.info.frag.first
  376. = (unsigned int) ((char *) ptr - (char *) NULL) % BLOCKSIZE
  377. >> type;
  378. prev->next = _fraghead[type].next;
  379. prev->prev = &_fraghead[type];
  380. prev->prev->next = prev;
  381. if (prev->next)
  382. prev->next->prev = prev;
  383. }
  384. break;
  385. }
  386. }
  387. /* Resize the given region to the new size, returning a pointer
  388. to the (possibly moved) region. This is optimized for speed;
  389. some benchmarks seem to indicate that greater compactness is
  390. achieved by unconditionally allocating and copying to a
  391. new region. */
  392. void * realloc (void *ptr, size_t size)
  393. {
  394. void *result, *previous;
  395. size_t block, blocks, type;
  396. size_t oldlimit;
  397. if (!ptr)
  398. return malloc(size);
  399. if (!size) {
  400. LOCK;
  401. free_unlocked(ptr);
  402. result = malloc_unlocked(0);
  403. UNLOCK;
  404. return(result);
  405. }
  406. LOCK;
  407. block = BLOCK(ptr);
  408. switch (type = _heapinfo[block].busy.type) {
  409. case 0:
  410. /* Maybe reallocate a large block to a small fragment. */
  411. if (size <= BLOCKSIZE / 2) {
  412. if ((result = malloc_unlocked(size)) != NULL) {
  413. memcpy(result, ptr, size);
  414. free(ptr);
  415. }
  416. UNLOCK;
  417. return result;
  418. }
  419. /* The new size is a large allocation as well; see if
  420. we can hold it in place. */
  421. blocks = BLOCKIFY(size);
  422. if (blocks < _heapinfo[block].busy.info.size) {
  423. /* The new size is smaller; return excess memory
  424. to the free list. */
  425. _heapinfo[block + blocks].busy.type = 0;
  426. _heapinfo[block + blocks].busy.info.size
  427. = _heapinfo[block].busy.info.size - blocks;
  428. _heapinfo[block].busy.info.size = blocks;
  429. free(ADDRESS(block + blocks));
  430. UNLOCK;
  431. return ptr;
  432. } else if (blocks == _heapinfo[block].busy.info.size) {
  433. /* No size change necessary. */
  434. UNLOCK;
  435. return ptr;
  436. } else {
  437. /* Won't fit, so allocate a new region that will. Free
  438. the old region first in case there is sufficient adjacent
  439. free space to grow without moving. */
  440. blocks = _heapinfo[block].busy.info.size;
  441. /* Prevent free from actually returning memory to the system. */
  442. oldlimit = _heaplimit;
  443. _heaplimit = 0;
  444. free(ptr);
  445. _heaplimit = oldlimit;
  446. result = malloc_unlocked(size);
  447. if (!result) {
  448. /* Now we're really in trouble. We have to unfree
  449. the thing we just freed. Unfortunately it might
  450. have been coalesced with its neighbors. */
  451. if (_heapindex == block)
  452. malloc_unlocked(blocks * BLOCKSIZE);
  453. else {
  454. previous = malloc_unlocked((block - _heapindex) * BLOCKSIZE);
  455. malloc_unlocked(blocks * BLOCKSIZE);
  456. free(previous);
  457. }
  458. UNLOCK;
  459. return NULL;
  460. }
  461. if (ptr != result)
  462. memmove(result, ptr, blocks * BLOCKSIZE);
  463. UNLOCK;
  464. return result;
  465. }
  466. break;
  467. default:
  468. /* Old size is a fragment; type is logarithm to base two of
  469. the fragment size. */
  470. if ((size > 1 << (type - 1)) && (size <= 1 << type)) {
  471. /* New size is the same kind of fragment. */
  472. UNLOCK;
  473. return ptr;
  474. }
  475. else {
  476. /* New size is different; allocate a new space, and copy
  477. the lesser of the new size and the old. */
  478. result = malloc_unlocked(size);
  479. if (!result) {
  480. UNLOCK;
  481. return NULL;
  482. }
  483. memcpy(result, ptr, MIN(size, (size_t)(1 << type)));
  484. free(ptr);
  485. UNLOCK;
  486. return result;
  487. }
  488. break;
  489. }
  490. UNLOCK;
  491. }