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 | f68671f | 2021-07-05 14:14:44 -0700 | [diff] [blame] | 5 | #include <unistd.h> |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 6 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 7 | void *malloc_aligned(size_t size) |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 8 | { |
swissChili | 708d4c4 | 2021-07-04 17:40:07 -0700 | [diff] [blame] | 9 | // https://www.gnu.org/software/libc/manual/html_node/Aligned-Memory-Blocks.html |
| 10 | // On glibc malloc() and realloc() return 8-byte aligned addresses. |
| 11 | return malloc(size); |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 12 | } |
| 13 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 14 | void *realloc_aligned(void *addr, size_t size) |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 15 | { |
swissChili | 708d4c4 | 2021-07-04 17:40:07 -0700 | [diff] [blame] | 16 | return realloc(addr, size); |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 17 | } |
| 18 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 19 | void free_aligned(void *addr) |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 20 | { |
swissChili | 708d4c4 | 2021-07-04 17:40:07 -0700 | [diff] [blame] | 21 | free(addr); |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 22 | } |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 23 | |
swissChili | f68671f | 2021-07-05 14:14:44 -0700 | [diff] [blame] | 24 | void *link_program(dasm_State **Dst) |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 25 | { |
| 26 | size_t size; |
| 27 | void *buf; |
| 28 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 29 | dasm_link(Dst, &size); |
| 30 | buf = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, |
| 31 | 0); |
| 32 | dasm_encode(Dst, buf); |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 33 | |
swissChili | 53472e8 | 2021-05-08 16:06:32 -0700 | [diff] [blame] | 34 | mprotect(buf, size, PROT_READ | PROT_EXEC); |
swissChili | f3e7f18 | 2021-04-20 13:57:22 -0700 | [diff] [blame] | 35 | return buf; |
| 36 | } |
swissChili | f68671f | 2021-07-05 14:14:44 -0700 | [diff] [blame] | 37 | |
| 38 | bool file_exists(const char *path) |
| 39 | { |
| 40 | return access(path, F_OK) == 0; |
| 41 | } |