如何使用pyelftools/libdwarf查找一行代码

admin 2026-02-09 09:22:32

社区首页 >问答首页 >如何使用pyelftools/libdwarf查找一行代码问如何使用pyelftools/libdwarf查找一行代码ENStack Overflow用户提问于 2019-10-11 02:35:43回答 1查看 616关注 0票数 0我有一个函数名和一个距该函数顶部的偏移量。我知道我可以通过查看汇编清单文件找到代码行,并计算代码行的偏移量,然后以这种方式获得行号。

我正在尝试做的是使用.o文件来获取相同的信息。我可以看到ELF文件的DWARF信息,可以在DWARF数据中找到函数的骰子,但我如何真正看到该函数的指令信息并将其映射到一行代码。我一直在使用pyelftools,所以我希望能够使用它,但如果我不能使用pyelftools,我对其他选择持开放态度。

debuggingelfdwarfpyelftools关注问题分享EN回答 1推荐最新Stack Overflow用户发布于 2020-01-11 02:19:55

pyelftools中有一个示例可以做到这一点:https://github.com/eliben/pyelftools/blob/master/examples/dwarf_decode_address.py

具体来说,查找地址行的过程如下所示:

代码语言:javascript复制def decode_file_line(dwarfinfo, address):

# Go over all the line programs in the DWARF information, looking for

# one that describes the given address.

for CU in dwarfinfo.iter_CUs():

# First, look at line programs to find the file/line for the address

lineprog = dwarfinfo.line_program_for_CU(CU)

prevstate = None

for entry in lineprog.get_entries():

# We're interested in those entries where a new state is assigned

if entry.state is None:

continue

if entry.state.end_sequence:

# if the line number sequence ends, clear prevstate.

prevstate = None

continue

# Looking for a range of addresses in two consecutive states that

# contain the required address.

if prevstate and prevstate.address <= address < entry.state.address:

filename = lineprog['file_entry'][prevstate.file - 1].name

line = prevstate.line

return filename, line

prevstate = entry.state

return None, None收藏分享票数 1EN页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持原文链接:https://stackoverflow.com/questions/58329137

复制相关文章