aorecomp

Anarchy Online classic in the browser

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


client/runtime/native32.c (25947B)


      1 /*
      2  * native32: see native32.h for the model. Extracted from gunman's
      3  * client/runtime/runtime.c, which is where each of the non-obvious details below
      4  * was found the hard way; the comments say which.
      5  */
      6 #define WIN32_LEAN_AND_MEAN
      7 #define _CRT_SECURE_NO_WARNINGS
      8 #include <windows.h>
      9 #include <intrin.h>
     10 #include <stdio.h>
     11 #include <string.h>
     12 #include "native32.h"
     13 #include "recomp_trace.h"
     14 
     15 #if !defined(_WIN32) || !defined(__i386__)
     16 #error "native32 is MSVC x86 only: the bridge and the callback trampoline are inline asm"
     17 #endif
     18 
     19 int native32_trace_native, native32_trace_callbacks;
     20 
     21 typedef struct {
     22     uint32_t eax, ecx, edx, esp, ebx, esi, edi, ebp, fs, cur;
     23     double   st[8];
     24     int      fp_top;
     25     uint16_t fpu_cw;
     26     uint64_t mm[8];
     27     xmm_t    xmm[8];
     28     uint32_t mxcsr;
     29 } regs_t;
     30 
     31 static void regs_save(regs_t* r) {
     32     r->eax = g_eax; r->ecx = g_ecx; r->edx = g_edx; r->esp = g_esp;
     33     r->ebx = g_ebx; r->esi = g_esi; r->edi = g_edi; r->ebp = g_ebp;
     34     r->fs = g_fs_base; r->cur = g_cur_func;
     35     memcpy(r->st, g_st, sizeof g_st); r->fp_top = g_fp_top; r->fpu_cw = g_fpu_cw;
     36     memcpy(r->mm, g_mm, sizeof g_mm);
     37     memcpy(r->xmm, g_xmm, sizeof g_xmm); r->mxcsr = g_mxcsr;
     38 }
     39 
     40 static void regs_load(const regs_t* r) {
     41     g_eax = r->eax; g_ecx = r->ecx; g_edx = r->edx; g_esp = r->esp;
     42     g_ebx = r->ebx; g_esi = r->esi; g_edi = r->edi; g_ebp = r->ebp;
     43     g_fs_base = r->fs; g_cur_func = r->cur;
     44     memcpy(g_st, r->st, sizeof g_st); g_fp_top = r->fp_top; g_fpu_cw = r->fpu_cw;
     45     memcpy(g_mm, r->mm, sizeof g_mm);
     46     memcpy(g_xmm, r->xmm, sizeof g_xmm); g_mxcsr = r->mxcsr;
     47 }
     48 
     49 /* ------------------------------------------------------------- machine lock */
     50 
     51 static CRITICAL_SECTION g_mach;
     52 static DWORD g_mach_tls = TLS_OUT_OF_INDEXES;
     53 
     54 /* Argument slots copied per call. Reading past a callee's real arguments is
     55  * harmless while those words are mapped (mach_enter leaves room); CreateFontA
     56  * (14) is the widest common Win32 call. */
     57 /* ccr.dll!InputConfig_t::CreateHotkey (0x10003260) passes 31 DWORD
     58  * arguments to sscanf. A 32-word area preserves native stack alignment. */
     59 #define BRIDGE_SLOTS 32
     60 
     61 #define GUEST_STACK (4u << 20)
     62 
     63 /* A guest thread's TIB. Lifted code reads fs:[n] as MEM32(g_fs_base + n); the
     64  * real TEB stays the host's, so a guest SEH frame never lands on a chain
     65  * Windows walks. The PEB is the real one: code that reads fs:[30h] wants it. */
     66 static uint32_t make_tib(uint32_t lo, uint32_t hi) {
     67     uint32_t* t = (uint32_t*)VirtualAlloc(NULL, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
     68     t[0] = 0xFFFFFFFFu;                          /* ExceptionList: end of chain */
     69     t[1] = hi;                                   /* StackBase                   */
     70     t[2] = lo;                                   /* StackLimit                  */
     71     t[0x18 / 4] = (uint32_t)(uintptr_t)t;        /* Self                        */
     72     t[0x24 / 4] = GetCurrentThreadId();
     73     t[0x30 / 4] = __readfsdword(0x30);
     74     return (uint32_t)(uintptr_t)t;
     75 }
     76 
     77 typedef struct { regs_t r; int depth; } mstate;
     78 
     79 /* Nests: a callback that arrives while this thread is inside a native call
     80  * claims again, and only the outermost claim loads the saved state. */
     81 void mach_enter(void) {
     82     EnterCriticalSection(&g_mach);
     83     mstate* m = (mstate*)TlsGetValue(g_mach_tls);
     84     if (!m) {
     85         /* Stack left for a fault handler after an overflow: without it the
     86          * report itself overflows and the process just vanishes. */
     87         ULONG guarantee = 64 * 1024;
     88         SetThreadStackGuarantee(&guarantee);
     89         m = (mstate*)calloc(1, sizeof *m);
     90         uint32_t lo = (uint32_t)(uintptr_t)VirtualAlloc(NULL, GUEST_STACK,
     91                           MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
     92         /* The bridge copies BRIDGE_SLOTS words up from esp whatever the
     93          * callee takes, so the first call made from an empty stack must not
     94          * read off the end of it. With 64 bytes of headroom it did, and faulted
     95          * whenever ASLR left the next page unmapped: the selftest crashed on
     96          * about two runs in three. */
     97         m->r.esp = lo + GUEST_STACK - BRIDGE_SLOTS * 4 - 64;
     98         m->r.fs = make_tib(lo, lo + GUEST_STACK);
     99         m->r.fpu_cw = 0x027F;
    100         m->r.mxcsr = 0x1F80;              /* exceptions masked, round to nearest */
    101         TlsSetValue(g_mach_tls, m);
    102     }
    103     if (m->depth++ == 0) regs_load(&m->r);
    104 }
    105 
    106 void mach_leave(void) {
    107     mstate* m = (mstate*)TlsGetValue(g_mach_tls);
    108     if (--m->depth == 0) regs_save(&m->r);
    109     LeaveCriticalSection(&g_mach);
    110 }
    111 
    112 /* RECOMP_BACKEDGE's hand-over: let another guest thread take the machine.
    113  * Only the outermost claim can give it up; inside a callback the lock is
    114  * still held further out, and the loop simply runs on. */
    115 static void native32_yield(void) {
    116     mstate* m = (mstate*)TlsGetValue(g_mach_tls);
    117     if (!m || m->depth != 1) return;
    118     mach_leave();
    119     SwitchToThread();
    120     mach_enter();
    121 }
    122 
    123 /* ---------------------------------------------------------------- modules */
    124 
    125 #define MAX_MODULES 38
    126 static struct { uint32_t base, span; char name[MAX_PATH]; } g_mods[MAX_MODULES];
    127 static int g_mod_n;
    128 
    129 static recomp_func_t dispatch_find(uint32_t va);
    130 
    131 int native32_in_guest(uint32_t va) {
    132     for (int i = 0; i < g_mod_n; i++)
    133         if (va >= g_mods[i].base && va < g_mods[i].base + g_mods[i].span) return 1;
    134     return 0;
    135 }
    136 
    137 /* Allocate only zero-filled data and callback-address space. */
    138 uint32_t guest_map(const char* name, uint32_t base, uint32_t span) {
    139     if (g_mod_n == MAX_MODULES) return 0;
    140     void* data = VirtualAlloc((void*)(uintptr_t)base, span,
    141                              MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
    142     if (!data) return 0;
    143     g_mods[g_mod_n].base = base;
    144     g_mods[g_mod_n].span = span;
    145     strncpy(g_mods[g_mod_n++].name, name, MAX_PATH - 1);
    146     return span;
    147 }
    148 
    149 uint32_t native32_module(const char* name) {
    150     const char* file = strrchr(name, '\\');
    151     file = file ? file + 1 : name;
    152     for (int i = 0; i < g_mod_n; i++)
    153         if (!_stricmp(g_mods[i].name, file)) return g_mods[i].base;
    154     return 0;
    155 }
    156 
    157 /* GetProcAddress over a mapped guest image: a name, or an ordinal below
    158  * 0x10000. Forwarders are not followed; no guest module has needed one. */
    159 uint32_t native32_export(uint32_t base, const char* name) {
    160     uint8_t* b = (uint8_t*)(uintptr_t)base;
    161     IMAGE_NT_HEADERS32* nt = (IMAGE_NT_HEADERS32*)(b + ((IMAGE_DOS_HEADER*)b)->e_lfanew);
    162     IMAGE_DATA_DIRECTORY dd = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
    163     if (!dd.VirtualAddress) return 0;
    164     IMAGE_EXPORT_DIRECTORY* e = (IMAGE_EXPORT_DIRECTORY*)(b + dd.VirtualAddress);
    165     uint32_t* funcs = (uint32_t*)(b + e->AddressOfFunctions);
    166     uint32_t* names = (uint32_t*)(b + e->AddressOfNames);
    167     uint16_t* ords = (uint16_t*)(b + e->AddressOfNameOrdinals);
    168     uint32_t idx = 0xFFFFFFFFu;
    169     if ((uintptr_t)name < 0x10000) idx = (uint32_t)(uintptr_t)name - e->Base;
    170     else
    171         for (uint32_t i = 0; i < e->NumberOfNames; i++)
    172             if (!strcmp((const char*)(b + names[i]), name)) { idx = ords[i]; break; }
    173     return idx < e->NumberOfFunctions && funcs[idx] ? base + funcs[idx] : 0;
    174 }
    175 
    176 /* ---------------------------------------------------------------- names */
    177 
    178 #define MAX_NAMES 4096
    179 static struct { uint32_t va; char name[60]; } g_names[MAX_NAMES];
    180 static int g_name_n;
    181 
    182 const char* native32_name(uint32_t va) {
    183     for (int i = 0; i < g_name_n; i++)
    184         if (g_names[i].va == va) return g_names[i].name;
    185     return NULL;
    186 }
    187 
    188 static void add_name(uint32_t va, const char* dll, const char* fn) {
    189     if (g_name_n < MAX_NAMES && !native32_name(va)) {
    190         _snprintf(g_names[g_name_n].name, sizeof g_names[0].name - 1, "%s!%s", dll, fn);
    191         g_names[g_name_n++].va = va;
    192     }
    193 }
    194 
    195 /* ------------------------------------------------------- guest -> Windows */
    196 
    197 static uint32_t g_native_target;
    198 
    199 /* Synthetic VAs for hand shims: a reserved, never-committed range, so no real
    200  * code or data can share an address with one. */
    201 static uint32_t g_shim_page;
    202 static native32_shim_t* g_shims;
    203 static int g_nshims;
    204 #define IS_SHIM_VA(va) (g_shim_page && (va) >= g_shim_page && (va) < g_shim_page + 0x10000u)
    205 
    206 static void native_bridge(void) {
    207     /* The guest's last error, as the previous native call left it: the trace
    208      * below and mach_leave's TlsGetValue would reset it before this call. */
    209     DWORD guest_error = GetLastError();
    210     uint32_t fn = g_native_target;
    211     uint32_t* src = (uint32_t*)(uintptr_t)(g_esp + 4);   /* past the dummy ret */
    212     uint32_t this_ecx = g_ecx, r_eax, r_edx, purge;
    213     uint16_t sw0, sw1;
    214     double r_st = 0;
    215     const char* saved_import = g_cur_import;
    216     if (native32_trace_native) {
    217         const char* n = native32_name(fn);
    218         fprintf(stderr, "[native] %-32s (%08X %08X %08X %08X) from sub_%08X",
    219                 n ? n : "?", src[0], src[1], src[2], src[3], g_cur_func);
    220         if (!n) fprintf(stderr, " @%08X", fn);
    221         for (int k = 0; k < 4; k++) {       /* arguments that are strings (gunman) */
    222             MEMORY_BASIC_INFORMATION mbi;
    223             const char* p = (const char*)(uintptr_t)src[k];
    224             if (src[k] < 0x10000 || !VirtualQuery(p, &mbi, sizeof mbi) ||
    225                 mbi.State != MEM_COMMIT || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)))
    226                 continue;
    227             size_t room = (size_t)((const char*)mbi.BaseAddress + mbi.RegionSize - p), len = 0;
    228             while (len < room && len < 96 && p[len] >= 0x20 && p[len] < 0x7F) len++;
    229             if (len >= 3 && (len == room || len == 96 || !p[len]))
    230                 fprintf(stderr, " a%d=\"%.*s\"", k, (int)len, p);
    231         }
    232     }
    233     g_cur_import = native32_name(fn);
    234     if (!g_cur_import) g_cur_import = "(native)";
    235     mach_leave();
    236     SetLastError(guest_error);
    237     /* The locals are reached through whatever base register the compiler
    238      * chose, and the asm must leave it alone. MSVC uses ebp; clang-cl uses
    239      * esi (its x86 base pointer, for a frame it realigns), so the old
    240      * `mov esi, src` for rep movsd cut the frame off and the next local read
    241      * was garbage: the first native call jumped to 0 (KotOR, clang-cl). So:
    242      * no esi or ebp, every input in a register before esp moves, and the
    243      * arguments copied by pushes, highest slot first.
    244      *
    245      * Nor does the callee have to keep the C ABI. It is usually Windows, but
    246      * it can be the guest's own hand-written asm, run natively because no lift
    247      * can hold it (code in a data section, a native module), and that was
    248      * only ever called from inline asm that saved everything: UT's Fire.dll
    249      * returns with ebx and ebp changed. So ebp, esi and ebx are saved on the
    250      * stack, and the esp anchor is kept in this thread's TEB
    251      * (ArbitraryUserPointer, fs:[0x14], its old value saved and put back, so a
    252      * nested bridge through a callback unwinds in order). */
    253     __asm {
    254         fnstsw ax
    255         mov  sw0, ax             ; x87 TOP before
    256         mov  edx, src
    257         mov  eax, fn
    258         mov  edi, this_ecx
    259         push ebp
    260         push esi
    261         push ebx
    262         push dword ptr fs:[0x14]
    263         mov  ecx, BRIDGE_SLOTS
    264     copy_args:
    265         push dword ptr [edx + ecx * 4 - 4]
    266         dec  ecx
    267         jnz  copy_args
    268         mov  fs:[0x14], esp      ; the anchor: survives any callee
    269         mov  ecx, edi            ; thiscall / COM 'this'
    270         call eax
    271         mov  ecx, esp
    272         mov  esp, fs:[0x14]
    273         sub  ecx, esp            ; bytes the callee popped
    274         add  esp, BRIDGE_SLOTS * 4
    275         pop  dword ptr fs:[0x14]
    276         pop  ebx
    277         pop  esi
    278         pop  ebp                 ; the frame is reachable again
    279         mov  r_eax, eax
    280         mov  r_edx, edx
    281         mov  purge, ecx
    282         fxam                     ; C3..C0 classify st(0)
    283         fnstsw ax
    284         mov  sw1, ax             ; x87 TOP after
    285     }
    286     /* A float result comes back in st(0): TOP moved down by exactly one and
    287      * st(0) is not empty. A native fninit/_fpreset also moves TOP; without the
    288      * fxam check that read as a returned float and pushed junk onto the lifted
    289      * stack (gunman: every later frame rendered NaNs). */
    290     int st_ret = (((sw0 >> 11) - (sw1 >> 11)) & 7) == 1 && (sw1 & 0x4100) != 0x4100;
    291     if (st_ret) __asm fstp r_st
    292     /* The callee's last error belongs to the guest, but mach_enter's
    293      * TlsGetValue resets it to 0 (TlsGetValue always does), and so does
    294      * stdio. A guest that loops on FindNextFileA until GetLastError() says
    295      * ERROR_NO_MORE_FILES then never stopped (KotOR's resource scan): the
    296      * value has to survive both ways across the bridge, into GetLastError
    297      * itself and back out of FindNextFileA. */
    298     DWORD last_error = GetLastError();
    299     mach_enter();
    300     if (st_ret) fp_push_impl(g_st, &g_fp_top, r_st);
    301     g_cur_import = saved_import;
    302     g_eax = r_eax;
    303     g_edx = r_edx;
    304     g_esp += 4 + purge;
    305     if (native32_trace_native) fprintf(stderr, " -> %08X\n", r_eax);
    306     SetLastError(last_error);
    307 }
    308 
    309 static recomp_func_t dispatch_find(uint32_t va) {
    310     uint32_t lo = 0, hi = recomp_dispatch_count;
    311     while (lo < hi) {
    312         uint32_t mid = lo + (hi - lo) / 2, m = recomp_dispatch_table[mid].address;
    313         if (m == va) return recomp_dispatch_table[mid].func;
    314         if (m < va) lo = mid + 1; else hi = mid;
    315     }
    316     return NULL;
    317 }
    318 
    319 recomp_func_t recomp_lookup(uint32_t va) {
    320     return dispatch_find(va);
    321 }
    322 
    323 /* Anything that is neither a shim nor inside a guest module is native: an
    324  * import, a GetProcAddress result, a COM method. */
    325 recomp_func_t recomp_lookup_import(uint32_t va) {
    326     if (IS_SHIM_VA(va)) {
    327         for (int i = 0; i < g_nshims; i++)
    328             if (g_shims[i].va == va) return g_shims[i].fn;
    329         return NULL;
    330     }
    331     if (va < 0x10000u) return NULL;
    332     if (native32_in_guest(va)) {
    333         fprintf(stderr, "[native32] unlifted guest target 0x%08X from 0x%08X\n", va, g_cur_func);
    334         exit(3);
    335     }
    336     g_native_target = va;
    337     return native_bridge;
    338 }
    339 
    340 /* Built-in shims every host gets, ahead of its own.
    341  *
    342  * CreateThread: the thread runs LIFTED code on its native stack, and a lifted
    343  * function's frame is several times the original's (register locals, flag
    344  * state, the C compiler's own spills), so the size the original asked for is
    345  * far too small. The Movies' worker threads overflowed theirs, and with no
    346  * stack left even the fault report died. Reserve 16 MB (committed on demand). */
    347 #define GUEST_THREAD_STACK (16u << 20)
    348 static void shim_CreateThread(void) {
    349     uint32_t* a = (uint32_t*)(uintptr_t)(g_esp + 4);
    350     SIZE_T size = a[1] > GUEST_THREAD_STACK ? a[1] : GUEST_THREAD_STACK;
    351     HANDLE h = CreateThread((LPSECURITY_ATTRIBUTES)(uintptr_t)a[0], size,
    352                             (LPTHREAD_START_ROUTINE)(uintptr_t)a[2], (LPVOID)(uintptr_t)a[3],
    353                             a[4] | STACK_SIZE_PARAM_IS_A_RESERVATION, (LPDWORD)(uintptr_t)a[5]);
    354     g_eax = (uint32_t)(uintptr_t)h;
    355     g_esp += 4 + 6 * 4;
    356 }
    357 
    358 /* RaiseException(0x406D1388): MSVC's SetThreadName, which only an attached
    359  * debugger is meant to see. The guest wraps it in
    360  *     __try { RaiseException(0x406D1388, ...); } __except (EXCEPTION_EXECUTE_HANDLER) {}
    361  * but its __try frame is on the guest's SEH chain, which Windows never walks
    362  * (eh32.c handles C++ frames only), so the exception went unhandled and ended
    363  * the process with that code: Tiberium Wars, naming its first worker thread.
    364  * Returning is what the empty __except does. Any other code is raised for real. */
    365 static void shim_RaiseException(void) {
    366     uint32_t* a = (uint32_t*)(uintptr_t)(g_esp + 4);
    367     if (a[0] != 0x406D1388u)
    368         RaiseException(a[0], a[1], a[2], (const ULONG_PTR*)(uintptr_t)a[3]);
    369     g_esp += 4 + 4 * 4;
    370 }
    371 
    372 /* _CxxThrowException: a guest throw is dispatched over the guest's own
    373  * frames (eh32.c), so the guest's catch blocks run. */
    374 void native32_shim_CxxThrowException(void);
    375 
    376 /* msvcrt helpers that take their arguments on the x87 stack (x87crt.c): the
    377  * bridge passes stack arguments only, and the lifted FPU stack is g_st. */
    378 #define X87CRT(n) void native32_shim_##n(void);
    379 X87CRT(ftol) X87CRT(CIsqrt) X87CRT(CIsin) X87CRT(CIcos) X87CRT(CItan) X87CRT(CIasin)
    380 X87CRT(CIacos) X87CRT(CIatan) X87CRT(CIexp) X87CRT(CIlog) X87CRT(CIlog10) X87CRT(CIsinh)
    381 X87CRT(CIcosh) X87CRT(CItanh) X87CRT(CIpow) X87CRT(CIfmod) X87CRT(CIatan2)
    382 X87CRT(controlfp) X87CRT(control87)
    383 
    384 void native32_shim_EH_prolog(void) {
    385     PUSH32(g_esp, 0xFFFFFFFFu);
    386     PUSH32(g_esp, g_eax);
    387     g_eax = MEM32(g_fs_base);
    388     PUSH32(g_esp, g_eax);
    389     g_eax = MEM32(g_esp + 12);
    390     MEM32(g_fs_base) = g_esp;
    391     MEM32(g_esp + 12) = g_ebp;
    392     g_ebp = g_esp + 12;
    393     PUSH32(g_esp, g_eax);
    394     g_esp += 4;
    395 }
    396 
    397 static native32_shim_t g_builtin[] = {
    398     { "_EH_prolog", native32_shim_EH_prolog },
    399     { "CreateThread", shim_CreateThread },
    400     { "RaiseException", shim_RaiseException },
    401     { "_CxxThrowException", native32_shim_CxxThrowException },
    402     { "_ftol", native32_shim_ftol },
    403     { "_CIsqrt", native32_shim_CIsqrt }, { "_CIsin", native32_shim_CIsin },
    404     { "_CIcos", native32_shim_CIcos }, { "_CItan", native32_shim_CItan },
    405     { "_CIasin", native32_shim_CIasin }, { "_CIacos", native32_shim_CIacos },
    406     { "_CIatan", native32_shim_CIatan }, { "_CIexp", native32_shim_CIexp },
    407     { "_CIlog", native32_shim_CIlog }, { "_CIlog10", native32_shim_CIlog10 },
    408     { "_CIsinh", native32_shim_CIsinh }, { "_CIcosh", native32_shim_CIcosh },
    409     { "_CItanh", native32_shim_CItanh }, { "_CIpow", native32_shim_CIpow },
    410     { "_CIfmod", native32_shim_CIfmod }, { "_CIatan2", native32_shim_CIatan2 },
    411     { "_controlfp", native32_shim_controlfp }, { "_control87", native32_shim_control87 },
    412 };
    413 
    414 int native32_bind(uint32_t base, native32_shim_t* shims, int nshims) {
    415     uint8_t* b = (uint8_t*)(uintptr_t)base;
    416     IMAGE_NT_HEADERS32* nt = (IMAGE_NT_HEADERS32*)(b + ((IMAGE_DOS_HEADER*)b)->e_lfanew);
    417     IMAGE_DATA_DIRECTORY dd = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
    418     IMAGE_IMPORT_DESCRIPTOR* d = (IMAGE_IMPORT_DESCRIPTOR*)(b + dd.VirtualAddress);
    419     int native = 0, shimmed = 0, guested = 0, missing = 0;
    420     /* The host's shims, then every built-in the host did not replace. */
    421     int nb = (int)(sizeof g_builtin / sizeof g_builtin[0]);
    422     native32_shim_t* all = (native32_shim_t*)calloc(nshims + nb, sizeof *all);
    423     int n = 0;
    424     for (int i = 0; i < nshims; i++) all[n++] = shims[i];
    425     for (int i = 0; i < nb; i++) {
    426         int dup = 0;
    427         for (int k = 0; k < nshims; k++) dup |= !strcmp(shims[k].name, g_builtin[i].name);
    428         if (!dup) all[n++] = g_builtin[i];
    429     }
    430     /* Every entry gets its VA now, not only the ones this module imports: a
    431      * host binding several guest modules calls this once per module, each
    432      * call builds a new array and it replaces g_shims, so a VA set only on
    433      * the first module's copy was lost to the second, and the first module's
    434      * shimmed imports stopped resolving. Same array in, same VAs out. */
    435     for (int i = 0; i < n; i++) all[i].va = g_shim_page + 16 * i;
    436     shims = all;
    437     nshims = n;
    438     g_shims = shims;
    439     g_nshims = nshims;
    440     for (; dd.VirtualAddress && d->Name; d++) {
    441         const char* dll = (const char*)(b + d->Name);
    442         /* A guest module importing from another one (a game DLL calling back
    443          * into its engine EXE) binds to the guest's own exports: those VAs are
    444          * in the dispatch table. LoadLibrary would load the original binary as
    445          * native code, or fail. */
    446         uint32_t guest = native32_module(dll);
    447         /* Loaded at its first import the host did not shim: a DLL every one
    448          * of whose imports is shimmed (a host that stubs a whole library out)
    449          * is never loaded, so its DllMain never runs. */
    450         HMODULE h = NULL;
    451         uint32_t* ilt = (uint32_t*)(b + (d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk));
    452         uint32_t* iat = (uint32_t*)(b + d->FirstThunk);
    453         for (; *ilt; ilt++, iat++) {
    454             int by_ord = (*ilt & 0x80000000u) != 0;
    455             const char* nm = by_ord ? (const char*)(uintptr_t)(*ilt & 0xFFFF) : (const char*)(b + *ilt + 2);
    456             uint32_t va = 0;
    457             for (int i = 0; !guest && !by_ord && i < nshims; i++)
    458                 if (!strcmp(shims[i].name, nm)) {
    459                     va = shims[i].va;
    460                     shimmed++;
    461                 }
    462             if (!va) {
    463                 if (!guest && !h) h = LoadLibraryA(dll);
    464                 va = guest ? native32_export(guest, nm)
    465                    : h ? (uint32_t)(uintptr_t)GetProcAddress(h, nm) : 0;
    466                 if (va && guest) guested++;
    467                 else if (va) native++;
    468                 else {
    469                     fprintf(stderr, "[bind] %s!%s%s unresolved\n", dll, by_ord ? "#" : "",
    470                             by_ord ? "" : nm);
    471                     missing++;
    472                 }
    473             }
    474             if (va && !by_ord) add_name(va, dll, nm);
    475             *iat = va;
    476         }
    477     }
    478     fprintf(stderr, "[bind] 0x%08X: %d native, %d guest, %d shimmed, %d unresolved\n",
    479             base, native, guested, shimmed, missing);
    480     return missing;
    481 }
    482 
    483 /* ------------------------------------------------------- Windows -> guest */
    484 
    485 /* Runs a lifted function for a native caller. `sp` points at the native
    486  * caller's [ret][args...]. Returns eax in the low half and the bytes the
    487  * callee popped in the high half, for cb_tramp's variable `ret n`. */
    488 static uint64_t __cdecl cb_run(uint32_t va, uint32_t* sp, uint32_t ecx) {
    489     recomp_func_t f = IS_SHIM_VA(va) ? recomp_lookup_import(va) : recomp_lookup(va);
    490     if (native32_trace_callbacks)
    491         fprintf(stderr, "[callback] sub_%08X (%08X %08X %08X %08X)\n", va, sp[1], sp[2], sp[3], sp[4]);
    492     mach_enter();
    493     regs_t saved;
    494     regs_save(&saved);
    495     g_esp -= BRIDGE_SLOTS * 4;
    496     memcpy((void*)(uintptr_t)g_esp, sp + 1, BRIDGE_SLOTS * 4);
    497     PUSH32(g_esp, RECOMP_RETADDR);
    498     uint32_t before = g_esp;
    499     g_ecx = ecx;
    500     f();
    501     uint32_t eax = g_eax, purge = g_esp - before - 4;
    502     /* The other half of the st(0) transfer: a lifted function returning a
    503      * float leaves it on the LIFTED x87 stack, and the native caller is about
    504      * to fstp its own. */
    505     int st_ret = g_fp_top == saved.fp_top + 1;
    506     double cb_st = g_st[0];
    507     regs_load(&saved);
    508     mach_leave();
    509     if (st_ret) __asm fld cb_st
    510     return ((uint64_t)purge << 32) | eax;
    511 }
    512 
    513 static __declspec(naked) void cb_tramp(void) {
    514     __asm {
    515         mov  edx, esp            ; [ret][args]
    516         push ecx
    517         push edx
    518         push eax                 ; the guest VA, planted by the VEH
    519         call cb_run
    520         add  esp, 12
    521         pop  ecx                 ; native return address
    522         add  esp, edx            ; pop what the guest callee popped
    523         jmp  ecx
    524     }
    525 }
    526 
    527 static LONG CALLBACK native32_veh(EXCEPTION_POINTERS* ep) {
    528     EXCEPTION_RECORD* er = ep->ExceptionRecord;
    529     uint32_t pc = (uint32_t)(uintptr_t)er->ExceptionAddress;
    530     /* An instruction fetch: Windows says so (8, execute). Wine on Apple
    531      * Silicon (CrossOver, 32-bit code under Rosetta) reports it as a read,
    532      * but a read of the faulting instruction's own address is a fetch too:
    533      * Wine calling a window procedure in the shim page came through as
    534      * "read of 0x032D0170" at 0x032D0170, and the game died creating its
    535      * window. */
    536     int fetch = er->NumberParameters >= 2 &&
    537                 (er->ExceptionInformation[0] == 8 || (uint32_t)er->ExceptionInformation[1] == pc);
    538     if (er->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && fetch &&
    539         (native32_in_guest(pc) || IS_SHIM_VA(pc))) {
    540         if (recomp_lookup(pc) || IS_SHIM_VA(pc)) {
    541             ep->ContextRecord->Eax = pc;
    542             ep->ContextRecord->Eip = (DWORD)(uintptr_t)cb_tramp;
    543             return EXCEPTION_CONTINUE_EXECUTION;
    544         }
    545         fprintf(stderr, "[callback] Windows called guest 0x%08X, which is not lifted\n", pc);
    546     }
    547     return EXCEPTION_CONTINUE_SEARCH;
    548 }
    549 
    550 /* ---------------------------------------------------------------- setup */
    551 
    552 void native32_init(void) {
    553     /* Every Windows -> guest call relies on the guest's code faulting when it
    554      * is fetched. Windows enforces that for a /NXCOMPAT exe; Wine does not
    555      * unless DEP is asked for, and otherwise answers the first fetch by making
    556      * the page executable and running the shipping machine code. */
    557     SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
    558     DWORD dep_flags;
    559     BOOL dep_permanent;
    560     if (!GetProcessDEPPolicy(GetCurrentProcess(), &dep_flags, &dep_permanent) ||
    561         !(dep_flags & PROCESS_DEP_ENABLE)) {
    562         fprintf(stderr, "[native32] process DEP is required\n");
    563         exit(3);
    564     }
    565     InitializeCriticalSection(&g_mach);
    566     recomp_yield_hook = native32_yield;
    567     g_mach_tls = TlsAlloc();
    568     g_shim_page = (uint32_t)(uintptr_t)VirtualAlloc(NULL, 0x10000, MEM_RESERVE, PAGE_NOACCESS);
    569     AddVectoredExceptionHandler(1, native32_veh);
    570 }
    571 
    572 void native32_call_guest(uint32_t va, int nargs, const uint32_t* args) {
    573     recomp_func_t f = recomp_lookup(va);
    574     if (!f) { fprintf(stderr, "[native32] no lifted function at 0x%08X\n", va); exit(3); }
    575     mach_enter();
    576     for (int i = nargs - 1; i >= 0; i--) PUSH32(g_esp, args[i]);
    577     PUSH32(g_esp, RECOMP_RETADDR);
    578     f();
    579     mach_leave();
    580 }
    581 
    582 void native32_dump_icalls(int n) {
    583     fprintf(stderr, "last indirect calls (newest first):\n");
    584     for (int i = 1; i <= n && i <= (int)g_icall_trace_idx; i++) {
    585         uint32_t k = (g_icall_trace_idx - i) & (ICALL_TRACE_SIZE - 1);
    586         const char* nm = native32_name(g_icall_trace[k]);
    587         fprintf(stderr, "  0x%08X  from 0x%08X  %s\n", g_icall_trace[k], g_icall_from[k], nm ? nm : "");
    588     }
    589 }
    590 
    591 /* Built-in bodies kept in their own files, compiled as part of this one so a
    592  * host's build needs no change when one is added. */
    593 #include "eh32.c"
    594 #include "x87crt.c"