88 lines
2 KiB
C
88 lines
2 KiB
C
/* SPDX-License-Identifier: GPL-2.0-only */
|
|
#include <arch/page.h>
|
|
#include <kernel/common.h>
|
|
#include <kernel/slab.h>
|
|
#include <kernel/proc.h>
|
|
#include <kernel/slab.h>
|
|
#include <kernel/page.h>
|
|
#include <kernel/mem.h>
|
|
|
|
#include <lib/string.h>
|
|
|
|
#include "elf.h"
|
|
|
|
int elf_get_headers(const char *file, struct ehdr **out_ehdr, struct phdr **out_phdrs, uaddr_t *entry)
|
|
{
|
|
struct ehdr *ehdr = kalloc(sizeof(struct ehdr), ALLOC_KERN);
|
|
if (!ehdr)
|
|
return -ENOMEM;
|
|
|
|
struct phdr *phdrs = kalloc(ehdr->e_phnum * sizeof(struct phdr), ALLOC_KERN);
|
|
if (!phdrs) {
|
|
kfree(ehdr);
|
|
return -ENOMEM;
|
|
}
|
|
|
|
memcpy(ehdr, file, sizeof(struct ehdr));
|
|
|
|
static char elf_signature[4] = {0x7f, 'E', 'L', 'F'};
|
|
if (memcmp(elf_signature, ehdr->e_ident, 4) || ehdr->e_type != ET_EXEC) {
|
|
kfree(ehdr);
|
|
kfree(phdrs);
|
|
return -ENOEXEC;
|
|
}
|
|
|
|
memcpy(phdrs, file + ehdr->e_phoff, ehdr->e_phnum * sizeof(struct phdr));
|
|
|
|
*out_ehdr = ehdr;
|
|
*out_phdrs = phdrs;
|
|
*entry = ehdr->e_entry;
|
|
|
|
return ehdr->e_phnum;
|
|
}
|
|
|
|
ssize_t proc_load_file(const char *file, struct proc *proc)
|
|
{
|
|
struct ehdr *ehdr;
|
|
struct phdr *phdrs;
|
|
|
|
uaddr_t entry = 0;
|
|
int res = elf_get_headers(file, &ehdr, &phdrs, &entry);
|
|
|
|
if (res < 0)
|
|
return res;
|
|
|
|
proc->ehdr = ehdr;
|
|
proc->phdrs = phdrs;
|
|
proc->n_phdrs = res;
|
|
proc->entry = entry;
|
|
|
|
for (int i = 0; i < res; i++) {
|
|
struct phdr *cur = phdrs + i;
|
|
if (cur->p_type != PT_LOAD)
|
|
continue;
|
|
int flags = PAGE_USER;
|
|
if (!(cur->p_flags & PF_R))
|
|
continue;
|
|
if (cur->p_flags & PF_W)
|
|
flags |= PAGE_RW;
|
|
if (!(cur->p_flags & PF_X))
|
|
flags |= PAGE_XD;
|
|
|
|
vaddr_t page_vaddr = cur->p_vaddr & PAGE_MASK;
|
|
size_t vaddr_offset = cur->p_vaddr & (PAGE_SIZE - 1);
|
|
size_t map_size = ALIGN_UP(cur->p_memsz + vaddr_offset, PAGE_SIZE);
|
|
|
|
char *program = kalloc(map_size, ALLOC_USER);
|
|
|
|
if (!program)
|
|
return -ENOMEM;
|
|
|
|
memcpy(program + vaddr_offset, file + cur->p_offset, cur->p_filesz);
|
|
memset(program + vaddr_offset + cur->p_filesz, 0, cur->p_memsz - cur->p_filesz);
|
|
|
|
proc_mmap(proc, TO_PHYS(program), page_vaddr, map_size, flags);
|
|
}
|
|
|
|
return entry;
|
|
}
|