59 lines
1.7 KiB
Nim
59 lines
1.7 KiB
Nim
# MARKUS MAIWALD (ARCHITECT) | VOXIS FORGE (AI)
|
|
# Rumpk Phase 8: The Summoning (ELF Loader)
|
|
|
|
import fs/tar, loader/elf
|
|
|
|
proc kprint(s: cstring) {.importc, cdecl.}
|
|
proc kprintln(s: cstring) {.importc, cdecl.}
|
|
|
|
# Assembly trampoline to jump to userland
|
|
proc rumpk_enter_userland*(entry: uint64) {.importc, cdecl.}
|
|
|
|
proc kload*(path: string): uint64 =
|
|
# 1. Read ELF File from VFS
|
|
let file_content = vfs_read_file(path)
|
|
if file_content.len == 0:
|
|
kprint("[Loader] Error: File not found or empty: '")
|
|
kprint(cstring(path))
|
|
kprintln("'")
|
|
return 0
|
|
|
|
# 2. Verify ELF Header
|
|
let ehdr = cast[ptr Elf64_Ehdr](unsafeAddr file_content[0])
|
|
|
|
if ehdr.e_ident[0] != 0x7F or ehdr.e_ident[1] != 'E'.uint8 or
|
|
ehdr.e_ident[2] != 'L'.uint8 or ehdr.e_ident[3] != 'F'.uint8:
|
|
kprintln("[Loader] Error: Invalid ELF magic.")
|
|
return 0
|
|
|
|
if ehdr.e_machine != 243: # EM_RISCV
|
|
kprintln("[Loader] Error: Binary is not for RISC-V.")
|
|
return 0
|
|
|
|
# 3. Parse Program Headers
|
|
let base_ptr = cast[uint64](unsafeAddr file_content[0])
|
|
|
|
for i in 0 ..< int(ehdr.e_phnum):
|
|
let phdr_offset = ehdr.e_phoff + uint64(i * int(ehdr.e_phentsize))
|
|
let phdr = cast[ptr Elf64_Phdr](base_ptr + phdr_offset)
|
|
|
|
if phdr.p_type == PT_LOAD:
|
|
let dest = cast[ptr UncheckedArray[byte]](phdr.p_vaddr)
|
|
let src = cast[ptr UncheckedArray[byte]](base_ptr + phdr.p_offset)
|
|
|
|
# Clear BSS (memsz > filesz)
|
|
if phdr.p_memsz > 0:
|
|
zeroMem(dest, phdr.p_memsz)
|
|
|
|
# Copy Data
|
|
if phdr.p_filesz > 0:
|
|
copyMem(dest, src, phdr.p_filesz)
|
|
|
|
return ehdr.e_entry
|
|
|
|
proc kexec*(path: string) =
|
|
let entry = kload(path)
|
|
if entry != 0:
|
|
kprintln("[Loader] Transferring Consciousness...")
|
|
rumpk_enter_userland(entry)
|