blob: fa6336f5ef0dc3c36fc717637ac691be928b2ad7 [file] [log] [blame]
swissChili8cfb7c42021-04-18 21:17:58 -07001#include "plat.h"
swissChilib51552c2021-08-03 10:23:37 -07002#include <stdio.h>
swissChili8cfb7c42021-04-18 21:17:58 -07003#include <stdlib.h>
4#include <string.h>
swissChilif3e7f182021-04-20 13:57:22 -07005#include <sys/mman.h>
swissChilif68671f2021-07-05 14:14:44 -07006#include <unistd.h>
swissChili4691cf62021-08-05 21:34:57 -07007#ifndef NO_READLINE
swissChili7e1393c2021-07-07 12:59:12 -07008#include <readline/readline.h>
9#include <readline/history.h>
swissChili4691cf62021-08-05 21:34:57 -070010#endif
swissChili8cfb7c42021-04-18 21:17:58 -070011
swissChili53472e82021-05-08 16:06:32 -070012void *malloc_aligned(size_t size)
swissChili8cfb7c42021-04-18 21:17:58 -070013{
swissChili708d4c42021-07-04 17:40:07 -070014 // https://www.gnu.org/software/libc/manual/html_node/Aligned-Memory-Blocks.html
15 // On glibc malloc() and realloc() return 8-byte aligned addresses.
16 return malloc(size);
swissChili8cfb7c42021-04-18 21:17:58 -070017}
18
swissChili53472e82021-05-08 16:06:32 -070019void *realloc_aligned(void *addr, size_t size)
swissChili8cfb7c42021-04-18 21:17:58 -070020{
swissChili708d4c42021-07-04 17:40:07 -070021 return realloc(addr, size);
swissChili8cfb7c42021-04-18 21:17:58 -070022}
23
swissChili53472e82021-05-08 16:06:32 -070024void free_aligned(void *addr)
swissChili8cfb7c42021-04-18 21:17:58 -070025{
swissChili708d4c42021-07-04 17:40:07 -070026 free(addr);
swissChili8cfb7c42021-04-18 21:17:58 -070027}
swissChilif3e7f182021-04-20 13:57:22 -070028
swissChilif68671f2021-07-05 14:14:44 -070029void *link_program(dasm_State **Dst)
swissChilif3e7f182021-04-20 13:57:22 -070030{
31 size_t size;
32 void *buf;
33
swissChili53472e82021-05-08 16:06:32 -070034 dasm_link(Dst, &size);
35 buf = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1,
36 0);
37 dasm_encode(Dst, buf);
swissChilif3e7f182021-04-20 13:57:22 -070038
swissChili53472e82021-05-08 16:06:32 -070039 mprotect(buf, size, PROT_READ | PROT_EXEC);
swissChilif3e7f182021-04-20 13:57:22 -070040 return buf;
41}
swissChilif68671f2021-07-05 14:14:44 -070042
43bool file_exists(const char *path)
44{
45 return access(path, F_OK) == 0;
46}
swissChili7e1393c2021-07-07 12:59:12 -070047
48char *read_input_line(char *prompt)
49{
swissChili4691cf62021-08-05 21:34:57 -070050#ifndef NO_READLINE
swissChili7e1393c2021-07-07 12:59:12 -070051 return readline(prompt);
swissChili4691cf62021-08-05 21:34:57 -070052#else
53 return "";
54#endif
swissChili7e1393c2021-07-07 12:59:12 -070055}
56
57void add_line_to_history(char *line)
58{
swissChili4691cf62021-08-05 21:34:57 -070059#ifndef NO_READLINE
swissChili7e1393c2021-07-07 12:59:12 -070060 add_history(line);
swissChili4691cf62021-08-05 21:34:57 -070061#endif
swissChili7e1393c2021-07-07 12:59:12 -070062}