aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


tools/client/build_game.py (12708B)


      1 """Translate Clientr and its game DLLs into C and compile their dispatch set."""
      2 
      3 import concurrent.futures
      4 import hashlib
      5 import json
      6 import pathlib
      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 work = root / "local/client/game-14.9.1"
     16 client = root / "anarchy-vanilla-14.9.1"
     17 work.mkdir(exist_ok=True)
     18 (work / "images").mkdir(exist_ok=True)
     19 sys.path.insert(0, str(upstream))
     20 from tools.lift import translator, generate
     21 import game_eh
     22 
     23 
     24 class GameDisassembler(translator.Disassembler):
     25     def disassemble_at(self, va, max_bytes=4096):
     26         bounds = self.code_section_bounds(va)
     27         if bounds is not None:
     28             yield from super().disassemble_at(va, min(max_bytes, bounds[1] - va))
     29 
     30 
     31 def write_dispatch(entries, objects):
     32     (work / "dispatch.c").write_text('#include "recomp_types.h"\n' +
     33         "".join(f"void {name}(void);\n" for address, name in sorted(entries)) +
     34         "const recomp_dispatch_entry_t recomp_dispatch_table[] = {\n" +
     35         "".join(f"    {{0x{address:08X}u, {name}}},\n" for address, name in sorted(entries)) +
     36         "};\n" + f"const uint32_t recomp_dispatch_count = {len(entries)};\n", encoding="ascii")
     37     (work / "objects.rsp").write_text("\n".join('"' + obj.replace("\\", "/") + '"'
     38                                                  for obj in objects), encoding="ascii")
     39 
     40 
     41 # These are identified third-party products, rather than game implementation.
     42 vendors = {
     43     "ace.dll": "ACE", "aced.dll": "ACE", "acemfc.dll": "ACE",
     44     "ctreestd.dll": "FairCom", "dsetup.dll": "Microsoft DirectX",
     45     "dxdiag.exe": "Microsoft DirectX", "intro.exe": "RAD Bink/Smacker",
     46     "mfc42.dll": "Microsoft runtime", "msvcp60.dll": "Microsoft runtime",
     47     "msvcp60d.dll": "Microsoft runtime", "msvcrtd.dll": "Microsoft runtime",
     48     "mss32.dll": "Miles Sound System", "patchw32.dll": "Patch library",
     49 }
     50 inventory = json.loads((work / "inventory.json").read_text())
     51 modules = sorted(inventory["modules"], key=lambda module: module["path"].lower())
     52 scope = []
     53 excluded_executables = []
     54 image_index = 0
     55 for module in modules:
     56     source = client / module["path"]
     57     assert hashlib.sha256(source.read_bytes()).hexdigest() == module["sha256"]
     58     if source.name.lower() in vendors:
     59         continue
     60     # Inventory slots keep DLL addresses stable when separate executables are excluded.
     61     base = 0x20000000 + image_index * 0x01000000
     62     image_index += 1
     63     if source.suffix.lower() == ".exe" and source.name.lower() != "clientr.exe":
     64         excluded_executables.append(source.name)
     65         continue
     66     # Parse only relocations: pefile's ImportData.address setter rewrites ILT
     67     # name RVAs when relocate_image updates already-parsed import addresses.
     68     pe = pefile.PE(str(source), fast_load=True)
     69     pe.parse_data_directories(directories=[5])
     70     if pe.OPTIONAL_HEADER.DATA_DIRECTORY[5].Size:
     71         pe.relocate_image(base)
     72         pe.OPTIONAL_HEADER.ImageBase = base
     73     else:
     74         base = pe.OPTIONAL_HEADER.ImageBase
     75     pe.write(str(work / "images" / source.name))
     76     original = pefile.PE(str(source))
     77     rebased = pefile.PE(str(work / "images" / source.name))
     78     assert [(dll.dll, [(entry.name, entry.ordinal) for entry in dll.imports])
     79             for dll in original.DIRECTORY_ENTRY_IMPORT] == [
     80                 (dll.dll, [(entry.name, entry.ordinal) for entry in dll.imports])
     81                 for dll in rebased.DIRECTORY_ENTRY_IMPORT]
     82     scope.append({"name": source.name, "sha256": module["sha256"],
     83                   "base": base, "entry": base + pe.OPTIONAL_HEADER.AddressOfEntryPoint,
     84                   "dll": bool(pe.FILE_HEADER.Characteristics & 0x2000)})
     85 (work / "scope.json").write_text(json.dumps({"game": scope, "vendors": vendors,
     86     "excluded_executables": excluded_executables}, indent=2))
     87 
     88 # Every game DLL is mapped before imports are resolved.
     89 (work / "game-modules.h").write_text(
     90     "static const struct { const char *name; uint32_t base, entry; } game_modules[] = {\n" +
     91     "".join(f'    {{"{module["name"]}", 0x{module["base"]:08X}u, '
     92             f'0x{module["entry"]:08X}u}},\n' for module in scope) +
     93     "};\nstatic const int game_module_count = sizeof(game_modules) / sizeof(game_modules[0]);\n",
     94     encoding="ascii")
     95 compiler = root / "toolchains/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe"
     96 report = []
     97 client_entries = []
     98 client_objects = []
     99 fingerprint = hashlib.sha256(pathlib.Path(__file__).read_bytes())
    100 fingerprint.update(pathlib.Path(game_eh.__file__).read_bytes())
    101 for directory in ("tools/lift", "tools/disasm", "tools/pe", "runtime/recomp32"):
    102     for source in sorted((upstream / directory).iterdir()):
    103         if source.suffix in (".py", ".h"):
    104             fingerprint.update(source.read_bytes())
    105 fingerprint.update(str(compiler.stat().st_mtime_ns).encode())
    106 pipeline_hash = fingerprint.hexdigest()
    107 
    108 
    109 def compile_batch(directory, filename, batch):
    110     source = directory / filename
    111     code = header + "\n\n".join(batch)
    112     obj = source.with_suffix(".o")
    113     command = [str(compiler), "-O2", "-fno-strict-aliasing", "-fms-extensions",
    114                "-I", str(upstream / "runtime/recomp32"), "-c", str(source), "-o", str(obj)]
    115     fingerprint = hashlib.sha256((code + repr(command) + str(compiler.stat().st_mtime_ns)).encode())
    116     for header_path in sorted((upstream / "runtime/recomp32").glob("*.h")):
    117         fingerprint.update(header_path.read_bytes())
    118     stamp = source.with_suffix(".sha256")
    119     if obj.exists() and stamp.exists() and stamp.read_text() == fingerprint.hexdigest():
    120         return str(obj)
    121 
    122     # Each compiler owns its source, object and diagnostic log.
    123     source.write_text(code, encoding="ascii")
    124     result = subprocess.run(command, capture_output=True, text=True)
    125     source.with_suffix(".log").write_text(result.stdout + result.stderr)
    126     if result.returncode:
    127         print(result.stderr, flush=True)
    128     result.check_returncode()
    129     stamp.write_text(fingerprint.hexdigest())
    130     return str(obj)
    131 
    132 
    133 # Compile smallest inputs first for early runtime probes.
    134 for module in sorted(scope, key=lambda module: (client / module["name"]).stat().st_size):
    135     directory = work / module["name"]
    136     directory.mkdir(exist_ok=True)
    137     stamp = directory / "completed.json"
    138     if stamp.exists():
    139         cached = json.loads(stamp.read_text())
    140         if (cached["pipeline"] == pipeline_hash and cached["input"] == module["sha256"]
    141                 and all(pathlib.Path(obj).exists() for obj in cached["objects"])):
    142             report.append(cached["report"])
    143             client_entries.extend(json.loads((directory / "functions.json").read_text()))
    144             client_objects.extend(cached["objects"])
    145             write_dispatch(client_entries, client_objects)
    146             (work / "translation.json").write_text(json.dumps(report, indent=2))
    147             print(f'REUSED {module["name"]}', flush=True)
    148             continue
    149     info, data, imports = translator.load_pe(str(work / "images" / module["name"]))
    150     # Exclude proven alignment padding and stop each decode at its code section.
    151     # Keep non-padding raw tails, since Windows can execute code placed there.
    152     for section in info.sections:
    153         if section.is_code and 0 < section.virtual_size < section.raw_size:
    154             padding = data[section.raw_offset + section.virtual_size:
    155                            section.raw_offset + section.raw_size]
    156             if all(byte in (0, 0x90, 0xCC) for byte in padding):
    157                 section.raw_size = section.virtual_size
    158     info.code_end = max(info.image_base + section.va_end for section in info.sections
    159                         if section.is_code and section.name != ".bind")
    160     disassembler = GameDisassembler(data, info.image_base, info.sections)
    161     seeds = {module["entry"]} | {info.image_base + export.rva for export in info.exports
    162                                 if info.code_start <= info.image_base + export.rva < info.code_end}
    163     functions = disassembler.find_functions(info.code_start, info.code_end, imports, seeds=seeds)
    164 
    165     # Raw E8 scans can mistake an instruction displacement for a CALL target.
    166     # Use decoded instructions reachable from real roots to disprove such starts.
    167     trusted = set()
    168     pending = list(seeds)
    169     while pending:
    170         address = pending.pop()
    171         if address in functions and address not in trusted:
    172             trusted.add(address)
    173             pending.extend(functions[address].calls_to)
    174     interior = bytearray(info.code_end - info.code_start)
    175     for address in trusted:
    176         for block in functions[address].blocks.values():
    177             for instruction in block.instructions:
    178                 offset = instruction.address - info.code_start
    179                 interior[offset + 1:offset + instruction.size] = b"\1" * (instruction.size - 1)
    180     discarded = [address for address in functions if address not in trusted
    181                  and interior[address - info.code_start]]
    182     for address in discarded:
    183         del functions[address]
    184     (directory / "discarded-interior-entries.json").write_text(json.dumps(discarded))
    185     print(f"Removed {len(discarded)} untrusted entries inside trusted instructions", flush=True)
    186     lifter = translator.Lifter(iat_map=imports, lifted=set())
    187     entries = []
    188     unsupported = []
    189     objects = []
    190     chunks = []
    191     instructions_count = 0
    192     for address, function in sorted(functions.items()):
    193         instructions = {instruction.address: instruction for block in function.blocks.values()
    194                         for instruction in block.instructions}
    195         leaders = set(function.blocks)
    196         resumes = game_eh.add_exception_resumes(disassembler, address, functions, instructions, leaders)
    197         instructions = [instructions[key] for key in sorted(instructions)]
    198         assert all(disassembler.is_code_address(instruction.address) and
    199                    instruction.end_address <= disassembler.code_section_bounds(instruction.address)[1]
    200                    for instruction in instructions)
    201         instructions_count += len(instructions)
    202         code = generate.lift_function_linear(lifter, f"sub_{address:08X}", instructions,
    203                                              leaders, address, eh_resume=resumes)
    204         # Unsupported instructions must fail visibly if reached, never act as NOPs.
    205         lines = []
    206         for line in code.splitlines():
    207             if "UNIMPLEMENTED:" in line:
    208                 unsupported.append({"function": address, "instruction": line.strip()})
    209                 line = '    fprintf(stderr, "%s\\n", ' + json.dumps(line.strip()) + '); abort();'
    210             lines.append(line)
    211         chunks.append("\n".join(lines))
    212         entries.append((address, f"sub_{address:08X}"))
    213     (directory / "functions.json").write_text(json.dumps(entries))
    214     (directory / "unsupported.json").write_text(json.dumps(unsupported, indent=2))
    215 
    216     # Keep ordinary filenames stable, splitting only oversized hundred-function batches.
    217     header = ('#define RECOMP_GENERATED_CODE\n#include "recomp_types.h"\n'
    218               '#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n'
    219               '#include <string.h>\n\n')
    220     batches = []
    221     for offset in range(0, len(chunks), 100):
    222         parts = [[]]
    223         size = len(header)
    224         for body in chunks[offset:offset + 100]:
    225             if parts[-1] and size + len(body) + 2 > 16 * 1024 * 1024:
    226                 parts.append([])
    227                 size = len(header)
    228             parts[-1].append(body)
    229             size += len(body) + 2
    230         for index, part in enumerate(parts):
    231             suffix = f"-{index:02d}" if len(parts) > 1 else ""
    232             batches.append((f"lifted-{offset // 100:04d}{suffix}.c", part))
    233     with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
    234         jobs = [pool.submit(compile_batch, directory, filename, batch) for filename, batch in batches]
    235         objects = [job.result() for job in jobs]
    236     report.append({"name": module["name"], "functions": len(entries),
    237                    "instructions": instructions_count, "unsupported": len(unsupported),
    238                    "objects": len(objects)})
    239     (work / "translation.json").write_text(json.dumps(report, indent=2))
    240     client_entries.extend(entries)
    241     client_objects.extend(objects)
    242     write_dispatch(client_entries, client_objects)
    243     (directory / "completed.json").write_text(json.dumps({
    244         "pipeline": pipeline_hash, "input": module["sha256"],
    245         "report": report[-1], "objects": objects}, indent=2))
    246     print(f'COMPILED {module["name"]}: {len(entries)} functions, '
    247           f'{len(unsupported)} unsupported instructions', flush=True)
    248