You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用dwarf.exp运行基础DWARF调试示例?

手动添加DWARF调试信息入门示例解决方案

前置依赖安装

首先确保安装DejaGNU测试框架及编译工具:

sudo apt-get install dejagnu gcc make

编写example.exp调试脚本

dwarf.exp是GDB测试套件的Tcl工具,需通过DejaGNU环境调用,以下是实现局部变量foo(值为3)调试信息的脚本:

# example.exp
load_lib dwarf.exp

set testfile "main"
set srcfile ${testfile}.c
set binfile ${objdir}/${testfile}

# 编译无调试信息的可执行文件
if { [gdb_compile "${srcdir}/${srcfile}" "${binfile}" executable {debug}] != "" } {
    untested "编译失败"
    return -1
}

# 生成DWARF调试信息汇编代码
set asm_file [standard_output_file ${testfile}-dwarf.s]
Dwarf::assemble $asm_file {
    cu {} {
        DW_TAG_compile_unit {
            DW_AT_language @DW_LANG_C
            DW_AT_name     "main.c"
            DW_AT_comp_dir "$srcdir"
        } {
            DW_TAG_subprogram {
                DW_AT_name     "main"
                DW_AT_low_pc   0x0 ;# 替换为实际main函数起始地址(用objdump -d main查看)
                DW_AT_high_pc  0x10 ;# 替换为实际main函数结束地址
                DW_AT_type     @int_type
            } {
                DW_TAG_variable {
                    DW_AT_name     "foo"
                    DW_AT_type     @int_type
                    DW_AT_location {DW_OP_constu 3 DW_OP_stack_value} ;# 硬编码值为3
                }
            }
            DW_TAG_base_type {
                DW_AT_name     "int"
                DW_AT_encoding @DW_ATE_signed
                DW_AT_byte_size 4
            } -> int_type
        }
    }
}

# 编译DWARF汇编为目标文件并合并到原可执行文件
if { [gdb_compile "${asm_file}" "${binfile}-dwarf.o" object {nodebug}] != "" } {
    untested "DWARF目标文件编译失败"
    return -1
}
exec ld -r "${binfile}" "${binfile}-dwarf.o" -o "${binfile}-with-dwarf"

# GDB验证调试信息
gdb_exit
gdb_start
gdb_reinitialize_dir $srcdir
gdb_load ${binfile}-with-dwarf

gdb_test "print foo" "= 3" "验证局部变量foo的值"

准备配套main.c

创建最简无调试信息的主程序:

// main.c
int main() {
    int foo = 3;
    return 0;
}

运行测试与验证

  1. 执行脚本生成带手动DWARF信息的可执行文件:
runtest --tool gdb example.exp
  1. 若脚本执行成功,可直接用GDB验证:
gdb main-with-dwarf
(gdb) print foo
$1 = 3

关键注意事项

  • 必须用runtest运行脚本:dwarf.exp依赖DejaGNU测试框架,无法单独执行
  • 修正地址范围:脚本中DW_AT_low_pc和DW_AT_high_pc需替换为objdump -d main输出的main函数实际起始/结束地址
  • 链接方式:用ld -r执行重定位链接,确保DWARF信息正确合并到原可执行文件

内容的提问来源于stack exchange,提问作者nostromo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 09:33:10