55fe68e866253316faeab0076ba78d46b4881f78
[musl] / src / malloc / memalign.c
1 #include <stdlib.h>
2 #include <stdint.h>
3 #include <errno.h>
4 #include "libc.h"
5
6 /* This function should work with most dlmalloc-like chunk bookkeeping
7  * systems, but it's only guaranteed to work with the native implementation
8  * used in this library. */
9
10 void *__memalign(size_t align, size_t len)
11 {
12         unsigned char *mem, *new, *end;
13         size_t header, footer;
14
15         if ((align & -align) != align) {
16                 errno = EINVAL;
17                 return NULL;
18         }
19
20         if (len > SIZE_MAX - align) {
21                 errno = ENOMEM;
22                 return NULL;
23         }
24
25         if (align <= 4*sizeof(size_t)) {
26                 if (!(mem = malloc(len)))
27                         return NULL;
28                 return mem;
29         }
30
31         if (!(mem = malloc(len + align-1)))
32                 return NULL;
33
34         header = ((size_t *)mem)[-1];
35         new = (void *)((uintptr_t)mem + align-1 & -align);
36
37         if (!(header & 7)) {
38                 ((size_t *)new)[-2] = ((size_t *)mem)[-2] + (new-mem);
39                 ((size_t *)new)[-1] = ((size_t *)mem)[-1] - (new-mem);
40                 return new;
41         }
42
43         end = mem + (header & -8);
44         footer = ((size_t *)end)[-2];
45
46         ((size_t *)mem)[-1] = header&7 | new-mem;
47         ((size_t *)new)[-2] = footer&7 | new-mem;
48         ((size_t *)new)[-1] = header&7 | end-new;
49         ((size_t *)end)[-2] = footer&7 | end-new;
50
51         if (new != mem) free(mem);
52         return new;
53 }
54
55 weak_alias(__memalign, memalign);