aorecomp

Anarchy Online classic in the browser

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


tools/client/export_standalone_data.py (5346B)


      1 """One-time extraction of source initializers; normal builds need no game PEs."""
      2 
      3 import hashlib
      4 import json
      5 import pathlib
      6 import struct
      7 
      8 import pefile
      9 
     10 import standalone_text_data
     11 
     12 
     13 root = pathlib.Path(__file__).resolve().parents[2]
     14 directory = root / "client/data"
     15 directory.mkdir(exist_ok=True)
     16 scope = json.loads((root / "client/scope.json").read_text())
     17 audit = []
     18 handlers = {}
     19 initializers = []
     20 
     21 for module in scope["game"]:
     22     source = root / "local/client/game-14.9.1/images" / module["name"]
     23     pe = pefile.PE(str(source))
     24     assert pe.OPTIONAL_HEADER.ImageBase == module["base"]
     25     text_ranges, module_handlers, text_audit = standalone_text_data.extract(
     26         pe, root / "client/game" / module["name"])
     27     assert not text_audit["unresolved"], module["name"]
     28     assert not text_audit["code_outside_executable_sections"], module["name"]
     29     handlers.update(module_handlers)
     30 
     31     # Recreate only the PE metadata needed by imports, exports and Win32 resources.
     32     # The DOS program/stub and the original instructions are never copied.
     33     nt_offset = pe.DOS_HEADER.e_lfanew
     34     header_end = nt_offset + 24 + pe.FILE_HEADER.SizeOfOptionalHeader + 40 * len(pe.sections)
     35     header = bytearray(header_end)
     36     struct.pack_into("<H", header, 0, 0x5A4D)
     37     struct.pack_into("<I", header, 0x3C, nt_offset)
     38     header[nt_offset:] = pe.__data__[nt_offset:header_end]
     39     struct.pack_into("<II", header, nt_offset + 12, 0, 0)
     40     for index in (4, 5, 6, 11):
     41         struct.pack_into("<II", header, nt_offset + 24 + 96 + index * 8, 0, 0)
     42     for index, section in enumerate(pe.sections):
     43         offset = nt_offset + 24 + pe.FILE_HEADER.SizeOfOptionalHeader + index * 40
     44         struct.pack_into("<II", header, offset + 16, 0, 0)
     45         struct.pack_into("<I", header, offset + 36, section.Characteristics & ~0x20000020)
     46     ranges = [(0, bytes(header))]
     47     sections = []
     48     for section in pe.sections:
     49         name = section.Name.rstrip(b"\0").decode("ascii")
     50         if section.Characteristics & 0x20000020 or name in (".reloc", ".debug", ".bind"):
     51             continue
     52         data = section.get_data()[:section.Misc_VirtualSize].rstrip(b"\0")
     53         if data:
     54             ranges.append((section.VirtualAddress, data))
     55             sections.append({"name": name, "rva": section.VirtualAddress, "bytes": len(data)})
     56     ranges.extend(text_ranges)
     57 
     58     # Keep each module's initial values beside its generated C implementation.
     59     symbol = module["name"].replace(".", "_")
     60     lines = ['#include "guest_memory.h"', '#include <stdlib.h>', '#include <string.h>', '']
     61     for index, (rva, data) in enumerate(ranges):
     62         lines.append(f"/* Initial data at RVA 0x{rva:X}. */")
     63         lines.append(f"static const unsigned char data_{index}[] = {{")
     64         for offset in range(0, len(data), 16):
     65             lines.append("    " + ",".join(f"0x{byte:02x}" for byte in data[offset:offset + 16]) + ",")
     66         lines.extend(["};", ""])
     67     lines.append(f"void game_data_{symbol}(void) {{")
     68     lines.append(f'    if (!guest_map("{module["name"]}", 0x{module["base"]:08X}u, '
     69                  f'0x{pe.OPTIONAL_HEADER.SizeOfImage:X}u)) abort();')
     70     for index, (rva, data) in enumerate(ranges):
     71         lines.append(f"    memcpy((void *)guest_address(0x{module['base'] + rva:08X}u), data_{index}, sizeof(data_{index}));")
     72     lines.extend(["}", ""])
     73     (directory / f"{symbol}.c").write_text("\n".join(lines), encoding="ascii")
     74     initializers.append(f"game_data_{symbol}")
     75     audit.append({"module": module["name"], "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
     76                   "base": module["base"], "span": pe.OPTIONAL_HEADER.SizeOfImage,
     77                   "code_sections": [{"rva": section.VirtualAddress, "bytes": section.Misc_VirtualSize}
     78                                     for section in pe.sections if section.Characteristics & 0x20000020],
     79                   "data_bytes": sum(len(data) for rva, data in ranges),
     80                   "sections": sections, "text_data": text_audit})
     81     pe.close()
     82     print(f'{module["name"]}: {audit[-1]["data_bytes"]} data bytes', flush=True)
     83 
     84 # Exception handlers use source metadata rather than decoding original stubs.
     85 lines = ['#include "game-data.h"', '']
     86 lines.extend(f"void {name}(void);" for name in initializers)
     87 lines.extend(['', 'void game_data_init(void) {'])
     88 lines.extend(f"    {name}();" for name in initializers)
     89 lines.extend(['}', '', 'static const struct { uint32_t handler, info; } handlers[] = {'])
     90 lines.extend(f"    {{0x{handler:08X}u, 0x{info:08X}u}}," for handler, info in sorted(handlers.items()))
     91 lines.extend(['};', '', 'uint32_t game_funcinfo(uint32_t handler) {',
     92     '    unsigned lo = 0, hi = sizeof(handlers) / sizeof(handlers[0]);',
     93     '    while (lo < hi) {', '        unsigned mid = lo + (hi - lo) / 2;',
     94     '        if (handlers[mid].handler == handler) return handlers[mid].info;',
     95     '        if (handlers[mid].handler < handler) lo = mid + 1; else hi = mid;',
     96     '    }', '    return 0;', '}', ''])
     97 (directory / "game-data.c").write_text("\n".join(lines), encoding="ascii")
     98 (directory / "game-data.h").write_text(
     99     '#pragma once\n#include <stdint.h>\nvoid game_data_init(void);\nuint32_t game_funcinfo(uint32_t handler);\n',
    100     encoding="ascii")
    101 (directory / "extraction.json").write_text(json.dumps(audit, indent=2) + "\n")