#!/usr/bin/env python3 import argparse import os import struct from pathlib import Path ELF_HEADER_SIZE = 64 ELF_SECTION_SIZE = 64 ELF_MACHINE_X86_64 = 62 ELF_SECTION_RELA = 4 ELF_RELA_SIZE = 24 ORBIS_GOTPCREL = 40 STANDARD_GOTPCREL = 9 class ElfFormatError(ValueError): pass def _validate_elf(data: bytes) -> tuple[int, int, int]: if len(data) < ELF_HEADER_SIZE or data[:5] != b"\x7fELF\x02": raise ElfFormatError("expected an ELF64 object") if data[5] != 1: raise ElfFormatError("expected a little-endian ELF object") if struct.unpack_from(" len(data): raise ElfFormatError("ELF section headers extend outside the file") return section_offset, section_entry_size, section_count def _relocation_replacements(data: bytes) -> tuple[tuple[int, int], ...]: section_offset, section_entry_size, section_count = _validate_elf(data) replacements: list[tuple[int, int]] = [] for section_index in range(section_count): header_offset = section_offset + section_index * section_entry_size if struct.unpack_from(" len(data): raise ElfFormatError("ELF relocation section extends outside the file") for entry_offset in range( relocation_offset, relocation_offset + relocation_size, ELF_RELA_SIZE ): info_offset = entry_offset + 8 info = struct.unpack_from(" tuple[bytes, int]: replacements = _relocation_replacements(data) chunks: list[bytes] = [] previous_offset = 0 for info_offset, info in replacements: chunks.extend((data[previous_offset:info_offset], struct.pack(" tuple[int, int]: if not input_directory.is_dir(): raise FileNotFoundError(f"input directory does not exist: {input_directory}") if input_directory.resolve() == output_directory.resolve(): raise ValueError("input and output directories must differ") files = tuple(path for path in sorted(input_directory.iterdir()) if path.is_file()) output_directory.mkdir(parents=True, exist_ok=True) relocation_count = 0 for source in files: patched, count = patch_elf(source.read_bytes()) destination = output_directory / source.name destination.write_bytes(patched) os.chmod(destination, source.stat().st_mode) relocation_count += count return len(files), relocation_count def main() -> int: parser = argparse.ArgumentParser( description="normalize Sony Orbis x86-64 GOTPCREL relocations for LLVM tools" ) parser.add_argument("input_directory", type=Path) parser.add_argument("output_directory", type=Path) args = parser.parse_args() file_count, relocation_count = patch_directory( args.input_directory, args.output_directory ) print(f"patched {relocation_count} relocations across {file_count} objects") return 0 if __name__ == "__main__": raise SystemExit(main())