背景

试图用Rust做操作系统小组作业,某组员遇到环境配置问题。我尝试了一下,发现网上中文资料确实比较少,而且官方文档翻译略有过时。(可能有Rust更新比较快的原因。于是写了篇没什么用的流水账记录一下编译一个启用Rust支持的Linux kernel的过程。

环境配置

本文所述内容均在archlinux下进行。

省流版(不保证完全准确,在我这能跑):
https://www.kernel.org/ 下载linux-6.8.2源码
在linux-6.8.2目录下切换rustc版本

rustup override set $(scripts/min-tool-version.sh rustc)

添加rust-src

rustup component add rust-src

安装bindgen-cli
注意:此处中文文档已经滞后,需要安装的是bindgen-cli而非bindgen.
详见: https://github.com/rust-lang/cargo/issues/11249

cargo install --locked --version $(scripts/min-tool-version.sh bindgen) bindgen-cli

需要将~/.cargo/bin添加到环境变量
生成rust-analyzer配置文件

make LLVM=1 rust-analyzer

查看rust工具链是否符合要求

make LLVM=1 rustavailable

在我这的输出是(我没锁bindgen版本)

❯ make LLVM=1 rustavailable
***
*** Rust bindings generator 'bindgen' is too new. This may or may not work.
***   Your version:     0.69.4
***   Expected version: 0.65.1
***
***
*** Please see Documentation/rust/quick-start.rst for details
*** on how to set up the Rust support.
***
Rust is available!

然后就可以编译内核了

编译内核启用rust支持

在linux-6.8.2目录下

make LLVM=1 menuconfig

若依赖没有问题,则可以开启Rust support,否则默认不显示。
可以利用menuconfig的/搜索功能,搜索RUST查看依赖。

General Setup
    ->Rust support设为Y
Kernel hacking
    -> Sample kernel code
        -> Rust samples
          -> rust_print

将Sample kernel code设为Y,rust_print设为M(编译为Kernel Module)。
编译:

make LLVM=1 -j16 bzImage samples/rust/rust_print.ko

测试

使用busybox等工具构建根文件系统,将生成的rust_print.ko添加到根文件系统(命名为rustmod.cpio)中,然后qemu启动进行测试。

#!/bin/sh
qemu-system-x86_64 -kernel ./linux-6.8.2/arch/x86/boot/bzImage \
	--initrd ./rustmod.cpio \
	-nographic \
	--append "console=ttyS0"

参考链接

https://docs.kernel.org/rust/quick-start.html