Files
SUB-OS/kernel/elf.c
T
subhobhai943andClaude Opus 5 ecdc5be435 feat(exec): Run userland in ring 3 with an ELF64 loader and per-process page tables
SUB-OS had a syscall table and user GDT descriptors but nothing that could
actually leave ring 0: lazybox and the shell run as kernel code, and
syscall_handler() was never reachable from a user program. This adds the
missing path end to end on x86_64.

Address spaces (arch/x86_64/mm/vmspace.c)
- The boot page tables identity-map the low 4 GB off PML4[0] and leave the
  rest empty, so userland is given its own PML4 slot (512 GiB) rather than
  holes punched in the kernel's 2 MB huge-page map. A process PML4 shares
  entry 0 with the kernel and privately owns entry 1.
- Frames outside the identity map are refused rather than written through an
  unmapped pointer; lifting that needs a recursive map or a higher-half
  direct map, which is noted in the file.

ELF loader (kernel/elf.c)
- Validates ELF64/little-endian/ET_EXEC/machine, bounds-checks every program
  header against both the image and the user address range, and lays PT_LOAD
  segments into an address space. Frames arrive zeroed, so .bss is covered.

Ring transition (arch/x86_64/cpu/usermode.asm)
- user_enter() drops to ring 3 via iretq after scrubbing every GPR, and
  user_return() unwinds back to it when the process exits, so exec looks like
  a call that blocks until the program finishes.

Syscalls
- INT 0x80 installed at DPL 3 with the Linux x86_64 register convention.
  The process gets its own kernel stack for the trap, because TSS.rsp0 must
  not point at the stack user_enter() is standing on.
- Every user pointer is range-checked before use. The process page tables are
  still live during a syscall, so without that check a program could pass a
  kernel address and have write(2) dump kernel text to the console. The new
  /sbin/init asserts both a wild pointer and a kernel pointer are rejected.
- write(2) to stdout/stderr routes through the new console_write(), which
  reuses printk's routing so output reaches serial and the framebuffer
  console rather than only the VGA text buffer.

Faults
- A ring 3 exception now kills that process and reports CR2 instead of
  panicking the machine.

Userland (userland/init/)
- /sbin/init is a real freestanding static executable, linked at the user
  base and embedded in the kernel image by scripts/mkblob.py. It reports its
  pid, verifies .bss was zeroed and .data is writable, checks the two pointer
  rejections, and exits.

aarch64 and armv8i keep building: the loader and exec path are portable, and
those ports get honest vmspace stubs that fail cleanly rather than pretending
to run a program with kernel privileges.

Verified under QEMU: init loads at 0x80004000a0, reports pid 1, .bss zeroed,
.data writable, both bad pointers rejected, and exits 0 back into the shell.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0161Jh7uCEMLYEMNPsjC1LKf
2026-08-25 06:37:20 +00:00

117 lines
4.2 KiB
C

