malloc.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 int bin_index(size_t x)
  97. {
  98. x = x / SIZE_ALIGN - 1;
  99. if (x <= 32) return x;
  100. if (x > 0x1c00) return 63;
  101. return ((union { float v; uint32_t r; }){(int)x}.r>>21) - 496;
  102. }
  103. static int bin_index_up(size_t x)
  104. {
  105. x = x / SIZE_ALIGN - 1;
  106. if (x <= 32) return x;
  107. return ((union { float v; uint32_t r; }){(int)x}.r+0x1fffff>>21) - 496;
  108. }
  109. #if 0
  110. void __dump_heap(int x)
  111. {
  112. struct chunk *c;
  113. int i;
  114. for (c = (void *)mal.heap; CHUNK_SIZE(c); c = NEXT_CHUNK(c))
  115. fprintf(stderr, "base %p size %zu (%d) flags %d/%d\n",
  116. c, CHUNK_SIZE(c), bin_index(CHUNK_SIZE(c)),
  117. c->csize & 15,
  118. NEXT_CHUNK(c)->psize & 15);
  119. for (i=0; i<64; i++) {
  120. if (mal.bins[i].head != BIN_TO_CHUNK(i) && mal.bins[i].head) {
  121. fprintf(stderr, "bin %d: %p\n", i, mal.bins[i].head);
  122. if (!(mal.binmap & 1ULL<<i))
  123. fprintf(stderr, "missing from binmap!\n");
  124. } else if (mal.binmap & 1ULL<<i)
  125. fprintf(stderr, "binmap wrongly contains %d!\n", i);
  126. }
  127. }
  128. #endif
  129. void *__expand_heap(size_t *);
  130. static struct chunk *expand_heap(size_t n)
  131. {
  132. static int heap_lock[2];
  133. static void *end;
  134. void *p;
  135. struct chunk *w;
  136. /* The argument n already accounts for the caller's chunk
  137. * overhead needs, but if the heap can't be extended in-place,
  138. * we need room for an extra zero-sized sentinel chunk. */
  139. n += SIZE_ALIGN;
  140. lock(heap_lock);
  141. p = __expand_heap(&n);
  142. if (!p) {
  143. unlock(heap_lock);
  144. return 0;
  145. }
  146. /* If not just expanding existing space, we need to make a
  147. * new sentinel chunk below the allocated space. */
  148. if (p != end) {
  149. /* Valid/safe because of the prologue increment. */
  150. n -= SIZE_ALIGN;
  151. p = (char *)p + SIZE_ALIGN;
  152. w = MEM_TO_CHUNK(p);
  153. w->psize = 0 | C_INUSE;
  154. }
  155. /* Record new heap end and fill in footer. */
  156. end = (char *)p + n;
  157. w = MEM_TO_CHUNK(end);
  158. w->psize = n | C_INUSE;
  159. w->csize = 0 | C_INUSE;
  160. /* Fill in header, which may be new or may be replacing a
  161. * zero-size sentinel header at the old end-of-heap. */
  162. w = MEM_TO_CHUNK(p);
  163. w->csize = n | C_INUSE;
  164. unlock(heap_lock);
  165. return w;
  166. }
  167. static int adjust_size(size_t *n)
  168. {
  169. /* Result of pointer difference must fit in ptrdiff_t. */
  170. if (*n-1 > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) {
  171. if (*n) {
  172. errno = ENOMEM;
  173. return -1;
  174. } else {
  175. *n = SIZE_ALIGN;
  176. return 0;
  177. }
  178. }
  179. *n = (*n + OVERHEAD + SIZE_ALIGN - 1) & SIZE_MASK;
  180. return 0;
  181. }
  182. static void unbin(struct chunk *c, int i)
  183. {
  184. if (c->prev == c->next)
  185. a_and_64(&mal.binmap, ~(1ULL<<i));
  186. c->prev->next = c->next;
  187. c->next->prev = c->prev;
  188. c->csize |= C_INUSE;
  189. NEXT_CHUNK(c)->psize |= C_INUSE;
  190. }
  191. static int alloc_fwd(struct chunk *c)
  192. {
  193. int i;
  194. size_t k;
  195. while (!((k=c->csize) & C_INUSE)) {
  196. i = bin_index(k);
  197. lock_bin(i);
  198. if (c->csize == k) {
  199. unbin(c, i);
  200. unlock_bin(i);
  201. return 1;
  202. }
  203. unlock_bin(i);
  204. }
  205. return 0;
  206. }
  207. static int alloc_rev(struct chunk *c)
  208. {
  209. int i;
  210. size_t k;
  211. while (!((k=c->psize) & C_INUSE)) {
  212. i = bin_index(k);
  213. lock_bin(i);
  214. if (c->psize == k) {
  215. unbin(PREV_CHUNK(c), i);
  216. unlock_bin(i);
  217. return 1;
  218. }
  219. unlock_bin(i);
  220. }
  221. return 0;
  222. }
  223. /* pretrim - trims a chunk _prior_ to removing it from its bin.
  224. * Must be called with i as the ideal bin for size n, j the bin
  225. * for the _free_ chunk self, and bin j locked. */
  226. static int pretrim(struct chunk *self, size_t n, int i, int j)
  227. {
  228. size_t n1;
  229. struct chunk *next, *split;
  230. /* We cannot pretrim if it would require re-binning. */
  231. if (j < 40) return 0;
  232. if (j < i+3) {
  233. if (j != 63) return 0;
  234. n1 = CHUNK_SIZE(self);
  235. if (n1-n <= MMAP_THRESHOLD) return 0;
  236. } else {
  237. n1 = CHUNK_SIZE(self);
  238. }
  239. if (bin_index(n1-n) != j) return 0;
  240. next = NEXT_CHUNK(self);
  241. split = (void *)((char *)self + n);
  242. split->prev = self->prev;
  243. split->next = self->next;
  244. split->prev->next = split;
  245. split->next->prev = split;
  246. split->psize = n | C_INUSE;
  247. split->csize = n1-n;
  248. next->psize = n1-n;
  249. self->csize = n | C_INUSE;
  250. return 1;
  251. }
  252. static void trim(struct chunk *self, size_t n)
  253. {
  254. size_t n1 = CHUNK_SIZE(self);
  255. struct chunk *next, *split;
  256. if (n >= n1 - DONTCARE) return;
  257. next = NEXT_CHUNK(self);
  258. split = (void *)((char *)self + n);
  259. split->psize = n | C_INUSE;
  260. split->csize = n1-n | C_INUSE;
  261. next->psize = n1-n | C_INUSE;
  262. self->csize = n | C_INUSE;
  263. free(CHUNK_TO_MEM(split));
  264. }
  265. void *malloc(size_t n)
  266. {
  267. struct chunk *c;
  268. int i, j;
  269. if (adjust_size(&n) < 0) return 0;
  270. if (n > MMAP_THRESHOLD) {
  271. size_t len = n + OVERHEAD + PAGE_SIZE - 1 & -PAGE_SIZE;
  272. char *base = __mmap(0, len, PROT_READ|PROT_WRITE,
  273. MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  274. if (base == (void *)-1) return 0;
  275. c = (void *)(base + SIZE_ALIGN - OVERHEAD);
  276. c->csize = len - (SIZE_ALIGN - OVERHEAD);
  277. c->psize = SIZE_ALIGN - OVERHEAD;
  278. return CHUNK_TO_MEM(c);
  279. }
  280. i = bin_index_up(n);
  281. for (;;) {
  282. uint64_t mask = mal.binmap & -(1ULL<<i);
  283. if (!mask) {
  284. c = expand_heap(n);
  285. if (!c) return 0;
  286. if (alloc_rev(c)) {
  287. struct chunk *x = c;
  288. c = PREV_CHUNK(c);
  289. NEXT_CHUNK(x)->psize = c->csize =
  290. x->csize + CHUNK_SIZE(c);
  291. }
  292. break;
  293. }
  294. j = first_set(mask);
  295. lock_bin(j);
  296. c = mal.bins[j].head;
  297. if (c != BIN_TO_CHUNK(j)) {
  298. if (!pretrim(c, n, i, j)) unbin(c, j);
  299. unlock_bin(j);
  300. break;
  301. }
  302. unlock_bin(j);
  303. }
  304. /* Now patch up in case we over-allocated */
  305. trim(c, n);
  306. return CHUNK_TO_MEM(c);
  307. }
  308. void *__malloc0(size_t n)
  309. {
  310. void *p = malloc(n);
  311. if (p && !IS_MMAPPED(MEM_TO_CHUNK(p))) {
  312. size_t *z;
  313. n = (n + sizeof *z - 1)/sizeof *z;
  314. for (z=p; n; n--, z++) if (*z) *z=0;
  315. }
  316. return p;
  317. }
  318. void *realloc(void *p, size_t n)
  319. {
  320. struct chunk *self, *next;
  321. size_t n0, n1;
  322. void *new;
  323. if (!p) return malloc(n);
  324. if (adjust_size(&n) < 0) return 0;
  325. self = MEM_TO_CHUNK(p);
  326. n1 = n0 = CHUNK_SIZE(self);
  327. if (IS_MMAPPED(self)) {
  328. size_t extra = self->psize;
  329. char *base = (char *)self - extra;
  330. size_t oldlen = n0 + extra;
  331. size_t newlen = n + extra;
  332. /* Crash on realloc of freed chunk */
  333. if (extra & 1) a_crash();
  334. if (newlen < PAGE_SIZE && (new = malloc(n))) {
  335. memcpy(new, p, n-OVERHEAD);
  336. free(p);
  337. return new;
  338. }
  339. newlen = (newlen + PAGE_SIZE-1) & -PAGE_SIZE;
  340. if (oldlen == newlen) return p;
  341. base = __mremap(base, oldlen, newlen, MREMAP_MAYMOVE);
  342. if (base == (void *)-1)
  343. return newlen < oldlen ? p : 0;
  344. self = (void *)(base + extra);
  345. self->csize = newlen - extra;
  346. return CHUNK_TO_MEM(self);
  347. }
  348. next = NEXT_CHUNK(self);
  349. /* Crash on corrupted footer (likely from buffer overflow) */
  350. if (next->psize != self->csize) a_crash();
  351. /* Merge adjacent chunks if we need more space. This is not
  352. * a waste of time even if we fail to get enough space, because our
  353. * subsequent call to free would otherwise have to do the merge. */
  354. if (n > n1 && alloc_fwd(next)) {
  355. n1 += CHUNK_SIZE(next);
  356. next = NEXT_CHUNK(next);
  357. }
  358. /* FIXME: find what's wrong here and reenable it..? */
  359. if (0 && n > n1 && alloc_rev(self)) {
  360. self = PREV_CHUNK(self);
  361. n1 += CHUNK_SIZE(self);
  362. }
  363. self->csize = n1 | C_INUSE;
  364. next->psize = n1 | C_INUSE;
  365. /* If we got enough space, split off the excess and return */
  366. if (n <= n1) {
  367. //memmove(CHUNK_TO_MEM(self), p, n0-OVERHEAD);
  368. trim(self, n);
  369. return CHUNK_TO_MEM(self);
  370. }
  371. /* As a last resort, allocate a new chunk and copy to it. */
  372. new = malloc(n-OVERHEAD);
  373. if (!new) return 0;
  374. memcpy(new, p, n0-OVERHEAD);
  375. free(CHUNK_TO_MEM(self));
  376. return new;
  377. }
  378. void free(void *p)
  379. {
  380. struct chunk *self = MEM_TO_CHUNK(p);
  381. struct chunk *next;
  382. size_t final_size, new_size, size;
  383. int reclaim=0;
  384. int i;
  385. if (!p) return;
  386. if (IS_MMAPPED(self)) {
  387. size_t extra = self->psize;
  388. char *base = (char *)self - extra;
  389. size_t len = CHUNK_SIZE(self) + extra;
  390. /* Crash on double free */
  391. if (extra & 1) a_crash();
  392. __munmap(base, len);
  393. return;
  394. }
  395. final_size = new_size = CHUNK_SIZE(self);
  396. next = NEXT_CHUNK(self);
  397. /* Crash on corrupted footer (likely from buffer overflow) */
  398. if (next->psize != self->csize) a_crash();
  399. for (;;) {
  400. if (self->psize & next->csize & C_INUSE) {
  401. self->csize = final_size | C_INUSE;
  402. next->psize = final_size | C_INUSE;
  403. i = bin_index(final_size);
  404. lock_bin(i);
  405. lock(mal.free_lock);
  406. if (self->psize & next->csize & C_INUSE)
  407. break;
  408. unlock(mal.free_lock);
  409. unlock_bin(i);
  410. }
  411. if (alloc_rev(self)) {
  412. self = PREV_CHUNK(self);
  413. size = CHUNK_SIZE(self);
  414. final_size += size;
  415. if (new_size+size > RECLAIM && (new_size+size^size) > size)
  416. reclaim = 1;
  417. }
  418. if (alloc_fwd(next)) {
  419. size = CHUNK_SIZE(next);
  420. final_size += size;
  421. if (new_size+size > RECLAIM && (new_size+size^size) > size)
  422. reclaim = 1;
  423. next = NEXT_CHUNK(next);
  424. }
  425. }
  426. if (!(mal.binmap & 1ULL<<i))
  427. a_or_64(&mal.binmap, 1ULL<<i);
  428. self->csize = final_size;
  429. next->psize = final_size;
  430. unlock(mal.free_lock);
  431. self->next = BIN_TO_CHUNK(i);
  432. self->prev = mal.bins[i].tail;
  433. self->next->prev = self;
  434. self->prev->next = self;
  435. /* Replace middle of large chunks with fresh zero pages */
  436. if (reclaim) {
  437. uintptr_t a = (uintptr_t)self + SIZE_ALIGN+PAGE_SIZE-1 & -PAGE_SIZE;
  438. uintptr_t b = (uintptr_t)next - SIZE_ALIGN & -PAGE_SIZE;
  439. #if 1
  440. __madvise((void *)a, b-a, MADV_DONTNEED);
  441. #else
  442. __mmap((void *)a, b-a, PROT_READ|PROT_WRITE,
  443. MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0);
  444. #endif
  445. }
  446. unlock_bin(i);
  447. }