qemu-调试内核

编译内核源码

  • 下载

    1
    git clone https://github.com/torvalds/linux.git $KERNEL
  • 生成默认的配置

    1
    2
    3
    cd $KERNEL
    make defconfig
    make kvmconfig
  • 编辑.config,开启一些选项

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    # gdb config
    CONFIG_GDB_SCRIPTS=y
    CONFIG_DEBUG_INFO=y
    # CONFIG_DEBUG_INFO_REDUCED is not set
    # CONFIG_RANDOMIZE_BASE is not set

    # kgdb config
    # CONFIG_STRICT_KERNEL_RWX is not set
    CONFIG_FRAME_POINTER=y
    CONFIG_KGDB=y
    CONFIG_KGDB_SERIAL_CONSOLE=y

    # kdb config
    # CONFIG_STRICT_KERNEL_RWX is not set
    CONFIG_FRAME_POINTER=y
    CONFIG_KGDB=y
    CONFIG_KGDB_SERRIAL_CONSOLE=y
    CONFIG_KGDB_KDB=y
    CONFIG_KDB_KEYBOARD=y

    # manually debug using the SysRq-G
    CONFIG_MAGIC_SysRq=y
  • 重新生成config文件,其中有一些子选项,默认即可

    1
    make oldconfig
  • 使用GCC编译内核

    1
    make -j$(nproc)

gdb调试

  • qemu启动的时候添加选项 ‘-gdb tcp:1234’
  • 内核命令行添加’nokaslr’

qemu启动项如下:

1
2
3
4
5
6
7
8
qemu-system-x86_64 -S -smp 2 -m 4G -enable-kvm -cpu host \
-net nic -net user,hostfwd=tcp::10022-:22 \
-gdb tcp::1234 \
-kernel ./kernel/arch/x86/boot/bzImage -nographic \
-device virtio-scsi-pci,id=scsi \
-device scsi-hd,bus=scsi.0,drive=d0 \
-drive file=wheezy.img,format=raw,if=none,id=d0 \
-append "root=/dev/sda noaslr"

gdb命令:

1
2
3
gdb vmlinux
target remote :1234
c

kgdb, kdb调试

qemu启动项如下:

1
2
3
4
5
6
7
8
qemu-system-x86_64 -smp 2 -m 4G -enable-kvm -cpu host \
-net nic -net user,hostfwd=tcp::10022-:22 \
-kernel ./kernel/arch/x86/boot/bzImage -nographic \
-device virtio-scsi-pci,id=scsi \
-device scsi-hd,bus=scsi.0,drive=d0 \
-drive file=wheezy.img,format=raw,if=none,id=d0 \
-append "root=/dev/sda noaslr kgdbwait kgdboc=ttyS0,115200" \
-serial tcp::1234,server,nowait

强制下断点:
开一个终端连接qemu里的系统,以root用户执行:

1
echo g > /proc/sysrq-trigger