anos/src/lib.rs

109 lines
2.3 KiB
Rust
Raw Normal View History

2021-12-09 11:51:38 +00:00
#![no_std]
#![cfg_attr(test, no_main)]
#![feature(custom_test_frameworks)]
#![test_runner(crate::test_runner)]
#![reexport_test_harness_main = "test_main"]
2022-01-09 09:13:30 +00:00
#![feature(abi_x86_interrupt)]
2022-01-13 08:19:54 +00:00
#![feature(alloc_error_handler)]
extern crate alloc;
2021-12-09 11:51:38 +00:00
use core::panic::PanicInfo;
2022-01-10 09:45:04 +00:00
pub mod gdt;
2022-01-13 04:11:03 +00:00
pub mod interrupts;
2022-01-13 04:09:37 +00:00
pub mod memory;
2022-01-13 04:11:03 +00:00
pub mod serial;
pub mod vga_buffer;
2022-01-13 08:19:54 +00:00
pub mod allocator;
2021-12-09 11:51:38 +00:00
pub trait Testable {
fn run(&self) -> ();
}
impl<T> Testable for T
where
T: Fn(),
{
fn run(&self) {
2022-01-13 04:11:03 +00:00
serial_print!("{}...\t", core::any::type_name::<T>()); // 打印函数名
self(); // 执行这个函数。由于 T 具有 Fn() trait 所以它能够作为一个函数被直接调用
serial_println!("[ok]"); // 打印 "[ok]"
2021-12-09 11:51:38 +00:00
}
}
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);
2022-01-11 09:09:13 +00:00
hlt_loop();
2021-12-09 11:51:38 +00:00
}
#[cfg(test)]
2022-01-13 04:09:37 +00:00
use bootloader::{entry_point, BootInfo};
#[cfg(test)]
entry_point!(test_kernel_main);
#[cfg(test)]
fn test_kernel_main(_boot_info: &'static BootInfo) -> ! {
2022-01-09 09:13:30 +00:00
init();
2021-12-09 11:51:38 +00:00
test_main();
2022-01-11 09:09:13 +00:00
hlt_loop();
2021-12-09 11:51:38 +00:00
}
#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
test_panic_handler(info)
}
2022-01-09 09:13:30 +00:00
#[test_case]
fn test_breakpoint_exception() {
x86_64::instructions::interrupts::int3();
// 如果程序继续运行则说明测试成功
// 用 cargo test 运行全部测试
// 或 cargo test --lib 仅运行库测试
}
2021-12-09 11:51:38 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum QemuExitCode {
Success = 0x10,
Failed = 0x11,
}
pub fn exit_qemu(exit_code: QemuExitCode) {
use x86_64::instructions::port::Port;
unsafe {
2022-01-13 04:11:03 +00:00
let mut port = Port::new(0xf4); // iobase port
2021-12-09 11:51:38 +00:00
port.write(exit_code as u32);
}
}
2022-01-11 09:09:13 +00:00
pub fn hlt_loop() -> ! {
loop {
x86_64::instructions::hlt();
}
}
2022-01-13 08:19:54 +00:00
#[alloc_error_handler]
fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! {
panic!("allocation error: {:?}", layout);
}
2022-01-09 09:13:30 +00:00
pub fn init() {
2022-01-10 09:45:04 +00:00
gdt::init();
2022-01-09 09:13:30 +00:00
interrupts::init_idt();
2022-01-11 09:09:13 +00:00
unsafe { interrupts::PICS.lock().initialize() };
x86_64::instructions::interrupts::enable();
2022-01-09 09:13:30 +00:00
}