From 134eee3a287f1521ba7fb4c50b93c8663f2292ef Mon Sep 17 00:00:00 2001 From: ates Date: Thu, 26 Nov 2026 10:13:12 +0300 Subject: [PATCH] Cover CLWB addressing and log unhandled guest exceptions Signed-off-by: ates --- CHANGELOG.md | 1 + shims/runtime_veh/runtime_veh.cpp | 168 ++++++++++++------ .../conformance/test_veh_clwb/CMakeLists.txt | 3 + tests/conformance/test_veh_clwb/main.cpp | 28 ++- .../test_veh_clwb/main_unhandled.cpp | 13 ++ 5 files changed, 145 insertions(+), 68 deletions(-) create mode 100644 tests/conformance/test_veh_clwb/main_unhandled.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 16ee66a5..4d8e8071 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added +- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409). - Added Section 0 (`First-Time Contributor Onboarding`) to `AGENTS.md` (`CLAUDE.md` symlink) giving coding agents a turnkey step-by-step onboarding flow (preflight, `bx-cli doctor`, unclaimed `status: ready` issue discovery, claiming, scoped implementation, local verification including hosts without CrossOver, DCO commit, and PR CI watching). - Overhauled the repository into a clean 6-track parallel hybrid workspace (Milestone M0) designed for 5–8+ concurrent contributors and coding agents: added frozen cross-DLL ABI headers and canonical `.def` export tables (`abi/`), native ARM64 Rust workspace (`launcher/crates/{bx-cli,bx-probe,bx-telemetry}` with `env_clear()` child environment isolation, and `shader-transpiler/crates/dxbc-accc`), CMake + `mingw-w64` superbuild (`shims/`, `scripts/build-shims.sh`) producing 16 standalone x86-64 PE32+ shim DLLs (`bx_runtime_veh.dll` with working `clwb` VEH trap and JSONL logger, `xmem.dll`, `XCRDAPI.dll`, `d3d12_xs.dll`, `xg_xs.dll`, `xgameruntime.dll`, `GameInput.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, and PSM/ntuser forwarders) with strict PE Export Directory verification (exact names, ordinals, forwarders, zero extra exports, zero dynamic MinGW runtime dependencies), auto-discovered synthetic PE32+ conformance tests (`tests/conformance/`), `.github/workflows/hybrid-ci.yml`, `.github/ISSUE_TEMPLATE/track-handoff.yml`, `docs/adr/0006-retire-in-tree-native-workspace.md`, `docs/architecture/parallel-tracks.md`, and `docs/issues/wave-1-backlog.md`. Unified `docs/roadmap.md`, `CONTRIBUTING.md`, `AGENTS.md`, `README.md`, and `.github/CODEOWNERS` (retaining global `* @MacosPorters/maintainers` fallback and full provenance/independent-verification rules). Verified locally on Apple M5 (macOS 27.2.1, CrossOver 26.3, Rosetta 2) with all Rust checks, strict 16-DLL export verification, and live `test_veh_clwb.exe` + `test_shim_exports.exe` smoke tests passing. - Documented the original Windows workload set and Phase 1 hybrid measurement protocol (#353), including receipt-field sources, percentile definitions, negative controls and independent reproduction requirements. The protocol identifies the unmerged runner candidate and its missing raw traces and measurements; it adds no execution or compatibility claim. diff --git a/shims/runtime_veh/runtime_veh.cpp b/shims/runtime_veh/runtime_veh.cpp index fba24535..b7275efb 100644 --- a/shims/runtime_veh/runtime_veh.cpp +++ b/shims/runtime_veh/runtime_veh.cpp @@ -13,6 +13,8 @@ CRITICAL_SECTION g_log_lock; bool g_log_lock_ready = false; HANDLE g_log_handle = INVALID_HANDLE_VALUE; PVOID g_veh_handle = nullptr; +LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr; +std::atomic_flag g_crash_logged{}; std::atomic g_clwb_traps{0}; bx_runtime_config_t g_config = { BX_ABI_VERSION, @@ -45,90 +47,131 @@ void write_log_line(const char* line, size_t len) { } } -/* - * Decode an x86-64 `clwb m8` instruction at `ip`. - * Encoding: [legacy prefixes] 0x66 [REX 0x40..0x4F] 0x0F 0xAE /6 (mod != 3). - * Returns total instruction length in bytes, or 0 if `ip` is not `clwb`. - */ -size_t decode_clwb_length(const uint8_t* ip) { +constexpr size_t kMaxInstructionLength = 15; + +size_t read_instruction(uint64_t rip, uint8_t (&bytes)[kMaxInstructionLength]) { + HANDLE process = GetCurrentProcess(); + if (ReadProcessMemory(process, reinterpret_cast(rip), + bytes, sizeof(bytes), nullptr)) { + return sizeof(bytes); + } + + // A short instruction can end immediately before an inaccessible page. + size_t size = 0; + while (size < sizeof(bytes) && + ReadProcessMemory(process, reinterpret_cast(rip + size), + &bytes[size], 1, nullptr)) { + ++size; + } + return size; +} + +// CLWB is 66 0F AE /6 with a memory operand. The address-size override +// selects 32-bit addressing but leaves the ModRM/SIB displacement lengths intact. +size_t decode_clwb_length(const uint8_t* ip, size_t size) { size_t idx = 0; bool has_66 = false; - bool has_addr_override = false; - - while (idx < 6) { - uint8_t b = ip[idx]; - if (b == 0x66) { + while (idx < size) { + const uint8_t byte = ip[idx]; + if (byte == 0x66) { has_66 = true; - idx++; - } else if (b == 0x67) { - has_addr_override = true; - idx++; - } else if (b == 0x26 || b == 0x2E || b == 0x36 || b == 0x3E || b == 0x64 || b == 0x65) { - idx++; - } else { + } else if (byte != 0x67 && byte != 0x26 && byte != 0x2E && + byte != 0x36 && byte != 0x3E && byte != 0x64 && byte != 0x65) { break; } - } - (void)has_addr_override; - if (!has_66) { - return 0; + ++idx; } - if ((ip[idx] & 0xF0) == 0x40) { - idx++; /* Optional REX prefix */ + while (idx < size && (ip[idx] & 0xF0) == 0x40) { + ++idx; } - - if (ip[idx] != 0x0F || ip[idx + 1] != 0xAE) { + if (!has_66 || size - idx < 3 || ip[idx] != 0x0F || ip[idx + 1] != 0xAE) { return 0; } idx += 2; - uint8_t modrm = ip[idx++]; - uint8_t mod = (modrm >> 6) & 0x3; - uint8_t reg = (modrm >> 3) & 0x7; - uint8_t rm = modrm & 0x7; - - /* `clwb` requires memory operand (mod != 3) and opcode extension /6. */ + const uint8_t modrm = ip[idx++]; + const uint8_t mod = modrm >> 6; + const uint8_t reg = (modrm >> 3) & 7; + const uint8_t rm = modrm & 7; if (mod == 3 || reg != 6) { return 0; } + uint8_t base = rm; if (rm == 4) { - uint8_t sib = ip[idx++]; - if (mod == 0 && (sib & 0x7) == 5) { - idx += 4; /* disp32 with no base */ + if (idx == size) { + return 0; } - } else if (mod == 0 && rm == 5) { - idx += 4; /* RIP-relative disp32 */ + base = ip[idx++] & 7; } - if (mod == 1) { - idx += 1; /* disp8 */ - } else if (mod == 2) { - idx += 4; /* disp32 */ + idx += 1; + } else if (mod == 2 || (mod == 0 && base == 5)) { + idx += 4; } - - return idx; + return idx <= size ? idx : 0; } -bool is_adx_opcode(const uint8_t* ip) { +bool is_adx_opcode(const uint8_t* ip, size_t size) { size_t idx = 0; - bool has_66_or_f3 = false; - while (idx < 4) { - if (ip[idx] == 0x66 || ip[idx] == 0xF3) { - has_66_or_f3 = true; - idx++; - } else { - break; - } + while (idx < size && (ip[idx] == 0x66 || ip[idx] == 0xF3)) { + ++idx; } - if (!has_66_or_f3) { + if (idx == 0) { return false; } - if ((ip[idx] & 0xF0) == 0x40) { - idx++; + if (idx < size && (ip[idx] & 0xF0) == 0x40) { + ++idx; } - return ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6; + return size - idx >= 4 && ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6; +} + +LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) { + // Wine can invoke the top-level filter again for the same terminal fault. + if (ep && ep->ExceptionRecord && ep->ContextRecord && + !g_crash_logged.test_and_set(std::memory_order_relaxed)) { + const CONTEXT& ctx = *ep->ContextRecord; + MEMORY_BASIC_INFORMATION region{}; + unsigned long long module_base = 0; + if (VirtualQuery(reinterpret_cast(ctx.Rip), ®ion, sizeof(region)) && + region.Type == MEM_IMAGE) { + module_base = reinterpret_cast(region.AllocationBase); + } + + char line[1024]; + int length = std::snprintf( + line, sizeof(line), + "{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"ERROR\",\"sub\":\"runtime_veh\"," + "\"event\":\"unhandled_exception\",\"exception_code\":\"0x%08lx\"," + "\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\"," + "\"rip\":\"0x%016llx\",\"rsp\":\"0x%016llx\"," + "\"registers\":{\"rax\":\"0x%016llx\",\"rbx\":\"0x%016llx\"," + "\"rcx\":\"0x%016llx\",\"rdx\":\"0x%016llx\",\"rsi\":\"0x%016llx\"," + "\"rdi\":\"0x%016llx\",\"rbp\":\"0x%016llx\",\"r8\":\"0x%016llx\"," + "\"r9\":\"0x%016llx\",\"r10\":\"0x%016llx\",\"r11\":\"0x%016llx\"," + "\"r12\":\"0x%016llx\",\"r13\":\"0x%016llx\",\"r14\":\"0x%016llx\"," + "\"r15\":\"0x%016llx\"}}\n", + static_cast(GetTickCount64()), GetCurrentThreadId(), + ep->ExceptionRecord->ExceptionCode, module_base, + module_base ? ctx.Rip - module_base : 0ULL, ctx.Rip, ctx.Rsp, + ctx.Rax, ctx.Rbx, ctx.Rcx, ctx.Rdx, ctx.Rsi, ctx.Rdi, ctx.Rbp, + ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15); + // A crashed thread may already own the regular logger's lock. + HANDLE output = g_log_handle != INVALID_HANDLE_VALUE + ? g_log_handle : GetStdHandle(STD_ERROR_HANDLE); + if (length > 0 && length < static_cast(sizeof(line)) && + output && output != INVALID_HANDLE_VALUE) { + DWORD written = 0; + WriteFile(output, line, static_cast(length), &written, nullptr); + } + } + + const LONG disposition = g_previous_filter ? g_previous_filter(ep) : EXCEPTION_CONTINUE_SEARCH; + if (disposition == EXCEPTION_CONTINUE_EXECUTION) { + g_crash_logged.clear(std::memory_order_relaxed); + } + return disposition; } LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) { @@ -139,9 +182,10 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) { return EXCEPTION_CONTINUE_SEARCH; } - auto* ip = reinterpret_cast(ep->ContextRecord->Rip); + uint8_t ip[kMaxInstructionLength]{}; + const size_t size = read_instruction(ep->ContextRecord->Rip, ip); if (g_config.enable_clwb_veh) { - size_t len = decode_clwb_length(ip); + size_t len = decode_clwb_length(ip, size); if (len > 0) { uint64_t count = g_clwb_traps.fetch_add(1, std::memory_order_relaxed) + 1; if (count == 1 || (count & (count - 1)) == 0) { @@ -158,7 +202,7 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) { } } - if (g_config.enable_adx_tripwire && is_adx_opcode(ip)) { + if (g_config.enable_adx_tripwire && is_adx_opcode(ip, size)) { char msg[160]; std::snprintf(msg, sizeof(msg), "rip=0x%016llx bytes=%02x %02x %02x %02x %02x", @@ -262,9 +306,15 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) { init_config_and_logging(); bx_veh_install(); + g_previous_filter = SetUnhandledExceptionFilter(log_unhandled_exception); bx_log_emit(BX_LOG_INFO, "runtime_veh", "attached", g_config.profile == BX_PROFILE_ANACONDA ? "profile=anaconda" : "profile=lockhart"); } else if (reason == DLL_PROCESS_DETACH) { + // Preserve a filter installed by the guest after this DLL attached. + const auto current_filter = SetUnhandledExceptionFilter(g_previous_filter); + if (current_filter != log_unhandled_exception) { + SetUnhandledExceptionFilter(current_filter); + } if (g_veh_handle) { RemoveVectoredExceptionHandler(g_veh_handle); g_veh_handle = nullptr; diff --git a/tests/conformance/test_veh_clwb/CMakeLists.txt b/tests/conformance/test_veh_clwb/CMakeLists.txt index 7e4edcb7..6ca4d04c 100644 --- a/tests/conformance/test_veh_clwb/CMakeLists.txt +++ b/tests/conformance/test_veh_clwb/CMakeLists.txt @@ -2,3 +2,6 @@ add_executable(test_veh_clwb main.cpp) target_include_directories(test_veh_clwb PRIVATE "${BX_ABI_INCLUDE_DIR}") target_compile_options(test_veh_clwb PRIVATE -mavx2 -mfma) target_link_libraries(test_veh_clwb PRIVATE bx_runtime_veh xmem kernel32) + +add_executable(test_veh_unhandled main_unhandled.cpp) +target_link_libraries(test_veh_unhandled PRIVATE bx_runtime_veh kernel32) diff --git a/tests/conformance/test_veh_clwb/main.cpp b/tests/conformance/test_veh_clwb/main.cpp index dbddd967..c4567498 100644 --- a/tests/conformance/test_veh_clwb/main.cpp +++ b/tests/conformance/test_veh_clwb/main.cpp @@ -29,15 +29,25 @@ int main() { } } - /* 2. Verify clwb trapping via bx_runtime_veh.dll (both legacy and REX forms) */ - alignas(64) uint8_t buf[128] = {0x42}; - uint64_t before = bx_veh_get_clwb_trap_count(); - __asm__ volatile("clwb (%0)" :: "r"(buf) : "memory"); - __asm__ volatile("clwb 64(%0)" :: "r"(buf) : "memory"); - uint64_t after = bx_veh_get_clwb_trap_count(); - std::printf("clwb traps observed: %llu -> %llu\n", - static_cast(before), - static_cast(after)); + // Fixed registers ensure the assembler emits the intended ModRM/REX forms. + alignas(64) uint8_t buf[512] = {0x42}; + const uint64_t before = bx_veh_get_clwb_trap_count(); + __asm__ volatile( + "clwb (%%rax)\n\t" + "clwb 64(%%rax)\n\t" + "clwb 256(%%rax)\n\t" + "mov %%rax, %%r8\n\t" + "clwb (%%r8)\n\t" + "clwb 64(%%rax,%%rcx,4)\n\t" + "clwb (%%rip)" + :: "a"(buf), "c"(8) : "r8", "memory"); + const uint64_t delta = bx_veh_get_clwb_trap_count() - before; + if (delta != 6) { + std::fprintf(stderr, "FAIL: expected 6 CLWB traps, observed %llu\n", + static_cast(delta)); + return 4; + } + std::printf("CLWB traps observed: %llu\n", static_cast(delta)); /* 3. Verify basic XMem allocation + transfer + stats contract */ void* src = XMemAlloc(4096, 0); diff --git a/tests/conformance/test_veh_clwb/main_unhandled.cpp b/tests/conformance/test_veh_clwb/main_unhandled.cpp new file mode 100644 index 00000000..bb611dd3 --- /dev/null +++ b/tests/conformance/test_veh_clwb/main_unhandled.cpp @@ -0,0 +1,13 @@ +#include +#include + +extern "C" uint64_t bx_veh_get_clwb_trap_count(void); + +// Run in its own process. The launcher should report failure and the trace +// should contain a single unhandled_exception with RAX set to the marker. +int main() { + SetErrorMode(SEM_NOGPFAULTERRORBOX); + const uint64_t marker = 0x123456789abcdef0ULL + bx_veh_get_clwb_trap_count(); + __asm__ volatile("ud2" :: "a"(marker) : "memory"); + return 1; +}