summaryrefslogtreecommitdiff
path: root/src/kernel/linker/elf.cpp
blob: 6c45f10080f2470bddc3effdfedf4fcfc79e2b57 (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
52
53
54
55
56
57
#include "elf.h"
#include <mem/paging.h>
#include <mem/seg.h>
#include <lib/std.h>
#include <core/sys.h>

int elf_check(uint8_t *data) {
	elf_ehdr *h = (elf_ehdr*)data;
	if (h->e_ident[0] == 0x7F && h->e_ident[1] == 'E' && h->e_ident[2] == 'L' && h->e_ident[3] == 'F') return 0;
	return -1;
}

thread_entry elf_load(uint8_t *data, process* process) {
	elf_ehdr *ehdr = (elf_ehdr*)data;
	elf_phdr *phdr;
	int i;
	size_t dataseg = 0;
	if (elf_check(data)) return 0;

	cli();
	page_directory *r = current_pagedir;
	pagedir_switch(process->pagedir);

	phdr = (elf_phdr*)((uint8_t*)(data + ehdr->e_phoff));
	for (i = 0; i < ehdr->e_phnum; i++) {
		if (phdr[i].p_type == PT_LOAD) {
			(new simpleseg(phdr[i].p_vaddr, phdr[i].p_memsz, (phdr[i].p_flags & PF_W) != 0))->map(process->pagedir, 0);
			memcpy((uint8_t*)phdr[i].p_vaddr, data + phdr[i].p_offset, phdr[i].p_filesz);
			if (phdr[i].p_memsz > phdr[i].p_filesz) {
				memset((uint8_t*)((size_t)phdr[i].p_vaddr + phdr[i].p_filesz), 0, phdr[i].p_memsz - phdr[i].p_filesz);
			}
			if (phdr[i].p_vaddr + phdr[i].p_memsz > dataseg) {
				dataseg = phdr[i].p_vaddr + phdr[i].p_memsz;
				dataseg = (dataseg & 0xFFFFF000) + 0x1000;
			}
		}
	}

	process->data = dataseg;

	pagedir_switch(r);
	sti();

	return (thread_entry)ehdr->e_entry;
}

process* elf_exec(uint8_t *data, int privilege, char** args) {
	if (elf_check(data) != 0) return 0;
	
	process* p = new process(0, 0, privilege);

	thread_entry e = elf_load(data, p);

	new thread(p, e, p->set_args(args), 0);

	return p;
}