ditch the priority inheritance locks; use malloc's version of lock
[musl] / src / malloc / lite_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[2];
16         size_t align=1;
17
18         if (!n) n++;
19         if (n > SIZE_MAX/2) goto toobig;
20
21         while (align<n && align<ALIGN)
22                 align += align;
23         n = n + align - 1 & -align;
24
25         LOCK(lock);
26         if (!cur) cur = brk = __brk(0)+16;
27         base = cur + align-1 & -align;
28         if (n > SIZE_MAX - PAGE_SIZE - base) goto fail;
29         if (base+n > brk) {
30                 new = base+n + PAGE_SIZE-1 & -PAGE_SIZE;
31                 if (__brk(new) != new) goto fail;
32                 brk = new;
33         }
34         cur = base+n;
35         UNLOCK(lock);
36
37         return (void *)base;
38
39 fail:
40         UNLOCK(lock);
41 toobig:
42         errno = ENOMEM;
43         return 0;
44 }
45
46 weak_alias(__simple_malloc, malloc);