aorecomp

Anarchy Online classic in the browser

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


tools/client/native32_probe.py (10961B)


      1 """Build and run native32's selftest with the available 32-bit LLVM compiler."""
      2 
      3 import pathlib
      4 import subprocess
      5 
      6 
      7 root = pathlib.Path(__file__).resolve().parents[2]
      8 upstream = root / "local/references/reconstruction-reference/pcrecomp/runtime"
      9 work = root / "local/client/native32"
     10 work.mkdir(exist_ok=True)
     11 
     12 # Clang's x86 Windows target supports the MS assembly used by this runtime.
     13 source = (upstream / "native32/native32.c").read_text()
     14 guard = '#if !defined(_MSC_VER) || !defined(_M_IX86)'
     15 assert source.count(guard) == 1
     16 source = source.replace(guard, '#if !defined(_WIN32) || !defined(__i386__)')
     17 source = source.replace('#include <windows.h>', '#include <windows.h>\n#include <intrin.h>')
     18 
     19 # All game modules must stay non-executable, including embedded code in data.
     20 assert source.count('#define MAX_MODULES 32') == 1
     21 source = source.replace('#define MAX_MODULES 32', '#define MAX_MODULES 38')
     22 assert source.count('#define BRIDGE_SLOTS 24') == 1
     23 source = source.replace('#define BRIDGE_SLOTS 24', '''/* ccr.dll!InputConfig_t::CreateHotkey (0x10003260) passes 31 DWORD
     24  * arguments to sscanf. A 32-word area preserves native stack alignment. */
     25 #define BRIDGE_SLOTS 32''')
     26 start = source.index('/* A call into a guest module outside its code sections:')
     27 end = source.index('static int cmp_u32', start)
     28 source = source[:start] + source[end:]
     29 start = source.index('int native32_set_native(uint32_t base) {')
     30 end = source.index('int native32_in_guest', start)
     31 source = source[:start] + '''int native32_set_native(uint32_t base) {
     32     fprintf(stderr, "[native32] original machine code forbidden at 0x%08X\\n", base);
     33     exit(3);
     34 }
     35 
     36 ''' + source[end:]
     37 fallback = 'if (native32_in_guest(va) && !native_module_at(va) && !data_section_code(va)) return NULL;'
     38 assert source.count(fallback) == 1
     39 source = source.replace(fallback, '''if (native32_in_guest(va)) {
     40         fprintf(stderr, "[native32] unlifted guest target 0x%08X from 0x%08X\\n", va, g_cur_func);
     41         exit(3);
     42     }''')
     43 start = source.index('    IMAGE_NT_HEADERS32* nt', source.index('uint32_t native32_map('))
     44 end = source.index('    return span;', start)
     45 source = source[:start] + '''    DWORD old;
     46     if (!VirtualProtect((void*)(uintptr_t)base, span, PAGE_READWRITE, &old)) {
     47         fprintf(stderr, "[native32] cannot make mapped image non-executable\\n");
     48         exit(3);
     49     }
     50 ''' + source[end:]
     51 source = source.replace('SetProcessDEPPolicy(PROCESS_DEP_ENABLE);', '''SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
     52     DWORD dep_flags;
     53     BOOL dep_permanent;
     54     if (!GetProcessDEPPolicy(GetCurrentProcess(), &dep_flags, &dep_permanent) ||
     55         !(dep_flags & PROCESS_DEP_ENABLE)) {
     56         fprintf(stderr, "[native32] process DEP is required\\n");
     57         exit(3);
     58     }''')
     59 
     60 # MSVCRT!_EH_prolog changes its caller's stack/frame and SEH chain, so it cannot
     61 # use an ordinary native-call bridge. Match the helper's x86 instruction effects.
     62 marker = "static native32_shim_t g_builtin[] = {"
     63 assert source.count(marker) == 1
     64 source = source.replace(marker, '''void native32_shim_EH_prolog(void) {
     65     PUSH32(g_esp, 0xFFFFFFFFu);
     66     PUSH32(g_esp, g_eax);
     67     g_eax = MEM32(g_fs_base);
     68     PUSH32(g_esp, g_eax);
     69     g_eax = MEM32(g_esp + 12);
     70     MEM32(g_fs_base) = g_esp;
     71     MEM32(g_esp + 12) = g_ebp;
     72     g_ebp = g_esp + 12;
     73     PUSH32(g_esp, g_eax);
     74     g_esp += 4;
     75 }
     76 
     77 ''' + marker + '\n    { "_EH_prolog", native32_shim_EH_prolog },')
     78 (work / "native32.c").write_text(source, encoding="ascii")
     79 
     80 # The GNU target cannot emit the selftest's MSVC lexical SEH frame. Observe the
     81 # same forwarded Windows exception with VEH instead of removing its assertion.
     82 test = (upstream / "native32/native32_selftest.c").read_text()
     83 test = test.replace("static int fails;", """static int fails;
     84 static int raised;
     85 static LONG CALLBACK exception_probe(EXCEPTION_POINTERS *ep) {
     86     if (ep->ExceptionRecord->ExceptionCode != 0xE0001234u)
     87         return EXCEPTION_CONTINUE_SEARCH;
     88     raised = 1;
     89     return EXCEPTION_CONTINUE_EXECUTION;
     90 }""")
     91 test = test.replace("int raised = 0;", "raised = 0;")
     92 test = test.replace("""__try { call((void*)(uintptr_t)slot, 4, args, &after); }
     93             __except (GetExceptionCode() == 0xE0001234u) { raised = 1; }""", """PVOID handler = AddVectoredExceptionHandler(1, exception_probe);
     94             call((void*)(uintptr_t)slot, 4, args, &after);
     95             RemoveVectoredExceptionHandler(handler);""")
     96 assert "__try {" not in test
     97 (work / "native32_selftest.c").write_text(test, encoding="ascii")
     98 
     99 # Compile copied runtime sources; keep the pinned upstream checkout untouched.
    100 compiler = root / "toolchains/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe"
    101 command = [str(compiler), "-O2", "-fms-extensions",
    102            "-I", str(upstream / "native32"), "-I", str(upstream / "recomp32"),
    103            str(work / "native32_selftest.c"), str(work / "native32.c"),
    104            str(upstream / "recomp32/image_loader.c"),
    105            str(upstream / "recomp32/recomp_trace.c"),
    106            "-o", str(work / "native32-selftest.exe")]
    107 result = subprocess.run(command, capture_output=True, text=True)
    108 (work / "build.log").write_text(subprocess.list2cmdline(command) + "\n" +
    109                                result.stdout + result.stderr, encoding="utf-8")
    110 print(result.stdout + result.stderr, end="")
    111 result.check_returncode()
    112 
    113 # Compare the special CRT frame-builder against its native register ABI.
    114 eh_command = command.copy()
    115 eh_command[eh_command.index(str(work / "native32_selftest.c"))] = str(
    116     root / "tools/client/eh_prolog_test.c")
    117 eh_command[-1] = str(work / "eh-prolog-test.exe")
    118 result = subprocess.run(eh_command, capture_output=True, text=True)
    119 (work / "eh-prolog-build.log").write_text(subprocess.list2cmdline(eh_command) + "\n" +
    120                                          result.stdout + result.stderr, encoding="utf-8")
    121 result.check_returncode()
    122 result = subprocess.run([str(work / "eh-prolog-test.exe")], capture_output=True, text=True, timeout=30)
    123 (work / "eh-prolog-test.log").write_text(result.stdout + result.stderr +
    124                                         f"\nExit: {result.returncode}\n", encoding="utf-8")
    125 print(result.stdout + result.stderr, end="")
    126 result.check_returncode()
    127 
    128 # The loader fixture uses hr's original image as non-executable data; its only
    129 # executable entry is a test C body, independent of the bulk game translation.
    130 (work / "game-modules.h").write_text('''static const struct {
    131     const char *name;
    132     uint32_t base, entry;
    133 } game_modules[] = {
    134     {"hr.dll", 0x10000000u, 0x100012e1u},
    135     {"bbr.dll", 0x20000000u, 0x20123999u},
    136     {"dr.dll", 0x21000000u, 0x21001c6bu}
    137 };
    138 static const int game_module_count = 3;
    139 ''', encoding="ascii")
    140 host_command = [str(compiler), "-O2", "-fms-extensions",
    141                 "-I", str(work), "-I", str(upstream / "native32"),
    142                 "-I", str(upstream / "recomp32"),
    143                 str(root / "tools/client/game_host_test.c"),
    144                 str(work / "native32.c"),
    145                 str(upstream / "recomp32/image_loader.c"),
    146                 str(upstream / "recomp32/recomp_trace.c"),
    147                 "-o", str(work / "game-host-test.exe")]
    148 result = subprocess.run(host_command, capture_output=True, text=True)
    149 (work / "game-host-build.log").write_text(subprocess.list2cmdline(host_command) + "\n" +
    150                                          result.stdout + result.stderr, encoding="utf-8")
    151 result.check_returncode()
    152 result = subprocess.run([str(work / "game-host-test.exe")], cwd=root,
    153                         capture_output=True, text=True, timeout=30)
    154 (work / "game-host-test.log").write_text(result.stdout + result.stderr +
    155                                        f"\nExit: {result.returncode}\n", encoding="utf-8")
    156 print(result.stdout + result.stderr, end="")
    157 result.check_returncode()
    158 assert "exception code=" not in result.stderr
    159 result = subprocess.run([str(work / "game-host-test.exe"), "fault-diagnostic"], cwd=root,
    160                         capture_output=True, text=True, timeout=30)
    161 (work / "game-host-fault.log").write_text(result.stdout + result.stderr, encoding="utf-8")
    162 result.check_returncode()
    163 assert "access=write address=deadbeef" in result.stderr
    164 assert "func=11223344" in result.stderr and "esp=deaddead" in result.stderr
    165 assert "game-host-test.exe base=" in result.stderr and "native eax=55667788" in result.stderr
    166 result = subprocess.run([str(work / "game-host-test.exe"), "debug-output"], cwd=root,
    167                         capture_output=True, text=True, timeout=30)
    168 (work / "game-host-debug-output.log").write_text(result.stdout + result.stderr, encoding="utf-8")
    169 result.check_returncode()
    170 assert "[game-debug] resource fixture diagnostic" in result.stderr
    171 assert "exception code=" not in result.stderr
    172 result = subprocess.run([str(work / "game-host-test.exe"), "module-factory"], cwd=root,
    173                         capture_output=True, text=True, timeout=30)
    174 (work / "game-host-module-factory.log").write_text(result.stdout + result.stderr +
    175                                                 f"\nExit: {result.returncode}\n", encoding="utf-8")
    176 result.check_returncode()
    177 
    178 # Exercise native-to-guest callback entry and explicit refusal of original code.
    179 for operation in ("create", "shell", "spawn", "exec", "system", "vendor-other-path", "vendor"):
    180     result = subprocess.run([str(work / "game-host-test.exe"), operation], cwd=root,
    181                             capture_output=True, text=True, timeout=30)
    182     (work / ("game-host-refuse-" + operation + ".log")).write_text(
    183         result.stdout + result.stderr + f"\nExit: {result.returncode}\n", encoding="utf-8")
    184     assert result.returncode == (0 if operation == "vendor" else 3), result.returncode
    185 
    186 command[command.index(str(work / "native32_selftest.c"))] = str(
    187     root / "tools/client/native32_probe.c")
    188 command[-1] = str(work / "native32-probe.exe")
    189 result = subprocess.run(command, capture_output=True, text=True)
    190 (work / "probe-build.log").write_text(subprocess.list2cmdline(command) + "\n" +
    191                                      result.stdout + result.stderr, encoding="utf-8")
    192 result.check_returncode()
    193 for arguments, expected in [([], 0), (["unknown-data"], 3), (["enable-original"], 3)]:
    194     result = subprocess.run([str(work / "native32-probe.exe"), *arguments],
    195                             capture_output=True, text=True, timeout=30)
    196     (work / ("probe-" + (arguments[0] if arguments else "callbacks") + ".log")).write_text(
    197         result.stdout + result.stderr + f"\nExit: {result.returncode}\n", encoding="utf-8")
    198     print(result.stdout + result.stderr, end="")
    199     assert result.returncode == expected, result.returncode
    200 result = subprocess.run([str(work / "native32-selftest.exe")],
    201                         capture_output=True, text=True, timeout=30)
    202 (work / "selftest.log").write_text(result.stdout + result.stderr +
    203                                   f"\nExit: {result.returncode}\n", encoding="utf-8")
    204 print(result.stdout + result.stderr, end="")
    205 result.check_returncode()