From 271d9a1feaa31eb921fc09ab38c43d18906bcbb5 Mon Sep 17 00:00:00 2001 From: Michael Shaw Date: Wed, 22 Nov 2023 20:15:24 -0500 Subject: [PATCH] elf: correctly load data segment --- include/kernel/elf.h | 4 ++++ sched/load.c | 18 ++++++++++++++---- usr.bin/test1/start.S | 7 ++++++- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/include/kernel/elf.h b/include/kernel/elf.h index c249619..e551bcb 100644 --- a/include/kernel/elf.h +++ b/include/kernel/elf.h @@ -61,6 +61,10 @@ #define SHN_ABS 0xFFF1 #define SHN_COMMON 0xFFF2 +#define PF_X 0x1 +#define PF_W 0x2 +#define PF_R 0x4 + #define ELF64_R_TYPE(i) ((i)&0xffffffff) #define ELF64_R_SYM(i) ((i) >> 32) diff --git a/sched/load.c b/sched/load.c index aeb8cc6..b541fd6 100644 --- a/sched/load.c +++ b/sched/load.c @@ -73,7 +73,6 @@ pid_t elf_load_proc(char *fname) proc->cr3 &= (~hhdm_start); - /* map text segment */ struct elf64_program_header *phdr = (struct elf64_program_header *)(buf + hdr->e_phoff); for (unsigned int i = 0; i < hdr->e_phnum; i++) { if (phdr[i].p_type != PT_LOAD) @@ -82,8 +81,19 @@ pid_t elf_load_proc(char *fname) uintptr_t vaddr = phdr[i].p_vaddr; size_t len = MAX(0x1000, npow2(phdr[i].p_filesz)); uintptr_t paddr = (uintptr_t)buddy_alloc(len); - (void)proc_mmap(proc, paddr & (~hhdm_start), vaddr, len, PAGE_RW | PAGE_PRESENT | PAGE_USER); - memcpy((void *)paddr, buf + phdr[i].p_offset, len); + + /* length to copy, not allocated length */ + len = phdr[i].p_filesz; + uint64_t flags = PAGE_PRESENT | PAGE_USER; + + if (phdr[i].p_flags & PF_W) + flags |= PAGE_RW; + + if (!(phdr[i].p_flags & PF_X)) + flags |= PAGE_XD; + + (void)proc_mmap(proc, paddr & (~hhdm_start), vaddr, len, flags); + memcpy((void *)paddr + (vaddr & 0xFFF), buf + phdr[i].p_offset, len); } /* set entry point */ @@ -98,7 +108,7 @@ pid_t elf_load_proc(char *fname) /* allocate user stack */ uintptr_t stack_buf = (uintptr_t)buddy_alloc(0x1000); uintptr_t u_stack_addr = 0x20002000; - (void)proc_mmap(proc, stack_buf & (~hhdm_start), u_stack_addr, 0x1000, PAGE_RW | PAGE_PRESENT | PAGE_USER); + (void)proc_mmap(proc, stack_buf & (~hhdm_start), u_stack_addr, 0x1000, PAGE_RW | PAGE_PRESENT | PAGE_USER | PAGE_XD); /* set stack pointer */ proc->regs.rsp = u_stack_addr + 0xFF0; diff --git a/usr.bin/test1/start.S b/usr.bin/test1/start.S index d919f3c..209dbc8 100644 --- a/usr.bin/test1/start.S +++ b/usr.bin/test1/start.S @@ -9,9 +9,14 @@ sys_exit = 60 .global _start _start: - movq $0x123456, %rdi + movq test_var, %rdi movq $sys_exit, %rax int $0x80 _no_exit: movq $0, %rbx jmp _no_exit + +.data +test_var: + .long 0xfeedbeef + .long 0xdeadbeef