summaryrefslogtreecommitdiff
path: root/src/libc/unistd/unistd.c
blob: 99899ce7a52cf7180a3e1ef2e51f00413880d99a (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
#include <bits/panic.h>
#include <camellia.h>
#include <camellia/syscalls.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <elfload.h>

int unlink(const char *path) {
	hid_t h = camellia_open(path, OPEN_WRITE);
	if (h < 0) return errno = -h, -1;
	long ret = _sys_remove(h);
	if (ret < 0) return errno = -ret, -1;
	return 0;
}

int rmdir(const char *path) {
	(void)path;
	__libc_panic("unimplemented");
}

int execv(const char *path, char *const argv[]) {
	return execve(path, argv, NULL);
}

int execvp(const char *path, char *const argv[]) {
	// TODO execvp
	return execve(path, argv, NULL);
}

int execvpe(const char *path, char *const argv[], char *const envp[]) {
	if (path[0] != '/') {
		char *exp = malloc(strlen(path) + 6);
		int ret;
		strcpy(exp, "/bin/");
		strcat(exp, path);
		ret = execve(exp, argv, envp);
		free(exp);
		return ret;
	}
	return execve(path, argv, envp);
}

int execve(const char *path, char *const argv[], char *const envp[]) {
	FILE *file = fopen(path, "e");
	char hdr[4] = {0};
	if (!file) {
		return errno = ENOENT, -1;
	}

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

	if (!memcmp("\x7f""ELF", hdr, 4)) {
		elf_execf(file, (void*)argv, (void*)envp);
		fclose(file);
		errno = EINVAL;
	} 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};
			char *endl = strchr(buf, '\n');
			if (endl) *endl = '\0';
			execve(buf, (void*)argv, envp);
		}
	} else {
		errno = EINVAL;
	}

	return -1;
}

pid_t getpgrp(void) {
	__libc_panic("unimplemented");
}

int getgroups(int size, gid_t list[]) {
	(void)size; (void)list;
	__libc_panic("unimplemented");
}

int dup(int oldfd) {
	return _sys_dup(oldfd, -1, 0);
}