编译环境
本文基于 Ubuntu 18.04.2,对Linux 4.20内核进行了构建,然后在qemu下启动。 参考文档:
编译过程
编译内核
源码下载:https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.20.tar.gz
下载后解压,然后安装几个依赖即可: 1
2
3
4tar -xvf linux-4.20.tar.gz
apt install libncurses5-dev bison flex
apt install libelf-dev libssl-dev1
2
3cd linux-4.20
ARCH=x86_64 make defconfig
make menuconfig1
2
3
4
5
6
7Kernel hacking ---> Compile-time checks and compiler options ---> Compile the kernel with debug info ---> yes
Kernel hacking ---> Compile-time checks and compiler options ---> Provide GDB scripts for kernel debugging ---> yes
General setup ---> Configure standard kernel features ---> yes
General setup ---> Configure standard kernel features ---> Load all symbols for debugging/ksymoops ---> yes
General setup ---> Configure standard kernel features ---> Include all symbols in kallsyms ---> yes
General setup -> Compiler optimization level (Optimize for performance) ---> Optimize for size
Kernel hacking ---> Memory Debugging ---> KASan: runtime memory debugger ---> yes1
ARCH=x86_64 make -j 2
创建initramfs
光有内核还不够,再用debootstrap来创建一个initramfs,命令中的"xenial"是Ubuntu 16.04的代号: 1
debootstrap --include linux-image-generic xenial debootstrap http://archive.ubuntu.com/ubuntu
1
2
3
4
5
6
7
8
9
10
11
12
13# chroot
chroot debootstrap
# 修改root密码
passwd root
# 添加用户,可选
/usr/sbin/adduser user
# 将根文件系统设置为可读写
cat << EOF | tee "debootstrap/etc/fstab"
/dev/vda / ext4 errors=remount-ro,acl 0 1
EOF1
virt-make-fs --format qcow2 --size +1G --type ext4 debootstrap xenial-debootstrap.ext4.qcow2
注:下面的qemu和gdb最好都在screen中新开会话执行,这样不阻塞你的ssh会话。
编译好的kernel配合initramfs可以直接在qemu下启动: 1
2
3
4qemu-system-x86_64 -kernel linux-4.20/arch/x86_64/boot/bzImage \
-drive file=xenial-debootstrap.ext4.qcow2 \
-net nic -net user,hostfwd=tcp::2222-:22,hostfwd=tcp::9999-:9999,hostfwd=tcp::8000-:8000 \
-nographic -append "root=/dev/sda console=ttyS0"1
2
3
4qemu-system-x86_64 -kernel linux-4.20/arch/x86_64/boot/bzImage \
-drive file=xenial-debootstrap.ext4.qcow2 \
-net nic -net user,hostfwd=tcp::2222-:22,hostfwd=tcp::9999-:9999,hostfwd=tcp::8000-:8000 \
-nographic -append "root=/dev/sda console=ttyS0" -s -S1
2gdb vmlinux
target remote localhost:1234