环境
- Time 2022-11-13
- WSL-Ubuntu 22.04
- QEMU 6.2.0
- Rust 1.67.0-nightly
前言
说明
参考:https://os.phil-opp.com/minimal-rust-kernel
目标
将上一节编写的可执行文件制作成 QEMU 可以启动的镜像,并使用 QEMU 调试。
main.rs
#![no_std]
#![no_main]
static HELLO: &[u8] = b"Hello World!";
#[no_mangle]
pub extern "C" fn _start() -> ! {
let vga_buffer = 0xb8000 as *mut u8;
for (i, &byte) in HELLO.iter().enumerate() {
unsafe {
*vga_buffer.offset(i as isize * 2) = byte;
*vga_buffer.offset(i as isize * 2 + 1) = 0xb;
}
}
loop {}
}
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
Cargo.toml
[package]
edition = "2021"
name = "mos"
version = "0.1.0"
[dependencies]
bootloader = "0.9.8"
制作镜像
安装命令:cargo install bootimage
构建命令:cargo bootimage
root@jiangbo12490:~/git/game# cargo install bootimage
Blocking waiting for file lock on package cache
Updating crates.io index
Ignored package `bootimage v0.10.3` is already installed, use --force to override
root@jiangbo12490:~/git/game# cargo bootimage
WARNING: `CARGO_MANIFEST_DIR` env variable not set
Building kernel
Compiling mos v0.1.0 (/root/git/game)
Finished dev [unoptimized + debuginfo] target(s) in 0.27s
Building bootloader
Compiling bootloader v0.9.23 (/root/.cargo/registry/src/github.com-1ecc6299db9ec823/bootloader-0.9.23)
Finished release [optimized + debuginfo] target(s) in 0.57s
Created bootimage for `mos` at `/root/git/game/target/mos/debug/bootimage-mos.bin`
启动 QEMU 脚本
#! /usr/bin/bash
cargo bootimage
qemu-system-x86_64 -drive format=raw,file=target/mos/debug/bootimage-mos.bin \
-display curses -s -S
GDB 调试脚本
#! /usr/bin/bash
gdb target/mos/debug/mos \
-ex "target remote localhost:1234" \
-ex "break _start" -ex "continue"
文件目录结构
├── Cargo.lock
├── Cargo.toml
├── gdb.sh
├── mos.json
├── qemu.sh
├── rust-toolchain
├── src
│ └── main.rs
└── .cargo
└── config.toml
效果
总结
使用 Rust 编写了一个在 x64 平台上的独立可执行程序,并且使用 QEMU 运行和 GDB 调试。