1#![no_std]
19#![cfg_attr(test, no_main)]
20#![feature(custom_test_frameworks)]
21#![test_runner(crate::test_runner)]
22#![reexport_test_harness_main = "test_main"]
23
24#[cfg(test)]
25use core::arch::global_asm;
26use core::panic::PanicInfo;
27
28pub 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 {
60 fn run(&self) -> ();
61}
62
63impl<T> Testable for T
64where
65 T: Fn(),
66{
67 fn run(&self) {
68 serial_print!("{}...\t", core::any::type_name::<T>());
69 self();
70 serial_println!("[ok]");
71 }
72}
73
74pub fn test_runner(tests: &[&dyn Testable]) {
76 serial_println!("Running {} tests", tests.len());
77 for test in tests {
78 test.run();
79 }
80 exit_qemu(QemuExitCode::Success);
81}
82
83pub fn test_panic_handler(info: &PanicInfo) -> ! {
85 serial_println!("[failed]\n");
86 serial_println!("Error: {}\n", info);
87 exit_qemu(QemuExitCode::Failed);
88 hlt_loop();
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96#[repr(u32)]
97pub enum QemuExitCode {
98 Success = 0x10,
99 Failed = 0x11,
100}
101
102pub fn exit_qemu(exit_code: QemuExitCode) {
107 let reason: usize = match exit_code {
108 QemuExitCode::Success => 0,
109 QemuExitCode::Failed => 1,
110 };
111 serial_println!("[QEMU] Exiting with code {:?}", exit_code);
112
113 unsafe {
116 core::arch::asm!(
117 "li a7, 0x53525354", "li a6, 0", "li a0, 0", "mv a1, {reason}", "ecall",
122 "li a7, 8", "li a6, 0",
124 "li a0, 0",
125 "mv a1, {reason}",
126 "ecall",
127 "2:",
128 "wfi",
129 "j 2b",
130 reason = in(reg) reason,
131 options(noreturn)
132 );
133 }
134}
135
136pub fn init() {
146 serial_println!("[INIT] Initializing RISC-V OS");
147
148 interrupts::init_idt();
150
151 serial_println!("[INIT] Initialization complete");
152}
153
154pub fn hlt_loop() -> ! {
160 loop {
161 riscv::asm::wfi();
162 }
163}
164
165#[cfg(test)]
171#[panic_handler]
172fn panic(info: &PanicInfo) -> ! {
173 test_panic_handler(info)
174}
175
176#[cfg(test)]
181global_asm!(
182 ".section .text.entry",
183 ".globl _start",
184 "_start:",
185 " la sp, stack_end",
186 " la t0, bss_start",
187 " la t1, bss_end",
188 "1:",
189 " bgeu t0, t1, 2f",
190 " sd zero, (t0)",
191 " addi t0, t0, 8",
192 " j 1b",
193 "2:",
194 " call test_kernel_main",
195 "3:",
196 " wfi",
197 " j 3b",
198);
199
200#[cfg(test)]
201#[no_mangle]
202pub extern "C" fn test_kernel_main() -> ! {
203 init();
204 init_test_heap();
205 test_main();
206 hlt_loop();
207}
208
209#[cfg(test)]
210fn init_test_heap() {
211 extern "C" {
212 static kernel_end: u8;
213 }
214
215 let kernel_end_addr = unsafe { &kernel_end as *const u8 as usize };
216 let mut memory_manager = memory::init(kernel_end_addr);
217 allocator::init_heap(&mut memory_manager.frame_allocator).expect("heap initialization failed");
218}