finish unifying thread register handling in preparation for porting
[musl] / src / malloc / __simple_malloc.c
1 #include <stdlib.h>
2 #include <stdint.h>
3 #include <limits.h>
4 #include <errno.h>
5 #include "libc.h"
6
7 uintptr_t __brk(uintptr_t);
8
9 #define ALIGN 16
10
11 void *__simple_malloc(size_t n)
12 {
13         static uintptr_t cur, brk;
14         uintptr_t base, new;
15         static int lock;
16         size_t align=1;
17
18         if (n < SIZE_MAX - ALIGN)
19                 while (align<n && align<ALIGN)
20                         align += align;
21         n = n + align - 1 & -align;
22
23         LOCK(&lock);
24         if (!cur) cur = brk = __brk(0)+16;
25         if (n > SIZE_MAX - brk) goto fail;
26
27         base = cur + align-1 & -align;
28         if (base+n > brk) {
29                 new = base+n + PAGE_SIZE-1 & -PAGE_SIZE;
30                 if (__brk(new) != new) goto fail;
31                 brk = new;
32         }
33         cur = base+n;
34         UNLOCK(&lock);
35
36         return (void *)base;
37
38 fail:
39         UNLOCK(&lock);
40         errno = ENOMEM;
41         return 0;
42 }
43
44 weak_alias(__simple_malloc, malloc);