pythonelfpyelftools

Grabbing program header information with pyelftools


I am simply trying to grab the program header information with pyelftools (the offset, virtual address, and physical address).

This can be done from the terminal by running:

readelf -l <elf_file>

But I am having trouble getting the same information from pyelftools. From the examples, I have pieced together this:

elffile = ELFFile(stream)
section_header = elffile.structs.Elf_Shdr.parse_stream(stream)
print (section_header)

Note: Elf_Shdr is the program header file.

This will print the offset, virtual address, physical address, etc. But not in the hexadecimal format I want, or like how readelf prints it. Is there a way to get it to print out the hex format like readelf?


Solution

  • Some strange things in your post happen.

    You say:

    I am simply trying to grab the program header information with pyelftools (the offset, virtual address, and physical address).

    Note: Elf_Shdr is the program header file.

    But Elf_Shdr is not Program header, it is Section header. Look at elftools/elf/structs.py

    Elf_Shdr:
                    Section header
    

    Then in your code you parse file twice by some reason. First string is enough to parse it, you can access all header data from elffile object:

    for segment in elffile.iter_segments():
        header = segment.header
        for key, value in header.items():
            if isinstance(value, int):
                print(key, hex(value))
    

    Here I iterate over all segments (they are described by Program headers) of ELF file, then iterate over all attributes in header and print them as hex if it is integer. No magic here, header is just Container for standard dictionary.

    Also you may be interested in readelf implemented with pyelftools - here.