$ sudo apt install git $ sudo apt install build-essential kernel-package fakeroot libncurses5-dev libssl-dev ccache flex bison libelf-dev
# 使用 git 下载 Linux 源码并切换到合适的 commit,或者直接从官网下载 tarball $ git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
$ 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 时,若在内网使用,记得设置代理服务器。
$ 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
$ 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