#![no_std]
#![cfg_attr(test, no_main)]
#![feature(custom_test_frameworks)]
#![test_runner(crate::test_runner)]
#![reexport_test_harness_main = "test_main"]
#[cfg(test)]
use core::arch::global_asm;
use core::panic::PanicInfo;
pub mod allocator; pub mod block; pub mod console; pub mod errno; pub mod event_log; pub mod fs; pub mod grading; pub mod interrupts; pub mod mem_utils; pub mod memory; pub mod process; pub mod serial; pub mod shell; pub mod syscall; pub mod task;
extern crate alloc;
pub trait Testable {
fn run(&self) -> ();
}
impl<T> Testable for T
where
T: Fn(),
{
fn run(&self) {
serial_print!("{}...\t", core::any::type_name::<T>());
self();
serial_println!("[ok]");
}
}
pub fn test_runner(tests: &[&dyn Testable]) {
serial_println!("Running {} tests", tests.len());
for test in tests {
test.run();
}
exit_qemu(QemuExitCode::Success);
}
pub fn test_panic_handler(info: &PanicInfo) -> ! {
serial_println!("[failed]\n");
serial_println!("Error: {}\n", info);
exit_qemu(QemuExitCode::Failed);
hlt_loop();
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum QemuExitCode {
Success = 0x10,
Failed = 0x11,
}
pub fn exit_qemu(exit_code: QemuExitCode) {
let reason: usize = match exit_code {
QemuExitCode::Success => 0,
QemuExitCode::Failed => 1,
};
serial_println!("[QEMU] Exiting with code {:?}", exit_code);
unsafe {
core::arch::asm!(
"li a7, 0x53525354", "li a6, 0", "li a0, 0", "mv a1, {reason}", "ecall",
"li a7, 8", "li a6, 0",
"li a0, 0",
"mv a1, {reason}",
"ecall",
"2:",
"wfi",
"j 2b",
reason = in(reg) reason,
options(noreturn)
);
}
}
pub fn init() {
serial_println!("[INIT] Initializing RISC-V OS");
interrupts::init_idt();
serial_println!("[INIT] Initialization complete");
}
pub fn hlt_loop() -> ! {
loop {
riscv::asm::wfi();
}
}
#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
test_panic_handler(info)
}
#[cfg(test)]
global_asm!(
".section .text.entry",
".globl _start",
"_start:",
" la sp, stack_end",
" la t0, bss_start",
" la t1, bss_end",
"1:",
" bgeu t0, t1, 2f",
" sd zero, (t0)",
" addi t0, t0, 8",
" j 1b",
"2:",
" call test_kernel_main",
"3:",
" wfi",
" j 3b",
);
#[cfg(test)]
#[no_mangle]
pub extern "C" fn test_kernel_main() -> ! {
init();
init_test_heap();
test_main();
hlt_loop();
}
#[cfg(test)]
fn init_test_heap() {
extern "C" {
static kernel_end: u8;
}
let kernel_end_addr = unsafe { &kernel_end as *const u8 as usize };
let mut memory_manager = memory::init(kernel_end_addr);
allocator::init_heap(&mut memory_manager.frame_allocator).expect("heap initialization failed");
}