aboutsummaryrefslogtreecommitdiff
path: root/kernel/features/load.c
blob: 65d76d4c942b46ca7262ce14579443dfa5cbf4a7 (plain) (blame)
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
// MIT License, Copyright (c) 2020 Marvin Borner

#include <errno.h>
#include <fs.h>
#include <load.h>
#include <mem.h>
#include <mm.h>
#include <str.h>

#include <print.h>

#define PROC_STACK_SIZE 0x4000

s32 bin_load(const char *path, struct proc *proc)
{
	if (!path || !memory_valid(path) || !proc)
		return -EFAULT;

	struct stat s = { 0 };
	memory_bypass_enable();
	s32 stat = vfs_stat(path, &s);
	memory_bypass_disable();
	if (stat != 0)
		return stat;

	strcpy(proc->name, path);

	struct page_dir *prev;
	memory_backup_dir(&prev);
	memory_switch_dir(proc->page_dir);

	u32 size = PAGE_ALIGN_UP(s.size);
	u32 data = (u32)memory_alloc(proc->page_dir, size, MEMORY_USER | MEMORY_CLEAR);

	memory_bypass_enable();
	s32 read = vfs_read(proc->name, (void *)data, 0, s.size);
	memory_bypass_disable();
	if (read <= 0) {
		memory_switch_dir(prev);
		return read;
	}

	u32 stack = (u32)memory_alloc(proc->page_dir, PROC_STACK_SIZE, MEMORY_USER | MEMORY_CLEAR);
	proc->regs.ebp = stack;
	proc->regs.useresp = stack;
	proc->regs.eip = data;
	proc->entry = data;

	memory_switch_dir(prev);
	return 0;
}