malloc.c 12 KB

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