#include <kernel/elf.h>
#include <kernel/printk.h>
#include <lib/string.h>
#include <mm/vmspace.h>
#if defined(__x86_64__)
#define ELF_NATIVE_MACHINE EM_X86_64
#elif defined(__aarch64__)
#define ELF_NATIVE_MACHINE EM_AARCH64
#else
#define ELF_NATIVE_MACHINE EM_ARM
#endif
static const char* const elf_errors[] = {
[0] = "ok",
[-ELF_ETRUNCATED] = "image is truncated",
[-ELF_EMAGIC] = "not an ELF object",
[-ELF_ECLASS] = "not a little-endian ELF64 object",
[-ELF_ETYPE] = "not a static executable",
[-ELF_EMACHINE] = "built for a different architecture",
[-ELF_ERANGE] = "segment falls outside the user address range",
[-ELF_ENOMEM] = "out of memory",
[-ELF_ENOENTRY] = "entry point is not inside a loadable segment",
};
const char* elf_strerror(int err) {
unsigned idx = (unsigned)(-err);
if (err > 0 || idx >= sizeof(elf_errors) / sizeof(elf_errors[0]) || !elf_errors[idx]) {
return "unknown error";
}
return elf_errors[idx];
}
static int elf_prot_of(Elf64_Word p_flags) {
int prot = VM_PROT_USER;
if (p_flags & PF_R) prot |= VM_PROT_READ;
if (p_flags & PF_W) prot |= VM_PROT_WRITE;
if (p_flags & PF_X) prot |= VM_PROT_EXEC;
return prot;
}
static int elf_check_header(const Elf64_Ehdr* eh, size_t len) {
if (len < sizeof(Elf64_Ehdr)) return ELF_ETRUNCATED;
if (eh->e_ident[0] != 0x7F || eh->e_ident[1] != 'E' ||
eh->e_ident[2] != 'L' || eh->e_ident[3] != 'F') {
return ELF_EMAGIC;
}
if (eh->e_ident[EI_CLASS] != ELFCLASS64 ||
eh->e_ident[EI_DATA] != ELFDATA2LSB) {
return ELF_ECLASS;
}
/* Only static executables: a PT_INTERP image would need a loader we have
* no business running this early. */
if (eh->e_type != ET_EXEC) return ELF_ETYPE;
if (eh->e_machine != ELF_NATIVE_MACHINE) return ELF_EMACHINE;
if (eh->e_phnum == 0 || eh->e_phentsize != sizeof(Elf64_Phdr)) return ELF_ETRUNCATED;
/* The program header table itself has to be inside the image. */
uint64_t ph_bytes = (uint64_t)eh->e_phnum * eh->e_phentsize;
if (eh->e_phoff > len || ph_bytes > len - eh->e_phoff) return ELF_ETRUNCATED;
return ELF_OK;
}
int elf_load(vmspace_t* vm, const void* image, size_t len,
uint64_t* entry_out, uint64_t* brk_out) {
if (!vm || !image) return ELF_EMAGIC;
const Elf64_Ehdr* eh = (const Elf64_Ehdr*)image;
int err = elf_check_header(eh, len);
if (err != ELF_OK) return err;
const Elf64_Phdr* ph = (const Elf64_Phdr*)((const uint8_t*)image + eh->e_phoff);
uint64_t brk = 0;
bool entry_mapped = false;
for (Elf64_Half i = 0; i < eh->e_phnum; i++) {
const Elf64_Phdr* p = &ph[i];
if (p->p_type != PT_LOAD || p->p_memsz == 0) continue;
/* A segment may declare more memory than it stores (.bss), but never
* less, and its file image must lie inside the blob we were handed. */
if (p->p_filesz > p->p_memsz) return ELF_ETRUNCATED;
if (p->p_offset > len || p->p_filesz > len - p->p_offset) return ELF_ETRUNCATED;
/* Keep every mapping inside the slot reserved for userland, and reject
* a length that would wrap past the top of the address space. */
if (p->p_vaddr < USER_BASE) return ELF_ERANGE;
if (p->p_memsz > USER_LIMIT - p->p_vaddr) return ELF_ERANGE;
err = vmspace_alloc(vm, p->p_vaddr, p->p_memsz, elf_prot_of(p->p_flags));
if (err != 0) return ELF_ENOMEM;
if (p->p_filesz) {
err = vmspace_write(vm, p->p_vaddr,
(const uint8_t*)image + p->p_offset, p->p_filesz);
if (err != 0) return ELF_ENOMEM;
}
/* vmspace_alloc hands back zeroed pages, so .bss needs no extra work. */
uint64_t seg_end = p->p_vaddr + p->p_memsz;
if (seg_end > brk) brk = seg_end;
if (eh->e_entry >= p->p_vaddr && eh->e_entry < seg_end) entry_mapped = true;
}
if (!brk) return ELF_ERANGE;
if (!entry_mapped) return ELF_ENOENTRY;
if (entry_out) *entry_out = eh->e_entry;
if (brk_out) {
*brk_out = (brk + VM_PAGE_SIZE - 1) & ~(VM_PAGE_SIZE - 1);
}
return ELF_OK;
}