malloc.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. #define _GNU_SOURCE
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <limits.h>
  5. #include <stdint.h>
  6. #include <errno.h>
  7. #include <sys/mman.h>
  8. #include "libc.h"
  9. #include "atomic.h"
  10. #include "pthread_impl.h"
  11. #if defined(__GNUC__) && defined(__PIC__)
  12. #define inline inline __attribute__((always_inline))
  13. #endif
  14. void *__mmap(void *, size_t, int, int, int, off_t);
  15. int __munmap(void *, size_t);
  16. void *__mremap(void *, size_t, size_t, int, ...);
  17. int __madvise(void *, size_t, int);
  18. struct chunk {
  19. size_t psize, csize;
  20. struct chunk *next, *prev;
  21. };
  22. struct bin {
  23. volatile int lock[2];
  24. struct chunk *head;
  25. struct chunk *tail;
  26. };
  27. static struct {
  28. volatile uint64_t binmap;
  29. struct bin bins[64];
  30. volatile int free_lock[2];
  31. } mal;
  32. #define SIZE_ALIGN (4*sizeof(size_t))
  33. #define SIZE_MASK (-SIZE_ALIGN)
  34. #define OVERHEAD (2*sizeof(size_t))
  35. #define MMAP_THRESHOLD (0x1c00*SIZE_ALIGN)
  36. #define DONTCARE 16
  37. #define RECLAIM 163840
  38. #define CHUNK_SIZE(c) ((c)->csize & -2)
  39. #define CHUNK_PSIZE(c) ((c)->psize & -2)
  40. #define PREV_CHUNK(c) ((struct chunk *)((char *)(c) - CHUNK_PSIZE(c)))
  41. #define NEXT_CHUNK(c) ((struct chunk *)((char *)(c) + CHUNK_SIZE(c)))
  42. #define MEM_TO_CHUNK(p) (struct chunk *)((char *)(p) - OVERHEAD)
  43. #define CHUNK_TO_MEM(c) (void *)((char *)(c) + OVERHEAD)
  44. #define BIN_TO_CHUNK(i) (MEM_TO_CHUNK(&mal.bins[i].head))
  45. #define C_INUSE ((size_t)1)
  46. #define IS_MMAPPED(c) !((c)->csize & (C_INUSE))
  47. /* Synchronization tools */
  48. static inline void lock(volatile int *lk)
  49. {
  50. if (libc.threads_minus_1)
  51. while(a_swap(lk, 1)) __wait(lk, lk+1, 1, 1);
  52. }
  53. static inline void unlock(volatile int *lk)
  54. {
  55. if (lk[0]) {
  56. a_store(lk, 0);
  57. if (lk[1]) __wake(lk, 1, 1);
  58. }
  59. }
  60. static inline void lock_bin(int i)
  61. {
  62. lock(mal.bins[i].lock);
  63. if (!mal.bins[i].head)
  64. mal.bins[i].head = mal.bins[i].tail = BIN_TO_CHUNK(i);
  65. }
  66. static inline void unlock_bin(int i)
  67. {
  68. unlock(mal.bins[i].lock);
  69. }
  70. static int first_set(uint64_t x)
  71. {
  72. #if 1
  73. return a_ctz_64(x);
  74. #else
  75. static const char debruijn64[64] = {
  76. 0, 1, 2, 53, 3, 7, 54, 27, 4, 38, 41, 8, 34, 55, 48, 28,
  77. 62, 5, 39, 46, 44, 42, 22, 9, 24, 35, 59, 56, 49, 18, 29, 11,
  78. 63, 52, 6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,
  79. 51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12
  80. };
  81. static const char debruijn32[32] = {
  82. 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13,
  83. 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14
  84. };
  85. if (sizeof(long) < 8) {
  86. uint32_t y = x;
  87. if (!y) {
  88. y = x>>32;
  89. return 32 + debruijn32[(y&-y)*0x076be629 >> 27];
  90. }
  91. return debruijn32[(y&-y)*0x076be629 >> 27];
  92. }
  93. return debruijn64[(x&-x)*0x022fdd63cc95386dull >> 58];
  94. #endif
  95. }
  96. static const unsigned char bin_tab[60] = {
  97. 32,33,34,35,36,36,37,37,38,38,39,39,
  98. 40,40,40,40,41,41,41,41,42,42,42,42,43,43,43,43,
  99. 44,44,44,44,44,44,44,44,45,45,45,45,45,45,45,45,
  100. 46,46,46,46,46,46,46,46,47,47,47,47,47,47,47,47,
  101. };
  102. static int bin_index(size_t x)
  103. {
  104. x = x / SIZE_ALIGN - 1;
  105. if (x <= 32) return x;
  106. if (x < 512) return bin_tab[x/8-4];
  107. if (x > 0x1c00) return 63;
  108. return bin_tab[x/128-4] + 16;
  109. }
  110. static int bin_index_up(size_t x)
  111. {
  112. x = x / SIZE_ALIGN - 1;
  113. if (x <= 32) return x;
  114. x--;
  115. if (x < 512) return bin_tab[x/8-4] + 1;
  116. return bin_tab[x/128-4] + 17;
  117. }
  118. #if 0
  119. void __dump_heap(int x)
  120. {
  121. struct chunk *c;
  122. int i;
  123. for (c = (void *)mal.heap; CHUNK_SIZE(c); c = NEXT_CHUNK(c))
  124. fprintf(stderr, "base %p size %zu (%d) flags %d/%d\n",
  125. c, CHUNK_SIZE(c), bin_index(CHUNK_SIZE(c)),
  126. c->csize & 15,
  127. NEXT_CHUNK(c)->psize & 15);
  128. for (i=0; i<64; i++) {
  129. if (mal.bins[i].head != BIN_TO_CHUNK(i) && mal.bins[i].head) {
  130. fprintf(stderr, "bin %d: %p\n", i, mal.bins[i].head);
  131. if (!(mal.binmap & 1ULL<<i))
  132. fprintf(stderr, "missing from binmap!\n");
  133. } else if (mal.binmap & 1ULL<<i)
  134. fprintf(stderr, "binmap wrongly contains %d!\n", i);
  135. }
  136. }
  137. #endif
  138. void *__expand_heap(size_t *);
  139. static struct chunk *expand_heap(size_t n)
  140. {
  141. static int heap_lock[2];
  142. static void *end;
  143. void *p;
  144. struct chunk *w;
  145. /* The argument n already accounts for the caller's chunk
  146. * overhead needs, but if the heap can't be extended in-place,
  147. * we need room for an extra zero-sized sentinel chunk. */
  148. n += SIZE_ALIGN;
  149. lock(heap_lock);
  150. p = __expand_heap(&n);
  151. if (!p) {
  152. unlock(heap_lock);
  153. return 0;
  154. }
  155. /* If not just expanding existing space, we need to make a
  156. * new sentinel chunk below the allocated space. */
  157. if (p != end) {
  158. /* Valid/safe because of the prologue increment. */
  159. n -= SIZE_ALIGN;
  160. p = (char *)p + SIZE_ALIGN;
  161. w = MEM_TO_CHUNK(p);
  162. w->psize = 0 | C_INUSE;
  163. }
  164. /* Record new heap end and fill in footer. */
  165. end = (char *)p + n;
  166. w = MEM_TO_CHUNK(end);
  167. w->psize = n | C_INUSE;
  168. w->csize = 0 | C_INUSE;
  169. /* Fill in header, which may be new or may be replacing a
  170. * zero-size sentinel header at the old end-of-heap. */
  171. w = MEM_TO_CHUNK(p);
  172. w->csize = n | C_INUSE;
  173. unlock(heap_lock);
  174. return w;
  175. }
  176. static int adjust_size(size_t *n)
  177. {
  178. /* Result of pointer difference must fit in ptrdiff_t. */
  179. if (*n-1 > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) {
  180. if (*n) {
  181. errno = ENOMEM;
  182. return -1;
  183. } else {
  184. *n = SIZE_ALIGN;
  185. return 0;
  186. }
  187. }
  188. *n = (*n + OVERHEAD + SIZE_ALIGN - 1) & SIZE_MASK;
  189. return 0;
  190. }
  191. static void unbin(struct chunk *c, int i)
  192. {
  193. if (c->prev == c->next)
  194. a_and_64(&mal.binmap, ~(1ULL<<i));
  195. c->prev->next = c->next;
  196. c->next->prev = c->prev;
  197. c->csize |= C_INUSE;
  198. NEXT_CHUNK(c)->psize |= C_INUSE;
  199. }
  200. static int alloc_fwd(struct chunk *c)
  201. {
  202. int i;
  203. size_t k;
  204. while (!((k=c->csize) & C_INUSE)) {
  205. i = bin_index(k);
  206. lock_bin(i);
  207. if (c->csize == k) {
  208. unbin(c, i);
  209. unlock_bin(i);
  210. return 1;
  211. }
  212. unlock_bin(i);
  213. }
  214. return 0;
  215. }
  216. static int alloc_rev(struct chunk *c)
  217. {
  218. int i;
  219. size_t k;
  220. while (!((k=c->psize) & C_INUSE)) {
  221. i = bin_index(k);
  222. lock_bin(i);
  223. if (c->psize == k) {
  224. unbin(PREV_CHUNK(c), i);
  225. unlock_bin(i);
  226. return 1;
  227. }
  228. unlock_bin(i);
  229. }
  230. return 0;
  231. }
  232. /* pretrim - trims a chunk _prior_ to removing it from its bin.
  233. * Must be called with i as the ideal bin for size n, j the bin
  234. * for the _free_ chunk self, and bin j locked. */
  235. static int pretrim(struct chunk *self, size_t n, int i, int j)
  236. {
  237. size_t n1;
  238. struct chunk *next, *split;
  239. /* We cannot pretrim if it would require re-binning. */
  240. if (j < 40) return 0;
  241. if (j < i+3) {
  242. if (j != 63) return 0;
  243. n1 = CHUNK_SIZE(self);
  244. if (n1-n <= MMAP_THRESHOLD) return 0;
  245. } else {
  246. n1 = CHUNK_SIZE(self);
  247. }
  248. if (bin_index(n1-n) != j) return 0;
  249. next = NEXT_CHUNK(self);
  250. split = (void *)((char *)self + n);
  251. split->prev = self->prev;
  252. split->next = self->next;
  253. split->prev->next = split;
  254. split->next->prev = split;
  255. split->psize = n | C_INUSE;
  256. split->csize = n1-n;
  257. next->psize = n1-n;
  258. self->csize = n | C_INUSE;
  259. return 1;
  260. }
  261. static void trim(struct chunk *self, size_t n)
  262. {
  263. size_t n1 = CHUNK_SIZE(self);
  264. struct chunk *next, *split;
  265. if (n >= n1 - DONTCARE) return;
  266. next = NEXT_CHUNK(self);
  267. split = (void *)((char *)self + n);
  268. split->psize = n | C_INUSE;
  269. split->csize = n1-n | C_INUSE;
  270. next->psize = n1-n | C_INUSE;
  271. self->csize = n | C_INUSE;
  272. free(CHUNK_TO_MEM(split));
  273. }
  274. void *malloc(size_t n)
  275. {
  276. struct chunk *c;
  277. int i, j;
  278. if (adjust_size(&n) < 0) return 0;
  279. if (n > MMAP_THRESHOLD) {
  280. size_t len = n + OVERHEAD + PAGE_SIZE - 1 & -PAGE_SIZE;
  281. char *base = __mmap(0, len, PROT_READ|PROT_WRITE,
  282. MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  283. if (base == (void *)-1) return 0;
  284. c = (void *)(base + SIZE_ALIGN - OVERHEAD);
  285. c->csize = len - (SIZE_ALIGN - OVERHEAD);
  286. c->psize = SIZE_ALIGN - OVERHEAD;
  287. return CHUNK_TO_MEM(c);
  288. }
  289. i = bin_index_up(n);
  290. for (;;) {
  291. uint64_t mask = mal.binmap & -(1ULL<<i);
  292. if (!mask) {
  293. c = expand_heap(n);
  294. if (!c) return 0;
  295. if (alloc_rev(c)) {
  296. struct chunk *x = c;
  297. c = PREV_CHUNK(c);
  298. NEXT_CHUNK(x)->psize = c->csize =
  299. x->csize + CHUNK_SIZE(c);
  300. }
  301. break;
  302. }
  303. j = first_set(mask);
  304. lock_bin(j);
  305. c = mal.bins[j].head;
  306. if (c != BIN_TO_CHUNK(j)) {
  307. if (!pretrim(c, n, i, j)) unbin(c, j);
  308. unlock_bin(j);
  309. break;
  310. }
  311. unlock_bin(j);
  312. }
  313. /* Now patch up in case we over-allocated */
  314. trim(c, n);
  315. return CHUNK_TO_MEM(c);
  316. }
  317. static size_t mal0_clear(char *p, size_t pagesz, size_t n)
  318. {
  319. #ifdef __GNUC__
  320. typedef uint64_t __attribute__((__may_alias__)) T;
  321. #else
  322. typedef unsigned char T;
  323. #endif
  324. char *pp = p + n;
  325. size_t i = (uintptr_t)pp & (pagesz - 1);
  326. for (;;) {
  327. pp = memset(pp - i, 0, i);
  328. if (pp - p < pagesz) return pp - p;
  329. for (i = pagesz; i; i -= 2*sizeof(T), pp -= 2*sizeof(T))
  330. if (((T *)pp)[-1] | ((T *)pp)[-2])
  331. break;
  332. }
  333. }
  334. void *__malloc0(size_t n)
  335. {
  336. void *p = malloc(n);
  337. if (!p || IS_MMAPPED(MEM_TO_CHUNK(p)))
  338. return p;
  339. if (n >= PAGE_SIZE)
  340. n = mal0_clear(p, PAGE_SIZE, n);
  341. return memset(p, 0, n);
  342. }
  343. void *realloc(void *p, size_t n)
  344. {
  345. struct chunk *self, *next;
  346. size_t n0, n1;
  347. void *new;
  348. if (!p) return malloc(n);
  349. if (adjust_size(&n) < 0) return 0;
  350. self = MEM_TO_CHUNK(p);
  351. n1 = n0 = CHUNK_SIZE(self);
  352. if (IS_MMAPPED(self)) {
  353. size_t extra = self->psize;
  354. char *base = (char *)self - extra;
  355. size_t oldlen = n0 + extra;
  356. size_t newlen = n + extra;
  357. /* Crash on realloc of freed chunk */
  358. if (extra & 1) a_crash();
  359. if (newlen < PAGE_SIZE && (new = malloc(n-OVERHEAD))) {
  360. n0 = n;
  361. goto copy_free_ret;
  362. }
  363. newlen = (newlen + PAGE_SIZE-1) & -PAGE_SIZE;
  364. if (oldlen == newlen) return p;
  365. base = __mremap(base, oldlen, newlen, MREMAP_MAYMOVE);
  366. if (base == (void *)-1)
  367. goto copy_realloc;
  368. self = (void *)(base + extra);
  369. self->csize = newlen - extra;
  370. return CHUNK_TO_MEM(self);
  371. }
  372. next = NEXT_CHUNK(self);
  373. /* Crash on corrupted footer (likely from buffer overflow) */
  374. if (next->psize != self->csize) a_crash();
  375. /* Merge adjacent chunks if we need more space. This is not
  376. * a waste of time even if we fail to get enough space, because our
  377. * subsequent call to free would otherwise have to do the merge. */
  378. if (n > n1 && alloc_fwd(next)) {
  379. n1 += CHUNK_SIZE(next);
  380. next = NEXT_CHUNK(next);
  381. }
  382. /* FIXME: find what's wrong here and reenable it..? */
  383. if (0 && n > n1 && alloc_rev(self)) {
  384. self = PREV_CHUNK(self);
  385. n1 += CHUNK_SIZE(self);
  386. }
  387. self->csize = n1 | C_INUSE;
  388. next->psize = n1 | C_INUSE;
  389. /* If we got enough space, split off the excess and return */
  390. if (n <= n1) {
  391. //memmove(CHUNK_TO_MEM(self), p, n0-OVERHEAD);
  392. trim(self, n);
  393. return CHUNK_TO_MEM(self);
  394. }
  395. copy_realloc:
  396. /* As a last resort, allocate a new chunk and copy to it. */
  397. new = malloc(n-OVERHEAD);
  398. if (!new) return 0;
  399. copy_free_ret:
  400. memcpy(new, p, n0-OVERHEAD);
  401. free(CHUNK_TO_MEM(self));
  402. return new;
  403. }
  404. void free(void *p)
  405. {
  406. struct chunk *self, *next;
  407. size_t final_size, new_size, size;
  408. int reclaim=0;
  409. int i;
  410. if (!p) return;
  411. self = MEM_TO_CHUNK(p);
  412. if (IS_MMAPPED(self)) {
  413. size_t extra = self->psize;
  414. char *base = (char *)self - extra;
  415. size_t len = CHUNK_SIZE(self) + extra;
  416. /* Crash on double free */
  417. if (extra & 1) a_crash();
  418. __munmap(base, len);
  419. return;
  420. }
  421. final_size = new_size = CHUNK_SIZE(self);
  422. next = NEXT_CHUNK(self);
  423. /* Crash on corrupted footer (likely from buffer overflow) */
  424. if (next->psize != self->csize) a_crash();
  425. for (;;) {
  426. if (self->psize & next->csize & C_INUSE) {
  427. self->csize = final_size | C_INUSE;
  428. next->psize = final_size | C_INUSE;
  429. i = bin_index(final_size);
  430. lock_bin(i);
  431. lock(mal.free_lock);
  432. if (self->psize & next->csize & C_INUSE)
  433. break;
  434. unlock(mal.free_lock);
  435. unlock_bin(i);
  436. }
  437. if (alloc_rev(self)) {
  438. self = PREV_CHUNK(self);
  439. size = CHUNK_SIZE(self);
  440. final_size += size;
  441. if (new_size+size > RECLAIM && (new_size+size^size) > size)
  442. reclaim = 1;
  443. }
  444. if (alloc_fwd(next)) {
  445. size = CHUNK_SIZE(next);
  446. final_size += size;
  447. if (new_size+size > RECLAIM && (new_size+size^size) > size)
  448. reclaim = 1;
  449. next = NEXT_CHUNK(next);
  450. }
  451. }
  452. if (!(mal.binmap & 1ULL<<i))
  453. a_or_64(&mal.binmap, 1ULL<<i);
  454. self->csize = final_size;
  455. next->psize = final_size;
  456. unlock(mal.free_lock);
  457. self->next = BIN_TO_CHUNK(i);
  458. self->prev = mal.bins[i].tail;
  459. self->next->prev = self;
  460. self->prev->next = self;
  461. /* Replace middle of large chunks with fresh zero pages */
  462. if (reclaim) {
  463. uintptr_t a = (uintptr_t)self + SIZE_ALIGN+PAGE_SIZE-1 & -PAGE_SIZE;
  464. uintptr_t b = (uintptr_t)next - SIZE_ALIGN & -PAGE_SIZE;
  465. #if 1
  466. __madvise((void *)a, b-a, MADV_DONTNEED);
  467. #else
  468. __mmap((void *)a, b-a, PROT_READ|PROT_WRITE,
  469. MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0);
  470. #endif
  471. }
  472. unlock_bin(i);
  473. }