blob: 27779507429940f7cb04604dacfb7014720ce07e [file] [log] [blame]
swissChili8cfb7c42021-04-18 21:17:58 -07001#include "plat.h"
2#include <stdlib.h>
3#include <string.h>
swissChilif3e7f182021-04-20 13:57:22 -07004#include <sys/mman.h>
swissChili8cfb7c42021-04-18 21:17:58 -07005
swissChili53472e82021-05-08 16:06:32 -07006void *malloc_aligned(size_t size)
swissChili8cfb7c42021-04-18 21:17:58 -07007{
swissChili53472e82021-05-08 16:06:32 -07008 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;
swissChili8cfb7c42021-04-18 21:17:58 -070012 return aligned_ptr;
13}
14
swissChili53472e82021-05-08 16:06:32 -070015void *realloc_aligned(void *addr, size_t size)
swissChili8cfb7c42021-04-18 21:17:58 -070016{
swissChili53472e82021-05-08 16:06:32 -070017 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;
swissChili8cfb7c42021-04-18 21:17:58 -070020
swissChilid2899182021-07-02 13:30:41 -070021 memcpy(aligned_ptr, addr, ((uintptr_t *)addr)[-2]);
swissChili53472e82021-05-08 16:06:32 -070022
swissChili8cfb7c42021-04-18 21:17:58 -070023 return aligned_ptr;
24}
25
swissChili53472e82021-05-08 16:06:32 -070026void free_aligned(void *addr)
swissChili8cfb7c42021-04-18 21:17:58 -070027{
28 void **ptr = (void **)addr;
swissChili53472e82021-05-08 16:06:32 -070029 free(ptr[-1]);
swissChili8cfb7c42021-04-18 21:17:58 -070030}
swissChilif3e7f182021-04-20 13:57:22 -070031
swissChili53472e82021-05-08 16:06:32 -070032void *link(dasm_State **Dst)
swissChilif3e7f182021-04-20 13:57:22 -070033{
34 size_t size;
35 void *buf;
36
swissChili53472e82021-05-08 16:06:32 -070037 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);
swissChilif3e7f182021-04-20 13:57:22 -070041
swissChili53472e82021-05-08 16:06:32 -070042 mprotect(buf, size, PROT_READ | PROT_EXEC);
swissChilif3e7f182021-04-20 13:57:22 -070043 return buf;
44}