Compile your first kernel

Fri Jun 14 2024

Compile your first kernel

(纯干货警告)

安装必要工具和依赖

cargo install --locked sccache; # sccache 是一个类似 ccache 的编译缓存工具,可以用于加速编译
sudo dnf5 builddep kernel;

安装工具链

sudo dnf5 install lld clang;
sudo ln -irs /bin/cc /bin/clang;
sudo ln -irs /bin/ld /bin/lld;

或者自行编译工具链(笔者选择的是自行编译,但 llvm 项目较大,实测 64 核心跑满,用 clang + mold 大约需要15分钟左右,clang版本号为 clang version 19.0.0git ([email protected]:xdlinux/llvm-project.git 331eb8a0047504f3ae2cdf2d6c60b93e5d0543f1)

sudo dnf5 install clang mold ninja-build;
sudo dnf5 builddep clang;
sudo ln -irs /bin/cc /bin/clang;
sudo ln -irs /bin/ld /bin/mold;
git clone https://linux.xidian.edu.cn/git/xdlinux/llvm-project --depth 1 && cd llvm-project || exit 1;
mkdir -p build && cd build || exit 1;
cmake -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra;lldb;lld;polly;cross-project-tests" -DCMAKE_BUILD_TYPE=Release -G "Ninja" ../llvm -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache;
ninja -j64;
ln -irs ./bin/* "$HOME/.local/bin";
ln -irs "$HOME/.local/bin/cc" "$HOME/.local/bin/clang";
ln -irs "$HOME/.local/bin/ld" "$HOME/.local/bin/lld";

配置内核并编译,可以选择开启编译器优化、LTO和控制流检查等静态分析选项

git clone https://linux.xidian.edu.cn/git/xdlinux/linux --depth 1 && cd linux || exit 1;
make menuconfig;
make -j64 LLVM=1 CC="sccache clang"; 

制作 initrd,用于加载 userspace 程序

curl https://dl-cdn.alpinelinux.org/alpine/v3.20/releases/x86_64/alpine-minirootfs-3.20.0-x86_64.tar.gz -o alpine-minirootfs-3.20.0-x86_64.tar.gz && \
mkdir -p rootfs && \
tar xvf alpine-minirootfs-3.20.0-x86_64.tar.gz -C rootfs && \
cd rootfs && \
find -print | cpio -ov --null --format=newc >> ../alpine.cpio;

用 qemu 进行模拟,加载内核和 initrd

sudo modprobe kvm && \
sudo qemu-system-x86_64 \
-nographic \
-kernel linux/arch/x86_64/boot/bzImage \
-initrd alpine.cpio \
-m 512 \
-append "root=/dev/ram rdinit=/bin/sh console=ttyS0" \
-s \
-monitor tcp:localhost:1111,server,nowait \
--enable-kvm \
-cpu host;