malloc.c 12 KB

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