This commit is contained in:
2021-12-09 19:51:38 +08:00
parent aab190baea
commit 3e153fb1a9
8 changed files with 256 additions and 29 deletions

69
src/lib.rs Normal file
View File

@@ -0,0 +1,69 @@
#![no_std]
#![cfg_attr(test, no_main)]
#![feature(custom_test_frameworks)]
#![test_runner(crate::test_runner)]
#![reexport_test_harness_main = "test_main"]
use core::panic::PanicInfo;
pub mod serial;
pub mod vga_buffer;
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(); // 执行这个函数。由于 T 具有 Fn() trait 所以它能够作为一个函数被直接调用
serial_println!("[ok]"); // 打印 "[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);
loop {}
}
#[cfg(test)]
#[no_mangle]
pub extern "C" fn _start() -> ! {
test_main();
loop {}
}
#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
test_panic_handler(info)
}
#[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 {
let mut port = Port::new(0xf4); // iobase port
port.write(exit_code as u32);
}
}

View File

@@ -1,12 +1,11 @@
#![no_std] // 不链接 Rust 标准库
#![no_main] // 禁用 main 入口点,因为没有运行时
#![feature(custom_test_frameworks)]
#![test_runner(anos::test_runner)]
#![reexport_test_harness_main = "test_main"]
use core::panic::PanicInfo;
mod vga_buffer;
// 定义一个 byte string 类型的静态变量
static HELLO: &[u8] = b"Hello World!";
use anos::println;
#[no_mangle] // 不重整函数名,否则编译器可能会生成名为 _ZN3blog_os4_start7hb173fedf945531caE 的函数
// extern "C" 告诉编译器这个函数应当使用 C 语言的调用约定
@@ -15,9 +14,14 @@ static HELLO: &[u8] = b"Hello World!";
pub extern "C" fn _start() -> ! {
println!("Hello World{}", "!");
#[cfg(test)]
test_main();
loop {}
}
// 在非测试模式下,将 panic 信息打印到 VGA 缓冲区
#[cfg(not(test))]
#[panic_handler]
// panic! 时将会进行栈展开,执行各种 drop 函数来回收垃圾
// 禁用标准库之后,这些东西就都没有了,我们需要把它重写一遍
@@ -25,3 +29,9 @@ fn panic(info: &PanicInfo) -> ! {
println!("{}", info);
loop {}
}
#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
anos::test_panic_handler(info)
}

32
src/serial.rs Normal file
View File

@@ -0,0 +1,32 @@
use uart_16550::SerialPort;
use spin::Mutex;
use lazy_static::lazy_static;
lazy_static! {
pub static ref SERIAL1: Mutex<SerialPort> = {
let mut serial_port = unsafe { SerialPort::new(0x3F8) };
serial_port.init();
Mutex::new(serial_port)
};
}
#[doc(hidden)]
pub fn _print(args: ::core::fmt::Arguments) {
use core::fmt::Write;
SERIAL1.lock().write_fmt(args).expect("Printing to serial failed");
}
#[macro_export]
macro_rules! serial_print {
($($arg:tt)*) => {
$crate::serial::_print(format_args!($($arg)*));
};
}
#[macro_export]
macro_rules! serial_println {
() => ($crate::serial_print!("\n"));
($fmt:expr) => ($crate::serial_print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => ($crate::serial_print!(
concat!($fmt, "\n"), $($arg)*));
}

View File

@@ -125,38 +125,25 @@ impl fmt::Write for Writer {
}
}
lazy_static! {
pub static ref WRITER: Mutex<Writer> = Mutex::new(Writer {
// 将 Writer 设置为静态以便调用
lazy_static! { // 内置的 static 会用到标准库里的一些东西,所以这里用 lazy_static
pub static ref WRITER: Mutex<Writer> = Mutex::new(Writer { // 用互斥锁来防止冲突
column_position: 0,
color_code: ColorCode::new(Color::Yellow, Color::Black),
buffer: unsafe { &mut *(0xb8000 as *mut Buffer) }
});
}
pub fn print_something() {
use core::fmt::Write;
let mut writer = Writer {
column_position: 0,
color_code: ColorCode::new(Color::Yellow, Color::Black),
// VGA Buffer 从 0xb8000 开始
buffer: unsafe { &mut *(0xb8000 as *mut Buffer) },
};
writer.write_byte(b'H');
writer.write_string("ello ");
writer.write_string("Wörld!");
write!(writer, "The numbers are {} and {}", 42, 1.0/3.0).unwrap();
}
// 将宏导出到 crate 的根,这样我们就可以用
// use crate::println
// 来使用它
#[macro_export]
macro_rules! print {
macro_rules! print { // print!()
($($arg:tt)*) => ($crate::vga_buffer::_print(format_args!($($arg)*)));
}
#[macro_export]
macro_rules! println {
macro_rules! println { // println!()
() => ($crate::print!("\n"));
($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
}
@@ -168,3 +155,25 @@ pub fn _print(args: fmt::Arguments) {
use core::fmt::Write;
WRITER.lock().write_fmt(args).unwrap();
}
#[test_case]
fn test_println_simple() { // 测试单行 println!
println!("test_println_simple output");
}
#[test_case]
fn test_println_many() { // 测试多行 println!
for _ in 0..100 {
println!("test_println_many output");
}
}
#[test_case]
fn test_println_output() { // 测试字符是否真的打印到了屏幕上
let s = "Some test string that fits on a single line";
println!("{}", s);
for (i, c) in s.chars().enumerate() {
let screen_char = WRITER.lock().buffer.chars[BUFFER_HEIGHT - 2][i].read();
assert_eq!(char::from(screen_char.ascii_character), c);
}
}