使用Qemu调试linux内核

1. 配置内核

 Kernel hacking
     Compile-time checks and compiler options  --->
         [*]   Provide GDB scripts for kernel debugging 
     [*] Kernel debugging 

编译内核,生成的可调试内核文件为vmlinux.

2. 启动Qemu

启动命令

qemu-system-aarch64 -m 1G -cpu cortex-a53 -smp 4 -machine virt \
                    -initrd rootfs.cpio.gz \
                    -kernel Image \
                    -append 'root=/dev/ram0 console=ttyAMA0 nokaslr' \
                    -monitor tcp::4447,server,telnet,nowait \
                    -serial stdio \
                    -S \
                    -s \
                    -nographic
  • -append:需要加上nokaslr内核参数,防止内核段基地址被随机映射
  • -S:让QEMU启动后CPU先Pause住不运行
  • -s:是-gdb tcp::1234的简写, 让QEMU侧的gdb server监听在1234端口等待调试

3. GDB调试内核

  • gdb 7.2+ (recommended: 7.4+) with python support enabled (typically true for distributions)

配置内核编译路径 编辑~/.gdbinit文件,没有则新建,添加如下命令:

add-auto-load-safe-path /path/to/linux-build

调试内核

aarch64-linux-gnu-gdb ./vmlinux

连接到Qemu虚拟机

(gdb) target remote 192.168.10.2:1234

添加断点

 (gdb) b start_kernel

运行

(gdb) c Continuing. Thread 1 hit Breakpoint 1, start_kernel () at init/main.c:482 482 { (gdb) bt #0 start_kernel () at init/main.c:482 #1 0xffff000008ac01d8 in __primary_switched () at arch/arm64/kernel/head.S:451 Backtrace stopped: previous frame identical to this frame (corrupt stack?) (gdb) 可以看到内核在start_kernel断点处停止。

4. 内核提供的调试命令

   function lx_current -- Return current task
   function lx_module -- Find module by name and return the module variable
   function lx_per_cpu -- Return per-cpu variable
   function lx_task_by_pid -- Find Linux task by PID and return the task_struct variable
   function lx_thread_info -- Calculate Linux thread_info from task variable
   function lx_thread_info_by_pid -- Calculate Linux thread_info from task variable found by pid
   lx-cmdline --  Report the Linux Commandline used in the current kernel
   lx-cpus -- List CPU status arrays
   lx-dmesg -- Print Linux kernel log buffer
   lx-iomem -- Identify the IO memory resource locations defined by the kernel
   lx-ioports -- Identify the IO port resource locations defined by the kernel
   lx-list-check -- Verify a list consistency
   lx-lsmod -- List currently loaded modules
   lx-mounts -- Report the VFS mounts of the current process namespace
   lx-ps -- Dump Linux tasks
   lx-symbols -- (Re-)load symbols of Linux kernel and currently loaded modules
   lx-version --  Report the Linux Version of the current kernel

5. 引用

Related Posts