minimalc/arch/x86_64.c

92 lines
1.8 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 %5, %%r10\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;
}
#define SYS_CLOSE 3
int close(unsigned int fd) {
int rtn;
asm volatile(
"syscall"
: "=a"(rtn)
: "a"(SYS_CLOSE), "D"(fd)
: "rcx", "r11"
);
return rtn;
}
#define SYS_FSYNC 74
int fsync(unsigned int fd) {
int rtn;
asm volatile(
"syscall"
: "=a"(rtn)
: "a"(SYS_FSYNC), "D"(fd)
: "rcx", "r11"
);
return rtn;
}
#endif /* ifdef __x86_64__ */