aorecomp

Anarchy Online classic in the browser

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


client/runtime/eh32.c (12516B)


      1 /*
      2  * eh32: guest C++ exceptions for lifted x86-32 code (MSVC's frame-based EH).
      3  *
      4  * A guest `throw` reaches _CxxThrowException, which would RaiseException on
      5  * the host and walk the host's SEH chain: it has never heard of the guest's
      6  * frames, so a throw the guest would catch one frame up kills the process.
      7  * That is not an edge case. Unreal signals recoverable failures by throwing
      8  * (UObject::StaticLoadObject catches its own "can't resolve package name"),
      9  * and every `guard`/`unguard` is a try/catch.
     10  *
     11  * x86 MSVC registers its handlers on the stack, so the guest describes its own
     12  * frames: fs:[0] heads a chain of {next, handler} records that the lifted
     13  * prologues build in guest memory exactly as the original did. A C++ frame's
     14  * handler is a stub `mov eax, FuncInfo; jmp __CxxFrameHandler`, and FuncInfo
     15  * holds the unwind map (state -> destructor funclet) and the try blocks. The
     16  * frame's state index is at record+8 and its ebp is record+12. So the throw is
     17  * dispatched here, entirely from guest data, the way __CxxFrameHandler would:
     18  *
     19  *   1. walk the chain for a try block that covers its frame's state and has a
     20  *      catch matching a type in the ThrowInfo (by decorated name, since the
     21  *      thrower and the catcher can be different modules);
     22  *   2. run every unwind funclet between the throw and that frame, and the
     23  *      catching frame's own down to the try block;
     24  *   3. store the exception object in the catch's variable, run the catch
     25  *      funclet as guest code (ebp = the frame's), which returns where the
     26  *      function continues;
     27  *   4. longjmp into the lifted body that owns the frame. generate.py gives
     28  *      every function that installs a handler a setjmp landing pad at entry
     29  *      (RECOMP_EH_ENTER) and a label at each continuation (tools/lift/eh32.py).
     30  *
     31  * A throw nothing in the guest catches goes to the real _CxxThrowException,
     32  * so the host's crash report sees it as before.
     33  *
     34  * Included at the end of native32.c, so hosts need no change to their build.
     35  *
     36  * ponytail: C++ frames only. A __try/__except (SEH, _except_handler3) frame
     37  * is skipped, not asked: its filter could catch a C++ throw, and its __finally
     38  * blocks do not run on the way past. Add when a title catches that way.
     39  */
     40 #ifndef RECOMP_PORTABLE
     41 #define WIN32_LEAN_AND_MEAN
     42 #include <windows.h>
     43 #endif
     44 #include <stdio.h>
     45 #include <string.h>
     46 
     47 #include "recomp_types.h"
     48 #include "game-data.h"
     49 #include "guest_jump.h"
     50 
     51 #define EH_MAGIC_VC6   0x19930520u
     52 #define EH_MAGIC_VC7   0x19930521u
     53 #define EH_MAGIC_VC8   0x19930522u
     54 
     55 #ifdef RECOMP_PORTABLE
     56 #define EH_THREAD_LOCAL _Thread_local
     57 #else
     58 #define EH_THREAD_LOCAL __declspec(thread)
     59 #endif
     60 static EH_THREAD_LOCAL recomp_ehframe_t* t_frames;   /* newest first */
     61 /* The exception a running catch funclet holds, for a bare `throw;`. */
     62 static EH_THREAD_LOCAL uint32_t t_cur_obj, t_cur_info;
     63 
     64 #ifdef RECOMP_PORTABLE
     65 static _Thread_local guest_jump_frame *t_jumps;
     66 
     67 void guest_jump_leave(guest_jump_frame *frame)
     68 {
     69     for (guest_jump_frame *p = t_jumps; p; p = p->prev)
     70         if (p == frame) { t_jumps = frame->prev; return; }
     71 }
     72 
     73 /* A caught C++ exception also invalidates abandoned setjmp landing pads. */
     74 static void discard_jumps(uint32_t stack)
     75 {
     76     while (t_jumps && t_jumps->entry_esp < stack) t_jumps = t_jumps->prev;
     77 }
     78 
     79 void guest_jump_save(guest_jump_frame *frame)
     80 {
     81     if (MEM32(g_esp + 8)) {
     82         fprintf(stderr, "Unsupported _setjmp3 unwind arguments from %08x\n", g_cur_func);
     83         abort();
     84     }
     85     guest_jump_leave(frame);
     86     frame->prev = t_jumps;
     87     frame->buffer = MEM32(g_esp + 4);
     88     frame->function = g_cur_func;
     89     t_jumps = frame;
     90 
     91     /* MSVCRT x86 _JUMP_BUFFER. Unused unwind-data words remain untouched. */
     92     uint32_t b = frame->buffer, registration = MEM32(g_fs_base);
     93     MEM32(b) = g_ebp;
     94     MEM32(b + 4) = g_ebx;
     95     MEM32(b + 8) = g_edi;
     96     MEM32(b + 12) = g_esi;
     97     MEM32(b + 16) = g_esp;
     98     MEM32(b + 20) = MEM32(g_esp);
     99     MEM32(b + 24) = registration;
    100     MEM32(b + 28) = registration == UINT32_MAX ? UINT32_MAX : MEM32(registration + 12);
    101     MEM32(b + 32) = 0x56433230;
    102     MEM32(b + 36) = 0;
    103     g_eax = 0;
    104     g_esp += 4;
    105     g_flag_k = FK_NONE;
    106 }
    107 
    108 /* _endthreadex abandons guest frames without running C++ stack destructors. */
    109 void recomp_eh_thread_exit(void)
    110 {
    111     t_frames = NULL;
    112     t_jumps = NULL;
    113     t_cur_obj = t_cur_info = 0;
    114 }
    115 #endif
    116 
    117 void recomp_eh_push(recomp_ehframe_t* f) { f->prev = t_frames; t_frames = f; }
    118 
    119 void recomp_eh_pop(recomp_ehframe_t* f) {
    120     /* A longjmp past this frame already dropped it. */
    121     for (recomp_ehframe_t* p = t_frames; p; p = p->prev)
    122         if (p == f) { t_frames = f->prev; return; }
    123 }
    124 
    125 /* The generated handler metadata replaces runtime inspection of x86 stubs. */
    126 static uint32_t funcinfo(uint32_t handler) {
    127 #ifdef RECOMP_PORTABLE
    128     extern uint32_t recomp_funcinfo(uint32_t handler);
    129     uint32_t fi = recomp_funcinfo(handler);
    130 #else
    131     uint32_t fi = game_funcinfo(handler);
    132 #endif
    133     if (!fi) return 0;
    134 #ifndef RECOMP_PORTABLE
    135     if (IsBadReadPtr((void*)ADDR(fi), 20)) return 0;
    136 #endif
    137     uint32_t magic = MEM32(fi);
    138     return magic == EH_MAGIC_VC6 || magic == EH_MAGIC_VC7 || magic == EH_MAGIC_VC8 ? fi : 0;
    139 }
    140 
    141 /* Run guest code at va as MSVC's _CallSettingFrame does: ebp = the frame's,
    142  * on the current guest stack. Returns eax; every other register is kept. */
    143 static uint32_t call_funclet(uint32_t va, uint32_t frame_ebp) {
    144     recomp_func_t fn = recomp_lookup(va);
    145     if (!fn) {
    146         fprintf(stderr, "[eh32] funclet 0x%08X is not lifted\n", va);
    147         return 0;
    148     }
    149     uint32_t esp = g_esp, ebp = g_ebp, ebx = g_ebx, esi = g_esi, edi = g_edi, cur = g_cur_func;
    150     g_ebp = frame_ebp;
    151     g_esp -= 4;
    152     MEM32(g_esp) = 0;                   /* return address: the funclet's ret pops it */
    153     fn();
    154     uint32_t eax = g_eax;
    155     g_esp = esp, g_ebp = ebp, g_ebx = ebx, g_esi = esi, g_edi = edi, g_cur_func = cur;
    156     return eax;
    157 }
    158 
    159 /* Destroy a C++ frame's locals from its current state down to `to`. */
    160 static void unwind_to(uint32_t rec, uint32_t fi, int to) {
    161     int s = (int)MEM32(rec + 8);
    162     uint32_t map = MEM32(fi + 8);
    163     int max = (int)MEM32(fi + 4);
    164     while (s != to && s >= 0 && s < max) {
    165         int next = (int)MEM32(map + 8 * s);
    166         uint32_t action = MEM32(map + 8 * s + 4);
    167         MEM32(rec + 8) = (uint32_t)next;
    168         if (action) call_funclet(action, rec + 12);
    169         s = next;
    170     }
    171 }
    172 
    173 #ifdef RECOMP_PORTABLE
    174 void guest_longjmp(void)
    175 {
    176     uint32_t b = MEM32(g_esp + 4), value = MEM32(g_esp + 8);
    177     guest_jump_frame *frame = t_jumps;
    178     while (frame && frame->buffer != b) frame = frame->prev;
    179     if (!frame) {
    180         fprintf(stderr, "longjmp has no live landing pad for %08x\n", b);
    181         abort();
    182     }
    183 
    184     /* Unwind intervening C++ frames using the same guest destructor metadata. */
    185     uint32_t registration = MEM32(b + 24);
    186     for (uint32_t rec = MEM32(g_fs_base); rec != registration; rec = MEM32(rec)) {
    187         uint32_t fi = rec && rec != UINT32_MAX ? funcinfo(MEM32(rec + 4)) : 0;
    188         if (!fi) {
    189             fprintf(stderr, "Unsupported longjmp SEH frame %08x\n", rec);
    190             abort();
    191         }
    192         unwind_to(rec, fi, -1);
    193     }
    194     if (registration != UINT32_MAX && MEM32(registration + 12) != MEM32(b + 28)) {
    195         fprintf(stderr, "Unsupported longjmp local SEH unwind at %08x\n", registration);
    196         abort();
    197     }
    198     MEM32(g_fs_base) = registration;
    199     while (t_frames && t_frames->entry_esp < frame->entry_esp) t_frames = t_frames->prev;
    200     t_jumps = frame;
    201 
    202     g_ebp = MEM32(b);
    203     g_ebx = MEM32(b + 4);
    204     g_edi = MEM32(b + 8);
    205     g_esi = MEM32(b + 12);
    206     g_esp = MEM32(b + 16) + 4;
    207     g_eax = value ? value : 1;
    208     g_cur_func = frame->function;
    209     g_flag_k = FK_NONE;
    210     longjmp(frame->host, 1);
    211 }
    212 #endif
    213 
    214 /* The ThrowInfo's CatchableType that a catch of `type` takes, or 0. */
    215 static uint32_t catchable(uint32_t info, uint32_t type) {
    216     uint32_t arr = MEM32(info + 12);
    217     int n = (int)MEM32(arr);
    218     for (int i = 0; i < n; i++) {
    219         uint32_t ct = MEM32(arr + 4 + 4 * i);
    220         uint32_t td = MEM32(ct + 4);
    221         if (td == type || !strcmp((const char*)ADDR(td + 8), (const char*)ADDR(type + 8)))
    222             return ct;
    223     }
    224     return 0;
    225 }
    226 
    227 /* Store the thrown object into the catch's variable. */
    228 static void bind_catch_object(uint32_t handler, uint32_t ct, uint32_t obj, uint32_t frame_ebp) {
    229     uint32_t adj = MEM32(handler), disp = MEM32(handler + 8);
    230     if (!MEM32(handler + 4) || !disp || !ct) return;       /* catch(...) or no variable */
    231     uint32_t dst = frame_ebp + disp;
    232     uint32_t src = obj + MEM32(ct + 8);                     /* this-displacement (mdisp) */
    233     uint32_t size = MEM32(ct + 20), copy = MEM32(ct + 24);
    234     if (adj & 8) MEM32(dst) = src;                          /* by reference */
    235     else if (MEM32(ct) & 1 || !copy) memcpy((void*)ADDR(dst), (void*)ADDR(src), size);
    236     else {                                                  /* copy constructor, thiscall */
    237         uint32_t ecx = g_ecx;
    238         g_ecx = dst;
    239         g_esp -= 4;
    240         MEM32(g_esp) = src;
    241         call_funclet(copy, g_ebp);   /* ret 4 pops the argument */
    242         g_ecx = ecx;
    243     }
    244 }
    245 
    246 static int dispatch(uint32_t obj, uint32_t info) {
    247     uint32_t top = MEM32(g_fs_base);
    248     for (uint32_t rec = top; rec && rec != 0xFFFFFFFFu; rec = MEM32(rec)) {
    249         uint32_t fi = funcinfo(MEM32(rec + 4));
    250         if (!fi) continue;
    251         int state = (int)MEM32(rec + 8);
    252         uint32_t tries = MEM32(fi + 16);
    253         int ntry = (int)MEM32(fi + 12);
    254         for (int t = 0; t < ntry; t++) {
    255             uint32_t tb = tries + 20 * t;
    256             int lo = (int)MEM32(tb), hi = (int)MEM32(tb + 4), ncatch = (int)MEM32(tb + 12);
    257             if (state < lo || state > hi) continue;
    258             for (int c = 0; c < ncatch; c++) {
    259                 uint32_t h = MEM32(tb + 16) + 16 * c;
    260                 uint32_t type = MEM32(h + 4);
    261                 uint32_t ct = type ? catchable(info, type) : 0;
    262                 if (type && !ct) continue;
    263                 /* Caught: unwind everything above, then this frame to the try. */
    264                 for (uint32_t r = top; r != rec; r = MEM32(r)) {
    265                     uint32_t f = funcinfo(MEM32(r + 4));
    266                     if (f) unwind_to(r, f, -1);
    267                 }
    268                 unwind_to(rec, fi, lo);
    269                 MEM32(g_fs_base) = rec;
    270                 MEM32(rec + 8) = (uint32_t)(hi + 1);
    271                 uint32_t ebp = rec + 12;
    272                 bind_catch_object(h, ct, obj, ebp);
    273                 uint32_t prev_obj = t_cur_obj, prev_info = t_cur_info;
    274                 t_cur_obj = obj, t_cur_info = info;
    275                 uint32_t resume = call_funclet(MEM32(h + 12), ebp);
    276                 t_cur_obj = prev_obj, t_cur_info = prev_info;
    277                 /* The catch returned: continue in the frame's own function,
    278                  * on its stack as its prologue left it ([ebp-0x10]). */
    279                 for (recomp_ehframe_t* f = t_frames; f; f = f->prev) {
    280                     if (f->entry_esp != ebp + 4) continue;
    281                     t_frames = f;
    282                     g_ebp = ebp;
    283                     g_esp = MEM32(ebp - 0x10);
    284                     g_eax = resume;
    285                     f->resume = resume;
    286 #ifdef RECOMP_PORTABLE
    287                     discard_jumps(f->entry_esp);
    288 #endif
    289                     longjmp(f->jb, 1);
    290                 }
    291                 fprintf(stderr, "[eh32] frame 0x%08X caught, but no lifted body owns it (resume 0x%08X)\n",
    292                         ebp, resume);
    293                 return 0;
    294             }
    295         }
    296     }
    297     return 0;
    298 }
    299 
    300 #ifndef RECOMP_PORTABLE
    301 typedef void (__stdcall *cxx_throw_t)(void*, void*);
    302 #endif
    303 
    304 /* _CxxThrowException(object, ThrowInfo), stdcall, in the lifted model. */
    305 void native32_shim_CxxThrowException(void) {
    306     uint32_t obj = MEM32(g_esp + 4), info = MEM32(g_esp + 8);
    307     if (!info) obj = t_cur_obj, info = t_cur_info;          /* `throw;` */
    308     g_esp += 4;                                             /* the call's return address */
    309     if (info) dispatch(obj, info);
    310     /* Nothing in the guest catches it: the host's crash report does. */
    311 #ifdef RECOMP_PORTABLE
    312     fprintf(stderr, "Uncaught guest C++ exception: object=%08x info=%08x\n", obj, info);
    313     abort();
    314 #else
    315     static cxx_throw_t real;
    316     if (!real) real = (cxx_throw_t)GetProcAddress(LoadLibraryA("msvcrt.dll"), "_CxxThrowException");
    317     real((void*)(uintptr_t)obj, (void*)(uintptr_t)info);
    318 #endif
    319 }