0188-输出宏和错误信息

环境

  • 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 输出到 500
    for 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 newline
                0x20..=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();
}
posted @   jiangbo4444  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2020-07-16 【JavaScript】照片库
点击右上角即可分享
微信分享提示