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