Created
February 4, 2025 04:03
-
-
Save jarkkojs/1f64ab5b1c92deec7d75b23504f7d890 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
from elftools.elf.elffile import ELFFile | |
R_RISCV_ADD32 = 35 | |
R_RISCV_SUB32 = 39 | |
def main(): | |
if len(sys.argv) != 2: | |
sys.exit(1) | |
filename = sys.argv[1] | |
with open(filename, 'rb') as f: | |
elf_file = ELFFile(f) | |
relocs_map = {} | |
for sec in elf_file.iter_sections(): | |
if not hasattr(sec, 'iter_relocations'): | |
continue | |
symbol_table = None | |
if sec['sh_link']: | |
symbol_table = elf_file.get_section(sec['sh_link']) | |
for rel in sec.iter_relocations(): | |
r_type = rel['r_info_type'] | |
if r_type not in (R_RISCV_ADD32, R_RISCV_SUB32): | |
continue | |
addr = rel['r_offset'] | |
sym_val = 0 | |
if symbol_table: | |
sym = symbol_table.get_symbol(rel['r_info_sym']) | |
sym_val = sym['st_value'] | |
addend = rel['r_addend'] if 'r_addend' in rel.entry else 0 | |
relocs_map.setdefault(addr, []).append((r_type, sym_val, addend)) | |
for addr in sorted(relocs_map.keys()): | |
group = relocs_map[addr] | |
has_add = any(r_type == R_RISCV_ADD32 for r_type, _, _ in group) | |
has_sub = any(r_type == R_RISCV_SUB32 for r_type, _, _ in group) | |
if not (has_add and has_sub): | |
continue | |
add_sub_offset = sum(sym_val + addend for r_type, sym_val, addend in group if r_type == R_RISCV_ADD32) | |
add_sub_offset -= sum(sym_val + addend for r_type, sym_val, addend in group if r_type == R_RISCV_SUB32) | |
if add_sub_offset == 0: | |
continue | |
address_str = f"0x{addr:08x}" | |
print(f"{address_str:<16s} {add_sub_offset:<16d}") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment