summaryrefslogtreecommitdiff
path: root/src/user_bootstrap/main.c
blob: 8fed3cee8a2070132e51473af5b8477b0cfd3ee7 (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
#include <shared/flags.h>
#include <shared/mem.h>
#include <shared/syscalls.h>
#include <user/lib/elfload.h>

extern char _bss_start;
extern char _bss_end;
extern char _initrd;

static void *tar_find(void *tar, const char *path);
static int oct_parse(char *str, size_t len);

static void *tar_find(void *tar, const char *path) {
	size_t path_len = strlen(path);
	int size;
	if (path_len > 100) return NULL;

	for (size_t off = 0;;) {
		if (0 != memcmp(tar + off + 257, "ustar", 5))
			return NULL; // not a metadata sector, end of archive

		_klogf("%s", tar + off);
		size = oct_parse(tar + off + 124, 11);
		if (0 == memcmp(tar + off, path, path_len) &&
				*(char*)(tar + off + path_len) == '\0')
		{
			return tar + off + 512;
		}
		off += 512;
		off += (size + 511) & ~511;
	}
}

static int oct_parse(char *str, size_t len) {
	int res = 0;
	for (size_t i = 0; i < len; i++) {
		res *= 8;
		res += str[i] - '0'; // no format checking
	}
	return res;
}


__attribute__((section(".text.startup")))
int main(void) {
	_syscall_memflag(&_bss_start, &_bss_end - &_bss_start, MEMFLAG_PRESENT);

	void *init = tar_find(&_initrd, "init.elf");
	if (!init) {
		_klogf("couldn't find init.elf\n");
		_syscall_exit(0);
	}
	void (*entry)(void*) = elf_partialexec(init);
	if (entry) {
		// TODO dynamically link initrd
		entry(&_initrd);
	} else {
		_klogf("couldn't execute init.elf\n");
	}
	_syscall_exit(0);
}