diff options
| author | OreoFR <noreply@users.noreply.github.com> | 2026-11-28 05:28:00 +0100 |
|---|---|---|
| committer | OreoFR <noreply@users.noreply.github.com> | 2026-11-28 05:28:00 +0100 |
| commit | 5d677b7ba2b2dd5b128455edf2b92bea6da4dcc2 (patch) | |
| tree | cca8090de22564ac93e738a50eedd77885732956 | |
| parent | 63a73515d1fc26c309ac0d9cd13ec9afd2fa5016 (diff) | |
cpu_emulation: a CLWB #UD on a site another thread rewrote continues at it (RT-CLWB-PATCH)
Threads that fault on the same CLWB site together lost the race: a #UD handled
after another thread rewrote the site decoded CLFLUSHOPT (or the NOP), did not
know it and returned EXCEPTION_CONTINUE_SEARCH, which ends the title.
- The handler continues at a site that already holds the form written on this
host (or the NOP's halfway state): the CPU runs it.
- One lock around unprotect, re-check, write and protect again, so two threads
never interleave on a page; a site found rewritten under it is not written.
- The NOP is written opcode first (66 0F 1F /6 in between is a NOP too).
- The sites counter counts each site once, by the thread that wrote it.
cpu_emulation_test calls the handler with a made-up #UD, so it runs on hosts
with CLWB: first #UD, a second one on the rewritten site, and 16 threads on
2048 fresh execute-read sites. Before the fix 27958 of 32768 concurrent #UDs
were passed on, 4810 rewrites were counted for 2048 sites and pages were left
writable; with it all checks pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | runtime/src/cpu_emulation.h | 79 | ||||
| -rw-r--r-- | runtime/test/cpu_emulation_test.cpp | 112 |
2 files changed, 177 insertions, 14 deletions
diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index 777a536bd..4f9565dcc 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h | |||
| @@ -356,7 +356,11 @@ inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, | |||
| 356 | // 66 0F AE /6 (CLWB) becomes 66 0F AE /7 (CLFLUSHOPT): the same operand and length, and it writes the line back too | 356 | // 66 0F AE /6 (CLWB) becomes 66 0F AE /7 (CLFLUSHOPT): the same operand and length, and it writes the line back too |
| 357 | // (then evicts it). A host without CLFLUSHOPT gets 66 0F 1F /0, a NOP of the same length that touches no memory. | 357 | // (then evicts it). A host without CLFLUSHOPT gets 66 0F 1F /0, a NOP of the same length that touches no memory. |
| 358 | // LEONIDA_CLWB_PATCH=0 keeps emulating every execution instead. | 358 | // LEONIDA_CLWB_PATCH=0 keeps emulating every execution instead. |
| 359 | inline bool patch_clwb(uint64_t rip, const uint8_t* code, std::size_t length) { | 359 | // Threads of that worker reach the same site together: a #UD handled after another thread rewrote the site finds |
| 360 | // the new instruction there and continues at it, and the rewrite itself is done once, under a lock. | ||
| 361 | |||
| 362 | // 1: rewrite as CLFLUSHOPT, 2: as the NOP (no CLFLUSHOPT on this host), 0: LEONIDA_CLWB_PATCH=0. | ||
| 363 | inline int clwb_patch_mode() { | ||
| 360 | static const int mode = [] { | 364 | static const int mode = [] { |
| 361 | char value[4]{}; | 365 | char value[4]{}; |
| 362 | if (GetEnvironmentVariableA("LEONIDA_CLWB_PATCH", value, sizeof(value)) > 0 && value[0] == '0') return 0; | 366 | if (GetEnvironmentVariableA("LEONIDA_CLWB_PATCH", value, sizeof(value)) > 0 && value[0] == '0') return 0; |
| @@ -364,24 +368,70 @@ inline bool patch_clwb(uint64_t rip, const uint8_t* code, std::size_t length) { | |||
| 364 | __cpuidex(r, 7, 0); | 368 | __cpuidex(r, 7, 0); |
| 365 | return ((r[1] >> 23) & 1) ? 1 : 2; // EBX bit 23: CLFLUSHOPT | 369 | return ((r[1] >> 23) & 1) ? 1 : 2; // EBX bit 23: CLFLUSHOPT |
| 366 | }(); | 370 | }(); |
| 371 | return mode; | ||
| 372 | } | ||
| 373 | |||
| 374 | // How many CLWB sites were rewritten so far; each counts once, by the thread that wrote it. | ||
| 375 | inline std::atomic<unsigned>& clwb_sites() { | ||
| 376 | static std::atomic<unsigned> sites{0}; | ||
| 377 | return sites; | ||
| 378 | } | ||
| 379 | |||
| 380 | // True when `code` (`avail` bytes at a #UD) holds the form patch_clwb writes on this host, or the NOP's halfway | ||
| 381 | // state (66 0F 1F /6): another thread rewrote the site after this thread's #UD. Neither form raises #UD here, so the | ||
| 382 | // thread continues at the site and the CPU runs it. | ||
| 383 | inline bool clwb_rewritten(const uint8_t* code, std::size_t avail) { | ||
| 384 | const int mode = clwb_patch_mode(); | ||
| 385 | if (!mode) return false; | ||
| 386 | std::size_t i = 0; | ||
| 387 | bool p66 = false; | ||
| 388 | for (; i < avail && i < 14; ++i) { | ||
| 389 | const uint8_t b = code[i]; | ||
| 390 | if (b == 0x66) p66 = true; | ||
| 391 | else if (!((b & 0xF0) == 0x40 || b == 0x67 || b == 0x2E || b == 0x3E || b == 0x26 || b == 0x36 || | ||
| 392 | b == 0x64 || b == 0x65)) break; | ||
| 393 | } | ||
| 394 | if (!p66 || i + 3 > avail || code[i] != 0x0F || (code[i + 2] >> 6) == 3) return false; | ||
| 395 | const int reg = (code[i + 2] >> 3) & 7; | ||
| 396 | return mode == 1 ? code[i + 1] == 0xAE && reg == 7 : code[i + 1] == 0x1F && (reg == 0 || reg == 6); | ||
| 397 | } | ||
| 398 | |||
| 399 | inline bool patch_clwb(uint64_t rip, const uint8_t* code, std::size_t length) { | ||
| 400 | const int mode = clwb_patch_mode(); | ||
| 367 | if (!mode) return false; | 401 | if (!mode) return false; |
| 368 | std::size_t at = 0; | 402 | std::size_t at = 0; |
| 369 | while (at + 2 < length && !(code[at] == 0x0F && code[at + 1] == 0xAE)) ++at; | 403 | while (at + 2 < length && !(code[at] == 0x0F && code[at + 1] == 0xAE)) ++at; |
| 370 | if (at + 2 >= length) return false; | 404 | if (at + 2 >= length) return false; |
| 371 | uint8_t patched[3] = {0x0F, 0xAE, uint8_t(code[at + 2] | 0x08)}; // reg field 6 -> 7 | 405 | const uint8_t opcode = mode == 1 ? 0xAE : 0x1F; |
| 372 | if (mode == 2) patched[1] = 0x1F, patched[2] = uint8_t(code[at + 2] & ~0x38); // reg field 0 | 406 | const uint8_t modrm = mode == 1 ? uint8_t(code[at + 2] | 0x08) : uint8_t(code[at + 2] & ~0x38); // reg 7 or 0 |
| 373 | void* const where = reinterpret_cast<void*>(rip + at); | 407 | void* const where = reinterpret_cast<void*>(rip + at); |
| 408 | volatile uint8_t* const live = static_cast<volatile uint8_t*>(where); | ||
| 409 | // One thread at a time unprotects, checks, writes and protects again: without the lock a thread could write into | ||
| 410 | // a page another one has just set back to read-execute, or set it back to the read-write-execute it found. | ||
| 411 | static SRWLOCK lock = SRWLOCK_INIT; | ||
| 412 | AcquireSRWLockExclusive(&lock); | ||
| 413 | bool ok = live[1] == opcode && live[2] == modrm; // another thread rewrote it since this thread's #UD | ||
| 414 | bool wrote = false; | ||
| 374 | DWORD old = 0; | 415 | DWORD old = 0; |
| 375 | if (!VirtualProtect(where, sizeof patched, PAGE_EXECUTE_READWRITE, &old)) return false; | 416 | if (!ok && live[0] == 0x0F && live[1] == 0xAE && live[2] == code[at + 2] && |
| 376 | std::memcpy(where, patched, sizeof patched); | 417 | VirtualProtect(where, 3, PAGE_EXECUTE_READWRITE, &old)) { |
| 377 | VirtualProtect(where, sizeof patched, old, &old); | 418 | // Opcode first: between the two stores a thread running the site sees 66 0F 1F /6, a NOP as well. ModRM first |
| 378 | FlushInstructionCache(GetCurrentProcess(), where, sizeof patched); | 419 | // would show it 66 0F AE /0, FXSAVE's encoding with a 66 the SDM does not allow (a 512-byte store at the |
| 379 | static std::atomic<unsigned> sites{0}; | 420 | // operand, or a #UD that is no longer CLWB). CLFLUSHOPT only changes ModRM, one store. |
| 380 | const unsigned n = ++sites; | 421 | if (live[1] != opcode) live[1] = opcode; |
| 381 | if (n <= 4 || !(n & (n - 1))) | 422 | live[2] = modrm; |
| 382 | std::fprintf(stderr, "[rt] cpu: CLWB at %p rewritten as %s (%u sites so far)\n", reinterpret_cast<void*>(rip), | 423 | VirtualProtect(where, 3, old, &old); |
| 383 | mode == 1 ? "CLFLUSHOPT" : "a NOP", n); | 424 | FlushInstructionCache(GetCurrentProcess(), where, 3); |
| 384 | return true; | 425 | ok = wrote = true; |
| 426 | } | ||
| 427 | ReleaseSRWLockExclusive(&lock); | ||
| 428 | if (wrote) { | ||
| 429 | const unsigned n = ++clwb_sites(); | ||
| 430 | if (n <= 4 || !(n & (n - 1))) | ||
| 431 | std::fprintf(stderr, "[rt] cpu: CLWB at %p rewritten as %s (%u sites so far)\n", | ||
| 432 | reinterpret_cast<void*>(rip), mode == 1 ? "CLFLUSHOPT" : "a NOP", n); | ||
| 433 | } | ||
| 434 | return ok; | ||
| 385 | } | 435 | } |
| 386 | 436 | ||
| 387 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | 437 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { |
| @@ -391,7 +441,8 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | |||
| 391 | const std::size_t avail = readable(c->Rip, sizeof code); // the instruction may end at a page boundary | 441 | const std::size_t avail = readable(c->Rip, sizeof code); // the instruction may end at a page boundary |
| 392 | std::memcpy(code, reinterpret_cast<const void*>(c->Rip), avail); | 442 | std::memcpy(code, reinterpret_cast<const void*>(c->Rip), avail); |
| 393 | const Decoded d = decode(code, avail); | 443 | const Decoded d = decode(code, avail); |
| 394 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; | 444 | if (d.op == Op::none) |
| 445 | return clwb_rewritten(code, avail) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; | ||
| 395 | if (d.op == Op::clwb && patch_clwb(c->Rip, code, d.length)) return EXCEPTION_CONTINUE_EXECUTION; | 446 | if (d.op == Op::clwb && patch_clwb(c->Rip, code, d.length)) return EXCEPTION_CONTINUE_EXECUTION; |
| 396 | EXCEPTION_RECORD fault; | 447 | EXCEPTION_RECORD fault; |
| 397 | if (d.op == Op::clzero && !d.addr32 && d.length == 3) { | 448 | if (d.op == Op::clzero && !d.addr32 && d.length == 3) { |
diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp index 824c38718..b715320db 100644 --- a/runtime/test/cpu_emulation_test.cpp +++ b/runtime/test/cpu_emulation_test.cpp | |||
| @@ -5,10 +5,12 @@ | |||
| 5 | // The test prints which path each instruction took. No game files. | 5 | // The test prints which path each instruction took. No game files. |
| 6 | #include <windows.h> | 6 | #include <windows.h> |
| 7 | 7 | ||
| 8 | #include <atomic> | ||
| 8 | #include <cstdint> | 9 | #include <cstdint> |
| 9 | #include <cstdio> | 10 | #include <cstdio> |
| 10 | #include <cstring> | 11 | #include <cstring> |
| 11 | #include <initializer_list> | 12 | #include <initializer_list> |
| 13 | #include <thread> | ||
| 12 | #include <vector> | 14 | #include <vector> |
| 13 | 15 | ||
| 14 | #include "cpu_emulation.h" | 16 | #include "cpu_emulation.h" |
| @@ -350,6 +352,115 @@ void test_live(const ce::Host& host) { | |||
| 350 | Code ud({0x0F, 0x0B, 0xC3}); | 352 | Code ud({0x0F, 0x0B, 0xC3}); |
| 351 | check(!run(ud, nullptr, nullptr, &ex) && ex == STATUS_ILLEGAL_INSTRUCTION, "ud2 still faults"); | 353 | check(!run(ud, nullptr, nullptr, &ex) && ex == STATUS_ILLEGAL_INSTRUCTION, "ud2 still faults"); |
| 352 | } | 354 | } |
| 355 | |||
| 356 | // ---- CLWB rewritten in place, with the handler called on a made-up #UD ---- | ||
| 357 | // The #UD a CPU without CLWB raises is handed to the handler directly, so this runs on a host with CLWB too. A | ||
| 358 | // thread whose #UD is handled after another thread rewrote the same site reads the new bytes: it must continue at | ||
| 359 | // the site (the CPU runs the rewritten instruction), never pass the exception on. Each site is rewritten once. | ||
| 360 | |||
| 361 | // The handler's answer to a #UD at `rip`, and the RIP it continues at; -2 when the handler itself faulted. | ||
| 362 | LONG fake_ud(uint64_t rip, uint64_t* rip_after) { | ||
| 363 | EXCEPTION_RECORD record{}; | ||
| 364 | record.ExceptionCode = DWORD(STATUS_ILLEGAL_INSTRUCTION); | ||
| 365 | record.ExceptionAddress = reinterpret_cast<void*>(rip); | ||
| 366 | CONTEXT context{}; | ||
| 367 | context.Rip = rip; | ||
| 368 | EXCEPTION_POINTERS pointers{&record, &context}; | ||
| 369 | __try { | ||
| 370 | const LONG r = ce::handler(&pointers); | ||
| 371 | *rip_after = context.Rip; | ||
| 372 | return r; | ||
| 373 | } __except (EXCEPTION_EXECUTE_HANDLER) { | ||
| 374 | return -2; | ||
| 375 | } | ||
| 376 | } | ||
| 377 | |||
| 378 | bool call_at(const uint8_t* code, const void* in) { | ||
| 379 | __try { | ||
| 380 | reinterpret_cast<Fn>(const_cast<uint8_t*>(code))(in, nullptr); | ||
| 381 | return true; | ||
| 382 | } __except (EXCEPTION_EXECUTE_HANDLER) { | ||
| 383 | return false; | ||
| 384 | } | ||
| 385 | } | ||
| 386 | |||
| 387 | // clwb [rcx]; ret at `at` became CLFLUSHOPT [rcx] (reg field 7) or the NOP 0F 1F /0 with the same operand. | ||
| 388 | bool clwb_rewritten(const uint8_t* at) { | ||
| 389 | return at[0] == 0x66 && at[1] == 0x0F && at[4] == 0xC3 && (at[3] & 0xC7) == 0x01 && | ||
| 390 | ((at[2] == 0xAE && (at[3] & 0x38) == 0x38) || (at[2] == 0x1F && (at[3] & 0x38) == 0)); | ||
| 391 | } | ||
| 392 | |||
| 393 | bool executable_read_only(const void* p) { | ||
| 394 | MEMORY_BASIC_INFORMATION mbi{}; | ||
| 395 | return VirtualQuery(p, &mbi, sizeof mbi) && mbi.Protect == PAGE_EXECUTE_READ; | ||
| 396 | } | ||
| 397 | |||
| 398 | void test_clwb_rewrite() { | ||
| 399 | char value[4]{}; | ||
| 400 | if (GetEnvironmentVariableA("LEONIDA_CLWB_PATCH", value, sizeof(value)) > 0 && value[0] == '0') { | ||
| 401 | std::printf("clwb rewrite: skipped (LEONIDA_CLWB_PATCH=0)\n"); | ||
| 402 | return; | ||
| 403 | } | ||
| 404 | constexpr int kSites = 2048, kStride = 8, kThreads = 16; | ||
| 405 | const std::size_t bytes = std::size_t(kSites + 1) * kStride; | ||
| 406 | auto* mem = static_cast<uint8_t*>(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | ||
| 407 | check(mem != nullptr, "clwb rewrite: allocate the sites"); | ||
| 408 | if (!mem) return; | ||
| 409 | for (int s = 0; s <= kSites; ++s) { // clwb [rcx]; ret; int3 x3 | ||
| 410 | const uint8_t site[kStride] = {0x66, 0x0F, 0xAE, 0x31, 0xC3, 0xCC, 0xCC, 0xCC}; | ||
| 411 | std::memcpy(mem + std::size_t(s) * kStride, site, kStride); | ||
| 412 | } | ||
| 413 | DWORD old = 0; | ||
| 414 | VirtualProtect(mem, bytes, PAGE_EXECUTE_READ, &old); // as the game's code: the handler must unprotect it | ||
| 415 | FlushInstructionCache(GetCurrentProcess(), mem, bytes); | ||
| 416 | |||
| 417 | // (a) The first #UD rewrites the site and continues at it, which then runs on any host. | ||
| 418 | uint8_t* const one = mem + std::size_t(kSites) * kStride; | ||
| 419 | const uint64_t rip = reinterpret_cast<uint64_t>(one); | ||
| 420 | const unsigned before = ce::clwb_sites().load(); | ||
| 421 | uint64_t after = 0; | ||
| 422 | check(fake_ud(rip, &after) == EXCEPTION_CONTINUE_EXECUTION && after == rip, | ||
| 423 | "clwb rewrite: the first #UD continues at the site"); | ||
| 424 | check(clwb_rewritten(one), "clwb rewrite: the site is rewritten, operand kept"); | ||
| 425 | check(ce::clwb_sites().load() == before + 1, "clwb rewrite: the site is counted once"); | ||
| 426 | check(executable_read_only(one), "clwb rewrite: the page is execute-read again"); | ||
| 427 | alignas(64) static uint8_t line[64]; | ||
| 428 | check(call_at(one, line), "clwb rewrite: the rewritten site runs"); | ||
| 429 | |||
| 430 | // (b) A #UD handled after the site was rewritten (another thread's, in the game) continues at the site too. | ||
| 431 | after = 0; | ||
| 432 | check(fake_ud(rip, &after) == EXCEPTION_CONTINUE_EXECUTION && after == rip, | ||
| 433 | "clwb rewrite: a #UD on an already rewritten site continues at it"); | ||
| 434 | check(ce::clwb_sites().load() == before + 1, "clwb rewrite: an already rewritten site is not counted again"); | ||
| 435 | |||
| 436 | // (c) 16 threads take a #UD on each of 2048 fresh sites at once, in the same order so they meet on each site. | ||
| 437 | std::atomic<int> waiting{kThreads}, bad{0}; | ||
| 438 | std::vector<std::thread> threads; | ||
| 439 | for (int t = 0; t < kThreads; ++t) | ||
| 440 | threads.emplace_back([&] { | ||
| 441 | waiting.fetch_sub(1); | ||
| 442 | while (waiting.load()) std::this_thread::yield(); | ||
| 443 | for (int s = 0; s < kSites; ++s) { | ||
| 444 | const uint64_t at = reinterpret_cast<uint64_t>(mem + std::size_t(s) * kStride); | ||
| 445 | uint64_t continued = 0; | ||
| 446 | if (fake_ud(at, &continued) != EXCEPTION_CONTINUE_EXECUTION || continued != at) bad.fetch_add(1); | ||
| 447 | } | ||
| 448 | }); | ||
| 449 | for (auto& t : threads) t.join(); | ||
| 450 | if (bad.load()) std::fprintf(stderr, "clwb rewrite: %d of %d concurrent #UDs not continued at the site\n", | ||
| 451 | bad.load(), kThreads * kSites); | ||
| 452 | check(bad.load() == 0, "clwb rewrite: every concurrent #UD continues at its site"); | ||
| 453 | const unsigned counted = ce::clwb_sites().load() - before - 1; | ||
| 454 | if (counted != unsigned(kSites)) std::fprintf(stderr, "clwb rewrite: %u sites counted for %d\n", counted, kSites); | ||
| 455 | check(counted == unsigned(kSites), "clwb rewrite: each concurrently hit site is counted once"); | ||
| 456 | bool all = true; | ||
| 457 | for (int s = 0; s < kSites; ++s) all &= clwb_rewritten(mem + std::size_t(s) * kStride); | ||
| 458 | check(all, "clwb rewrite: every concurrently hit site is rewritten"); | ||
| 459 | check(executable_read_only(mem) && executable_read_only(mem + bytes - 1), | ||
| 460 | "clwb rewrite: the pages are execute-read again"); | ||
| 461 | std::printf("clwb rewrite: %d threads x %d sites\n", kThreads, kSites); | ||
| 462 | VirtualFree(mem, 0, MEM_RELEASE); | ||
| 463 | } | ||
| 353 | } // namespace | 464 | } // namespace |
| 354 | 465 | ||
| 355 | int main() { | 466 | int main() { |
| @@ -361,6 +472,7 @@ int main() { | |||
| 361 | host.clwb); | 472 | host.clwb); |
| 362 | check(ce::install(), "install the handler"); | 473 | check(ce::install(), "install the handler"); |
| 363 | test_live(host); | 474 | test_live(host); |
| 475 | test_clwb_rewrite(); | ||
| 364 | if (failures) { | 476 | if (failures) { |
| 365 | std::fprintf(stderr, "%d failure(s)\n", failures); | 477 | std::fprintf(stderr, "%d failure(s)\n", failures); |
| 366 | return 1; | 478 | return 1; |