malloc.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 (!initialized && !initialize()) {
  153. return NULL;
  154. }
  155. /* Determine the allocation policy based on the request size. */
  156. if (size <= BLOCKSIZE / 2) {
  157. /* Small allocation to receive a fragment of a block. Determine
  158. the logarithm to base two of the fragment size. */
  159. --size;
  160. for (log = 1; (size >>= 1) != 0; ++log)
  161. ;
  162. /* Look in the fragment lists for a free fragment of the
  163. desired size. */
  164. if ((next = _fraghead[log].next) != 0) {
  165. /* There are free fragments of this size. Pop a fragment
  166. out of the fragment list and return it. Update the block's
  167. nfree and first counters. */
  168. result = next;
  169. next->prev->next = next->next;
  170. if (next->next)
  171. next->next->prev = next->prev;
  172. block = BLOCK(result);
  173. if (--_heapinfo[block].busy.info.frag.nfree)
  174. _heapinfo[block].busy.info.frag.first
  175. = (unsigned int) ((char *) next->next - (char *) NULL)
  176. % BLOCKSIZE >> log;
  177. } else {
  178. /* No free fragments of the desired size, so get a new block
  179. and break it into fragments, returning the first. */
  180. result = malloc_unlocked(BLOCKSIZE);
  181. if (!result) {
  182. return NULL;
  183. }
  184. ++_fragblocks[log];
  185. /* Link all fragments but the first into the free list. */
  186. next = (struct list *) ((char *) result + (1 << log));
  187. next->next = 0;
  188. next->prev = &_fraghead[log];
  189. _fraghead[log].next = next;
  190. for (i = 2; i < BLOCKSIZE >> log; ++i) {
  191. next = (struct list *) ((char *) result + (i << log));
  192. next->next = _fraghead[log].next;
  193. next->prev = &_fraghead[log];
  194. next->prev->next = next;
  195. next->next->prev = next;
  196. }
  197. /* Initialize the nfree and first counters for this block. */
  198. block = BLOCK(result);
  199. _heapinfo[block].busy.type = log;
  200. _heapinfo[block].busy.info.frag.nfree = i - 1;
  201. _heapinfo[block].busy.info.frag.first = i - 1;
  202. }
  203. } else {
  204. /* Large allocation to receive one or more blocks. Search
  205. the free list in a circle starting at the last place visited.
  206. If we loop completely around without finding a large enough
  207. space we will have to get more memory from the system. */
  208. blocks = BLOCKIFY(size);
  209. start = block = _heapindex;
  210. while (_heapinfo[block].free.size < blocks) {
  211. block = _heapinfo[block].free.next;
  212. if (block == start) {
  213. /* Need to get more from the system. Check to see if
  214. the new core will be contiguous with the final free
  215. block; if so we don't need to get as much. */
  216. block = _heapinfo[0].free.prev;
  217. lastblocks = _heapinfo[block].free.size;
  218. if (_heaplimit && block + lastblocks == _heaplimit
  219. && (*__morecore)(0) == ADDRESS(block + lastblocks)
  220. && morecore((blocks - lastblocks) * BLOCKSIZE)) {
  221. /* Note that morecore() can change the location of
  222. the final block if it moves the info table and the
  223. old one gets coalesced into the final block. */
  224. block = _heapinfo[0].free.prev;
  225. _heapinfo[block].free.size += blocks - lastblocks;
  226. continue;
  227. }
  228. result = morecore(blocks * BLOCKSIZE);
  229. if (!result) {
  230. return NULL;
  231. }
  232. block = BLOCK(result);
  233. _heapinfo[block].busy.type = 0;
  234. _heapinfo[block].busy.info.size = blocks;
  235. return result;
  236. }
  237. }
  238. /* At this point we have found a suitable free list entry.
  239. Figure out how to remove what we need from the list. */
  240. result = ADDRESS(block);
  241. if (_heapinfo[block].free.size > blocks) {
  242. /* The block we found has a bit left over, so relink the
  243. tail end back into the free list. */
  244. _heapinfo[block + blocks].free.size
  245. = _heapinfo[block].free.size - blocks;
  246. _heapinfo[block + blocks].free.next
  247. = _heapinfo[block].free.next;
  248. _heapinfo[block + blocks].free.prev
  249. = _heapinfo[block].free.prev;
  250. _heapinfo[_heapinfo[block].free.prev].free.next
  251. = _heapinfo[_heapinfo[block].free.next].free.prev
  252. = _heapindex = block + blocks;
  253. } else {
  254. /* The block exactly matches our requirements, so
  255. just remove it from the list. */
  256. _heapinfo[_heapinfo[block].free.next].free.prev
  257. = _heapinfo[block].free.prev;
  258. _heapinfo[_heapinfo[block].free.prev].free.next
  259. = _heapindex = _heapinfo[block].free.next;
  260. }
  261. _heapinfo[block].busy.type = 0;
  262. _heapinfo[block].busy.info.size = blocks;
  263. }
  264. return result;
  265. }
  266. /* Return memory to the heap. */
  267. void free(void *ptr)
  268. {
  269. LOCK;
  270. free_unlocked(ptr);
  271. UNLOCK;
  272. }
  273. static void free_unlocked(void *ptr)
  274. {
  275. int block, blocks, i, type;
  276. struct list *prev, *next;
  277. if (ptr == NULL)
  278. return;
  279. block = BLOCK(ptr);
  280. switch (type = _heapinfo[block].busy.type) {
  281. case 0:
  282. /* Find the free cluster previous to this one in the free list.
  283. Start searching at the last block referenced; this may benefit
  284. programs with locality of allocation. */
  285. i = _heapindex;
  286. if (i > block)
  287. while (i > block)
  288. i = _heapinfo[i].free.prev;
  289. else {
  290. do
  291. i = _heapinfo[i].free.next;
  292. while (i > 0 && i < block);
  293. i = _heapinfo[i].free.prev;
  294. }
  295. /* Determine how to link this block into the free list. */
  296. if (block == i + _heapinfo[i].free.size) {
  297. /* Coalesce this block with its predecessor. */
  298. _heapinfo[i].free.size += _heapinfo[block].busy.info.size;
  299. block = i;
  300. } else {
  301. /* Really link this block back into the free list. */
  302. _heapinfo[block].free.size = _heapinfo[block].busy.info.size;
  303. _heapinfo[block].free.next = _heapinfo[i].free.next;
  304. _heapinfo[block].free.prev = i;
  305. _heapinfo[i].free.next = block;
  306. _heapinfo[_heapinfo[block].free.next].free.prev = block;
  307. }
  308. /* Now that the block is linked in, see if we can coalesce it
  309. with its successor (by deleting its successor from the list
  310. and adding in its size). */
  311. if (block + _heapinfo[block].free.size == _heapinfo[block].free.next) {
  312. _heapinfo[block].free.size
  313. += _heapinfo[_heapinfo[block].free.next].free.size;
  314. _heapinfo[block].free.next
  315. = _heapinfo[_heapinfo[block].free.next].free.next;
  316. _heapinfo[_heapinfo[block].free.next].free.prev = block;
  317. }
  318. /* Now see if we can return stuff to the system. */
  319. blocks = _heapinfo[block].free.size;
  320. if (blocks >= FINAL_FREE_BLOCKS && block + blocks == _heaplimit
  321. && (*__morecore)(0) == ADDRESS(block + blocks)) {
  322. _heaplimit -= blocks;
  323. (*__morecore)(-blocks * BLOCKSIZE);
  324. _heapinfo[_heapinfo[block].free.prev].free.next
  325. = _heapinfo[block].free.next;
  326. _heapinfo[_heapinfo[block].free.next].free.prev
  327. = _heapinfo[block].free.prev;
  328. block = _heapinfo[block].free.prev;
  329. }
  330. /* Set the next search to begin at this block. */
  331. _heapindex = block;
  332. break;
  333. default:
  334. /* Get the address of the first free fragment in this block. */
  335. prev = (struct list *) ((char *) ADDRESS(block)
  336. + (_heapinfo[block].busy.info.frag.first
  337. << type));
  338. if (_heapinfo[block].busy.info.frag.nfree == (BLOCKSIZE >> type) - 1
  339. && _fragblocks[type] > 1) {
  340. /* If all fragments of this block are free, remove them
  341. from the fragment list and free the whole block. */
  342. --_fragblocks[type];
  343. for (next = prev, i = 1; i < BLOCKSIZE >> type; ++i)
  344. next = next->next;
  345. prev->prev->next = next;
  346. if (next)
  347. next->prev = prev->prev;
  348. _heapinfo[block].busy.type = 0;
  349. _heapinfo[block].busy.info.size = 1;
  350. free_unlocked(ADDRESS(block));
  351. } else if (_heapinfo[block].busy.info.frag.nfree) {
  352. /* If some fragments of this block are free, link this fragment
  353. into the fragment list after the first free fragment of
  354. this block. */
  355. next = ptr;
  356. next->next = prev->next;
  357. next->prev = prev;
  358. prev->next = next;
  359. if (next->next)
  360. next->next->prev = next;
  361. ++_heapinfo[block].busy.info.frag.nfree;
  362. } else {
  363. /* No fragments of this block are free, so link this fragment
  364. into the fragment list and announce that it is the first
  365. free fragment of this block. */
  366. prev = (struct list *) ptr;
  367. _heapinfo[block].busy.info.frag.nfree = 1;
  368. _heapinfo[block].busy.info.frag.first
  369. = (unsigned int) ((char *) ptr - (char *) NULL) % BLOCKSIZE
  370. >> type;
  371. prev->next = _fraghead[type].next;
  372. prev->prev = &_fraghead[type];
  373. prev->prev->next = prev;
  374. if (prev->next)
  375. prev->next->prev = prev;
  376. }
  377. break;
  378. }
  379. }
  380. /* Resize the given region to the new size, returning a pointer
  381. to the (possibly moved) region. This is optimized for speed;
  382. some benchmarks seem to indicate that greater compactness is
  383. achieved by unconditionally allocating and copying to a
  384. new region. */
  385. void * realloc (void *ptr, size_t size)
  386. {
  387. void *result, *previous;
  388. size_t block, blocks, type;
  389. size_t oldlimit;
  390. if (!ptr)
  391. return malloc(size);
  392. if (!size) {
  393. LOCK;
  394. free_unlocked(ptr);
  395. result = malloc_unlocked(0);
  396. UNLOCK;
  397. return(result);
  398. }
  399. LOCK;
  400. block = BLOCK(ptr);
  401. switch (type = _heapinfo[block].busy.type) {
  402. case 0:
  403. /* Maybe reallocate a large block to a small fragment. */
  404. if (size <= BLOCKSIZE / 2) {
  405. if ((result = malloc_unlocked(size)) != NULL) {
  406. memcpy(result, ptr, size);
  407. free_unlocked(ptr);
  408. }
  409. UNLOCK;
  410. return result;
  411. }
  412. /* The new size is a large allocation as well; see if
  413. we can hold it in place. */
  414. blocks = BLOCKIFY(size);
  415. if (blocks < _heapinfo[block].busy.info.size) {
  416. /* The new size is smaller; return excess memory
  417. to the free list. */
  418. _heapinfo[block + blocks].busy.type = 0;
  419. _heapinfo[block + blocks].busy.info.size
  420. = _heapinfo[block].busy.info.size - blocks;
  421. _heapinfo[block].busy.info.size = blocks;
  422. free_unlocked(ADDRESS(block + blocks));
  423. UNLOCK;
  424. return ptr;
  425. } else if (blocks == _heapinfo[block].busy.info.size) {
  426. /* No size change necessary. */
  427. UNLOCK;
  428. return ptr;
  429. } else {
  430. /* Won't fit, so allocate a new region that will. Free
  431. the old region first in case there is sufficient adjacent
  432. free space to grow without moving. */
  433. blocks = _heapinfo[block].busy.info.size;
  434. /* Prevent free from actually returning memory to the system. */
  435. oldlimit = _heaplimit;
  436. _heaplimit = 0;
  437. free_unlocked(ptr);
  438. _heaplimit = oldlimit;
  439. result = malloc_unlocked(size);
  440. if (!result) {
  441. /* Now we're really in trouble. We have to unfree
  442. the thing we just freed. Unfortunately it might
  443. have been coalesced with its neighbors. */
  444. if (_heapindex == block)
  445. malloc_unlocked(blocks * BLOCKSIZE);
  446. else {
  447. previous = malloc_unlocked((block - _heapindex) * BLOCKSIZE);
  448. malloc_unlocked(blocks * BLOCKSIZE);
  449. free_unlocked(previous);
  450. }
  451. UNLOCK;
  452. return NULL;
  453. }
  454. if (ptr != result)
  455. memmove(result, ptr, blocks * BLOCKSIZE);
  456. UNLOCK;
  457. return result;
  458. }
  459. break;
  460. default:
  461. /* Old size is a fragment; type is logarithm to base two of
  462. the fragment size. */
  463. if ((size > 1 << (type - 1)) && (size <= 1 << type)) {
  464. /* New size is the same kind of fragment. */
  465. UNLOCK;
  466. return ptr;
  467. }
  468. else {
  469. /* New size is different; allocate a new space, and copy
  470. the lesser of the new size and the old. */
  471. result = malloc_unlocked(size);
  472. if (!result) {
  473. UNLOCK;
  474. return NULL;
  475. }
  476. memcpy(result, ptr, MIN(size, (size_t)(1 << type)));
  477. free_unlocked(ptr);
  478. UNLOCK;
  479. return result;
  480. }
  481. break;
  482. }
  483. UNLOCK;
  484. }