tools/client/generate_vendor.py (9691B)
1 """Translate vendor libraries while preserving guest layouts and ABI.""" 2 3 import hashlib 4 import json 5 import pathlib 6 import struct 7 import subprocess 8 import sys 9 10 import pefile 11 12 13 root = pathlib.Path(__file__).resolve().parents[2] 14 upstream = root / "local/references/reconstruction-reference/pcrecomp" 15 sys.path.insert(0, str(upstream)) 16 from tools.lift import translator, generate 17 import game_eh 18 import standalone_text_data 19 20 21 class VendorDisassembler(translator.Disassembler): 22 def disassemble_at(self, va, max_bytes=4096): 23 bounds = self.code_section_bounds(va) 24 if bounds is not None: 25 yield from super().disassemble_at(va, min(max_bytes, bounds[1] - va)) 26 27 28 def generate_vendor(filename, symbol, base, expected_hash): 29 # Stage generated output separately; never overwrite edited source files. 30 directory = root / "local/client" / f"linux-{symbol}" 31 source_directory = directory / "src" 32 assert not source_directory.exists(), f"Generated sources already exist: {source_directory}" 33 source_directory.mkdir(parents=True) 34 source = root / "anarchy-runtime-14.9.1" / filename 35 source_hash = hashlib.sha256(source.read_bytes()).hexdigest() 36 assert source_hash == expected_hash 37 pe = pefile.PE(str(source), fast_load=True) 38 pe.parse_data_directories(directories=[5]) 39 pe.relocate_image(base) 40 pe.OPTIONAL_HEADER.ImageBase = base 41 pe.write(str(directory / filename)) 42 pe.close() 43 44 # Use the same bounded discovery and exception continuation recovery as the game. 45 info, data, imports = translator.load_pe(str(directory / filename)) 46 for section in info.sections: 47 if section.is_code and 0 < section.virtual_size < section.raw_size: 48 padding = data[section.raw_offset + section.virtual_size:section.raw_offset + section.raw_size] 49 if all(byte in (0, 0x90, 0xcc) for byte in padding): 50 section.raw_size = section.virtual_size 51 info.code_end = max(info.image_base + section.va_end for section in info.sections 52 if section.is_code and section.name != ".bind") 53 disassembler = VendorDisassembler(data, info.image_base, info.sections) 54 pe = pefile.PE(str(directory / filename)) 55 entry = info.image_base + pe.OPTIONAL_HEADER.AddressOfEntryPoint 56 seeds = {entry} | {info.image_base + export.rva for export in info.exports 57 if info.code_start <= info.image_base + export.rva < info.code_end} 58 functions = disassembler.find_functions(info.code_start, info.code_end, imports, seeds=seeds) 59 trusted = set() 60 pending = list(seeds) 61 while pending: 62 address = pending.pop() 63 if address in functions and address not in trusted: 64 trusted.add(address) 65 pending.extend(functions[address].calls_to) 66 interior = bytearray(info.code_end - info.code_start) 67 for address in trusted: 68 for block in functions[address].blocks.values(): 69 for instruction in block.instructions: 70 offset = instruction.address - info.code_start 71 interior[offset + 1:offset + instruction.size] = b"\1" * (instruction.size - 1) 72 discarded = [address for address in functions if address not in trusted 73 and interior[address - info.code_start]] 74 for address in discarded: 75 del functions[address] 76 77 # Preserve unsupported instructions as explicit failures, not silent no-ops. 78 lifter = translator.Lifter(iat_map=imports, lifted=set()) 79 entries, chunks, unsupported = [], [], [] 80 for address, function in sorted(functions.items()): 81 instructions = {instruction.address: instruction for block in function.blocks.values() 82 for instruction in block.instructions} 83 leaders = set(function.blocks) 84 resumes = game_eh.add_exception_resumes(disassembler, address, functions, instructions, leaders) 85 instructions = [instructions[key] for key in sorted(instructions)] 86 code = generate.lift_function_linear(lifter, f"sub_{address:08X}", instructions, 87 leaders, address, eh_resume=resumes) 88 lines = [] 89 for line in code.splitlines(): 90 if "UNIMPLEMENTED:" in line: 91 unsupported.append({"function": address, "instruction": line.strip()}) 92 line = ' fprintf(stderr, "%s\\n", ' + json.dumps(line.strip()) + '); abort();' 93 lines.append(line) 94 chunks.append("\n".join(lines)) 95 entries.append((address, f"sub_{address:08X}")) 96 header = '#define RECOMP_GENERATED_CODE\n#include "recomp_types.h"\n\n' 97 for offset in range(0, len(chunks), 100): 98 (source_directory / f"lifted-{offset // 100:04d}.c").write_text( 99 header + "\n\n".join(chunks[offset:offset + 100]), encoding="ascii") 100 # Record both the upstream revision and local generator sources used by this run. 101 pipeline = [pathlib.Path(__file__), root / "tools/client" / f"generate_{symbol}.py", pathlib.Path(game_eh.__file__), pathlib.Path(standalone_text_data.__file__)] 102 for folder in ("tools/lift", "tools/disasm", "tools/pe"): 103 pipeline.extend(sorted((upstream / folder).glob("*.py"))) 104 pipeline_hash = hashlib.sha256() 105 for path in pipeline: 106 pipeline_hash.update(path.relative_to(root).as_posix().encode("ascii")) 107 pipeline_hash.update(path.read_bytes()) 108 (directory / "translation.json").write_text(json.dumps({ 109 "source_sha256": source_hash, "base": info.image_base, "entry": entry, 110 "pcrecomp_commit": subprocess.check_output([ 111 "git", "-c", f"safe.directory={upstream.as_posix()}", "-C", str(upstream), 112 "rev-parse", "HEAD"], text=True).strip(), 113 "pipeline_sha256": pipeline_hash.hexdigest(), 114 "functions": len(entries), "discarded_interior_entries": discarded, 115 "unsupported": unsupported}, indent=2), encoding="ascii") 116 117 # Keep only classified data and minimal import/export metadata, never executable bytes. 118 text_ranges, handlers, audit = standalone_text_data.extract(pe, source_directory) 119 (directory / "data-audit.json").write_text(json.dumps(audit, indent=2), encoding="ascii") 120 assert not audit["unresolved"], "Unresolved executable-section data; inspect data-audit.json" 121 assert not audit["code_outside_executable_sections"] 122 nt = pe.DOS_HEADER.e_lfanew 123 header_end = nt + 24 + pe.FILE_HEADER.SizeOfOptionalHeader + 40 * len(pe.sections) 124 metadata = bytearray(header_end) 125 struct.pack_into("<H", metadata, 0, 0x5a4d) 126 struct.pack_into("<I", metadata, 0x3c, nt) 127 metadata[nt:] = pe.__data__[nt:header_end] 128 struct.pack_into("<II", metadata, nt + 12, 0, 0) 129 for index in (4, 5, 6, 11): 130 struct.pack_into("<II", metadata, nt + 24 + 96 + index * 8, 0, 0) 131 for index, section in enumerate(pe.sections): 132 offset = nt + 24 + pe.FILE_HEADER.SizeOfOptionalHeader + index * 40 133 struct.pack_into("<II", metadata, offset + 16, 0, 0) 134 struct.pack_into("<I", metadata, offset + 36, section.Characteristics & ~0x20000020) 135 ranges = [(0, bytes(metadata))] 136 for section in pe.sections: 137 if section.Characteristics & 0x20000020 or section.Name.rstrip(b"\0") in (b".reloc", b".debug", b".bind"): 138 continue 139 payload = section.get_data()[:section.Misc_VirtualSize].rstrip(b"\0") 140 if payload: 141 ranges.append((section.VirtualAddress, payload)) 142 ranges.extend(text_ranges) 143 lines = ['#include "guest_memory.h"', '#include <stdlib.h>', '#include <string.h>', ''] 144 for index, (rva, payload) in enumerate(ranges): 145 lines.append(f"static const unsigned char data_{index}[] = {{") 146 for offset in range(0, len(payload), 16): 147 lines.append(" " + ",".join(f"0x{byte:02x}" for byte in payload[offset:offset + 16]) + ",") 148 lines.extend(["};", ""]) 149 lines.extend([f'void {symbol}_data_init(void) {{', 150 f' if (!guest_map("{filename}", 0x{base:08x}u, 0x{pe.OPTIONAL_HEADER.SizeOfImage:x}u)) abort();']) 151 for index, (rva, payload) in enumerate(ranges): 152 lines.append(f" memcpy((void *)guest_address(0x{info.image_base + rva:08x}u), data_{index}, sizeof(data_{index}));") 153 lines.append("}") 154 (source_directory / "data.c").write_text("\n".join(lines) + "\n", encoding="ascii") 155 156 # Separate dispatch and exception metadata let the Linux host add this library. 157 lines = ['#include "recomp_types.h"'] 158 lines.extend(f"void {name}(void);" for address, name in entries) 159 lines.append(f"const recomp_dispatch_entry_t {symbol}_dispatch[] = {{") 160 lines.extend(f" {{0x{address:08x}u, {name}}}," for address, name in entries) 161 lines.extend(["};", f"const uint32_t {symbol}_dispatch_count = {len(entries)};", 162 f"uint32_t {symbol}_funcinfo(uint32_t handler) {{", " switch (handler) {"]) 163 lines.extend(f" case 0x{handler:08x}u: return 0x{value:08x}u;" for handler, value in sorted(handlers.items())) 164 lines.extend([" default: return 0;", " }", "}"]) 165 (source_directory / "dispatch.c").write_text("\n".join(lines) + "\n", encoding="ascii") 166 (source_directory / "module.h").write_text( 167 '#pragma once\n#include "recomp_types.h"\n' 168 f'void {symbol}_data_init(void);\nuint32_t {symbol}_funcinfo(uint32_t handler);\n' 169 f'extern const recomp_dispatch_entry_t {symbol}_dispatch[];\n' 170 f'extern const uint32_t {symbol}_dispatch_count;\n' 171 f'#define {symbol.upper()}_ENTRY 0x{entry:08x}u\n', encoding="ascii") 172 print(f"Generated {filename}: {len(entries)} functions, {len(unsupported)} unsupported instructions, entry={entry:08x}")