mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:08:38 +00:00
Merge pull request #2559 from OreoFR/fix/clwb-patch-race
cpu_emulation: CLWB rewrite in place without the race between threads (follow-up of #1472)
This commit is contained in:
@ -350,6 +350,90 @@ inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail,
|
||||
return ClzeroLoopResult::ok;
|
||||
}
|
||||
|
||||
// CLWB is rewritten in place at its first #UD, so a loop over a buffer faults once instead of once per cache line.
|
||||
// The retail title's GPU upload worker flushes whole buffers that way (exe+0x532f1b0 on 1.0.2.1); under Wine a #UD
|
||||
// costs tens of microseconds, which kept that worker busy for minutes per buffer and the boot waiting on it.
|
||||
// 66 0F AE /6 (CLWB) becomes 66 0F AE /7 (CLFLUSHOPT): the same operand and length, and it writes the line back too
|
||||
// (then evicts it). A host without CLFLUSHOPT gets 66 0F 1F /0, a NOP of the same length that touches no memory.
|
||||
// LEONIDA_CLWB_PATCH=0 keeps emulating every execution instead.
|
||||
// Threads of that worker reach the same site together: a #UD handled after another thread rewrote the site finds
|
||||
// the new instruction there and continues at it, and the rewrite itself is done once, under a lock.
|
||||
|
||||
// 1: rewrite as CLFLUSHOPT, 2: as the NOP (no CLFLUSHOPT on this host), 0: LEONIDA_CLWB_PATCH=0.
|
||||
inline int clwb_patch_mode() {
|
||||
static const int mode = [] {
|
||||
char value[4]{};
|
||||
if (GetEnvironmentVariableA("LEONIDA_CLWB_PATCH", value, sizeof(value)) > 0 && value[0] == '0') return 0;
|
||||
int r[4];
|
||||
__cpuidex(r, 7, 0);
|
||||
return ((r[1] >> 23) & 1) ? 1 : 2; // EBX bit 23: CLFLUSHOPT
|
||||
}();
|
||||
return mode;
|
||||
}
|
||||
|
||||
// How many CLWB sites were rewritten so far; each counts once, by the thread that wrote it.
|
||||
inline std::atomic<unsigned>& clwb_sites() {
|
||||
static std::atomic<unsigned> sites{0};
|
||||
return sites;
|
||||
}
|
||||
|
||||
// True when `code` (`avail` bytes at a #UD) holds the form patch_clwb writes on this host, or the NOP's halfway
|
||||
// state (66 0F 1F /6): another thread rewrote the site after this thread's #UD. Neither form raises #UD here, so the
|
||||
// thread continues at the site and the CPU runs it.
|
||||
inline bool clwb_rewritten(const uint8_t* code, std::size_t avail) {
|
||||
const int mode = clwb_patch_mode();
|
||||
if (!mode) return false;
|
||||
std::size_t i = 0;
|
||||
bool p66 = false;
|
||||
for (; i < avail && i < 14; ++i) {
|
||||
const uint8_t b = code[i];
|
||||
if (b == 0x66) p66 = true;
|
||||
else if (!((b & 0xF0) == 0x40 || b == 0x67 || b == 0x2E || b == 0x3E || b == 0x26 || b == 0x36 ||
|
||||
b == 0x64 || b == 0x65)) break;
|
||||
}
|
||||
if (!p66 || i + 3 > avail || code[i] != 0x0F || (code[i + 2] >> 6) == 3) return false;
|
||||
const int reg = (code[i + 2] >> 3) & 7;
|
||||
return mode == 1 ? code[i + 1] == 0xAE && reg == 7 : code[i + 1] == 0x1F && (reg == 0 || reg == 6);
|
||||
}
|
||||
|
||||
inline bool patch_clwb(uint64_t rip, const uint8_t* code, std::size_t length) {
|
||||
const int mode = clwb_patch_mode();
|
||||
if (!mode) return false;
|
||||
std::size_t at = 0;
|
||||
while (at + 2 < length && !(code[at] == 0x0F && code[at + 1] == 0xAE)) ++at;
|
||||
if (at + 2 >= length) return false;
|
||||
const uint8_t opcode = mode == 1 ? 0xAE : 0x1F;
|
||||
const uint8_t modrm = mode == 1 ? uint8_t(code[at + 2] | 0x08) : uint8_t(code[at + 2] & ~0x38); // reg 7 or 0
|
||||
void* const where = reinterpret_cast<void*>(rip + at);
|
||||
volatile uint8_t* const live = static_cast<volatile uint8_t*>(where);
|
||||
// One thread at a time unprotects, checks, writes and protects again: without the lock a thread could write into
|
||||
// a page another one has just set back to read-execute, or set it back to the read-write-execute it found.
|
||||
static SRWLOCK lock = SRWLOCK_INIT;
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
bool ok = live[1] == opcode && live[2] == modrm; // another thread rewrote it since this thread's #UD
|
||||
bool wrote = false;
|
||||
DWORD old = 0;
|
||||
if (!ok && live[0] == 0x0F && live[1] == 0xAE && live[2] == code[at + 2] &&
|
||||
VirtualProtect(where, 3, PAGE_EXECUTE_READWRITE, &old)) {
|
||||
// Opcode first: between the two stores a thread running the site sees 66 0F 1F /6, a NOP as well. ModRM first
|
||||
// would show it 66 0F AE /0, FXSAVE's encoding with a 66 the SDM does not allow (a 512-byte store at the
|
||||
// operand, or a #UD that is no longer CLWB). CLFLUSHOPT only changes ModRM, one store.
|
||||
if (live[1] != opcode) live[1] = opcode;
|
||||
live[2] = modrm;
|
||||
VirtualProtect(where, 3, old, &old);
|
||||
FlushInstructionCache(GetCurrentProcess(), where, 3);
|
||||
ok = wrote = true;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
if (wrote) {
|
||||
const unsigned n = ++clwb_sites();
|
||||
if (n <= 4 || !(n & (n - 1)))
|
||||
std::fprintf(stderr, "[rt] cpu: CLWB at %p rewritten as %s (%u sites so far)\n",
|
||||
reinterpret_cast<void*>(rip), mode == 1 ? "CLFLUSHOPT" : "a NOP", n);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
|
||||
if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH;
|
||||
CONTEXT* c = info->ContextRecord;
|
||||
@ -357,7 +441,9 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
|
||||
const std::size_t avail = readable(c->Rip, sizeof code); // the instruction may end at a page boundary
|
||||
std::memcpy(code, reinterpret_cast<const void*>(c->Rip), avail);
|
||||
const Decoded d = decode(code, avail);
|
||||
if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH;
|
||||
if (d.op == Op::none)
|
||||
return clwb_rewritten(code, avail) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
|
||||
if (d.op == Op::clwb && patch_clwb(c->Rip, code, d.length)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
EXCEPTION_RECORD fault;
|
||||
if (d.op == Op::clzero && !d.addr32 && d.length == 3) {
|
||||
const uint64_t fault_rip = c->Rip;
|
||||
|
||||
@ -5,10 +5,12 @@
|
||||
// The test prints which path each instruction took. No game files.
|
||||
#include <windows.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "cpu_emulation.h"
|
||||
@ -334,11 +336,131 @@ void test_live(const ce::Host& host) {
|
||||
uint32_t marker = 0;
|
||||
check(run(wb, lines, &marker, &ex) && marker == 1, "clwb ran and execution continued after it");
|
||||
std::printf("clwb: %s\n", path(host.clwb));
|
||||
if (!host.clwb) {
|
||||
// Both sites were rewritten at their first #UD: CLFLUSHOPT (reg field 7) or the same-length NOP.
|
||||
const auto rewritten = [&](int at) {
|
||||
return (wb.mem[at] == 0xAE && (wb.mem[at + 1] & 0x38) == 0x38) ||
|
||||
(wb.mem[at] == 0x1F && (wb.mem[at + 1] & 0x38) == 0);
|
||||
};
|
||||
check(rewritten(4) && rewritten(8), "clwb sites rewritten in place");
|
||||
check(wb.mem[10] == 0x01 && wb.mem[11] == 0x08, "the rewritten clwb keeps its SIB and displacement");
|
||||
marker = 0;
|
||||
check(run(wb, lines, &marker, &ex) && marker == 1, "the rewritten code runs again");
|
||||
}
|
||||
|
||||
// A #UD the handler does not know stays an illegal-instruction exception: ud2; ret
|
||||
Code ud({0x0F, 0x0B, 0xC3});
|
||||
check(!run(ud, nullptr, nullptr, &ex) && ex == STATUS_ILLEGAL_INSTRUCTION, "ud2 still faults");
|
||||
}
|
||||
|
||||
// ---- CLWB rewritten in place, with the handler called on a made-up #UD ----
|
||||
// The #UD a CPU without CLWB raises is handed to the handler directly, so this runs on a host with CLWB too. A
|
||||
// thread whose #UD is handled after another thread rewrote the same site reads the new bytes: it must continue at
|
||||
// the site (the CPU runs the rewritten instruction), never pass the exception on. Each site is rewritten once.
|
||||
|
||||
// The handler's answer to a #UD at `rip`, and the RIP it continues at; -2 when the handler itself faulted.
|
||||
LONG fake_ud(uint64_t rip, uint64_t* rip_after) {
|
||||
EXCEPTION_RECORD record{};
|
||||
record.ExceptionCode = DWORD(STATUS_ILLEGAL_INSTRUCTION);
|
||||
record.ExceptionAddress = reinterpret_cast<void*>(rip);
|
||||
CONTEXT context{};
|
||||
context.Rip = rip;
|
||||
EXCEPTION_POINTERS pointers{&record, &context};
|
||||
__try {
|
||||
const LONG r = ce::handler(&pointers);
|
||||
*rip_after = context.Rip;
|
||||
return r;
|
||||
} __except (EXCEPTION_EXECUTE_HANDLER) {
|
||||
return -2;
|
||||
}
|
||||
}
|
||||
|
||||
bool call_at(const uint8_t* code, const void* in) {
|
||||
__try {
|
||||
reinterpret_cast<Fn>(const_cast<uint8_t*>(code))(in, nullptr);
|
||||
return true;
|
||||
} __except (EXCEPTION_EXECUTE_HANDLER) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// clwb [rcx]; ret at `at` became CLFLUSHOPT [rcx] (reg field 7) or the NOP 0F 1F /0 with the same operand.
|
||||
bool clwb_rewritten(const uint8_t* at) {
|
||||
return at[0] == 0x66 && at[1] == 0x0F && at[4] == 0xC3 && (at[3] & 0xC7) == 0x01 &&
|
||||
((at[2] == 0xAE && (at[3] & 0x38) == 0x38) || (at[2] == 0x1F && (at[3] & 0x38) == 0));
|
||||
}
|
||||
|
||||
bool executable_read_only(const void* p) {
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
return VirtualQuery(p, &mbi, sizeof mbi) && mbi.Protect == PAGE_EXECUTE_READ;
|
||||
}
|
||||
|
||||
void test_clwb_rewrite() {
|
||||
char value[4]{};
|
||||
if (GetEnvironmentVariableA("LEONIDA_CLWB_PATCH", value, sizeof(value)) > 0 && value[0] == '0') {
|
||||
std::printf("clwb rewrite: skipped (LEONIDA_CLWB_PATCH=0)\n");
|
||||
return;
|
||||
}
|
||||
constexpr int kSites = 2048, kStride = 8, kThreads = 16;
|
||||
const std::size_t bytes = std::size_t(kSites + 1) * kStride;
|
||||
auto* mem = static_cast<uint8_t*>(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
check(mem != nullptr, "clwb rewrite: allocate the sites");
|
||||
if (!mem) return;
|
||||
for (int s = 0; s <= kSites; ++s) { // clwb [rcx]; ret; int3 x3
|
||||
const uint8_t site[kStride] = {0x66, 0x0F, 0xAE, 0x31, 0xC3, 0xCC, 0xCC, 0xCC};
|
||||
std::memcpy(mem + std::size_t(s) * kStride, site, kStride);
|
||||
}
|
||||
DWORD old = 0;
|
||||
VirtualProtect(mem, bytes, PAGE_EXECUTE_READ, &old); // as the game's code: the handler must unprotect it
|
||||
FlushInstructionCache(GetCurrentProcess(), mem, bytes);
|
||||
|
||||
// (a) The first #UD rewrites the site and continues at it, which then runs on any host.
|
||||
uint8_t* const one = mem + std::size_t(kSites) * kStride;
|
||||
const uint64_t rip = reinterpret_cast<uint64_t>(one);
|
||||
const unsigned before = ce::clwb_sites().load();
|
||||
uint64_t after = 0;
|
||||
check(fake_ud(rip, &after) == EXCEPTION_CONTINUE_EXECUTION && after == rip,
|
||||
"clwb rewrite: the first #UD continues at the site");
|
||||
check(clwb_rewritten(one), "clwb rewrite: the site is rewritten, operand kept");
|
||||
check(ce::clwb_sites().load() == before + 1, "clwb rewrite: the site is counted once");
|
||||
check(executable_read_only(one), "clwb rewrite: the page is execute-read again");
|
||||
alignas(64) static uint8_t line[64];
|
||||
check(call_at(one, line), "clwb rewrite: the rewritten site runs");
|
||||
|
||||
// (b) A #UD handled after the site was rewritten (another thread's, in the game) continues at the site too.
|
||||
after = 0;
|
||||
check(fake_ud(rip, &after) == EXCEPTION_CONTINUE_EXECUTION && after == rip,
|
||||
"clwb rewrite: a #UD on an already rewritten site continues at it");
|
||||
check(ce::clwb_sites().load() == before + 1, "clwb rewrite: an already rewritten site is not counted again");
|
||||
|
||||
// (c) 16 threads take a #UD on each of 2048 fresh sites at once, in the same order so they meet on each site.
|
||||
std::atomic<int> waiting{kThreads}, bad{0};
|
||||
std::vector<std::thread> threads;
|
||||
for (int t = 0; t < kThreads; ++t)
|
||||
threads.emplace_back([&] {
|
||||
waiting.fetch_sub(1);
|
||||
while (waiting.load()) std::this_thread::yield();
|
||||
for (int s = 0; s < kSites; ++s) {
|
||||
const uint64_t at = reinterpret_cast<uint64_t>(mem + std::size_t(s) * kStride);
|
||||
uint64_t continued = 0;
|
||||
if (fake_ud(at, &continued) != EXCEPTION_CONTINUE_EXECUTION || continued != at) bad.fetch_add(1);
|
||||
}
|
||||
});
|
||||
for (auto& t : threads) t.join();
|
||||
if (bad.load()) std::fprintf(stderr, "clwb rewrite: %d of %d concurrent #UDs not continued at the site\n",
|
||||
bad.load(), kThreads * kSites);
|
||||
check(bad.load() == 0, "clwb rewrite: every concurrent #UD continues at its site");
|
||||
const unsigned counted = ce::clwb_sites().load() - before - 1;
|
||||
if (counted != unsigned(kSites)) std::fprintf(stderr, "clwb rewrite: %u sites counted for %d\n", counted, kSites);
|
||||
check(counted == unsigned(kSites), "clwb rewrite: each concurrently hit site is counted once");
|
||||
bool all = true;
|
||||
for (int s = 0; s < kSites; ++s) all &= clwb_rewritten(mem + std::size_t(s) * kStride);
|
||||
check(all, "clwb rewrite: every concurrently hit site is rewritten");
|
||||
check(executable_read_only(mem) && executable_read_only(mem + bytes - 1),
|
||||
"clwb rewrite: the pages are execute-read again");
|
||||
std::printf("clwb rewrite: %d threads x %d sites\n", kThreads, kSites);
|
||||
VirtualFree(mem, 0, MEM_RELEASE);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
@ -350,6 +472,7 @@ int main() {
|
||||
host.clwb);
|
||||
check(ce::install(), "install the handler");
|
||||
test_live(host);
|
||||
test_clwb_rewrite();
|
||||
if (failures) {
|
||||
std::fprintf(stderr, "%d failure(s)\n", failures);
|
||||
return 1;
|
||||
|
||||
Reference in New Issue
Block a user