如何在VSCode的launch.json中通过Bash命令动态配置调试地址?
问题
我的VS Code中launch.json包含如下调试配置:
{ "request": "launch", "type": "cortex-debug", "name": "Rt117xDemo Start", "cwd": "${workspaceFolder}", "executable": "${workspaceFolder}/FW/image/Rt117xDemo.elf", "servertype": "jlink", "device": "MIMXRT1176xxxA_M7", "interface": "swd", "rtos": "FreeRTOS", "svdFile": "${workspaceFolder}/FW/bsp/device/MIMXRT1175_cm7.svd", "runToEntryPoint": "main", "preLaunchTask": "build", "serverArgs": [ "-gui" ], "preLaunchCommands": [ "directory ${workspaceFolder}/FW" ], "postLaunchCommands": [ "monitor reg pc 0x30002100" ] }
我希望将postLaunchCommands中的固定地址0x30002100替换为Bash命令的输出,且每次启动调试(尤其是执行构建任务后)都自动运行该命令获取最新地址。
2023-06-23 更新
具体需要执行的Bash命令为从编译生成的ELF文件提取入口地址:
/path/to/arm-none-eabi-readelf -l ${workspaceFolder}/FW/image/Rt117xDemo.elf | sed -n 's/Entry point \(0x[[:xdigit:]]\{8\}\)/\1/p'
期望launch.json能写成类似如下形式:
"postLaunchCommands": [ "monitor reg pc ${command: 此处填入命令输出}" ]
解决方案
方法一:使用Command Variable扩展(推荐)
- 安装VS Code扩展:Command Variable(作者:rioj7)
- 修改
launch.json中的postLaunchCommands配置,注意JSON语法要求反斜杠需转义(\改为\\):
"postLaunchCommands": [ "monitor reg pc ${command:extension.commandvariable.shell.execute(/path/to/arm-none-eabi-readelf -l ${workspaceFolder}/FW/image/Rt117xDemo.elf | sed -n 's/Entry point \\(0x[[:xdigit:]]\\{8\\}\\)/\\1/p')}" ]
该配置会在每次启动调试时自动执行指定Bash命令,将输出结果直接替换到pc寄存器的赋值位置。
方法二:自定义任务+输入变量
- 在
.vscode/tasks.json中添加一个用于提取入口地址的任务:
{ "version": "2.0.0", "tasks": [ { "label": "fetch-entry-address", "type": "shell", "command": "/path/to/arm-none-eabi-readelf -l ${workspaceFolder}/FW/image/Rt117xDemo.elf | sed -n 's/Entry point \\(0x[[:xdigit:]]\\{8\\}\\)/\\1/p'", "problemMatcher": [], "presentation": { "echo": false, "reveal": "never" }, "outputCapture": "stdout" } ] }
- 在
launch.json中添加输入配置,并更新postLaunchCommands:
{ // 保留原有调试配置项... "inputs": [ { "id": "entryAddress", "type": "command", "command": "extension.commandvariable.task.output", "args": { "task": "fetch-entry-address", "line": 0, "trim": true } } ], "postLaunchCommands": [ "monitor reg pc ${input:entryAddress}" ] }
此方法通过先执行任务获取地址,再将任务输出作为变量传入调试命令,确保每次调试都能获取最新的入口地址。
内容的提问来源于stack exchange,提问作者mastupristi
相关产品推荐
相关产品推荐

