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