sharpemu icon indicating copy to clipboard operation
sharpemu copied to clipboard

Any guest fault hangs the emulator at 100% CPU with no vectored handler entered (minimal repro, no game needed)

Open soufian3hm opened this issue 3 months ago • 2 comments

Emulator Version / Commit

418eb7e (current main), Release, Windows 11 26200, .NET SDK 10.0.302. Host: Intel Core i7-11370H (Tiger Lake, GenuineIntel), RTX 3070 Laptop, 40 GB RAM.

Bug Description

Any exception raised while executing guest code hangs the emulator at 100% CPU. No vectored exception handler is ever entered, and nothing is printed.

Guest code that runs to completion works fine. Guest code that faults — for any reason — never comes back, and the fault-recovery machinery never runs.

That machinery is not a corner case: unresolved-import sentinels, lazily-committed page demand-paging, the guest-allocator hole recovery, the BMI/ABM fallback and the SSE4a fallback are all built on top of VectoredHandler. If no fault can reach it, none of them can fire.

I found this while trying to build a synthetic guest to test with, so the reproducer needs no game, no GPU and no proprietary data — a 4 KB file is enough.

Reproduction

make_guest.py below emits a bare decrypted PS5-style ELF. The header is exactly the shape tests/SharpEmu.Libs.Tests/Loader/SelfLoaderTests.cs asserts (Load_AcceptsBareDecryptedElf); the payload is hand-assembled x86-64.

import struct, sys, os

ELF_HEADER_SIZE, PHDR_SIZE = 0x40, 0x38

def build(code, vaddr=0x1000):
    file_off = ELF_HEADER_SIZE + PHDR_SIZE
    pad = (vaddr - file_off) % 0x1000
    file_off += pad
    eh = bytearray(ELF_HEADER_SIZE)
    eh[0x00:0x04] = b"\x7fELF"
    eh[0x04], eh[0x05], eh[0x06], eh[0x07], eh[0x08] = 2, 1, 1, 9, 2
    struct.pack_into("<H", eh, 0x10, 3)               # ET_DYN
    struct.pack_into("<H", eh, 0x12, 62)              # x86-64
    struct.pack_into("<I", eh, 0x14, 1)
    struct.pack_into("<Q", eh, 0x18, vaddr)           # e_entry
    struct.pack_into("<Q", eh, 0x20, ELF_HEADER_SIZE) # e_phoff
    struct.pack_into("<H", eh, 0x34, ELF_HEADER_SIZE)
    struct.pack_into("<H", eh, 0x36, PHDR_SIZE)
    struct.pack_into("<H", eh, 0x38, 1)
    ph = struct.pack("<IIQQQQQQ", 1, 7, file_off, vaddr, vaddr, len(code), len(code), 0x1000)
    return bytes(eh) + ph + b"\x00" * pad + code

CASES = {
    "RET": bytes([0x31, 0xC0, 0xC3]),                                    # xor eax,eax ; ret
    "UD2": bytes([0x0F, 0x0B]),                                          # ud2
    "AV":  bytes([0x48, 0x8B, 0x04, 0x25, 0, 0, 0, 0, 0xC3]),            # mov rax,[0] ; ret
}

for name, code in CASES.items():
    path = os.path.join(sys.argv[1], name, "eboot.bin")
    os.makedirs(os.path.dirname(path), exist_ok=True)
    open(path, "wb").write(build(code))
    print("wrote", path)
python make_guest.py <outdir>
SharpEmu --cpu-engine=native --log-level=info <outdir>/UD2/eboot.bin

Results

guest 2-byte / 9-byte payload result
RET xor eax,eax ; ret works — [LOADER][INFO] Guest returned: 0, clean exit
UD2 ud2 hangs, ~100% of one core, forever
AV mov rax,[0] ; ret hangs, ~100% of one core, forever

So the loader, the image mapping and the entry hand-off are all fine — RET proves guest code executes and returns normally. It is specifically the fault path that hangs, and it hangs for both #UD and a plain access violation, so it is not instruction-specific.

The log simply stops:

[LOADER][INFO] ExecuteEntry starting at 0x0000000800001000
[LOADER][INFO] RSP=0x00007FFFF01FFF98, RDI=0x00007FFFF01FFFA0
[LOADER][INFO] StackTop: 0x00007FFFF01FFF98
[LOADER][INFO] Calling guest entry...
                                          <- nothing further, ever

Guest returned: never prints, the NATIVE EXCEPTION CAUGHT! dump never prints, and the 20 s stall watchdog then reports a stale entry-time snapshot (rip still at the entry, rax=0), which is misleading — it looks like the guest never started when in fact it started, faulted, and got stuck.

The emulator's own self-test reproduces it without any guest at all. SHARPEMU_SENTINEL_PROBE=1 prints Running unresolved sentinel probe... and never prints Sentinel probe returned. — that probe is just CallNativeEntry((void*)65534), i.e. the unresolved-import sentinel path, and it hangs the same way.

What I ruled out

I instrumented a local build to narrow this down; all of the below is measured, not inferred.

  • The managed handlers are never entered. I added an unconditional counter+trace at the top of both VectoredHandler and RawVectoredHandlerManaged. Zero entries for the whole run, for every failing case. The exception never reaches managed code.
  • It is not CET. The emulator's mitigated-child relaunch works correctly here. Get-ProcessMitigation on the spinning child reports UserShadowStack: OFF, SetContextIpValidation: OFF, while the parent shows both ON — so the PROCESS_CREATION_MITIGATION_POLICY2_CET_*_ALWAYS_OFF attributes are being applied as intended.
  • It is not an uninitialised VEH lock. I logged _vehManagedEntryLock at each CreateExceptionHandlerTrampoline call: a valid non-null pointer, identical across all three trampolines, with owner=0 depth=0 at build time, and _hostRspSlotTlsIndex=8 (valid).
  • It is not my branch. Reproduced on pristine main with no local changes.
  • It is not an infinite loop in my test payload. UD2 is two bytes and AV is nine, neither has a backward branch.

