minimalc/arch/x86_64.c

68 lines
1.5 KiB
C

#if defined(__x86_64__)
#include "../int.h"
#define SYS_EXIT 60
void exit(int8_t status) {
asm volatile(
"syscall"
:
: "a"(SYS_EXIT), "D"(status)
:
);
for(;;);
}
#define SYS_WRITE 1
intptr_t write(int32_t fd, const void* buf, intptr_t size) {
intptr_t n_written = 0;
asm volatile (
"syscall\n"
"movq %0, %%rax\n"
: "=r"(n_written)
: "a"(SYS_WRITE), "D"(fd), "S"(buf), "d"(size) // RDI, RSI, RDX are used in x86-64 for write args
: "rcx", "r11"
);
return n_written;
}
#define SYS_READ 0
intptr_t read(int32_t fd, const void* buf, intptr_t size) {
intptr_t n_read = 0;
asm volatile (
"syscall\n"
"movq %0, %%rax\n"
: "=r"(n_read)
: "a"(SYS_READ), "D"(fd), "S"(buf), "d"(size) // RDI, RSI, RDX are used in x86-64 for write args
: "rcx", "r11", "memory"
);
return n_read;
}
#define SYS_FORK 57
uint32_t fork() {
uint64_t rtn;
asm volatile(
"syscall\n" // syscall
"movq %0, %%rax\n" // save return value
: "=r"(rtn)
: "a"(SYS_FORK)
:
);
return (uint32_t)rtn;
}
#define SYS_OPENAT 257
int32_t openat(int32_t fd, const char* filename, uint32_t flags, uint32_t mode) {
int32_t file;
asm volatile (
"mov %%r10, %5\n"
"syscall\n"
: "=a"(file)
: "a"(SYS_OPENAT), "D"(fd), "S"(filename), "d"(flags), "r"((uint64_t)mode) // RDI, RSI, RDX are used in x86-64 for write args
: "rcx", "r10", "r11"
);
return file;
}
#endif /* ifdef __x86_64__ */