編譯並運行內核鏡像
安裝包准備
$ sudo apt install git
$ sudo apt install build-essential kernel-package fakeroot libncurses5-dev libssl-dev ccache flex bison libelf-dev
下載 Linux 源碼
# 使用 git 下載 Linux 源碼並切換到合適的 commit,或者直接從官網下載 tarball
$ git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
linux內核鏡像編譯運行及gdb調試
$ cd linux
$ make ARCH=x86_64 x86_64_defconfig
$ make ARCH=x86_64 menuconfig # 打開 `Kernel hacking -> Compile-time checks and compiler options -> Compile the kernel with debug info -> Provide GDB scripts for kernel debugging`
$ make -j
$ qemu-system-x86_64 -no-kvm -kernel arch/x86/boot/bzImage -hda /dev/zero -append "root=/dev/zero console=ttyS0" -serial stdio -display none # 由於沒有根文件系統,並不會進入 shell,使用 Ctrl+C 退出
使用 gdb 調試內核啟動流程
$ qemu-system-x86_64 -s -S -no-kvm -kernel arch/x86/boot/bzImage -hda /dev/zero -append "root=/dev/zero console=ttyS0 nokaslr" -serial stdio -display none
# 重新開一個 shell session
$ cd /path/to/your/linux
$ gdb ./vmlinuz
(gdb) target remote localhost:1234
(gdb) break start_kernel
(gdb) c
(gdb) layout src
...
使用 buildroot 編譯 rootfs
在使用 buildroot 編譯 rootfs 時,若在內網使用,記得設置代理服務器。
$ git clone git://git.buildroot.net/buildroot
$ cd buildroot
$ make menuconfig
# select `Target Options -> Target Architecture -> x86_64`
# select `Filesystem images -> ext2/3/4 root file system -> ext4`
$ make -j
運行帶有 rootfs 的 linux kernel
$ cd /path/to/your/linux
$ qemu-system-x86_64 -no-kvm -kernel arch/x86/boot/bzImage \
-boot c -m 2048M -hda ../buildroot/output/images/rootfs.ext4 \
-append "root=/dev/sda rw console=ttyS0,115200 acpi=off nokaslr" \
-serial stdio -display none