summaryrefslogtreecommitdiff
path: root/src/user/lib/stdlib.c
blob: 11ca7b656628c858c595c93b118df29d6d60c604 (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
#include <camellia/syscalls.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <user/lib/elfload.h>

int errno = 0;

int fork(void) {
	return _syscall_fork(0, NULL);
}

int close(handle_t h) {
	return _syscall_close(h);
}

_Noreturn void exit(int c) {
	_syscall_exit(c);
}

int execv(const char *path, char *const argv[]) {
	FILE *file = fopen(path, "r");
	char hdr[4] = {0};
	if (!file)
		return -1;

	fread(hdr, 1, 4, file);
	fseek(file, 0, SEEK_SET);

	if (!memcmp("\x7f""ELF", hdr, 4)) {
		elf_execf(file, (void*)argv, NULL);
		fclose(file);
	} else if (!memcmp("#!", hdr, 2)) {
		char buf[256];
		fseek(file, 2, SEEK_SET);
		if (fgets(buf, sizeof buf, file)) {
			const char *argv [] = {buf, path, NULL};
			// TODO strchr
			char *s = buf;
			while (*s && *s != '\n') s++;
			*s = '\0';
			execv(argv[0], (void*)argv);
		}
	}

	errno = EINVAL;
	return -1;
}