1

How can I apply relocations of symbols in an elffile? I'm currently trying to archive this with pyelftools. Strangely, I could hardly find any information on how to do this, although some projects have to implement something like this (e.g. ida, angr, amoco, ...).

In other words: I want to know where elf imports will be located in virtual memory. Of course, the sections should adhere to these relocations.

Code snippets very appreciated.

0

So after some toying around with elftools, I found the following solution for import-symbols:

    for section in self._elf.iter_sections():
        if not isinstance(section, RelocationSection):
            continue
    symtable = self._elf.get_section(section['sh_link'])
    for relocation in section.iter_relocations():
        if not relocation['r_info_sym']:
            continue
        symbol = symtable.get_symbol(relocation['r_info_sym'])
        yield ImportSymbol(relocation['r_offset'], symbol.name)

The code is inspired by pyelftools readelf implementation

Although pyelftools offers some relocation handling, I've not yet seen a binary for which that actually works. It will complain it doesn't know some relocation types, but for the future, I'll post this snippet:

def _reloc_section(self, section):
    rh = RelocationHandler(self._elf)
    data = section.data()
    relocation_section = rh.find_relocations_for_section(section)
    if relocation_section:
        try:
            rh.apply_section_relocations(data, relocation_section)
        except Exception as e:
            print 'Could not relocate %s' % section.name
    return data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.