1

我有一个函数名和该函数顶部的偏移量。我知道我可以通过查看汇编列表文件找到代码行并计算代码行的偏移量并以这种方式获取行号。

我想要做的是使用 .o 文件来获取相同的信息。我可以看到 ELF 文件的 DWARF 信息,并且可以在 DWARF 数据中找到函数的 DIE,但是我如何实际查看该函数的指令信息并将其映射到一行代码。我一直在使用 pyelftools,所以我希望能够使用它,但如果我不能使用 pyelftools,我愿意接受其他选择。

4

1 回答 1

2

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

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

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
于 2020-01-10T18:19:55.257 回答