That leaves the hand-emitted VEH trampoline (CreateExceptionHandlerTrampoline, ~915 bytes) as the remaining suspect — it sits between the OS dispatch and the managed handler, and it contains the recursive managed-entry spinlock (lock cmpxchg + pause) plus the guest-stack/host-stack switch. A spin there would produce exactly this signature: 100% CPU, no managed entry, no output. I could not confirm which of its paths is stuck without a native debugger on the faulting thread, so I have stopped short of naming a line.

Why I think this matters

If this reproduces beyond my machine, it means fault-based recovery is entirely inoperative on affected hosts, and a title hits it the moment it touches an unresolved import — which is the normal path for anything not yet implemented. The symptom a user sees is "boots, shows something, then freezes", with no error and no log, which matches a lot of the compatibility reports.

I would be glad to be told this is machine-specific — that would itself be worth knowing, and I am happy to run further instrumented builds on this hardware to help narrow it.

Log File

[LOADER][INFO] VEH trampoline built: bytes=915 native_worker_abort=True
[LOADER][INFO] Raw exception handler installed: 0x000001B3B2345460
[LOADER][INFO] VEH trampoline built: bytes=915 native_worker_abort=True
[LOADER][INFO] Exception handler installed: 0x000001B3B2345B60
[LOADER][INFO] === Execute START ===
[LOADER][INFO] EntryPoint: 0x0000000800001000, ImportStubs: 0
[LOADER][INFO] Setup 0/0 import stubs (direct bridge, lle_redirects=0)
[LOADER][INFO] Patched 0 TLS loads, 0 TLS stores, 0 stack-canary accesses, 0 SSE4a EXTRQ blends
[LOADER][INFO] ExecuteEntry starting at 0x0000000800001000
[LOADER][INFO] Calling guest entry...
[LOADER][ERROR] Execution stalled with no import progress for 20s (imports=0).
[LOADER][ERROR] Stall snapshot: rip=0x0000000800001000 rsp=0x00007FFFF01FFF98 rax=0x0000000000000000
[LOADER][ERROR] Stall bytes @rip: 0F 0B 00 00 00 00 00 00 00 00 00 00 00 00 00 00

soufian3hm avatar Aug 06 '26 23:08 soufian3hm

Root-caused and fixed in #781 — it is two bytes.

The recursive managed-entry spinlock in the VEH trampoline emits F0 4C 0F B1 11 for what the comment on the same line calls lock cmpxchg [r9], r10. REX 0x4C has REX.B clear, so ModRM 0x11 addresses [rcx] — and in a vectored handler rcx is the EXCEPTION_POINTERS*. The acquire compared the exception-record pointer against the free-lock value (0), never matched, and jumped back to the top of the spin loop.

So the lock could never be acquired, on any host — deterministic, not a race — and no fault ever reached the managed handler.

I narrowed it by emitting flag-preserving counter bumps inside the trampoline itself and reading them from the stall watchdog:

entry=2  host-path=1  host-lock=0  host-returned=0
         guest-path=1 guest-stack-switched=1  guest-lock=0  guest-returned=0
lock owner=0x0 depth=0

Both paths reach the acquire, neither gets past it, and the lock is free the whole time — which is impossible for a correct spinlock.

With REX.B set (0x4D), the ud2 guest from the repro now reports NATIVE EXCEPTION CAUGHT! Code: 0xC000001D at the right address instead of spinning, and the access-violation guest reports 0xC0000005.

One part of this issue is not fixed by #781: SHARPEMU_SENTINEL_PROBE=1 still hangs afterwards, so TryRecoverUnresolvedSentinel has a separate defect on the CallNativeEntry((void*)65534) path. Leaving this issue open for that half unless a maintainer would rather split it out.

soufian3hm avatar Aug 06 '26 23:08 soufian3hm

Correcting my previous comment. I claimed SHARPEMU_SENTINEL_PROBE=1 still hangs after #781 and that TryRecoverUnresolvedSentinel therefore has a separate defect. That is wrong, and I would rather retract it than leave someone chasing a bug that is not there.

I had grepped the probe output for two strings, seen neither, and inferred a hang — without checking the exit code or how long it ran. Measured properly, with #781 applied, it terminates in 3-4 seconds, deterministically across repeated runs:

[LOADER][INFO] Running unresolved sentinel probe...
[LOADER][TRACE] VEH_AV first-chance at 0x000000000000FFFE type=8 target=0x000000000000FFFE
[LOADER][INFO] NATIVE EXCEPTION CAUGHT!
[LOADER][INFO]   Code: 0xC0000005
[LOADER][INFO]   Exception Address: 0x000000000000FFFE

It reaches the managed handler, prints full diagnostics, and fails fast with a clean managed stack trace. Before the fix it spun at 100% CPU producing none of that.

So #781 closes this issue in full, not half of it. All four synthetic guests behave correctly now: a clean ret returns, ud2 reports 0xC000001D, a null read reports 0xC0000005, and the register-form extrq reports 0xC000001D (which #776 then recovers rather than reporting).

One genuine observation remains, but it is not a defect: the probe never prints its own Sentinel probe returned. line, because it calls 0xFFFE from managed code and the sentinel recovery looks for a plausible guest return address on the stack. Finding none on a managed stack, it correctly declines. The probe is a self-test written for a guest-side sentinel and is simply not suited to being invoked that way — I am not proposing to change it.

soufian3hm avatar Aug 06 '26 23:08 soufian3hm