遇到的问题
使用 VSCode/Eclipse 调试过程中无法定位源码位置
原因分析
笔者的源码存放在 Windows 系统中,而编译过程则通过虚拟机中的 Ubuntu 完成。源码通过共享路径从 Windows 传递给 Ubuntu。由于 Windows 和 Ubuntu 的文件系统路径格式不同,Ubuntu 编译生成的 ELF 文件中记录的源文件路径与 Windows 上的实际路径不一致。这导致在使用 GDB 进行调试时,源文件路径映射失败。
解决办法
通过gdb工具修改源文件映射路径
通过 <(gdb) set substitute-path 编译路径 新路径> 规则调整 launch.json 文件下:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug @ Windows",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}\\rtthread.elf",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"miDebuggerServerAddress": "localhost:1234",
"serverLaunchTimeout": 2000,
"targetArchitecture": "ARM",
"MIMode": "gdb",
"miDebuggerPath": "D:\\Program Files\\Bouffalo\\toolchain\\toolchain_gcc_t-head_windows\\bin\\riscv64-unknown-elf-gdb.exe",
"customLaunchSetupCommands": [],
"launchCompleteCommand": "exec-run",
"setupCommands": [
{
"description": "Set source path substitution for debugging",
"text": "set substitute-path /mnt/hgfs/ d:/"
},
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
},
]
}
通过在 GDB 中添加命令 “set substitute-path /mnt/hgfs/ d:/”,将路径 /mnt/hgfs/ 替换为 d:/,从而正确调整了源文件的映射关系。这样,调试过程中 GDB 就能正确找到源文件的路径。
如果不知道源文件的路径,可在gdb终端中通过如下方式查看:
(gdb) dir ./main
通过ide修改源文件映射路径
在 VSCode 中,对于 C/C++ 语言类型的 ELF 文件,不支持直接修改路径映射。然而,Eclipse 则支持这一功能。
- 通过 Debug Configurations 找到如下配置:
- 添加文件映射路径转换规则,如下:
也可以实现与 GDB 工具处理相同的路径映射效果。
总结
在大多数 GDB 调试场景中,推荐使用方式 1 进行源文件路径的映射,因为方式 2 依赖于所使用的 IDE 必须具备路径映射功能支持。