编译x86_64 Linux内核并基于QEMU运行

编译并运行内核镜像

实验环境

x86_64 Ubuntu 20.04

安装包准备

$ 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

参考

本文来自博客园,作者:Legend_Lone,转载请注明原文链接:https://www.cnblogs.com/sun-ye/p/14983558.html

原文地址:https://www.cnblogs.com/sun-ye/p/14983558.html