summaryrefslogtreecommitdiff
path: root/service/lib/posix.c
blob: abc73bf02aebf75ae876ad94825bfd1ded894291 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <unistd.h>
#include <sys/mman.h>
#include <kjarna/syscall.h>
#include <stdnoreturn.h>

__attribute__((always_inline))
static inline int64_t syscall1(int syscall_index, uint64_t p1)
{
	int64_t result; 
	__asm__ ( 
		"movq %1, %%rax\n" 
		"movq %2, %%rdi\n" 
		"syscall\n" 
		: "=a"(result) 
		: "g"(syscall_index), "g"(p1)
		: "rdi"); 
	return result;
}

__attribute__((always_inline))
static inline int64_t syscall2(int syscall_index, uint64_t p1, uint64_t p2)
{
	int64_t result; 
	__asm__ ( 
		"movq %1, %%rax\n" 
		"movq %2, %%rdi\n" 
		"movq %3, %%rsi\n" 
		"syscall\n" 
		: "=a"(result) 
		: "g"(syscall_index), "g"(p1), "g"(p2)
		: "rdi", "rsi"); 
	return result;
}

__attribute__((always_inline))
static inline int64_t syscall3(int syscall_index, uint64_t p1, uint64_t p2, uint64_t p3)
{
	int64_t result; 
	__asm__ ( 
		"movq %1, %%rax\n" 
		"movq %2, %%rdi\n" 
		"movq %3, %%rsi\n" 
		"movq %4, %%rdx\n" 
		"syscall\n" 
		: "=a"(result) 
		: "g"(syscall_index), "g"(p1), "g"(p2), "g"(p3)
		: "rdi", "rsi","rdx"); 
	return result;
}

__attribute__((always_inline))
static inline int64_t syscall6(int syscall_index, uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4, uint64_t p5, uint64_t p6)
{
	int64_t result; 
	__asm__ ( 
		"movq %1, %%rax\n" 
		"movq %2, %%rdi\n" 
		"movq %3, %%rsi\n" 
		"movq %4, %%rdx\n" 
		"movq %5, %%r10\n" 
		"movq %6, %%r8\n" 
		"movq %7, %%r9\n" 
		"syscall\n" 
		: "=a"(result) 
		: "g"(syscall_index), "g"(p1), "g"(p2), "g"(p3), "g"(p4), "g"(p5), "g"(p6)
		: "rdi", "rsi","rdx", "r10", "r8", "r9"); 
	return result;
}

int open(const char *path, int flags, int mode)
{
	return (int)syscall3(SYS_OPEN, (uintptr_t)path, flags, mode);
}

int close(int fd)
{
	return (int)syscall1(SYS_CLOSE, fd);
}

off_t lseek(int fd, off_t offset, int whence)
{
	return syscall3(SYS_LSEEK, fd, offset, whence);
}

ssize_t read(int fd, void *buffer, size_t length)
{
	return syscall3(SYS_READ, fd, (uintptr_t)buffer, length);
}

ssize_t write(int fd, const void *buffer, size_t length)
{
	return syscall3(SYS_WRITE, fd, (uintptr_t)buffer, length);
}

void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
{
	return (void *)syscall6(SYS_MMAP, (uintptr_t)addr, length, prot, flags, fd, offset);
}

int munmap(void *addr, size_t length)
{
	return syscall2(SYS_MUNMAP, (uintptr_t)addr, length);
}

noreturn void _exit(int status)
{
	syscall1(SYS_EXIT, status);
	while(true);
}