Vscode 搭建 Linux 内核 调试环境 (gdb + qemu)

  • 搭建 Linux 内核调试环境

  • 资料来源:

    https://www.cnblogs.com/lijiang2023/p/17248676.html
    https://github.com/mengning/linuxkernel/tree/master/src/kerneldebuging

  • 更新

    1
    2023.06.15 初始

导语

最近重新接触底层相关内容,加强记录.

内核调试选项

make meauconfig 时

1
2
3
4
5
6
7
8
Kernel hacking  --->
Compile-time checks and compiler options --->
[*] Compile the kernel with debug info
[*] Provide GDB scripts for kernel debugging
 [*] Kernel debugging

Processor type and features ---->
[] Randomize the address of the kernel image (KASLR)
  • 一系列 debug 标志位
  • 关闭 KASLR 防止打断点失败.

gdb 调试内核需要的 vmlinux 在 /build/vmlinux

gdb + qemu

qemu 运行时必须要有 -s -S

  • -s 本地默认 1234 端口开启 gdb-server
  • -S 表示暂停执行等待 gdb 命令

一组 gdb 命令

1
2
3
4
5
6
b start_kernel # start_kernel 处设置断点
c # 继续执行
bt # 打印当前调用堆栈
list # 显示当前位置下附件的源码
next # 单步执行当前函数 不进入
step # 单步执行当前函数 进入函数

vscode

launch.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) linux",
"type": "cppdbg",
"request": "launch",
"preLaunchTask": "qemu",
"program": "${workspaceFolder}/uintr-linux-kernel/build/vmlinux",
"miDebuggerServerAddress": "localhost:1234",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerArgs": "-n",
"targetArchitecture": "x64",
"setupCommands": [
{
"text": "set arch i386:x86-64:intel",
"ignoreFailures": false
},
{
"text": "dir .",
"ignoreFailures": false
},
{
"text": "add-auto-load-safe-path ./",
"ignoreFailures": false
},
{
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}

tasks.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
"tasks": [
{
"label": "qemu",
"type": "shell",
"command": "./run.sh",
"presentation": {
"echo": true,
"clear": true,
"group": "vm"
},
"isBackground": true,
"problemMatcher": [
{
"pattern": [
{
"regexp": ".",
"file": 1,
"location": 2,
"message": 3
}
],
"background": {
"activeOnStart": true,
"beginsPattern": ".",
"endsPattern": ".",
}
}
]
}
],
"version": "2.0.0"
}

测试

  • /init/main.c -> start_kernel 打上断点, 启动 (gdb) linux 一切如常规程序调试.