From 0189cc9d771e5911b07fbf91ca18da3a338f8d30 Mon Sep 17 00:00:00 2001 From: Nathan Lee Date: Sat, 3 Oct 2026 21:37:57 -0500 Subject: add first userspace invocation --- website-emu/src/dev.js | 4 ++ website-emu/src/lib.rs | 95 ++++++++++++++++++++++++++++++--------- website-emu/src/state.rs | 13 +++++- website-initramfs/Makefile | 39 ++++++++++++++++ website-initramfs/progs/init.S | 4 ++ website-initramfs/sbin/init | Bin 0 -> 704 bytes website-kernel/arch/kernel.c | 33 ++++++++++++++ website-kernel/arch/mem.c | 15 ++++++- website-kernel/arch/start.S | 8 +++- website-kernel/fs/binfmt_elf.c | 12 ++--- website-kernel/fs/exec.S | 1 + website-kernel/fs/fs_cpio.c | 76 +++++++++++++++++++++++++++++++ website-kernel/include/fs/cpio.h | 24 ++++++++++ website-kernel/include/fs/elf.h | 1 + website-kernel/include/sys.h | 1 + website-src/index.html | 7 ++- website-src/initramfs.cpio | Bin 0 -> 1024 bytes 17 files changed, 301 insertions(+), 32 deletions(-) create mode 100644 website-initramfs/Makefile create mode 100644 website-initramfs/progs/init.S create mode 100755 website-initramfs/sbin/init create mode 100644 website-kernel/fs/fs_cpio.c create mode 100644 website-kernel/include/fs/cpio.h create mode 100644 website-src/initramfs.cpio diff --git a/website-emu/src/dev.js b/website-emu/src/dev.js index 4a22523..c4fe5fa 100644 --- a/website-emu/src/dev.js +++ b/website-emu/src/dev.js @@ -3,4 +3,8 @@ export function uart_push_line(line) { elem.classList.add("uart_line"); elem.textContent = line; document.body.appendChild(elem); +} + +export function log(line) { + console.log(line); } \ No newline at end of file diff --git a/website-emu/src/lib.rs b/website-emu/src/lib.rs index 9abffa0..b4d32e6 100644 --- a/website-emu/src/lib.rs +++ b/website-emu/src/lib.rs @@ -5,7 +5,8 @@ mod state; use wasm_bindgen::prelude::wasm_bindgen; use crate::core::*; use crate::mem::*; -use crate::state::CpuState; +use crate::state::{CpuState, Mode}; +use crate::state::Mode::USER; const REGISTER_NAME_WIDTH: u32 = 0b11111; @@ -19,6 +20,7 @@ const INITRD_LOAD: u32 = 0; #[wasm_bindgen(module = "/src/dev.js")] extern "C" { fn uart_push_line(line: &str); + fn log(line: &str); } #[repr(C)] @@ -142,10 +144,23 @@ pub fn boot(image: &[u8], initrd: &[u8], memory: &[u8]) { device_type: 1, // UART start: CONSOLE_LOAD, size: 1, + next: DRAM_LOAD + args_size + device_size * 2 + }; + let initramfs = Device { + device_type: 10, // DRAM, initrd + start: INITRD_LOAD, + size: initrd_size as u32, + next: DRAM_LOAD + args_size + device_size * 3 + }; + let kernel = Device { + device_type: 11, // DRAM, reserved + start: OS_LOAD, + size: os_size as u32, next: 0 }; + let args = BootArgs { - cmd_line: DRAM_LOAD + args_size + device_size * 2, + cmd_line: DRAM_LOAD + args_size + device_size * 4, devices: DRAM_LOAD + args_size }; @@ -167,6 +182,18 @@ pub fn boot(image: &[u8], initrd: &[u8], memory: &[u8]) { size_of::(), ) }; + let initramfs_bytes: &[u8] = unsafe { + std::slice::from_raw_parts( + &initramfs as *const Device as *const u8, + size_of::(), + ) + }; + let kernel_bytes: &[u8] = unsafe { + std::slice::from_raw_parts( + &kernel as *const Device as *const u8, + size_of::(), + ) + }; let cmd_line_bytes = cmd_line.as_bytes(); for i in 0..args_size { state.memory.write(DRAM_LOAD + i, args_bytes[i as usize]).unwrap(); @@ -174,9 +201,12 @@ pub fn boot(image: &[u8], initrd: &[u8], memory: &[u8]) { for i in 0..device_size { state.memory.write(DRAM_LOAD + args_size + i, dram_bytes[i as usize]).unwrap(); state.memory.write(DRAM_LOAD + args_size + device_size + i, uart_bytes[i as usize]).unwrap(); + state.memory.write(DRAM_LOAD + args_size + device_size * 2 + i, initramfs_bytes[i as usize]).unwrap(); + state.memory.write(DRAM_LOAD + args_size + device_size * 3 + i, kernel_bytes[i as usize]).unwrap(); + } for i in 0..cmd_line.len() as u32 { - state.memory.write(DRAM_LOAD + args_size + device_size * 2 + i, cmd_line_bytes[i as usize]).unwrap(); + state.memory.write(DRAM_LOAD + args_size + device_size * 4 + i, cmd_line_bytes[i as usize]).unwrap(); } state.pc = 0x80000000; @@ -223,7 +253,7 @@ fn handle_instruction(state: &mut CpuState) { 13 => divu(state, rd, rs1, rs2), 14 => rem(state, rd, rs1, rs2), 15 => remu(state, rd, rs1, rs2), - _ => panic!("Illegal instruction: {:x}", word), + _ => trap_ill(state), } } 0b0010011 => { @@ -240,13 +270,15 @@ fn handle_instruction(state: &mut CpuState) { 7 => andi(state, rd, rs1, imm), 1 => { if (imm >> 5) != 0 { - panic!("Illegal instruction: {:x}", word); + trap_ill(state); + return; } slli(state, rd, rs1, imm); } 5 => { if (imm >> 5) != 0 { - panic!("Illegal instruction: {:x}", word); + trap_ill(state); + return; } if (imm >> 5) & 0b1111111 == 0 { srli(state, rd, rs1, imm); @@ -256,7 +288,7 @@ fn handle_instruction(state: &mut CpuState) { } 2 => slti(state, rd, rs1, imm), 3 => sltiu(state, rd, rs1, imm), - _ => panic!("Illegal instruction: {:x}", word), + _ => trap_ill(state), } } 0b0000011 => { @@ -272,7 +304,7 @@ fn handle_instruction(state: &mut CpuState) { 2 => lw(state, rd, rs1, imm), 4 => lbu(state, rd, rs1, imm), 5 => lhu(state, rd, rs1, imm), - _ => panic!("Illegal instruction: {:x}", word), + _ => trap_ill(state) } } 0b0100011 => { @@ -288,7 +320,7 @@ fn handle_instruction(state: &mut CpuState) { 0 => sb(state, rs1, rs2, imm), 1 => sh(state, rs1, rs2, imm), 2 => sw(state, rs1, rs2, imm), - _ => panic!("Illegal instruction: {:x}", word), + _ => trap_ill(state) }; } 0b1100011 => { @@ -310,7 +342,7 @@ fn handle_instruction(state: &mut CpuState) { 5 => bge(state, rs1, rs2, imm), 6 => bltu(state, rs1, rs2, imm), 7 => bgeu(state, rs1, rs2, imm), - _ => panic!("Illegal instruction: {:x}", word), + _ => trap_ill(state) } return; } @@ -331,7 +363,8 @@ fn handle_instruction(state: &mut CpuState) { let sentinel = (word >> 12) & 0b111; if sentinel != 0 { - panic!("Illegal instruction: {:x}", word); + trap_ill(state); + return; } jalr(state, rd as usize, rs1 as usize, imm); @@ -356,13 +389,29 @@ fn handle_instruction(state: &mut CpuState) { match f3 { 0 => { match imm { - 0 => trap_to_kernel(state), // ecall - 258 => return_to_userspace(state), // sret + 0 => { + match state.mode { + Mode::MACHINE => {trap_ill(state); return;} + USER => { + trap_syscall(state); return;} + } + }, // ecall + 0x302 => { + let mpp = (state.csr[0x300 /* mstatus */] >> 11) & 0x3; + if mpp == 0 { + state.mode = USER; + } else { + state.mode = Mode::MACHINE; + } + + state.pc = state.csr[0x341 /* mepc */]; + return; + }, // mret 261 => { state.on = false; return; - } - _ => panic!("Illegal instruction: {:x}", word), + } // wfi + _ => trap_ill(state), } } // ecall 1 => csrrw(state, rd, rs1, imm as usize), @@ -372,20 +421,22 @@ fn handle_instruction(state: &mut CpuState) { 6 => csrrsi(state, rd, rs1 as u32, imm as usize), 7 => csrrci(state, rd, rs1 as u32, imm as usize), - _ => panic!("Illegal instruction: {:x}", word), + _ => trap_ill(state), } } // ecall (ebreak not implemented) - _ => panic!("Illegal instruction or todo: {:032b}", word), + _ => trap_ill(state), } state.pc += 4; } -fn trap_to_kernel(state: &mut CpuState) { - state.csr[0x341 /* mepc */] = state.pc; +fn trap_ill(state: &mut CpuState) { + log(format!("illegal intsruction: {:x}", state.memory.read_instruction(state.pc).expect(format!("pc {:x} does not map to valid memory", state.pc).as_str())).as_str()); state.pc = state.csr[0x305 /* mtvec */]; + state.csr[0x342 /* mcause */] = 2 /* synchronous, illegal instruction */; } -fn return_to_userspace(state: &mut CpuState) { - state.pc = state.csr[0x341 /* mepc */] + 4; -} +fn trap_syscall(state: &mut CpuState) { + state.pc = state.csr[0x305 /* mtvec */]; + state.csr[0x342 /* mcause */] = 8; +} \ No newline at end of file diff --git a/website-emu/src/state.rs b/website-emu/src/state.rs index 4b32713..62df0d0 100644 --- a/website-emu/src/state.rs +++ b/website-emu/src/state.rs @@ -1,11 +1,19 @@ use crate::mem::CpuMemory; +#[derive(Debug)] +pub enum Mode { + MACHINE, + USER +} + pub struct CpuState { pub memory: CpuMemory, pub registers: [u32; 32], pub csr: [u32; 4096], pub pc: u32, - pub on: bool + pub on: bool, + + pub mode: Mode } impl CpuState { @@ -15,7 +23,8 @@ impl CpuState { registers: [0u32; 32], csr: [0u32; 4096], pc: 0, - on: true + on: true, + mode: Mode::MACHINE, } } } diff --git a/website-initramfs/Makefile b/website-initramfs/Makefile new file mode 100644 index 0000000..57d303b --- /dev/null +++ b/website-initramfs/Makefile @@ -0,0 +1,39 @@ +CC = clang +LD = ld.lld +OBJCOPY = llvm-objcopy + +CFLAGS = \ + --target=riscv32-unknown-elf \ + -march=rv32im_zicsr \ + -mabi=ilp32 \ + -ffreestanding \ + -fno-builtin \ + -nostdlib \ + -nostdinc \ + -nodefaultlibs \ + -O2 -g3 \ + -Wall -Wextra -Werror -Wundef + +C_SRCS = $(shell find progs -type f -name "*.c") +S_SRCS = $(shell find progs -type f -name "*.S") +SRCS = $(C_SRCS) $(S_SRCS) +OBJS = $(basename $(SRCS)) + +$(V).SILENT: +progs: $(OBJS) + +%: %.c + @echo " CC $<" + $(CC) $(CFLAGS) $< -o $@ +%: %.S + @echo " AS $<" + $(CC) $(CFLAGS) -fuse-ld=lld $< -o $@ + +.PHONY: progs mkinitrd all clean +mkinitrd: + @echo " MKINITRD" + find . -print0 | cpio --null -ov -H newc > initramfs.cpio +clean: + @echo " CLEAN $(OBJS) initramfs.cpio" + $(RM) -f $(OBJS) initramfs.cpio +all: progs mkinitrd diff --git a/website-initramfs/progs/init.S b/website-initramfs/progs/init.S new file mode 100644 index 0000000..8693bda --- /dev/null +++ b/website-initramfs/progs/init.S @@ -0,0 +1,4 @@ +.global _start +.text +_start: + ecall diff --git a/website-initramfs/sbin/init b/website-initramfs/sbin/init new file mode 100755 index 0000000..335afd7 Binary files /dev/null and b/website-initramfs/sbin/init differ diff --git a/website-kernel/arch/kernel.c b/website-kernel/arch/kernel.c index 32d9dbd..8b8db6f 100644 --- a/website-kernel/arch/kernel.c +++ b/website-kernel/arch/kernel.c @@ -1,3 +1,5 @@ +#include "fs/cpio.h" +#include "fs/elf.h" #include #include #include @@ -6,6 +8,10 @@ #define DRAM_DEVICE 0 #define UART_DEVICE 1 +#define DRAM_RESERVED_INITRD 10 +#define DRAM_RESERVED_OTHER 11 + +extern void set_root(struct mempage_t *incoming_root); void serial_write(char value) { *(char *)SERIAL_PORT = value; @@ -22,6 +28,10 @@ void kernel_main(int hart, struct boot_args *args) { printk("BIOS provided device map:\n"); struct device *root = args->devices; + struct mempage_t *mem_root; + + void *initrd_base; + size_t initrd_size; while (root != NULL) { printk("....Device at 0x%x to 0x%x is ", @@ -31,18 +41,41 @@ void kernel_main(int hart, struct boot_args *args) { switch(root->device_type) { case DRAM_DEVICE: printk("generic DRAM device, usable\n"); + mem_root = (struct mempage_t *)root->start; + mem_root->next = NULL; + mem_root->size = root->size; break; case UART_DEVICE: printk("Web OS UART character device, not ns16550a compatible, MMIO device\n"); break; + case DRAM_RESERVED_INITRD: + + printk("generic DRAM device, not usable, reserved, initial ramdisk\n"); + initrd_base = (void *)root->start; + initrd_size = root->size; + break; + case DRAM_RESERVED_OTHER: + printk("generic DRAM device, not usable, reserved, other (likely kernel or firmware)\n"); + break; default: printk("unknown\n"); } root = root->next; } + + set_root(mem_root); + + printk("Using initramfs mounted at 0x%x, size %d\n", (uintptr_t)initrd_base, initrd_size); + printk("Skipping initramfs mount, invoking /sbin/init\n"); + void *file = cpio_get_file(initrd_base, initrd_size, "sbin/init"); + elf_exec(file); } void panic(char *cause) { printk("PANIC: %s\n", cause); } + +void handle_syscall() { + panic("syscall handler unimplemented"); +} diff --git a/website-kernel/arch/mem.c b/website-kernel/arch/mem.c index 301eb74..4b9a0b0 100644 --- a/website-kernel/arch/mem.c +++ b/website-kernel/arch/mem.c @@ -1,5 +1,6 @@ #include #include +#include static struct mempage_t *root; @@ -24,7 +25,6 @@ void set_root(struct mempage_t *incoming_root) { } void *kmalloc(size_t size) { - size = sizeof(size_t) + round_size(size, sizeof(struct mempage_t)); struct mempage_t *parent = NULL; struct mempage_t *node = root; @@ -92,3 +92,16 @@ void memzero(void *ptr, size_t size) { ((uint8_t *)ptr)[i] = 0; } } + +int memcmp(const void *s1, const void *s2, size_t n) { + const unsigned char *p1 = (const unsigned char *)s1; + const unsigned char *p2 = (const unsigned char *)s2; + + for (size_t i = 0; i < n; i++) { + if (p1[i] != p2[i]) { + return p1[i] - p2[i]; + } + } + + return 0; +} diff --git a/website-kernel/arch/start.S b/website-kernel/arch/start.S index 20ddeb1..b5c7a4b 100644 --- a/website-kernel/arch/start.S +++ b/website-kernel/arch/start.S @@ -2,12 +2,14 @@ .global _start .type _start, @function -.extern user_regs _start: csrw mstatus, zero csrw mie, zero + la t0, _syscall + csrw mtvec, t0 + la sp, __stack_top la t0, __data_load @@ -33,3 +35,7 @@ _start: call kernel_main wfi + +_syscall: + call handle_syscall + wfi diff --git a/website-kernel/fs/binfmt_elf.c b/website-kernel/fs/binfmt_elf.c index edf1781..f8073ae 100644 --- a/website-kernel/fs/binfmt_elf.c +++ b/website-kernel/fs/binfmt_elf.c @@ -1,5 +1,6 @@ #include #include +#include #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) @@ -34,10 +35,6 @@ int elf_chk_header(struct elf_header *header) { return 0; } - if (header->e_phoff != 0) { - return 0; // Not PIE - } - if (header->e_phentsize != sizeof(struct elf_program_header)) { return 0; } @@ -66,6 +63,7 @@ void elf_exec(void *executable) { struct elf_header *hdr = executable; if (!elf_chk_header(hdr)) { + printk("Magic bytes invalid, returning...\n"); return; } @@ -88,11 +86,15 @@ void elf_exec(void *executable) { continue; } - void *dst = (void *)(bias + (uintptr_t)base); + void *dst = (void *)(bias + phdrs[i].p_vaddr); + printk("section at file 0x%x will be loaded at 0x%x (v_addr requested: 0x%x)\n", + (uint8_t *)executable + phdrs[i].p_offset, dst, phdrs[i].p_vaddr); memcpy((uint8_t *)executable + phdrs[i].p_offset, dst, phdrs[i].p_filesz); memzero((uint8_t *)dst + phdrs[i].p_filesz, phdrs[i].p_memsz - phdrs[i].p_filesz); } + printk("Mounted program and will jump to entrypoint 0x%x (e_entry: 0x%x)\n", (uintptr_t)(hdr->e_entry + bias), (uintptr_t)hdr->e_entry); + __userspace_invoke((elf_entry)(hdr->e_entry + bias)); kfree(base); diff --git a/website-kernel/fs/exec.S b/website-kernel/fs/exec.S index 745761d..c16e73f 100644 --- a/website-kernel/fs/exec.S +++ b/website-kernel/fs/exec.S @@ -4,6 +4,7 @@ # __userspace_invoke(fn exec *entry) __userspace_invoke: + csrw mscratch, sp csrw mepc, a0 csrw mie, zero diff --git a/website-kernel/fs/fs_cpio.c b/website-kernel/fs/fs_cpio.c new file mode 100644 index 0000000..bbab632 --- /dev/null +++ b/website-kernel/fs/fs_cpio.c @@ -0,0 +1,76 @@ +#include +#include +#include +#include + +static inline int strcmp(const char *str1, const char* str2) { + while (*str1 && (*str1 == *str2)) { + ++str1; + ++str2; + } + return *(const unsigned char *)str1 - *(const unsigned char *)str2; +} + +static uint32_t parse_hex(const char *p) +{ + uint32_t value = 0; + + for (int i = 0; i < 8; i++) { + char c = p[i]; + value <<= 4; + + if (c >= '0' && c <= '9') + value |= c - '0'; + else if (c >= 'A' && c <= 'F') + value |= c - 'A' + 10; + else if (c >= 'a' && c <= 'f') + value |= c - 'a' + 10; + } + return value; +} + +void *cpio_get_file(void *archive, size_t size, const char *filename) { + const uint8_t *p = (uint8_t *)archive; + const uint8_t *end = archive + size; + + while (p + CPIO_HEADER_LEN <= end) { + const struct cpio_newc_hdr *hdr = + (const struct cpio_newc_hdr *)p; + + if (memcmp(hdr->magic, "070701", 6) && + memcmp(hdr->magic, "070702", 6)) { + printk("Error parsing cpio: bad magic number!\n"); + return NULL; + } + + uint32_t namesize = parse_hex(hdr->namesize); + uint32_t filesize = parse_hex(hdr->filesize); + + p += CPIO_HEADER_LEN; + + if (p + namesize > end) { + printk("Error parsing cpio: truncated filename\n"); + return NULL; + } + + const char *name = (const char *)p; + + if (strcmp(name, "TRAILER!!!") == 0) + return NULL; + + p += namesize; + + if (p + filesize > end) { + printk("Error parsing cpio: truncated file\n"); + return NULL; + } + + if (strcmp(name, filename) == 0) { + return (void*)p; + } + + p += filesize; + } + return NULL; +} + diff --git a/website-kernel/include/fs/cpio.h b/website-kernel/include/fs/cpio.h new file mode 100644 index 0000000..43440d2 --- /dev/null +++ b/website-kernel/include/fs/cpio.h @@ -0,0 +1,24 @@ +#pragma once +#include +#define CPIO_HEADER_LEN 110 + +struct cpio_newc_hdr { + char magic[6]; + char ino[8]; + char mode[8]; + char uid[8]; + char gid[8]; + char nlink[8]; + char mtime[8]; + char filesize[8]; + char devmajor[8]; + char devminor[8]; + char rdevmajor[8]; + char rdevminor[8]; + char namesize[8]; + char check[8]; +}; + +void *cpio_get_file(void *archive, size_t size, const char *filename); + + diff --git a/website-kernel/include/fs/elf.h b/website-kernel/include/fs/elf.h index 8157384..65d2817 100644 --- a/website-kernel/include/fs/elf.h +++ b/website-kernel/include/fs/elf.h @@ -77,3 +77,4 @@ struct elf_program_header { int elf_chk_header(struct elf_header *header); struct elf_section_header *elf_get_section(struct elf_header *hdr, void *data, uint32_t index); char *elf_get_section_name(struct elf_header *hdr, struct elf_section_header *section, void *data); +void elf_exec(void *executable); diff --git a/website-kernel/include/sys.h b/website-kernel/include/sys.h index 00ab4b7..bc0279d 100644 --- a/website-kernel/include/sys.h +++ b/website-kernel/include/sys.h @@ -25,3 +25,4 @@ void kfree(void *ptr); void memcpy(void *src, void *dst, size_t size); void memzero(void *ptr, size_t size); +int memcmp(const void *s1, const void *s2, size_t n); diff --git a/website-src/index.html b/website-src/index.html index b2eefd0..fa0187a 100644 --- a/website-src/index.html +++ b/website-src/index.html @@ -10,15 +10,20 @@ async function run() { await init(); const response = await fetch('/vmwebkrnl.bin'); + const initramfs = await fetch('/initramfs.cpio'); if (!response.ok) { console.log("OS image not present, not booting."); return; } + if (!initramfs.ok) { + console.log("Initial RAM filesystem not present, not booting."); + return; + } const image = new Uint8Array(await response.arrayBuffer()); const vmwebkrnl = new Uint8Array(2 * 1024 * 1024); vmwebkrnl.set(image); - const initrd = new Uint8Array(8); + const initrd = new Uint8Array(await initramfs.arrayBuffer()); const dram = new Uint8Array(1024 * 1024); boot(vmwebkrnl, initrd, dram); diff --git a/website-src/initramfs.cpio b/website-src/initramfs.cpio new file mode 100644 index 0000000..bdfe10d Binary files /dev/null and b/website-src/initramfs.cpio differ -- cgit v1.2.3