fix simple_malloc size restrictions
[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/2) goto toobig;
19
20         while (align<n && align<ALIGN)
21                 align += align;
22         n = n + align - 1 & -align;
23
24         LOCK(&lock);
25         if (!cur) cur = brk = __brk(0)+16;
26         base = cur + align-1 & -align;
27         if (n > SIZE_MAX - PAGE_SIZE - base) goto fail;
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 toobig:
41         errno = ENOMEM;
42         return 0;
43 }
44
45 weak_alias(__simple_malloc, malloc);