swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 1 | #include "plat.h" |
| 2 | #include <stdlib.h> |
| 3 | #include <string.h> |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 4 | #include <sys/mman.h> |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 5 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 6 | void *malloc_aligned(size_t size) |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 7 | { |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 8 | void *mem = malloc(size + 8 + sizeof(void *) * 2); |
| 9 | void **aligned_ptr = (void **)((uintptr_t)(mem + 8 + sizeof(void *)) & ~7); |
| 10 | aligned_ptr[-1] = mem; |
| 11 | aligned_ptr[-2] = (void *)size; |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 12 | return aligned_ptr; |
| 13 | } |
| 14 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 15 | void *realloc_aligned(void *addr, size_t size) |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 16 | { |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 17 | void *mem = malloc(size + 8 + sizeof(void *) * 2); |
| 18 | void **aligned_ptr = (void **)((uintptr_t)(mem + 8 + sizeof(void *)) & ~7); |
| 19 | aligned_ptr[-1] = mem; |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 20 | |
swissChili | d289918 | 2021-07-02 13:30:41 -0700 | [diff] [blame^] | 21 | memcpy(aligned_ptr, addr, ((uintptr_t *)addr)[-2]); |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 22 | |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 23 | return aligned_ptr; |
| 24 | } |
| 25 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 26 | void free_aligned(void *addr) |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 27 | { |
| 28 | void **ptr = (void **)addr; |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 29 | free(ptr[-1]); |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 30 | } |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 31 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 32 | void *link(dasm_State **Dst) |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 33 | { |
| 34 | size_t size; |
| 35 | void *buf; |
| 36 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 37 | dasm_link(Dst, &size); |
| 38 | buf = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, |
| 39 | 0); |
| 40 | dasm_encode(Dst, buf); |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 41 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 42 | mprotect(buf, size, PROT_READ | PROT_EXEC); |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 43 | return buf; |
| 44 | } |