环境
- Time 2022-11-13
- WSL-Ubuntu 22.04
- QEMU 6.2.0
- Rust 1.67.0-nightly
- VSCode 1.73.1
前言
说明
参考:https://os.phil-opp.com/vga-text-mode
目标
可以使用 println! 宏向屏幕输出错误,发送错误时,可以打印错误信息。
Cargo.toml
其中的 spin 为全局锁需要,lazy_static 为静态初始化需要。
[package]
edition = "2021"
name = "mos"
version = "0.1.0"[dependencies]
bootloader = "0.9.8"
spin = "0.9.4"
volatile = "0.2.6"
[dependencies.lazy_static]
features = ["spin_no_std"]
version = "1.4.0"
[build]
target = "mos.json"
静态初始化和宏
vga_buffer.rs 完整内容见附录。
// 静态初始化,全局变量
use lazy_static::lazy_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) },});
}// 定义 print! 和 println! 宏
#[macro_export]
macro_rules! print {($($arg:tt)*) => ($crate::vga_buffer::_print(format_args!($($arg)*)));
}#[macro_export]
macro_rules! println {() => ($crate::print!("\n"));($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
}#[doc(hidden)]
pub fn _print(args: core::fmt::Arguments) {use core::fmt::Write;WRITER.lock().write_fmt(args).unwrap();
}
主函数
#![no_std]
#![no_main]mod vga_buffer;#[no_mangle]
pub extern "C" fn _start() -> ! {// 实现从 1 输出到 500for i in 0..500 {print!("{i}_");}panic!("some thing wrong")
}#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> ! {println!("{}", info);loop {}
}
效果
总结
实现了向屏幕输出,自动换行,定义了 println! 宏,错误发生时,打印了异常信息。
附录
vga_buffer.rs
use spin::Mutex;
use volatile::Volatile;// 因为不是每种类型都使用到了,所以需要告诉编译器不警告
#[allow(dead_code)]
// 自动实现相关的 trait
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// 定义内存模型,和 u8 一样
#[repr(u8)]
pub enum Color {Black = 0,Blue = 1,Green = 2,Cyan = 3,Red = 4,Magenta = 5,Brown = 6,LightGray = 7,DarkGray = 8,LightBlue = 9,LightGreen = 10,LightCyan = 11,LightRed = 12,Pink = 13,Yellow = 14,White = 15,
}#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// 定义内存模型,和 u8 一样
#[repr(transparent)]
struct ColorCode(u8);impl ColorCode {fn new(foreground: Color, background: Color) -> ColorCode {// 一个字节的高四位表示背景色,低四位表示前景色ColorCode((background as u8) << 4 | (foreground as u8))}
}#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// 和 C 语言内存模式一致
#[repr(C)]
struct ScreenChar {// 要显示的字符ascii_character: u8,// 颜色装饰color_code: ColorCode,
}// 显示缓冲区的高度和宽度
const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH: usize = 80;// 显示缓冲区
#[repr(transparent)]
struct Buffer {chars: [[Volatile<ScreenChar>; BUFFER_WIDTH]; BUFFER_HEIGHT],
}pub struct Writer {// 记录写到第几列column_position: usize,// 定义需要写的颜色属性color_code: ColorCode,// 指向显示缓冲区的引用buffer: &'static mut Buffer,
}impl Writer {// 输出单个字节pub fn write_byte(&mut self, byte: u8) {match byte {b'\n' => self.new_line(),byte => {if self.column_position >= BUFFER_WIDTH {self.new_line();}let row = BUFFER_HEIGHT - 1;let col = self.column_position;let color_code = self.color_code;self.buffer.chars[row][col].write(ScreenChar {ascii_character: byte,color_code,});self.column_position += 1;}}}// 换行输出fn new_line(&mut self) {// 整体向上移动一行for row in 1..BUFFER_HEIGHT {for col in 0..BUFFER_WIDTH {let character = self.buffer.chars[row][col].read();self.buffer.chars[row - 1][col].write(character);}}// 清除最后一行的内容self.clear_row(BUFFER_HEIGHT - 1);self.column_position = 0;}// 在这一行输出全部的空格来清楚内容fn clear_row(&mut self, row: usize) {let blank = ScreenChar {ascii_character: b' ',color_code: self.color_code,};for col in 0..BUFFER_WIDTH {self.buffer.chars[row][col].write(blank);}}
}impl Writer {// 输出字符串pub fn write_string(&mut self, s: &str) {for byte in s.bytes() {match byte {// printable ASCII byte or newline0x20..=0x7e | b'\n' => self.write_byte(byte),// not part of printable ASCII range_ => self.write_byte(0xfe),}}}
}// 实现 Write,可以使用 write! 进行输出
impl core::fmt::Write for Writer {fn write_str(&mut self, s: &str) -> core::fmt::Result {self.write_string(s);Ok(())}
}// 静态初始化,全局变量
use lazy_static::lazy_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) },});
}// 定义 print! 和 println! 宏
#[macro_export]
macro_rules! print {($($arg:tt)*) => ($crate::vga_buffer::_print(format_args!($($arg)*)));
}#[macro_export]
macro_rules! println {() => ($crate::print!("\n"));($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
}#[doc(hidden)]
pub fn _print(args: core::fmt::Arguments) {use core::fmt::Write;WRITER.lock().write_fmt(args).unwrap();
}