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