load: add basic elf loading

This commit is contained in:
Michael Shaw 2023-11-16 23:22:27 -05:00
commit d60da85470
10 changed files with 193 additions and 127 deletions

View file

@ -3,6 +3,7 @@
#include <kernel/elf.h>
#include <kernel/slab.h>
#include <kernel/proc.h>
#include <kernel/gdt.h>
#include <fs/vfs.h>
#include <string.h>
@ -35,30 +36,74 @@ int elf_check_compat(char *buf)
return 0;
}
pid_t elf_load_proc(const char *proc_path)
pid_t elf_load_proc(char *fname)
{
int fd = open(proc_path, O_RDONLY);
int fd = open(fname, O_RDONLY);
if (fd < 0)
return fd;
char *buf = kmalloc(4096, ALLOC_KERN);
seek(fd, 0, SEEK_END);
size_t size = tell(fd);
seek(fd, 0, SEEK_SET);
char *buf = kmalloc(size, ALLOC_KERN);
if (!buf)
return -ENOMEM;
int ret = read(fd, buf, 4096);
read(fd, buf, size);
close(fd);
if (ret < 0)
return ret;
int ret;
ret = elf_check_compat(buf);
if (ret < 0) {
if ((ret = elf_check_compat(buf))) {
kfree(buf);
close(fd);
return ret;
}
close(fd);
struct elf64_header *hdr = (struct elf64_header *)buf;
return 0;
/* read data and text segments */
struct proc *proc = proc_create();
/* allocate page tables */
proc->cr3 = (uintptr_t)buddy_alloc(0x1000) & (~hhdm_start);
struct elf64_program_header *phdr = (struct elf64_program_header *)(buf + hdr->e_phoff);
for (int i = 0; i < hdr->e_phnum; i++) {
if (phdr[i].p_type == PT_LOAD) {
/* allocate memory for segment */
size_t psize = MAX(0x1000, npow2(phdr[i].p_memsz));
uintptr_t prog_buf = (uintptr_t)buddy_alloc(psize);
void *addr = proc_mmap(proc, prog_buf & (~hhdm_start), phdr[i].p_vaddr, psize, PAGE_RW | PAGE_PRESENT);
if (!addr) {
kfree(buf);
return -ENOMEM;
}
/* copy data from file to memory */
memcpy((void *)prog_buf, buf + phdr[i].p_offset, phdr[i].p_filesz);
/* zero out remaining memory */
memset((void *)prog_buf + phdr[i].p_filesz, 0, phdr[i].p_memsz - phdr[i].p_filesz);
}
}
/* set entry point */
proc->regs.rip = hdr->e_entry;
proc->regs.rflags = 0x202; /* interrupts enabled, IOPL = 0 */
/* descriptor #7 is the user code segment */
proc->regs.cs = 7 * sizeof(struct gdt_desc) | 0x3;
proc->regs.ss = 8 * sizeof(struct gdt_desc) | 0x3;
/* allocate user stack */
uintptr_t stack_buf = (uintptr_t)buddy_alloc(0x1000);
uintptr_t u_stack_addr = 0x202020202000;
(void)proc_mmap(proc, stack_buf & (~hhdm_start), u_stack_addr, 0x1000, PAGE_RW | PAGE_PRESENT);
/* set stack pointer */
proc->regs.rsp = u_stack_addr + 0x1000;
kfree(buf);
return proc->pid;
}

View file

@ -47,6 +47,29 @@ void schedule()
}
}
struct proc *proc_create()
{
struct proc *proc = kzalloc(sizeof(struct proc), ALLOC_KERN);
proc->pid = rbt_next_key(proc_tree);
proc->is_kernel = false;
struct rbnode *proc_node = rbt_insert(proc_tree, proc->pid);
proc_node->value = (uintptr_t)proc;
return proc;
}
struct proc *proc_get(pid_t pid)
{
struct rbnode *proc_node = rbt_search(proc_tree, pid);
if (proc_node)
return (void *)proc_node->value;
else
return NULL;
}
void proc_init(unsigned num_cpus)
{
/* allocate current process structs */