From 982c02890da53ffe8716b79248f09a0a854fc84b Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:52:27 -0500 Subject: [PATCH 1/7] Shared: the per-game state folder, its lock and atomic writes (wg_state.h) One header-only module for every WrongGPU program that changes per-game state after the install (the launcher, the front end and its menu plugin, the RR plugin): - the ONE state folder \wronggpu-setup (settings.ini: settings chosen in the launcher or a WrongGPU menu in the game, over wronggpu.ini's install defaults; model-choice.ini: the model choice record); - StateLock: a named mutex per game folder, named from the folder's file identity (volume serial + file index, so every spelling of the path gives the same name), open to every integrity level, bounded wait, abandoned = taken; - WriteAtomic: temporary file in the same folder (created only where nothing is), flushed, MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), the temporary file deleted on any failure; - settings.ini in a strict key=value format (corrupt = no keys); SetSettings is the locked read-modify-write (an unreadable file is never overwritten, the folder never created). test_wg_state (ctest wgshared_state): the format, real-file writes and cleanup, the lock name for several spellings, four child processes doing 50 locked increments each of one counter (200 at the end), a busy lock (bounded wait, nothing written) and a holder that dies (abandoned, taken). Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/CMakeLists.txt | 12 + clean/wgshared/include/wg_state.h | 298 +++++++++++++++++++++++++ clean/wgshared/tests/test_wg_state.cpp | 242 ++++++++++++++++++++ 3 files changed, 552 insertions(+) create mode 100644 clean/wgshared/include/wg_state.h create mode 100644 clean/wgshared/tests/test_wg_state.cpp diff --git a/clean/wgshared/CMakeLists.txt b/clean/wgshared/CMakeLists.txt index e868fee9..00721c49 100644 --- a/clean/wgshared/CMakeLists.txt +++ b/clean/wgshared/CMakeLists.txt @@ -45,6 +45,18 @@ if(WIN32) target_link_options(test_cross_reader PRIVATE -static) endif() add_test(NAME wgshared_cross_reader COMMAND test_cross_reader) + + # The per-game state folder (wg_state.h): strict settings.ini, atomic writes, the state lock across real processes. + add_executable(test_wg_state ${CMAKE_CURRENT_LIST_DIR}/tests/test_wg_state.cpp) + target_link_libraries(test_wg_state PRIVATE wg_shared_headers advapi32) + set_target_properties(test_wg_state PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + if(MSVC) + target_compile_options(test_wg_state PRIVATE /W4 /WX /permissive- /utf-8) + else() + target_compile_options(test_wg_state PRIVATE -Wall -Wextra -municode) + target_link_options(test_wg_state PRIVATE -static -municode) + endif() + add_test(NAME wgshared_state COMMAND test_wg_state) endif() find_package(Python3 COMPONENTS Interpreter QUIET) diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h new file mode 100644 index 00000000..6bb756c7 --- /dev/null +++ b/clean/wgshared/include/wg_state.h @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: MIT +#pragma once +// WrongGPU's per-game state folder (0.6.5): ONE folder per game, \wronggpu-setup (the launcher's state folder, +// beside the install record), holding everything WrongGPU's user interfaces change after the install: +// settings.ini settings chosen in the launcher or in a WrongGPU menu in the game (for example the RR plugin's +// rr_mode): they take precedence over the install's defaults in wronggpu.ini, which no WrongGPU +// program rewrites after the install (wronggpu.ini is the player's to edit); +// model-choice.ini the model choice record (clean/fsr/src/model_choice_record.h). +// The folder is always WrongGPU's: an uninstall removes these files, a repair or update keeps them. +// +// Every read-modify-write of a file in the folder, by any WrongGPU program (the launcher, the elevated worker, the front +// end, the menu plugin, the RR plugin), holds the game's state lock (StateLock): a named mutex per game folder, +// Local\WrongGPU-state-- +// taken from the game folder's file identity, so every spelling of the path (case, 8.3 names, a mapped drive or a +// junction to the same folder) gives the same name. The mutex grants SYNCHRONIZE and MUTEX_MODIFY_STATE to everyone and +// carries a low integrity label, so an elevated launcher and the game (any integrity) share it. A holder that dies leaves +// the mutex abandoned: the next waiter gets it (the files are replaced atomically, so they are whole either way). +// +// Writes are atomic (WriteAtomic): a new temporary file in the same folder (.wgtmp--, created only where +// nothing is), flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the file; the temporary file is deleted when +// any step fails. A reader sees the old file or the new one, never part of one. Temporary files never count as state. +// +// settings.ini, strictly (anything else is CORRUPT: readers treat the file as empty and say so; the next write replaces it): +// ; comment lines and blank lines +// key=value key: [a-z0-9_], 1..64 chars; value: [A-Za-z0-9_.+-], 0..256 chars; each key at most once; +// no sections, no spaces around '='; CRLF or LF line ends; UTF-8 without anything outside ASCII. +// Written for this project; Windows API and the C++ standard library only. +#include +#include +#include +#include + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#ifdef _MSC_VER +#pragma comment(lib, "advapi32.lib") +#endif + +namespace wgstate { + +constexpr const wchar_t* kStateFolder = L"wronggpu-setup"; +constexpr const wchar_t* kSettingsFile = L"settings.ini"; +constexpr const wchar_t* kModelChoiceFile = L"model-choice.ini"; +constexpr const wchar_t* kTempMark = L".wgtmp-"; // .wgtmp--: a write in progress (or one a crash left) +constexpr DWORD kDefaultWaitMs = 5000; + +inline std::wstring JoinPath(std::wstring a, const std::wstring& b) { + if (!a.empty() && a.back() != L'\\' && a.back() != L'/') a.push_back(L'\\'); + return a + b; +} +inline std::wstring StateDirOf(const std::wstring& gameDir) { return JoinPath(gameDir, kStateFolder); } +inline std::wstring SettingsPathOf(const std::wstring& gameDir) { return JoinPath(StateDirOf(gameDir), kSettingsFile); } +inline bool IsDirectory(const std::wstring& p) { + const DWORD a = GetFileAttributesW(p.c_str()); + return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY); +} +// A temporary file of WriteAtomic (its own name contains the mark; the state files' names never do). +inline bool IsTempName(const std::wstring& name) { return name.find(kTempMark) != std::wstring::npos; } + +// The state lock's name for the game folder `gameDir`; false (and *err) when the folder cannot be opened. +inline bool LockNameFor(const std::wstring& gameDir, std::wstring* name, DWORD* err = nullptr) { + HANDLE h = CreateFileW(gameDir.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + if (h == INVALID_HANDLE_VALUE) { + if (err) *err = GetLastError(); + return false; + } + BY_HANDLE_FILE_INFORMATION info{}; + const BOOL ok = GetFileInformationByHandle(h, &info); + const DWORD e = GetLastError(); + CloseHandle(h); + if (!ok) { + if (err) *err = e; + return false; + } + wchar_t buf[96]; + const unsigned long long index = (static_cast(info.nFileIndexHigh) << 32) | info.nFileIndexLow; + swprintf(buf, sizeof buf / sizeof buf[0], L"Local\\WrongGPU-state-%08lX-%016llX", static_cast(info.dwVolumeSerialNumber), index); + *name = buf; + return true; +} + +// The game's state lock, held from construction (when held()) to destruction. Bounded wait: not held after waitMs. +class StateLock { +public: + explicit StateLock(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) { + std::wstring name; + if (!LockNameFor(gameDir, &name, &err_)) return; + PSECURITY_DESCRIPTOR sd = nullptr; + SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, FALSE}; + // everyone: SYNCHRONIZE | MUTEX_MODIFY_STATE; SYSTEM and administrators: all; low integrity label (no write-up block) + if (ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;0x00100001;;;WD)(A;;GA;;;SY)(A;;GA;;;BA)S:(ML;;NW;;;LW)", + SDDL_REVISION_1, &sd, nullptr)) + sa.lpSecurityDescriptor = sd; + mutex_ = CreateMutexW(sa.lpSecurityDescriptor ? &sa : nullptr, FALSE, name.c_str()); + if (!mutex_ && GetLastError() == ERROR_ACCESS_DENIED) mutex_ = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, name.c_str()); + if (!mutex_) err_ = GetLastError(); + if (sd) LocalFree(sd); + if (!mutex_) return; + const DWORD w = WaitForSingleObject(mutex_, waitMs); + held_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; + abandoned_ = w == WAIT_ABANDONED; + if (!held_) err_ = w == WAIT_TIMEOUT ? WAIT_TIMEOUT : GetLastError(); + } + ~StateLock() { + if (held_) ReleaseMutex(mutex_); + if (mutex_) CloseHandle(mutex_); + } + StateLock(const StateLock&) = delete; + StateLock& operator=(const StateLock&) = delete; + bool held() const { return held_; } + bool abandoned() const { return abandoned_; } // the previous holder ended without releasing it + DWORD error() const { return err_; } // why not held: WAIT_TIMEOUT, or the Win32 error + +private: + HANDLE mutex_ = nullptr; + bool held_ = false, abandoned_ = false; + DWORD err_ = 0; +}; + +// The whole file. false: missing (*missing = true) or unreadable (*missing = false; *err the Win32 error). +inline bool ReadBytes(const std::wstring& path, std::string* out, bool* missing = nullptr, DWORD* err = nullptr) { + out->clear(); + if (missing) *missing = false; + HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + const DWORD e = GetLastError(); + if (missing) *missing = e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND; + if (err) *err = e; + return false; + } + char buf[4096]; + DWORD got = 0; + bool ok = true; + for (;;) { + if (!ReadFile(h, buf, sizeof buf, &got, nullptr)) { ok = false; if (err) *err = GetLastError(); break; } + if (!got) break; + out->append(buf, got); + if (out->size() > (1u << 20)) { ok = false; if (err) *err = ERROR_FILE_TOO_LARGE; break; } // no state file is that large + } + CloseHandle(h); + if (!ok) out->clear(); + return ok; +} + +// The atomic replace described above. false (and *err) when any step failed; the file is then as it was. +inline bool WriteAtomic(const std::wstring& path, const std::string& bytes, DWORD* err = nullptr) { + static volatile LONG counter = 0; + DWORD e = 0; + for (int attempt = 0; attempt < 16; ++attempt) { + const std::wstring tmp = path + kTempMark + std::to_wstring(GetCurrentProcessId()) + L"-" + std::to_wstring(InterlockedIncrement(&counter)); + HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + e = GetLastError(); + if (e == ERROR_FILE_EXISTS || e == ERROR_ALREADY_EXISTS) continue; + break; + } + DWORD put = 0; + bool ok = bytes.empty() || (WriteFile(h, bytes.data(), static_cast(bytes.size()), &put, nullptr) && put == bytes.size()); + if (!ok) e = GetLastError() ? GetLastError() : ERROR_WRITE_FAULT; + if (ok && !FlushFileBuffers(h)) { ok = false; e = GetLastError(); } + CloseHandle(h); + if (ok && !MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { ok = false; e = GetLastError(); } + if (!ok) { + DeleteFileW(tmp.c_str()); + break; + } + return true; + } + if (err) *err = e ? e : ERROR_FILE_EXISTS; + return false; +} + +// ---- settings.ini ------------------------------------------------------------------------------------------------- +struct Settings { + std::vector> kv; // in file order + bool present = false; // the file was there and read + bool corrupt = false; // it was there and not in the format above (kv empty) + std::string why; // what was wrong (corrupt), or why it could not be read +}; +inline bool KeyChar(char c) { return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'; } +inline bool ValueChar(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '+' || c == '-'; +} +inline bool ValidKey(const std::string& k) { + if (k.empty() || k.size() > 64) return false; + for (char c : k) if (!KeyChar(c)) return false; + return true; +} +inline bool ValidValue(const std::string& v) { + if (v.size() > 256) return false; + for (char c : v) if (!ValueChar(c)) return false; + return true; +} +inline const std::string* Get(const Settings& s, const std::string& key) { + for (const auto& p : s.kv) if (p.first == key) return &p.second; + return nullptr; +} +// Sets key=value (added at the end when new). false: not a valid key or value (nothing changed). +inline bool Set(Settings& s, const std::string& key, const std::string& value) { + if (!ValidKey(key) || !ValidValue(value)) return false; + for (auto& p : s.kv) if (p.first == key) { p.second = value; return true; } + s.kv.emplace_back(key, value); + return true; +} +// Parses settings.ini text strictly; a text not in the format gives corrupt = true and no keys. +inline Settings ParseSettings(const std::string& text) { + Settings s; + s.present = true; + size_t a = 0; + int lineNo = 0; + while (a < text.size()) { + size_t e = text.find('\n', a); + if (e == std::string::npos) e = text.size(); + std::string line = text.substr(a, e - a); + a = e + 1; + ++lineNo; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty() || line[0] == ';') { + for (char c : line) if (static_cast(c) >= 0x80 || (c < 0x20 && c != '\t')) { s.kv.clear(); s.corrupt = true; s.why = "line " + std::to_string(lineNo) + ": not plain text"; return s; } + continue; + } + const size_t eq = line.find('='); + const std::string k = eq == std::string::npos ? line : line.substr(0, eq), v = eq == std::string::npos ? std::string() : line.substr(eq + 1); + if (eq == std::string::npos || !ValidKey(k) || !ValidValue(v) || Get(s, k)) { + s.kv.clear(); + s.corrupt = true; + s.why = "line " + std::to_string(lineNo) + (eq == std::string::npos ? ": no key=value" : !ValidKey(k) ? ": not a valid key" : !ValidValue(v) ? ": not a valid value" : ": the key appears twice"); + return s; + } + s.kv.emplace_back(k, v); + } + return s; +} +inline std::string RenderSettings(const Settings& s) { + std::string out = "; WrongGPU: settings chosen in the launcher or in a WrongGPU menu in the game (they take precedence over wronggpu.ini)\r\n"; + for (const auto& p : s.kv) out += p.first + "=" + p.second + "\r\n"; + return out; +} +// settings.ini of the game in gameDir. Missing: present = false, no keys. Unreadable or corrupt: no keys, why says so. +inline Settings ReadSettings(const std::wstring& gameDir) { + std::string text; + bool missing = false; + DWORD err = 0; + if (!ReadBytes(SettingsPathOf(gameDir), &text, &missing, &err)) { + Settings s; + if (!missing) s.why = "unreadable (error " + std::to_string(err) + ")"; + return s; + } + return ParseSettings(text); +} + +enum class SetResult { Ok, NoStateFolder, Busy, Unreadable, Invalid, WriteFailed }; +inline const char* SetResultWords(SetResult r) { + switch (r) { + case SetResult::Ok: return "saved"; + case SetResult::NoStateFolder: return "no WrongGPU state folder for this game (not installed by the launcher)"; + case SetResult::Busy: return "another WrongGPU program kept the game's state lock"; + case SetResult::Unreadable: return "the settings file could not be read (left as it is)"; + case SetResult::Invalid: return "not a valid key or value"; + case SetResult::WriteFailed: return "the settings file could not be written"; + } + return "?"; +} +// The read-modify-write of settings.ini under the game's state lock: the changes applied to the file as it is now (a +// corrupt file starts empty; an unreadable one is never overwritten). The state folder is never created here: without it +// the game has no WrongGPU install of the launcher (NoStateFolder). *err: the Win32 error of a failure. +inline SetResult SetSettings(const std::wstring& gameDir, const std::vector>& changes, + DWORD waitMs = kDefaultWaitMs, DWORD* err = nullptr) { + for (const auto& c : changes) if (!ValidKey(c.first) || !ValidValue(c.second)) return SetResult::Invalid; + if (!IsDirectory(StateDirOf(gameDir))) return SetResult::NoStateFolder; + StateLock lock(gameDir, waitMs); + if (!lock.held()) { if (err) *err = lock.error(); return SetResult::Busy; } + std::string text; + bool missing = false; + DWORD e = 0; + Settings s; + if (ReadBytes(SettingsPathOf(gameDir), &text, &missing, &e)) s = ParseSettings(text); + else if (!missing) { if (err) *err = e; return SetResult::Unreadable; } + if (s.corrupt) s = Settings(); + bool changed = !s.present; + for (const auto& c : changes) { + const std::string* now = Get(s, c.first); + if (!now || *now != c.second) { Set(s, c.first, c.second); changed = true; } + } + if (!changed) return SetResult::Ok; + if (!WriteAtomic(SettingsPathOf(gameDir), RenderSettings(s), &e)) { if (err) *err = e; return SetResult::WriteFailed; } + return SetResult::Ok; +} + +} // namespace wgstate diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp new file mode 100644 index 00000000..779251ee --- /dev/null +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -0,0 +1,242 @@ +// SPDX-License-Identifier: MIT +// Tests of wg_state.h (the per-game state folder, its lock and atomic writes) on real files and real processes: the strict +// settings.ini format, atomic writes and their cleanup, one lock name for every spelling of a folder, mutual exclusion +// across processes (concurrent read-modify-write of one counter from several child processes loses no update), a busy +// lock (bounded wait), an abandoned lock (a child that dies holding it), an unreadable file never overwritten, a corrupt +// file replaced, and no state folder created. The test runs itself as the child process (--child ...). +// Written for this project. +#include +#include +#include +#include + +#include "wg_state.h" + +using namespace wgstate; + +static int g_fail = 0, g_pass = 0; +static void check(bool ok, const char* what) { + if (ok) ++g_pass; + else { ++g_fail; std::printf("FAIL: %s\n", what); } +} + +static std::wstring Exe() { + wchar_t b[MAX_PATH * 2]; + const DWORD n = GetModuleFileNameW(nullptr, b, MAX_PATH * 2); + return std::wstring(b, n); +} +static std::wstring TempRoot() { + wchar_t b[MAX_PATH * 2]; + const DWORD n = GetTempPathW(MAX_PATH * 2, b); + std::wstring r = JoinPath(std::wstring(b, n), L"wg-state-test-" + std::to_wstring(GetCurrentProcessId())); + CreateDirectoryW(r.c_str(), nullptr); + return r; +} +static void WriteText(const std::wstring& p, const std::string& t) { + HANDLE h = CreateFileW(p.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD put = 0; + if (h != INVALID_HANDLE_VALUE) { WriteFile(h, t.data(), static_cast(t.size()), &put, nullptr); CloseHandle(h); } +} +static std::string ReadText(const std::wstring& p) { std::string t; ReadBytes(p, &t); return t; } +static std::vector List(const std::wstring& dir) { + std::vector out; + WIN32_FIND_DATAW f; + HANDLE h = FindFirstFileW(JoinPath(dir, L"*").c_str(), &f); + if (h == INVALID_HANDLE_VALUE) return out; + do { if (wcscmp(f.cFileName, L".") && wcscmp(f.cFileName, L"..")) out.push_back(f.cFileName); } while (FindNextFileW(h, &f)); + FindClose(h); + return out; +} +static HANDLE Spawn(const std::wstring& args) { + std::wstring cmd = L"\"" + Exe() + L"\" " + args; + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(nullptr, &cmd[0], nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) return nullptr; + CloseHandle(pi.hThread); + return pi.hProcess; +} +static DWORD WaitExit(HANDLE p, DWORD ms = 60000) { + DWORD code = 999; + if (WaitForSingleObject(p, ms) == WAIT_OBJECT_0) GetExitCodeProcess(p, &code); + CloseHandle(p); + return code; +} +static unsigned long Counter(const std::wstring& game) { + const Settings s = ReadSettings(game); + const std::string* v = Get(s, "counter"); + return v ? std::strtoul(v->c_str(), nullptr, 10) : 0; +} + +static bool WaitFile(const std::wstring& p, DWORD ms = 30000) { + for (DWORD t = 0; t < ms; t += 20) { + if (GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES) return true; + Sleep(20); + } + return false; +} + +// child modes: --child-add : n locked read-modify-write increments; --child-hold : holds the +// lock for ms; --child-die : takes the lock and, once go exists, ends without releasing it +static int Child(int argc, wchar_t** argv) { + const std::wstring mode = argv[1], game = argv[2]; + if (mode == L"--child-add" && argc >= 4) { + const int n = _wtoi(argv[3]); + for (int i = 0; i < n; ++i) { + StateLock lock(game, 30000); + if (!lock.held()) return 3; + const Settings s = ReadSettings(game); + const std::string* v = Get(s, "counter"); + const unsigned long c = v ? std::strtoul(v->c_str(), nullptr, 10) : 0; + Settings w = s; + Set(w, "counter", std::to_string(c + 1)); + Sleep(0); // widen the window a lost update would need + if (!WriteAtomic(SettingsPathOf(game), RenderSettings(w))) return 4; + } + return 0; + } + if (mode == L"--child-hold" && argc >= 5) { + StateLock lock(game, 30000); + if (!lock.held()) return 3; + WriteText(argv[4], "ready"); + Sleep(static_cast(_wtoi(argv[3]))); + return 0; + } + if (mode == L"--child-die" && argc >= 5) { + StateLock* lock = new StateLock(game, 30000); // never released: the process ends holding it + if (!lock->held()) return 3; + WriteText(argv[3], "ready"); + WaitFile(argv[4]); // the parent has its own handle now + ExitProcess(0); + } + return 2; +} + +int wmain(int argc, wchar_t** argv) { + if (argc >= 3 && std::wstring(argv[1]).rfind(L"--child", 0) == 0) return Child(argc, argv); + const std::wstring root = TempRoot(); + + // ---- the strict format + { + Settings s = ParseSettings("; comment\r\n\r\nrr_mode=fast\r\nrr_enabled=1\n"); + check(s.present && !s.corrupt && s.kv.size() == 2 && *Get(s, "rr_mode") == "fast" && *Get(s, "rr_enabled") == "1", "parse: comments, blank lines, CRLF and LF"); + const char* bad[] = {"rr_mode = fast\r\n", "[wronggpu]\r\nrr_mode=fast\r\n", "RR_MODE=fast\r\n", "rr_mode=fast\r\nrr_mode=accurate\r\n", + "rr_mode\r\n", "rr_mode=fa st\r\n", "=fast\r\n", "rr_mode=f\xc3\xa4st\r\n", "; \xc3\xa4\r\n"}; + bool all = true; + for (const char* b : bad) { const Settings x = ParseSettings(b); all = all && x.corrupt && x.kv.empty() && !x.why.empty(); } + check(all, "parse: spaces, sections, upper case, a key twice, no '=', bad value, empty key, non-ASCII: corrupt, no keys"); + Settings r; + check(Set(r, "rr_mode", "fast") && Set(r, "rr_mode", "exact") && r.kv.size() == 1 && !Set(r, "Bad Key", "x") && !Set(r, "k", "a b"), "Set: replace, refuse bad key/value"); + const Settings back = ParseSettings(RenderSettings(r)); + check(!back.corrupt && back.kv == r.kv, "render -> parse round trip"); + } + + // ---- atomic writes and reads on real files + const std::wstring game = JoinPath(root, L"Game"); + CreateDirectoryW(game.c_str(), nullptr); + { + check(ReadSettings(game).present == false && ReadSettings(game).why.empty(), "no settings.ini: not present, no error"); + check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::NoStateFolder && !IsDirectory(StateDirOf(game)), + "no state folder: NoStateFolder, the folder is not created"); + CreateDirectoryW(StateDirOf(game).c_str(), nullptr); + check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::Ok && *Get(ReadSettings(game), "rr_mode") == "fast", "SetSettings writes the file"); + check(SetSettings(game, {{"rr_enabled", "0"}}) == SetResult::Ok && *Get(ReadSettings(game), "rr_mode") == "fast" && + *Get(ReadSettings(game), "rr_enabled") == "0", "a second key keeps the first"); + check(SetSettings(game, {{"rr mode", "x"}}) == SetResult::Invalid, "an invalid key: Invalid, nothing written"); + std::vector names = List(StateDirOf(game)); + check(names.size() == 1 && names[0] == kSettingsFile, "no temporary file stays after writes"); + DWORD e = 0; + check(!WriteAtomic(JoinPath(JoinPath(root, L"missing-folder"), L"x.ini"), "x", &e) && e != 0, "a write into a missing folder fails with its error"); + // corrupt: readers see no keys; the next write replaces the file + WriteText(SettingsPathOf(game), "rr_mode = fast\r\n"); + const Settings c = ReadSettings(game); + check(c.present && c.corrupt && c.kv.empty(), "a corrupt file reads as corrupt, no keys"); + check(SetSettings(game, {{"rr_mode", "accurate"}}) == SetResult::Ok && !ReadSettings(game).corrupt && *Get(ReadSettings(game), "rr_mode") == "accurate" && + ReadSettings(game).kv.size() == 1, "a corrupt file is replaced by the next write (only the new key)"); + // unreadable (held without sharing): never overwritten + const std::string before = ReadText(SettingsPathOf(game)); + HANDLE h = CreateFileW(SettingsPathOf(game).c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD err = 0; + const SetResult r = SetSettings(game, {{"rr_mode", "exact"}}, kDefaultWaitMs, &err); + CloseHandle(h); + check(r == SetResult::Unreadable && err != 0 && ReadText(SettingsPathOf(game)) == before, "an unreadable file: Unreadable, left as it was"); + names = List(StateDirOf(game)); + check(names.size() == 1, "no temporary file stays after the refused write"); + } + + // ---- one lock name for every spelling of the folder + { + std::wstring a, b, c, d; + check(LockNameFor(game, &a) && LockNameFor(game + L"\\", &b) && a == b && a.rfind(L"Local\\WrongGPU-state-", 0) == 0, "lock name: trailing backslash"); + std::wstring upper = game; + for (auto& ch : upper) ch = static_cast(towupper(ch)); + check(LockNameFor(upper, &c) && a == c, "lock name: another case"); + wchar_t shortp[MAX_PATH * 2]; + if (GetShortPathNameW(game.c_str(), shortp, MAX_PATH * 2)) check(LockNameFor(shortp, &d) && a == d, "lock name: the short (8.3) path"); + std::wstring other; + const std::wstring g2 = JoinPath(root, L"Other"); + CreateDirectoryW(g2.c_str(), nullptr); + check(LockNameFor(g2, &other) && other != a, "lock name: another folder, another name"); + DWORD e = 0; + check(!LockNameFor(JoinPath(root, L"nope"), &other, &e) && e != 0, "lock name: a missing folder fails"); + } + + // ---- mutual exclusion across processes: 4 children x 50 locked increments of one counter, no update lost + { + WriteText(SettingsPathOf(game), "counter=0\r\n"); + std::vector kids; + for (int i = 0; i < 4; ++i) kids.push_back(Spawn(L"--child-add \"" + game + L"\" 50")); + bool started = true, ok = true; + for (HANDLE k : kids) { if (!k) started = false; else ok = WaitExit(k, 120000) == 0 && ok; } + check(started && ok, "4 child processes ran their locked increments"); + check(Counter(game) == 200, "the counter is 200: the lock serialised every read-modify-write across processes"); + check(List(StateDirOf(game)).size() == 1, "no temporary file stays after concurrent writes"); + } + + // ---- busy: another process holds the lock; a bounded wait gives up (Busy), the file unchanged + { + const std::wstring ready = JoinPath(root, L"ready-hold"); + HANDLE k = Spawn(L"--child-hold \"" + game + L"\" 3000 \"" + ready + L"\""); + const bool up = k && WaitFile(ready); + const std::string before = ReadText(SettingsPathOf(game)); + DWORD err = 0; + const SetResult r = SetSettings(game, {{"rr_mode", "fast"}}, 200, &err); + check(up && r == SetResult::Busy && err == WAIT_TIMEOUT && ReadText(SettingsPathOf(game)) == before, "lock held elsewhere: Busy after the bounded wait, nothing written"); + if (k) WaitExit(k); + check(SetSettings(game, {{"rr_mode", "fast"}}, 5000) == SetResult::Ok, "after the holder ends: the write goes through"); + } + + // ---- abandoned: a child dies holding the lock; the next waiter gets it + { + const std::wstring ready = JoinPath(root, L"ready-die"); + const std::wstring go = JoinPath(root, L"go-die"); + HANDLE k = Spawn(L"--child-die \"" + game + L"\" \"" + ready + L"\" \"" + go + L"\""); + const bool up = k && WaitFile(ready); + std::wstring name; + LockNameFor(game, &name); + HANDLE keep = OpenMutexW(SYNCHRONIZE, FALSE, name.c_str()); // keeps the mutex object alive past the child's end + WriteText(go, "go"); + if (k) WaitExit(k); + { + StateLock lock(game, 5000); + if (!(up && keep && lock.held() && lock.abandoned())) + std::printf(" (up %d, kept handle %d, held %d, abandoned %d, error %lu)\n", up, keep != nullptr, lock.held(), lock.abandoned(), lock.error()); + check(up && keep && lock.held() && lock.abandoned(), "a holder that died: the lock is taken (abandoned), not stuck"); + } + if (keep) CloseHandle(keep); + StateLock again(game, 5000); + check(again.held() && !again.abandoned(), "after that: the lock is taken normally"); + } + + // cleanup (own files only) + for (const auto& n : List(StateDirOf(game))) DeleteFileW(JoinPath(StateDirOf(game), n).c_str()); + RemoveDirectoryW(StateDirOf(game).c_str()); + RemoveDirectoryW(game.c_str()); + RemoveDirectoryW(JoinPath(root, L"Other").c_str()); + DeleteFileW(JoinPath(root, L"ready-hold").c_str()); + DeleteFileW(JoinPath(root, L"ready-die").c_str()); + DeleteFileW(JoinPath(root, L"go-die").c_str()); + RemoveDirectoryW(root.c_str()); + std::printf("wg_state: %d passed, %d failed\n", g_pass, g_fail); + return g_fail ? 1 : 0; +} From f52252a8f234febfacd9d22a07f70bb64d36fa6a Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:01:46 -0500 Subject: [PATCH 2/7] Shared: the loaded marker (LoadedMarker, IsGameUsingWrongGPU) in wg_state.h A WrongGPU module loaded in the game keeps a named mutex Local\WrongGPU-loaded-- open (never owned) for the game folder; the object exists exactly while some process has it open, and the OS closes every handle of a process that ends or crashes, so a dead game leaves no stale marker. IsGameUsingWrongGPU(gameDir) only opens it (never creates). StateLock and the marker share CreateSharedMutex and NameFor. Tests: a marker in this process (any spelling of the folder), another folder, a missing folder, a child process holding it, and that child killed (TerminateProcess): not in use. Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/include/wg_state.h | 74 ++++++++++++++++++++++---- clean/wgshared/tests/test_wg_state.cpp | 33 ++++++++++++ 2 files changed, 96 insertions(+), 11 deletions(-) diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 6bb756c7..79736e98 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -16,6 +16,9 @@ // carries a low integrity label, so an elevated launcher and the game (any integrity) share it. A holder that dies leaves // the mutex abandoned: the next waiter gets it (the files are replaced atomically, so they are whole either way). // +// While a WrongGPU module is loaded in the game it keeps the game's LoadedMarker open (below); the launcher refuses an +// uninstall, repair or update while IsGameUsingWrongGPU says so. The OS drops the marker when the process ends or crashes. +// // Writes are atomic (WriteAtomic): a new temporary file in the same folder (.wgtmp--, created only where // nothing is), flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the file; the temporary file is deleted when // any step fails. A reader sees the old file or the new one, never part of one. Temporary files never count as state. @@ -86,23 +89,36 @@ inline bool LockNameFor(const std::wstring& gameDir, std::wstring* name, DWORD* return true; } +// Another per-game name of the same identity: prefix + "-". +inline bool NameFor(const wchar_t* prefix, const std::wstring& gameDir, std::wstring* name, DWORD* err) { + std::wstring lock; + if (!LockNameFor(gameDir, &lock, err)) return false; + *name = std::wstring(prefix) + lock.substr(lock.find(L"-state-") + 7); + return true; +} +// A named mutex every integrity level may open (created, or opened when it exists); nullptr with GetLastError on failure. +inline HANDLE CreateSharedMutex(const std::wstring& name) { + PSECURITY_DESCRIPTOR sd = nullptr; + SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, FALSE}; + // everyone: SYNCHRONIZE | MUTEX_MODIFY_STATE; SYSTEM and administrators: all; low integrity label (no write-up block) + if (ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;0x00100001;;;WD)(A;;GA;;;SY)(A;;GA;;;BA)S:(ML;;NW;;;LW)", SDDL_REVISION_1, &sd, nullptr)) + sa.lpSecurityDescriptor = sd; + HANDLE m = CreateMutexW(sa.lpSecurityDescriptor ? &sa : nullptr, FALSE, name.c_str()); + if (!m && GetLastError() == ERROR_ACCESS_DENIED) m = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, name.c_str()); + const DWORD e = GetLastError(); + if (sd) LocalFree(sd); + SetLastError(e); + return m; +} + // The game's state lock, held from construction (when held()) to destruction. Bounded wait: not held after waitMs. class StateLock { public: explicit StateLock(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) { std::wstring name; if (!LockNameFor(gameDir, &name, &err_)) return; - PSECURITY_DESCRIPTOR sd = nullptr; - SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, FALSE}; - // everyone: SYNCHRONIZE | MUTEX_MODIFY_STATE; SYSTEM and administrators: all; low integrity label (no write-up block) - if (ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;0x00100001;;;WD)(A;;GA;;;SY)(A;;GA;;;BA)S:(ML;;NW;;;LW)", - SDDL_REVISION_1, &sd, nullptr)) - sa.lpSecurityDescriptor = sd; - mutex_ = CreateMutexW(sa.lpSecurityDescriptor ? &sa : nullptr, FALSE, name.c_str()); - if (!mutex_ && GetLastError() == ERROR_ACCESS_DENIED) mutex_ = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, name.c_str()); - if (!mutex_) err_ = GetLastError(); - if (sd) LocalFree(sd); - if (!mutex_) return; + mutex_ = CreateSharedMutex(name); + if (!mutex_) { err_ = GetLastError(); return; } const DWORD w = WaitForSingleObject(mutex_, waitMs); held_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; abandoned_ = w == WAIT_ABANDONED; @@ -124,6 +140,42 @@ class StateLock { DWORD err_ = 0; }; +// ---- the loaded marker ---------------------------------------------------------------------------------------------- +// A WrongGPU module loaded in the game (the front end, the menu plugin, the RR plugin) keeps a LoadedMarker for the game +// folder for as long as it is loaded: a named mutex Local\WrongGPU-loaded-- (the same identity as +// the state lock) that it holds OPEN but never owns. The object exists exactly while some process has a handle to it, and the +// OS closes every handle of a process that ends, crashes or is killed: a dead game never leaves a stale marker. The launcher +// refuses an uninstall, repair or update while IsGameUsingWrongGPU(gameDir) is true. Same security as the state lock (every +// integrity level may open it). +class LoadedMarker { +public: + explicit LoadedMarker(const std::wstring& gameDir) { + std::wstring name; + if (!NameFor(L"Local\\WrongGPU-loaded-", gameDir, &name, &err_)) return; + handle_ = CreateSharedMutex(name); + if (!handle_) err_ = GetLastError(); + } + ~LoadedMarker() { if (handle_) CloseHandle(handle_); } + LoadedMarker(const LoadedMarker&) = delete; + LoadedMarker& operator=(const LoadedMarker&) = delete; + bool held() const { return handle_ != nullptr; } + DWORD error() const { return err_; } + +private: + HANDLE handle_ = nullptr; + DWORD err_ = 0; +}; +// A running process has WrongGPU loaded for the game folder gameDir (a LoadedMarker of it is open somewhere). Never creates the +// marker. A folder that cannot be opened: false. +inline bool IsGameUsingWrongGPU(const std::wstring& gameDir) { + std::wstring name; + DWORD err = 0; + if (!NameFor(L"Local\\WrongGPU-loaded-", gameDir, &name, &err)) return false; + HANDLE h = OpenMutexW(SYNCHRONIZE, FALSE, name.c_str()); + if (h) { CloseHandle(h); return true; } + return GetLastError() == ERROR_ACCESS_DENIED; // there, but not ours to open: still in use +} + // The whole file. false: missing (*missing = true) or unreadable (*missing = false; *err the Win32 error). inline bool ReadBytes(const std::wstring& path, std::string* out, bool* missing = nullptr, DWORD* err = nullptr) { out->clear(); diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp index 779251ee..1a9f76a6 100644 --- a/clean/wgshared/tests/test_wg_state.cpp +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -95,6 +95,13 @@ static int Child(int argc, wchar_t** argv) { } return 0; } + if (mode == L"--child-loaded" && argc >= 4) { // a "game" with WrongGPU loaded: the marker open until it is killed + LoadedMarker marker(game); + if (!marker.held()) return 3; + WriteText(argv[3], "ready"); + Sleep(120000); + return 0; + } if (mode == L"--child-hold" && argc >= 5) { StateLock lock(game, 30000); if (!lock.held()) return 3; @@ -228,6 +235,32 @@ int wmain(int argc, wchar_t** argv) { check(again.held() && !again.abandoned(), "after that: the lock is taken normally"); } + // ---- the loaded marker: in this process, in another one, and a dead owner (killed) leaves none + { + const std::wstring g2 = JoinPath(root, L"Other"); + check(!IsGameUsingWrongGPU(game) && !IsGameUsingWrongGPU(game), "no marker: not in use (and the check creates none)"); + { + LoadedMarker m(game); + std::wstring upper = game; + for (auto& ch : upper) ch = static_cast(towupper(ch)); + check(m.held() && IsGameUsingWrongGPU(game) && IsGameUsingWrongGPU(upper + L"\\") && !IsGameUsingWrongGPU(g2), + "a marker in this process: in use (any spelling of the folder), another folder not"); + } + check(!IsGameUsingWrongGPU(game), "the marker closed: not in use"); + check(!IsGameUsingWrongGPU(JoinPath(root, L"nope")), "a missing folder: not in use"); + const std::wstring ready = JoinPath(root, L"ready-loaded"); + HANDLE k = Spawn(L"--child-loaded \"" + game + L"\" \"" + ready + L"\""); + const bool up = k && WaitFile(ready); + check(up && IsGameUsingWrongGPU(game), "another process with the marker open: in use"); + if (k) { + TerminateProcess(k, 9); // the game crashes (no cleanup of its own) + WaitForSingleObject(k, 30000); + CloseHandle(k); + } + check(up && !IsGameUsingWrongGPU(game), "the owning process died: no stale marker, not in use"); + DeleteFileW(ready.c_str()); + } + // cleanup (own files only) for (const auto& n : List(StateDirOf(game))) DeleteFileW(JoinPath(StateDirOf(game), n).c_str()); RemoveDirectoryW(StateDirOf(game).c_str()); From 88b3b3585f10408c724b0d5f0575bdb6442d70ca Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:18:42 -0500 Subject: [PATCH 3/7] Shared: wg_state.h review fixes (the state lock gates the loaded protocol) - The loaded protocol: the game registers under the state lock before it reads any state (LoadedRegistration: bounded wait kRegisterWaitMs; not had in time, or no marker: ok() is false and the module runs with the defaults, touching no state); the launcher's OperationGuard takes the lock, asks QueryGameUse and holds the lock for the whole uninstall, repair or update, so nothing registers in between. - QueryGameUse is tri-state: NotRunning only when established (no marker, or the folder is gone); any lookup error is Unknown, and the guard refuses on Running and Unknown. - Names are Global\ (one per game folder for every session); every protected operation re-reads its state after taking the lock (documented; StateLock caches nothing). - WriteAtomic: input over kMaxStateBytes refused; checked chunks, a short write is ERROR_WRITE_FAULT; flush and close checked; the temporary file deleted when possible and reported otherwise (tempLeft); a test seam fails each step. - Paths go through the \\?\ form (full path, \\?\UNC\ for shares); DirectoryState tells missing from unknown; SetSettings reports AccessDenied (the game folder is not writable: the launcher's elevated repair) apart from other failures. - The parser rejects a CR that is not part of CRLF (also a bare final CR). Tests: every step's failure after the temporary file exists, a failed cleanup, oversized input, AccessDenied on a read-only state folder; lock names of case, trailing backslash, 8.3 name, \\?\ form, a junction and a path over MAX_PATH, each in its own process, and four processes using different aliases (200 locked increments); a holder dying mid-write (abandoned, the old whole file re-read); QueryGameUse Unknown on a lookup error and on a folder whose identity cannot be read (the guard refuses); a registered then killed child; a registration that waits for a running operation and one that gives up in time. Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/include/wg_state.h | 312 ++++++++++++++----- clean/wgshared/tests/test_wg_state.cpp | 396 ++++++++++++++++++------- 2 files changed, 526 insertions(+), 182 deletions(-) diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 79736e98..64f55842 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -6,29 +6,52 @@ // rr_mode): they take precedence over the install's defaults in wronggpu.ini, which no WrongGPU // program rewrites after the install (wronggpu.ini is the player's to edit); // model-choice.ini the model choice record (clean/fsr/src/model_choice_record.h). -// The folder is always WrongGPU's: an uninstall removes these files, a repair or update keeps them. +// The folder is always WrongGPU's: an uninstall removes these files, a repair or update keeps them. The launcher creates the +// folder; nothing here creates it. // -// Every read-modify-write of a file in the folder, by any WrongGPU program (the launcher, the elevated worker, the front -// end, the menu plugin, the RR plugin), holds the game's state lock (StateLock): a named mutex per game folder, -// Local\WrongGPU-state-- -// taken from the game folder's file identity, so every spelling of the path (case, 8.3 names, a mapped drive or a -// junction to the same folder) gives the same name. The mutex grants SYNCHRONIZE and MUTEX_MODIFY_STATE to everyone and -// carries a low integrity label, so an elevated launcher and the game (any integrity) share it. A holder that dies leaves -// the mutex abandoned: the next waiter gets it (the files are replaced atomically, so they are whole either way). +// THE STATE LOCK (StateLock) is the gate for everything below: a named mutex per game folder, +// Global\WrongGPU-state-- +// taken from the game folder's file identity, so every spelling of the path (case, 8.3 names, a junction or a mapped drive +// to the same folder, the \\?\ form) gives the same name. Global\: one name for every session (another account's game in +// the same library is seen too). The mutex grants SYNCHRONIZE and MUTEX_MODIFY_STATE to everyone and carries a low integrity +// label, so an elevated launcher and the game (any integrity) share it. It is a Windows mutex: owned by a THREAD, recursive +// for that thread (a nested StateLock on the same thread is taken at once). +// - Every read-modify-write of a state file holds it (SetSettings does; the model choice record's writer must too). +// - Every protected operation RE-READS the state it changes from disk after taking the lock: StateLock caches nothing, so +// a caller that re-reads never acts on a stale view. A holder that died leaves the mutex abandoned (abandoned() says so); +// the next taker gets it, and because writes are atomic (below) the files are whole: the old version or the new one. A +// temporary file such a holder left is never read as state (IsTempName) and goes with the uninstall. // -// While a WrongGPU module is loaded in the game it keeps the game's LoadedMarker open (below); the launcher refuses an -// uninstall, repair or update while IsGameUsingWrongGPU says so. The OS drops the marker when the process ends or crashes. +// THE LOADED PROTOCOL (no check-then-act race between a game starting and the launcher changing the game's files): +// - The game: every WrongGPU module that is loaded in the game registers BEFORE it reads or writes any state +// (LoadedRegistration): it takes the state lock (bounded wait, kRegisterWaitMs), opens its LoadedMarker +// (Global\WrongGPU-loaded--, held OPEN for as long as the module is loaded, never owned) and +// releases the lock. When the lock is not had in time (a long uninstall, repair or update is running) or the marker cannot +// be made, ok() is false: the module logs it and runs with the defaults, reading and writing no state that session. It +// never blocks the game for longer than the bounded wait. +// - The launcher: an uninstall, repair or update holds an OperationGuard for its WHOLE run: it takes the state lock, then +// asks QueryGameUse, and refuses unless the answer is NotRunning (Running and Unknown both refuse). The lock stays held +// until the operation ends, so no game can register in between. The guard is taken by the process that changes the +// files (the elevated worker when there is one), never by a parent waiting for it. +// The marker object exists exactly while some process has it open; the OS closes every handle of a process that ends, crashes +// or is killed, so a dead game leaves no stale marker and no PID is ever compared. // // Writes are atomic (WriteAtomic): a new temporary file in the same folder (.wgtmp--, created only where -// nothing is), flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the file; the temporary file is deleted when -// any step fails. A reader sees the old file or the new one, never part of one. Temporary files never count as state. +// nothing is), written in checked chunks, flushed and closed (both checked), then MoveFileExW(REPLACE_EXISTING | +// WRITE_THROUGH) over the file. On a failure the temporary file is deleted when possible; a temporary file that could not be +// deleted is reported (*tempLeft). A reader sees the old file or the new one, never part of one. State files are small: +// more than kMaxStateBytes is refused. +// Paths: every helper turns its path into the \\?\ form (full path; \\?\UNC\ for a share), so a game deeper than MAX_PATH +// works without the long-path setting. // // settings.ini, strictly (anything else is CORRUPT: readers treat the file as empty and say so; the next write replaces it): // ; comment lines and blank lines // key=value key: [a-z0-9_], 1..64 chars; value: [A-Za-z0-9_.+-], 0..256 chars; each key at most once; -// no sections, no spaces around '='; CRLF or LF line ends; UTF-8 without anything outside ASCII. +// no sections, no spaces around '='; CRLF or LF line ends (a CR anywhere else, also a bare final CR, +// is corrupt); ASCII only. // Written for this project; Windows API and the C++ standard library only. #include +#include #include #include #include @@ -51,24 +74,52 @@ constexpr const wchar_t* kStateFolder = L"wronggpu-setup"; constexpr const wchar_t* kSettingsFile = L"settings.ini"; constexpr const wchar_t* kModelChoiceFile = L"model-choice.ini"; constexpr const wchar_t* kTempMark = L".wgtmp-"; // .wgtmp--: a write in progress (or one a crash left) -constexpr DWORD kDefaultWaitMs = 5000; +constexpr DWORD kDefaultWaitMs = 5000; // the launcher's waits +constexpr DWORD kRegisterWaitMs = 2000; // the game's registration: never longer +constexpr size_t kMaxStateBytes = 1u << 20; // no state file is larger +constexpr DWORD kChunk = 64u * 1024u; + +// Test seam (tests only): called before each step of WriteAtomic ("write", "flush", "close", "move") and of its cleanup +// ("delete"); returning true makes that step fail as a failed call would (error ERROR_WRITE_FAULT). nullptr: never. +using FaultHook = bool (*)(const char* step); +inline FaultHook& TestFault() { static FaultHook hook = nullptr; return hook; } +inline bool Faulted(const char* step) { return TestFault() && TestFault()(step); } inline std::wstring JoinPath(std::wstring a, const std::wstring& b) { if (!a.empty() && a.back() != L'\\' && a.back() != L'/') a.push_back(L'\\'); return a + b; } +// The \\?\ form of a path (full path; \\?\UNC\server\share\... for a share; a path already in that form stays). +inline std::wstring ExtendedPath(const std::wstring& path) { + std::wstring p = path; + for (auto& c : p) if (c == L'/') c = L'\\'; + if (p.rfind(L"\\\\?\\", 0) == 0 || p.rfind(L"\\\\.\\", 0) == 0) return p; + const DWORD n = GetFullPathNameW(p.c_str(), 0, nullptr, nullptr); + if (n) { + std::wstring full(n, L'\0'); + const DWORD m = GetFullPathNameW(p.c_str(), n, &full[0], nullptr); + if (m && m < n) { full.resize(m); p = full; } + } + if (p.rfind(L"\\\\", 0) == 0) return L"\\\\?\\UNC\\" + p.substr(2); + return L"\\\\?\\" + p; +} inline std::wstring StateDirOf(const std::wstring& gameDir) { return JoinPath(gameDir, kStateFolder); } inline std::wstring SettingsPathOf(const std::wstring& gameDir) { return JoinPath(StateDirOf(gameDir), kSettingsFile); } -inline bool IsDirectory(const std::wstring& p) { - const DWORD a = GetFileAttributesW(p.c_str()); - return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY); -} // A temporary file of WriteAtomic (its own name contains the mark; the state files' names never do). inline bool IsTempName(const std::wstring& name) { return name.find(kTempMark) != std::wstring::npos; } -// The state lock's name for the game folder `gameDir`; false (and *err) when the folder cannot be opened. +enum class PathState { Present, Missing, Unknown }; // Unknown: it could not be told (access denied, a device error) +inline PathState DirectoryState(const std::wstring& path, DWORD* err = nullptr) { + const DWORD a = GetFileAttributesW(ExtendedPath(path).c_str()); + if (a != INVALID_FILE_ATTRIBUTES) return (a & FILE_ATTRIBUTE_DIRECTORY) ? PathState::Present : PathState::Missing; + const DWORD e = GetLastError(); + if (err) *err = e; + return e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND ? PathState::Missing : PathState::Unknown; +} + +// The state lock's name for the game folder `gameDir`; false (and *err) when the folder cannot be opened or identified. inline bool LockNameFor(const std::wstring& gameDir, std::wstring* name, DWORD* err = nullptr) { - HANDLE h = CreateFileW(gameDir.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + HANDLE h = CreateFileW(ExtendedPath(gameDir).c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); if (h == INVALID_HANDLE_VALUE) { if (err) *err = GetLastError(); @@ -84,11 +135,10 @@ inline bool LockNameFor(const std::wstring& gameDir, std::wstring* name, DWORD* } wchar_t buf[96]; const unsigned long long index = (static_cast(info.nFileIndexHigh) << 32) | info.nFileIndexLow; - swprintf(buf, sizeof buf / sizeof buf[0], L"Local\\WrongGPU-state-%08lX-%016llX", static_cast(info.dwVolumeSerialNumber), index); + swprintf(buf, sizeof buf / sizeof buf[0], L"Global\\WrongGPU-state-%08lX-%016llX", static_cast(info.dwVolumeSerialNumber), index); *name = buf; return true; } - // Another per-game name of the same identity: prefix + "-". inline bool NameFor(const wchar_t* prefix, const std::wstring& gameDir, std::wstring* name, DWORD* err) { std::wstring lock; @@ -131,8 +181,9 @@ class StateLock { StateLock(const StateLock&) = delete; StateLock& operator=(const StateLock&) = delete; bool held() const { return held_; } - bool abandoned() const { return abandoned_; } // the previous holder ended without releasing it - DWORD error() const { return err_; } // why not held: WAIT_TIMEOUT, or the Win32 error + // the previous holder ended without releasing it: informational (re-read the state from disk, as every holder must) + bool abandoned() const { return abandoned_; } + DWORD error() const { return err_; } // why not held: WAIT_TIMEOUT, or the Win32 error private: HANDLE mutex_ = nullptr; @@ -140,18 +191,14 @@ class StateLock { DWORD err_ = 0; }; -// ---- the loaded marker ---------------------------------------------------------------------------------------------- -// A WrongGPU module loaded in the game (the front end, the menu plugin, the RR plugin) keeps a LoadedMarker for the game -// folder for as long as it is loaded: a named mutex Local\WrongGPU-loaded-- (the same identity as -// the state lock) that it holds OPEN but never owns. The object exists exactly while some process has a handle to it, and the -// OS closes every handle of a process that ends, crashes or is killed: a dead game never leaves a stale marker. The launcher -// refuses an uninstall, repair or update while IsGameUsingWrongGPU(gameDir) is true. Same security as the state lock (every -// integrity level may open it). +// ---- the loaded protocol ------------------------------------------------------------------------------------------ +constexpr const wchar_t* kLoadedPrefix = L"Global\\WrongGPU-loaded-"; +// The marker alone (held open, never owned). Use it through LoadedRegistration, which takes the state lock around it. class LoadedMarker { public: explicit LoadedMarker(const std::wstring& gameDir) { std::wstring name; - if (!NameFor(L"Local\\WrongGPU-loaded-", gameDir, &name, &err_)) return; + if (!NameFor(kLoadedPrefix, gameDir, &name, &err_)) return; handle_ = CreateSharedMutex(name); if (!handle_) err_ = GetLastError(); } @@ -165,22 +212,97 @@ class LoadedMarker { HANDLE handle_ = nullptr; DWORD err_ = 0; }; -// A running process has WrongGPU loaded for the game folder gameDir (a LoadedMarker of it is open somewhere). Never creates the -// marker. A folder that cannot be opened: false. -inline bool IsGameUsingWrongGPU(const std::wstring& gameDir) { + +enum class GameUse { NotRunning, Running, Unknown }; +inline const char* GameUseWords(GameUse u) { + return u == GameUse::NotRunning ? "not running" : u == GameUse::Running ? "the game is running with WrongGPU loaded" + : "WrongGPU could not tell whether the game is running"; +} +// Whether a running process has WrongGPU loaded for the game folder gameDir. NotRunning ONLY when that is established: the +// folder is gone (nothing can run from it), or its marker does not exist. Any error on the way is Unknown (*err). Never +// creates the marker. Ask it under the state lock (OperationGuard does). +inline GameUse QueryGameUse(const std::wstring& gameDir, DWORD* err = nullptr) { std::wstring name; - DWORD err = 0; - if (!NameFor(L"Local\\WrongGPU-loaded-", gameDir, &name, &err)) return false; + DWORD e = 0; + if (!NameFor(kLoadedPrefix, gameDir, &name, &e)) { + if (err) *err = e; + return e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND ? GameUse::NotRunning : GameUse::Unknown; + } HANDLE h = OpenMutexW(SYNCHRONIZE, FALSE, name.c_str()); - if (h) { CloseHandle(h); return true; } - return GetLastError() == ERROR_ACCESS_DENIED; // there, but not ours to open: still in use + if (h) { CloseHandle(h); return GameUse::Running; } + e = GetLastError(); + if (err) *err = e; + if (e == ERROR_FILE_NOT_FOUND) return GameUse::NotRunning; + return e == ERROR_ACCESS_DENIED ? GameUse::Running : GameUse::Unknown; // there but not ours to open: in use } +// The game's side: register under the state lock before any state is read. ok() false: run with the defaults and touch no +// state this session (why() says what to log). Keep the object for as long as the module is loaded. +class LoadedRegistration { +public: + explicit LoadedRegistration(const std::wstring& gameDir, DWORD waitMs = kRegisterWaitMs) { + StateLock lock(gameDir, waitMs > kRegisterWaitMs ? kRegisterWaitMs : waitMs); + if (!lock.held()) { + err_ = lock.error(); + why_ = err_ == WAIT_TIMEOUT ? "the game's state lock was not free in time (an uninstall, repair or update of WrongGPU is running)" + : "the game's state lock could not be taken"; + return; + } + marker_.reset(new LoadedMarker(gameDir)); + if (!marker_->held()) { + err_ = marker_->error(); + why_ = "the loaded marker could not be made"; + marker_.reset(); + } + } + bool ok() const { return marker_ != nullptr; } + const char* why() const { return why_; } // "" when ok + DWORD error() const { return err_; } + +private: + std::unique_ptr marker_; + const char* why_ = ""; + DWORD err_ = 0; +}; + +// The launcher's side: hold for the whole uninstall, repair or update. Ok only when the lock is held and no game uses WrongGPU. +enum class GuardResult { Ok, Busy, GameRunning, Unknown }; +class OperationGuard { +public: + explicit OperationGuard(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) : lock_(gameDir, waitMs) { + if (!lock_.held()) { + err_ = lock_.error(); + const PathState s = DirectoryState(gameDir); + result_ = s == PathState::Missing ? GuardResult::Ok : err_ == WAIT_TIMEOUT ? GuardResult::Busy : GuardResult::Unknown; // (gone: nothing to guard) + return; + } + const GameUse u = QueryGameUse(gameDir, &err_); + result_ = u == GameUse::NotRunning ? GuardResult::Ok : u == GameUse::Running ? GuardResult::GameRunning : GuardResult::Unknown; + } + GuardResult result() const { return result_; } + DWORD error() const { return err_; } + const char* words() const { + switch (result_) { + case GuardResult::Ok: return ""; + case GuardResult::Busy: return "another WrongGPU program is changing this game's WrongGPU state right now; try again in a moment"; + case GuardResult::GameRunning: return "the game is running with WrongGPU loaded; close the game first"; + case GuardResult::Unknown: return "WrongGPU could not tell whether the game is running; close the game and try again"; + } + return "?"; + } + +private: + StateLock lock_; + GuardResult result_ = GuardResult::Unknown; + DWORD err_ = 0; +}; + +// ---- files --------------------------------------------------------------------------------------------------------- // The whole file. false: missing (*missing = true) or unreadable (*missing = false; *err the Win32 error). inline bool ReadBytes(const std::wstring& path, std::string* out, bool* missing = nullptr, DWORD* err = nullptr) { out->clear(); if (missing) *missing = false; - HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + HANDLE h = CreateFileW(ExtendedPath(path).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) { const DWORD e = GetLastError(); @@ -195,36 +317,59 @@ inline bool ReadBytes(const std::wstring& path, std::string* out, bool* missing if (!ReadFile(h, buf, sizeof buf, &got, nullptr)) { ok = false; if (err) *err = GetLastError(); break; } if (!got) break; out->append(buf, got); - if (out->size() > (1u << 20)) { ok = false; if (err) *err = ERROR_FILE_TOO_LARGE; break; } // no state file is that large + if (out->size() > kMaxStateBytes) { ok = false; if (err) *err = ERROR_FILE_TOO_LARGE; break; } } CloseHandle(h); if (!ok) out->clear(); return ok; } -// The atomic replace described above. false (and *err) when any step failed; the file is then as it was. -inline bool WriteAtomic(const std::wstring& path, const std::string& bytes, DWORD* err = nullptr) { +// The atomic replace described above. false: the file is as it was; *err the error of the step that failed +// (ERROR_FILE_TOO_LARGE: over kMaxStateBytes; ERROR_WRITE_FAULT: a short write). *tempLeft: a temporary file that could not +// be deleted after the failure ("" when none). +inline bool WriteAtomic(const std::wstring& path, const std::string& bytes, DWORD* err = nullptr, std::wstring* tempLeft = nullptr) { static volatile LONG counter = 0; + if (tempLeft) tempLeft->clear(); + if (bytes.size() > kMaxStateBytes) { if (err) *err = ERROR_FILE_TOO_LARGE; return false; } + const std::wstring target = ExtendedPath(path); DWORD e = 0; for (int attempt = 0; attempt < 16; ++attempt) { - const std::wstring tmp = path + kTempMark + std::to_wstring(GetCurrentProcessId()) + L"-" + std::to_wstring(InterlockedIncrement(&counter)); + const std::wstring tmp = target + kTempMark + std::to_wstring(GetCurrentProcessId()) + L"-" + std::to_wstring(InterlockedIncrement(&counter)); HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) { e = GetLastError(); if (e == ERROR_FILE_EXISTS || e == ERROR_ALREADY_EXISTS) continue; break; } - DWORD put = 0; - bool ok = bytes.empty() || (WriteFile(h, bytes.data(), static_cast(bytes.size()), &put, nullptr) && put == bytes.size()); - if (!ok) e = GetLastError() ? GetLastError() : ERROR_WRITE_FAULT; - if (ok && !FlushFileBuffers(h)) { ok = false; e = GetLastError(); } - CloseHandle(h); - if (ok && !MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { ok = false; e = GetLastError(); } - if (!ok) { - DeleteFileW(tmp.c_str()); - break; + bool ok = true; + for (size_t done = 0; ok && done < bytes.size();) { + const DWORD want = static_cast(bytes.size() - done < kChunk ? bytes.size() - done : kChunk); + DWORD put = 0; + if (Faulted("write")) { ok = false; e = ERROR_WRITE_FAULT; } + else if (!WriteFile(h, bytes.data() + done, want, &put, nullptr)) { ok = false; e = GetLastError(); } + else if (put != want) { ok = false; e = ERROR_WRITE_FAULT; } // a short write: always this error + else done += put; + } + if (ok) { + if (Faulted("flush")) { ok = false; e = ERROR_WRITE_FAULT; } + else if (!FlushFileBuffers(h)) { ok = false; e = GetLastError(); } } - return true; + if (Faulted("close")) { + CloseHandle(h); // (the handle is closed all the same; the step reports the failure) + if (ok) { ok = false; e = ERROR_WRITE_FAULT; } + } else if (!CloseHandle(h) && ok) { + ok = false; + e = GetLastError(); + } + if (ok) { + if (Faulted("move")) { ok = false; e = ERROR_WRITE_FAULT; } + else if (!MoveFileExW(tmp.c_str(), target.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { ok = false; e = GetLastError(); } + } + if (ok) return true; + if (Faulted("delete") || !DeleteFileW(tmp.c_str())) { + if (tempLeft) *tempLeft = tmp; // deleted when possible; reported otherwise + } + break; } if (err) *err = e ? e : ERROR_FILE_EXISTS; return false; @@ -266,27 +411,31 @@ inline bool Set(Settings& s, const std::string& key, const std::string& value) { inline Settings ParseSettings(const std::string& text) { Settings s; s.present = true; + auto corrupt = [&](int lineNo, const char* what) { + s.kv.clear(); + s.corrupt = true; + s.why = "line " + std::to_string(lineNo) + ": " + what; + return s; + }; size_t a = 0; int lineNo = 0; while (a < text.size()) { size_t e = text.find('\n', a); - if (e == std::string::npos) e = text.size(); + const bool lf = e != std::string::npos; + if (!lf) e = text.size(); std::string line = text.substr(a, e - a); a = e + 1; ++lineNo; - if (!line.empty() && line.back() == '\r') line.pop_back(); - if (line.empty() || line[0] == ';') { - for (char c : line) if (static_cast(c) >= 0x80 || (c < 0x20 && c != '\t')) { s.kv.clear(); s.corrupt = true; s.why = "line " + std::to_string(lineNo) + ": not plain text"; return s; } - continue; - } + if (lf && !line.empty() && line.back() == '\r') line.pop_back(); // CRLF; a CR anywhere else is not a line end + for (char c : line) + if (static_cast(c) >= 0x80 || (c < 0x20 && c != '\t')) return corrupt(lineNo, c == '\r' ? "a CR that is not part of CRLF" : "not plain text"); + if (line.empty() || line[0] == ';') continue; const size_t eq = line.find('='); const std::string k = eq == std::string::npos ? line : line.substr(0, eq), v = eq == std::string::npos ? std::string() : line.substr(eq + 1); - if (eq == std::string::npos || !ValidKey(k) || !ValidValue(v) || Get(s, k)) { - s.kv.clear(); - s.corrupt = true; - s.why = "line " + std::to_string(lineNo) + (eq == std::string::npos ? ": no key=value" : !ValidKey(k) ? ": not a valid key" : !ValidValue(v) ? ": not a valid value" : ": the key appears twice"); - return s; - } + if (eq == std::string::npos) return corrupt(lineNo, "no key=value"); + if (!ValidKey(k)) return corrupt(lineNo, "not a valid key"); + if (!ValidValue(v)) return corrupt(lineNo, "not a valid value"); + if (Get(s, k)) return corrupt(lineNo, "the key appears twice"); s.kv.emplace_back(k, v); } return s; @@ -296,7 +445,8 @@ inline std::string RenderSettings(const Settings& s) { for (const auto& p : s.kv) out += p.first + "=" + p.second + "\r\n"; return out; } -// settings.ini of the game in gameDir. Missing: present = false, no keys. Unreadable or corrupt: no keys, why says so. +// settings.ini of the game in gameDir, read now from disk. Missing: present = false, no keys. Unreadable or corrupt: no keys, +// why says so. inline Settings ReadSettings(const std::wstring& gameDir) { std::string text; bool missing = false; @@ -309,33 +459,40 @@ inline Settings ReadSettings(const std::wstring& gameDir) { return ParseSettings(text); } -enum class SetResult { Ok, NoStateFolder, Busy, Unreadable, Invalid, WriteFailed }; +enum class SetResult { Ok, NoStateFolder, StateFolderUnknown, Busy, Unreadable, Invalid, AccessDenied, WriteFailed }; inline const char* SetResultWords(SetResult r) { switch (r) { case SetResult::Ok: return "saved"; case SetResult::NoStateFolder: return "no WrongGPU state folder for this game (not installed by the launcher)"; + case SetResult::StateFolderUnknown: return "WrongGPU's state folder of this game could not be checked"; case SetResult::Busy: return "another WrongGPU program kept the game's state lock"; case SetResult::Unreadable: return "the settings file could not be read (left as it is)"; case SetResult::Invalid: return "not a valid key or value"; + case SetResult::AccessDenied: return "WrongGPU can't write to the game folder; run the launcher's repair as administrator"; case SetResult::WriteFailed: return "the settings file could not be written"; } return "?"; } -// The read-modify-write of settings.ini under the game's state lock: the changes applied to the file as it is now (a -// corrupt file starts empty; an unreadable one is never overwritten). The state folder is never created here: without it -// the game has no WrongGPU install of the launcher (NoStateFolder). *err: the Win32 error of a failure. +// The read-modify-write of settings.ini under the game's state lock: the file re-read from disk after the lock is taken, the +// changes applied (a corrupt file starts empty; an unreadable one is never overwritten), written atomically. The state folder +// is never created here. AccessDenied is its own result (the game folder is not writable for this process): consumers say +// so and offer the launcher's elevated repair. *err: the Win32 error of a failure; *tempLeft as in WriteAtomic. inline SetResult SetSettings(const std::wstring& gameDir, const std::vector>& changes, - DWORD waitMs = kDefaultWaitMs, DWORD* err = nullptr) { + DWORD waitMs = kDefaultWaitMs, DWORD* err = nullptr, std::wstring* tempLeft = nullptr) { for (const auto& c : changes) if (!ValidKey(c.first) || !ValidValue(c.second)) return SetResult::Invalid; - if (!IsDirectory(StateDirOf(gameDir))) return SetResult::NoStateFolder; + DWORD e = 0; + switch (DirectoryState(StateDirOf(gameDir), &e)) { + case PathState::Present: break; + case PathState::Missing: return SetResult::NoStateFolder; + case PathState::Unknown: if (err) *err = e; return e == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::StateFolderUnknown; + } StateLock lock(gameDir, waitMs); if (!lock.held()) { if (err) *err = lock.error(); return SetResult::Busy; } std::string text; bool missing = false; - DWORD e = 0; Settings s; if (ReadBytes(SettingsPathOf(gameDir), &text, &missing, &e)) s = ParseSettings(text); - else if (!missing) { if (err) *err = e; return SetResult::Unreadable; } + else if (!missing) { if (err) *err = e; return e == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::Unreadable; } if (s.corrupt) s = Settings(); bool changed = !s.present; for (const auto& c : changes) { @@ -343,7 +500,10 @@ inline SetResult SetSettings(const std::wstring& gameDir, const std::vector #include +#include #include #include @@ -33,15 +42,16 @@ static std::wstring TempRoot() { return r; } static void WriteText(const std::wstring& p, const std::string& t) { - HANDLE h = CreateFileW(p.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE h = CreateFileW(ExtendedPath(p).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); DWORD put = 0; if (h != INVALID_HANDLE_VALUE) { WriteFile(h, t.data(), static_cast(t.size()), &put, nullptr); CloseHandle(h); } } static std::string ReadText(const std::wstring& p) { std::string t; ReadBytes(p, &t); return t; } +static bool Exists(const std::wstring& p) { return GetFileAttributesW(ExtendedPath(p).c_str()) != INVALID_FILE_ATTRIBUTES; } static std::vector List(const std::wstring& dir) { std::vector out; WIN32_FIND_DATAW f; - HANDLE h = FindFirstFileW(JoinPath(dir, L"*").c_str(), &f); + HANDLE h = FindFirstFileW(JoinPath(ExtendedPath(dir), L"*").c_str(), &f); if (h == INVALID_HANDLE_VALUE) return out; do { if (wcscmp(f.cFileName, L".") && wcscmp(f.cFileName, L"..")) out.push_back(f.cFileName); } while (FindNextFileW(h, &f)); FindClose(h); @@ -62,30 +72,40 @@ static DWORD WaitExit(HANDLE p, DWORD ms = 60000) { CloseHandle(p); return code; } -static unsigned long Counter(const std::wstring& game) { - const Settings s = ReadSettings(game); - const std::string* v = Get(s, "counter"); - return v ? std::strtoul(v->c_str(), nullptr, 10) : 0; -} - static bool WaitFile(const std::wstring& p, DWORD ms = 30000) { for (DWORD t = 0; t < ms; t += 20) { - if (GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES) return true; + if (Exists(p)) return true; Sleep(20); } return false; } +// One quoted command-line argument (backslashes before the closing quote doubled, as the C runtime's parser wants). +static std::wstring Q(const std::wstring& s) { + size_t tail = 0; + while (tail < s.size() && s[s.size() - 1 - tail] == L'\\') ++tail; + return L"\"" + s + std::wstring(tail, L'\\') + L"\""; +} +static unsigned long Counter(const std::wstring& game) { + const Settings s = ReadSettings(game); + const std::string* v = Get(s, "counter"); + return v ? std::strtoul(v->c_str(), nullptr, 10) : 0; +} +static std::string Narrow(const std::wstring& w) { + std::string s; + for (wchar_t c : w) s.push_back(c < 0x80 ? static_cast(c) : '?'); + return s; +} +static ULONGLONG Now() { return GetTickCount64(); } -// child modes: --child-add : n locked read-modify-write increments; --child-hold : holds the -// lock for ms; --child-die : takes the lock and, once go exists, ends without releasing it +// ---- child modes static int Child(int argc, wchar_t** argv) { const std::wstring mode = argv[1], game = argv[2]; - if (mode == L"--child-add" && argc >= 4) { + if (mode == L"--child-add" && argc >= 4) { // n locked read-modify-write increments of one counter const int n = _wtoi(argv[3]); for (int i = 0; i < n; ++i) { StateLock lock(game, 30000); if (!lock.held()) return 3; - const Settings s = ReadSettings(game); + const Settings s = ReadSettings(game); // re-read after the lock is taken const std::string* v = Get(s, "counter"); const unsigned long c = v ? std::strtoul(v->c_str(), nullptr, 10) : 0; Settings w = s; @@ -95,180 +115,344 @@ static int Child(int argc, wchar_t** argv) { } return 0; } - if (mode == L"--child-loaded" && argc >= 4) { // a "game" with WrongGPU loaded: the marker open until it is killed - LoadedMarker marker(game); - if (!marker.held()) return 3; - WriteText(argv[3], "ready"); - Sleep(120000); + if (mode == L"--child-lockname" && argc >= 4) { // the lock name of this spelling, into a file + std::wstring name; + DWORD err = 0; + WriteText(argv[3], LockNameFor(game, &name, &err) ? Narrow(name) : "error " + std::to_string(err)); return 0; } - if (mode == L"--child-hold" && argc >= 5) { + if (mode == L"--child-hold" && argc >= 5) { // holds the lock for ms StateLock lock(game, 30000); if (!lock.held()) return 3; WriteText(argv[4], "ready"); Sleep(static_cast(_wtoi(argv[3]))); return 0; } - if (mode == L"--child-die" && argc >= 5) { - StateLock* lock = new StateLock(game, 30000); // never released: the process ends holding it + if (mode == L"--child-die-midwrite" && argc >= 5) { // takes the lock, half-writes a temporary file, dies holding the lock + StateLock* lock = new StateLock(game, 30000); if (!lock->held()) return 3; + HANDLE h = CreateFileW(ExtendedPath(SettingsPathOf(game) + kTempMark + L"crash-1").c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); + DWORD put = 0; + if (h != INVALID_HANDLE_VALUE) { WriteFile(h, "counter=99", 10, &put, nullptr); CloseHandle(h); } // no line end: half a file WriteText(argv[3], "ready"); - WaitFile(argv[4]); // the parent has its own handle now + WaitFile(argv[4]); // the parent keeps a handle to the mutex now ExitProcess(0); } + if (mode == L"--child-register" && argc >= 5) { // the game's registration (wait ms), then stays loaded until killed + const ULONGLONG t0 = Now(); + LoadedRegistration reg(game, static_cast(_wtoi(argv[3]))); + WriteText(argv[4], (reg.ok() ? "ok " : "no ") + std::to_string(Now() - t0) + " " + reg.why()); + if (!reg.ok()) return 0; + Sleep(120000); + return 0; + } return 2; } int wmain(int argc, wchar_t** argv) { if (argc >= 3 && std::wstring(argv[1]).rfind(L"--child", 0) == 0) return Child(argc, argv); const std::wstring root = TempRoot(); + const std::wstring game = JoinPath(root, L"Game"); + CreateDirectoryW(game.c_str(), nullptr); // ---- the strict format { Settings s = ParseSettings("; comment\r\n\r\nrr_mode=fast\r\nrr_enabled=1\n"); check(s.present && !s.corrupt && s.kv.size() == 2 && *Get(s, "rr_mode") == "fast" && *Get(s, "rr_enabled") == "1", "parse: comments, blank lines, CRLF and LF"); const char* bad[] = {"rr_mode = fast\r\n", "[wronggpu]\r\nrr_mode=fast\r\n", "RR_MODE=fast\r\n", "rr_mode=fast\r\nrr_mode=accurate\r\n", - "rr_mode\r\n", "rr_mode=fa st\r\n", "=fast\r\n", "rr_mode=f\xc3\xa4st\r\n", "; \xc3\xa4\r\n"}; + "rr_mode\r\n", "rr_mode=fa st\r\n", "=fast\r\n", "rr_mode=f\xc3\xa4st\r\n", "; \xc3\xa4\r\n", + "rr_mode=fast\r", "rr_mode=fa\rst\r\n", "rr_mode=fast\r\r\n", "; a\rb\n"}; bool all = true; for (const char* b : bad) { const Settings x = ParseSettings(b); all = all && x.corrupt && x.kv.empty() && !x.why.empty(); } - check(all, "parse: spaces, sections, upper case, a key twice, no '=', bad value, empty key, non-ASCII: corrupt, no keys"); + check(all, "parse: spaces, sections, upper case, a key twice, no '=', bad value, empty key, non-ASCII, a bare or embedded CR: corrupt"); + check(!ParseSettings("rr_mode=fast").corrupt, "parse: a last line without a line end is fine"); Settings r; check(Set(r, "rr_mode", "fast") && Set(r, "rr_mode", "exact") && r.kv.size() == 1 && !Set(r, "Bad Key", "x") && !Set(r, "k", "a b"), "Set: replace, refuse bad key/value"); const Settings back = ParseSettings(RenderSettings(r)); check(!back.corrupt && back.kv == r.kv, "render -> parse round trip"); } - // ---- atomic writes and reads on real files - const std::wstring game = JoinPath(root, L"Game"); - CreateDirectoryW(game.c_str(), nullptr); + // ---- atomic writes + const std::wstring state = StateDirOf(game); { - check(ReadSettings(game).present == false && ReadSettings(game).why.empty(), "no settings.ini: not present, no error"); - check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::NoStateFolder && !IsDirectory(StateDirOf(game)), + check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::NoStateFolder && DirectoryState(state) == PathState::Missing, "no state folder: NoStateFolder, the folder is not created"); - CreateDirectoryW(StateDirOf(game).c_str(), nullptr); + CreateDirectoryW(state.c_str(), nullptr); + const std::wstring f = SettingsPathOf(game); check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::Ok && *Get(ReadSettings(game), "rr_mode") == "fast", "SetSettings writes the file"); - check(SetSettings(game, {{"rr_enabled", "0"}}) == SetResult::Ok && *Get(ReadSettings(game), "rr_mode") == "fast" && - *Get(ReadSettings(game), "rr_enabled") == "0", "a second key keeps the first"); - check(SetSettings(game, {{"rr mode", "x"}}) == SetResult::Invalid, "an invalid key: Invalid, nothing written"); - std::vector names = List(StateDirOf(game)); - check(names.size() == 1 && names[0] == kSettingsFile, "no temporary file stays after writes"); + const std::string before = ReadText(f); DWORD e = 0; + check(!WriteAtomic(f, std::string(kMaxStateBytes + 1, 'x'), &e) && e == ERROR_FILE_TOO_LARGE && ReadText(f) == before, "over kMaxStateBytes: refused, the file unchanged"); + bool steps = true; + for (const char* step : {"write", "flush", "close", "move"}) { + static const char* failAt = nullptr; + failAt = step; + TestFault() = [](const char* s) { return std::strcmp(s, failAt) == 0; }; + std::wstring left; + e = 0; + const bool ok = WriteAtomic(f, "rr_mode=exact\r\n", &e, &left); + TestFault() = nullptr; + const bool good = !ok && e == ERROR_WRITE_FAULT && left.empty() && ReadText(f) == before && List(state).size() == 1; + if (!good) std::printf(" (failure at %s: ok %d, error %lu, left %d, files %zu)\n", step, ok, e, !left.empty(), List(state).size()); + steps = steps && good; + } + check(steps, "a failure at write / flush / close / move (after the temporary file exists): false, the file unchanged, no temporary file left"); + TestFault() = [](const char* s) { return std::strcmp(s, "move") == 0 || std::strcmp(s, "delete") == 0; }; + std::wstring left; + const bool ok = WriteAtomic(f, "rr_mode=exact\r\n", &e, &left); + TestFault() = nullptr; + check(!ok && !left.empty() && Exists(left) && IsTempName(left) && ReadText(f) == before, "a cleanup that fails: reported (tempLeft), the file unchanged"); + if (!left.empty()) DeleteFileW(left.c_str()); check(!WriteAtomic(JoinPath(JoinPath(root, L"missing-folder"), L"x.ini"), "x", &e) && e != 0, "a write into a missing folder fails with its error"); - // corrupt: readers see no keys; the next write replaces the file - WriteText(SettingsPathOf(game), "rr_mode = fast\r\n"); - const Settings c = ReadSettings(game); - check(c.present && c.corrupt && c.kv.empty(), "a corrupt file reads as corrupt, no keys"); - check(SetSettings(game, {{"rr_mode", "accurate"}}) == SetResult::Ok && !ReadSettings(game).corrupt && *Get(ReadSettings(game), "rr_mode") == "accurate" && - ReadSettings(game).kv.size() == 1, "a corrupt file is replaced by the next write (only the new key)"); - // unreadable (held without sharing): never overwritten - const std::string before = ReadText(SettingsPathOf(game)); - HANDLE h = CreateFileW(SettingsPathOf(game).c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + // corrupt, unreadable + WriteText(f, "rr_mode = fast\r\n"); + check(ReadSettings(game).corrupt && ReadSettings(game).kv.empty(), "a corrupt file reads as corrupt, no keys"); + check(SetSettings(game, {{"rr_mode", "accurate"}}) == SetResult::Ok && ReadSettings(game).kv.size() == 1, "a corrupt file is replaced by the next write"); + const std::string b2 = ReadText(f); + HANDLE h = CreateFileW(f.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); DWORD err = 0; const SetResult r = SetSettings(game, {{"rr_mode", "exact"}}, kDefaultWaitMs, &err); CloseHandle(h); - check(r == SetResult::Unreadable && err != 0 && ReadText(SettingsPathOf(game)) == before, "an unreadable file: Unreadable, left as it was"); - names = List(StateDirOf(game)); - check(names.size() == 1, "no temporary file stays after the refused write"); + check(r == SetResult::Unreadable && err != 0 && ReadText(f) == b2 && List(state).size() == 1, "an unreadable file: Unreadable, left as it was"); + // a state folder this process may not write: AccessDenied (its own result, for the elevated repair) + PSECURITY_DESCRIPTOR ro = nullptr, rw = nullptr; + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;0x1200a9;;;WD)", SDDL_REVISION_1, &ro, nullptr); // read and list only + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;WD)", SDDL_REVISION_1, &rw, nullptr); + const bool locked = ro && SetFileSecurityW(state.c_str(), DACL_SECURITY_INFORMATION, ro); + err = 0; + const SetResult denied = SetSettings(game, {{"rr_mode", "exact"}}, kDefaultWaitMs, &err); + if (rw) SetFileSecurityW(state.c_str(), DACL_SECURITY_INFORMATION, rw); // the owner may always change the DACL back + if (ro) LocalFree(ro); + if (rw) LocalFree(rw); + check(locked && denied == SetResult::AccessDenied && err == ERROR_ACCESS_DENIED && ReadText(f) == b2, "a folder this process may not write: AccessDenied, nothing written"); + check(std::string(SetResultWords(SetResult::AccessDenied)).find("administrator") != std::string::npos, "AccessDenied's words name the elevated repair"); + WriteText(f, "counter=0\r\n"); } - // ---- one lock name for every spelling of the folder + // ---- one lock name for every alias of the folder, each in a SEPARATE process + std::vector aliases; { - std::wstring a, b, c, d; - check(LockNameFor(game, &a) && LockNameFor(game + L"\\", &b) && a == b && a.rfind(L"Local\\WrongGPU-state-", 0) == 0, "lock name: trailing backslash"); + aliases.push_back(game); + aliases.push_back(game + L"\\"); std::wstring upper = game; for (auto& ch : upper) ch = static_cast(towupper(ch)); - check(LockNameFor(upper, &c) && a == c, "lock name: another case"); + aliases.push_back(upper); wchar_t shortp[MAX_PATH * 2]; - if (GetShortPathNameW(game.c_str(), shortp, MAX_PATH * 2)) check(LockNameFor(shortp, &d) && a == d, "lock name: the short (8.3) path"); - std::wstring other; - const std::wstring g2 = JoinPath(root, L"Other"); - CreateDirectoryW(g2.c_str(), nullptr); - check(LockNameFor(g2, &other) && other != a, "lock name: another folder, another name"); - DWORD e = 0; - check(!LockNameFor(JoinPath(root, L"nope"), &other, &e) && e != 0, "lock name: a missing folder fails"); + const bool haveShort = GetShortPathNameW(game.c_str(), shortp, MAX_PATH * 2) != 0; + if (haveShort) aliases.push_back(shortp); + aliases.push_back(L"\\\\?\\" + game); + const std::wstring junction = JoinPath(root, L"GameJunction"); + HANDLE mk = nullptr; + { + std::wstring cmd = L"cmd.exe /d /c mklink /J " + Q(junction) + L" " + Q(game) + L" >nul"; + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + if (CreateProcessW(nullptr, &cmd[0], nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) { CloseHandle(pi.hThread); mk = pi.hProcess; } + } + if (mk) WaitExit(mk); + const bool haveJunction = Exists(junction); + if (haveJunction) aliases.push_back(junction); + check(haveShort && haveJunction, "aliases made: the 8.3 short name and a junction"); + std::vector names; + bool all = true; + for (size_t i = 0; i < aliases.size(); ++i) { + const std::wstring out = JoinPath(root, L"name-" + std::to_wstring(i)); + HANDLE k = Spawn(L"--child-lockname " + Q(aliases[i]) + L" " + Q(out)); + all = all && k && WaitExit(k) == 0; + names.push_back(ReadText(out)); + DeleteFileW(out.c_str()); + } + bool same = all && !names.empty() && names[0].rfind("Global\\WrongGPU-state-", 0) == 0; + for (auto& n : names) same = same && n == names[0]; + if (!same) + for (size_t i = 0; i < names.size(); ++i) std::printf(" (alias %zu %s -> %s)\n", i, Narrow(aliases[i]).c_str(), names[i].c_str()); + check(same, "lock name: case, trailing backslash, 8.3 name, \\\\?\\ form and a junction give one name, each computed in its own process"); + // a folder deeper than MAX_PATH: the helpers work on it without the long-path setting + std::wstring deep = root; + while (deep.size() < MAX_PATH + 40) { + deep = JoinPath(deep, L"a-rather-long-folder-name-for-the-path-test"); + CreateDirectoryW(ExtendedPath(deep).c_str(), nullptr); + } + std::wstring dn; + CreateDirectoryW(ExtendedPath(StateDirOf(deep)).c_str(), nullptr); + check(LockNameFor(deep, &dn) && Narrow(dn) != names[0] && SetSettings(deep, {{"k", "v"}}) == SetResult::Ok && *Get(ReadSettings(deep), "k") == "v", + "a game folder deeper than MAX_PATH: lock name, write and read work"); + const std::wstring dout = JoinPath(root, L"name-deep"); + HANDLE k = Spawn(L"--child-lockname " + Q(deep) + L" " + Q(dout)); + if (k) WaitExit(k); + check(ReadText(dout) == Narrow(dn), "the deep folder's lock name is the same in another process"); + DeleteFileW(dout.c_str()); + // cleanup of the deep folders (own files only) + DeleteFileW(ExtendedPath(SettingsPathOf(deep)).c_str()); + RemoveDirectoryW(ExtendedPath(StateDirOf(deep)).c_str()); + while (deep.size() > root.size()) { + RemoveDirectoryW(ExtendedPath(deep).c_str()); + deep = deep.substr(0, deep.find_last_of(L'\\')); + } } - // ---- mutual exclusion across processes: 4 children x 50 locked increments of one counter, no update lost + // ---- mutual exclusion across processes that use DIFFERENT aliases: 4 x 50 locked increments, no update lost { WriteText(SettingsPathOf(game), "counter=0\r\n"); std::vector kids; - for (int i = 0; i < 4; ++i) kids.push_back(Spawn(L"--child-add \"" + game + L"\" 50")); - bool started = true, ok = true; - for (HANDLE k : kids) { if (!k) started = false; else ok = WaitExit(k, 120000) == 0 && ok; } - check(started && ok, "4 child processes ran their locked increments"); - check(Counter(game) == 200, "the counter is 200: the lock serialised every read-modify-write across processes"); - check(List(StateDirOf(game)).size() == 1, "no temporary file stays after concurrent writes"); + for (int i = 0; i < 4; ++i) kids.push_back(Spawn(L"--child-add " + Q(aliases[(i * 2 + 1) % aliases.size()]) + L" 50")); + bool ok = true; + for (HANDLE k : kids) ok = k && WaitExit(k, 120000) == 0 && ok; + check(ok && Counter(game) == 200, "4 processes, 4 different aliases, 50 locked increments each: 200 (one lock for all spellings)"); + check(List(state).size() == 1, "no temporary file stays after concurrent writes"); } - // ---- busy: another process holds the lock; a bounded wait gives up (Busy), the file unchanged + // ---- busy: a bounded wait gives up, nothing written { const std::wstring ready = JoinPath(root, L"ready-hold"); - HANDLE k = Spawn(L"--child-hold \"" + game + L"\" 3000 \"" + ready + L"\""); + HANDLE k = Spawn(L"--child-hold " + Q(game) + L" 3000 " + Q(ready)); const bool up = k && WaitFile(ready); const std::string before = ReadText(SettingsPathOf(game)); DWORD err = 0; const SetResult r = SetSettings(game, {{"rr_mode", "fast"}}, 200, &err); check(up && r == SetResult::Busy && err == WAIT_TIMEOUT && ReadText(SettingsPathOf(game)) == before, "lock held elsewhere: Busy after the bounded wait, nothing written"); if (k) WaitExit(k); - check(SetSettings(game, {{"rr_mode", "fast"}}, 5000) == SetResult::Ok, "after the holder ends: the write goes through"); + DeleteFileW(ready.c_str()); } - // ---- abandoned: a child dies holding the lock; the next waiter gets it + // ---- abandoned in the middle of a write: the next holder re-reads the old whole file { - const std::wstring ready = JoinPath(root, L"ready-die"); - const std::wstring go = JoinPath(root, L"go-die"); - HANDLE k = Spawn(L"--child-die \"" + game + L"\" \"" + ready + L"\" \"" + go + L"\""); + WriteText(SettingsPathOf(game), "counter=7\r\n"); + const std::wstring ready = JoinPath(root, L"ready-die"), go = JoinPath(root, L"go-die"); + HANDLE k = Spawn(L"--child-die-midwrite " + Q(game) + L" " + Q(ready) + L" " + Q(go)); const bool up = k && WaitFile(ready); std::wstring name; LockNameFor(game, &name); - HANDLE keep = OpenMutexW(SYNCHRONIZE, FALSE, name.c_str()); // keeps the mutex object alive past the child's end + HANDLE keep = OpenMutexW(SYNCHRONIZE, FALSE, name.c_str()); // keeps the mutex alive past the child's end WriteText(go, "go"); if (k) WaitExit(k); { StateLock lock(game, 5000); - if (!(up && keep && lock.held() && lock.abandoned())) - std::printf(" (up %d, kept handle %d, held %d, abandoned %d, error %lu)\n", up, keep != nullptr, lock.held(), lock.abandoned(), lock.error()); - check(up && keep && lock.held() && lock.abandoned(), "a holder that died: the lock is taken (abandoned), not stuck"); + const Settings s = ReadSettings(game); // re-read after the lock + check(up && keep && lock.held() && lock.abandoned() && !s.corrupt && *Get(s, "counter") == "7", + "a holder that died mid-write: the lock is taken (abandoned), the state re-read is the old whole file"); + std::wstring temp; + for (auto& n : List(state)) if (IsTempName(n)) temp = n; + check(!temp.empty(), "the half-written temporary file is there and named as a temporary file (never read as state)"); + check(SetSettings(game, {{"counter", "8"}}) == SetResult::Ok && *Get(ReadSettings(game), "counter") == "8", "a write under the abandoned-then-taken lock works"); + if (!temp.empty()) DeleteFileW(JoinPath(state, temp).c_str()); } if (keep) CloseHandle(keep); - StateLock again(game, 5000); - check(again.held() && !again.abandoned(), "after that: the lock is taken normally"); + DeleteFileW(ready.c_str()); + DeleteFileW(go.c_str()); } - // ---- the loaded marker: in this process, in another one, and a dead owner (killed) leaves none + // ---- the loaded protocol { - const std::wstring g2 = JoinPath(root, L"Other"); - check(!IsGameUsingWrongGPU(game) && !IsGameUsingWrongGPU(game), "no marker: not in use (and the check creates none)"); + DWORD err = 0; + check(QueryGameUse(game, &err) == GameUse::NotRunning && QueryGameUse(game) == GameUse::NotRunning, "no marker: NotRunning (and the query creates none)"); + check(QueryGameUse(JoinPath(root, L"gone")) == GameUse::NotRunning, "a folder that does not exist: NotRunning (nothing can run from it)"); { - LoadedMarker m(game); - std::wstring upper = game; - for (auto& ch : upper) ch = static_cast(towupper(ch)); - check(m.held() && IsGameUsingWrongGPU(game) && IsGameUsingWrongGPU(upper + L"\\") && !IsGameUsingWrongGPU(g2), - "a marker in this process: in use (any spelling of the folder), another folder not"); + LoadedRegistration reg(game); + check(reg.ok() && QueryGameUse(aliases.back()) == GameUse::Running, "registered in this process: Running (asked through another alias)"); } - check(!IsGameUsingWrongGPU(game), "the marker closed: not in use"); - check(!IsGameUsingWrongGPU(JoinPath(root, L"nope")), "a missing folder: not in use"); - const std::wstring ready = JoinPath(root, L"ready-loaded"); - HANDLE k = Spawn(L"--child-loaded \"" + game + L"\" \"" + ready + L"\""); - const bool up = k && WaitFile(ready); - check(up && IsGameUsingWrongGPU(game), "another process with the marker open: in use"); + check(QueryGameUse(game) == GameUse::NotRunning, "the registration ended: NotRunning"); + // a lookup error is Unknown, never NotRunning: an object of another type under the marker's name + { + std::wstring markerName; + NameFor(kLoadedPrefix, game, &markerName, nullptr); + HANDLE ev = CreateEventW(nullptr, TRUE, FALSE, markerName.c_str()); + err = 0; + const GameUse u = QueryGameUse(game, &err); + OperationGuard g(game, 1000); + check(ev && u == GameUse::Unknown && err != 0 && g.result() == GuardResult::Unknown && std::string(g.words()).find("could not tell") != std::string::npos, + "a marker lookup that fails: Unknown, and the launcher's guard refuses (Unknown)"); + if (ev) CloseHandle(ev); + } + // a game folder this process cannot open: Unknown, the guard refuses + { + const std::wstring locked = JoinPath(root, L"Locked"); + CreateDirectoryW(locked.c_str(), nullptr); + PSECURITY_DESCRIPTOR deny = nullptr, allow = nullptr, parentDeny = nullptr, parentAllow = nullptr; + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(D;;FA;;;WD)", SDDL_REVISION_1, &deny, nullptr); + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;WD)", SDDL_REVISION_1, &allow, nullptr); + // the parent must not grant listing either (listing a folder lets its entries' attributes be read) + const std::wstring parent = JoinPath(root, L"LockedParent"); + CreateDirectoryW(parent.c_str(), nullptr); + const std::wstring inner = JoinPath(parent, L"Game"); + CreateDirectoryW(inner.c_str(), nullptr); + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(D;;0x1;;;WD)(A;;FA;;;WD)", SDDL_REVISION_1, &parentDeny, nullptr); + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;WD)", SDDL_REVISION_1, &parentAllow, nullptr); + const bool set = deny && parentDeny && SetFileSecurityW(inner.c_str(), DACL_SECURITY_INFORMATION, deny) && + SetFileSecurityW(parent.c_str(), DACL_SECURITY_INFORMATION, parentDeny); + err = 0; + const GameUse u = QueryGameUse(inner, &err); + const GuardResult gr = OperationGuard(inner, 500).result(); + if (allow) SetFileSecurityW(inner.c_str(), DACL_SECURITY_INFORMATION, allow); + if (parentAllow) SetFileSecurityW(parent.c_str(), DACL_SECURITY_INFORMATION, parentAllow); + for (PSECURITY_DESCRIPTOR p : {deny, allow, parentDeny, parentAllow}) if (p) LocalFree(p); + if (!(set && u == GameUse::Unknown && err == ERROR_ACCESS_DENIED && gr == GuardResult::Unknown)) + std::printf(" (access-denied lookup: set %d, use %d, error %lu, guard %d)\n", set, static_cast(u), err, static_cast(gr)); + check(set && u == GameUse::Unknown && err == ERROR_ACCESS_DENIED && gr == GuardResult::Unknown, + "a game folder whose identity cannot be read (access denied): Unknown, the guard refuses"); + RemoveDirectoryW(inner.c_str()); + RemoveDirectoryW(parent.c_str()); + RemoveDirectoryW(locked.c_str()); + } + // a registered game in another process; then it crashes + const std::wstring out = JoinPath(root, L"reg-1"); + HANDLE k = Spawn(L"--child-register " + Q(game) + L" 2000 " + Q(out)); + const bool up = k && WaitFile(out) && ReadText(out).rfind("ok", 0) == 0; + OperationGuard* g = new OperationGuard(game, 1000); + check(up && QueryGameUse(game) == GameUse::Running && g->result() == GuardResult::GameRunning && std::string(g->words()).find("close the game") != std::string::npos, + "a game registered in another process: Running, the guard refuses (GameRunning)"); + delete g; if (k) { - TerminateProcess(k, 9); // the game crashes (no cleanup of its own) + TerminateProcess(k, 9); // the game crashes WaitForSingleObject(k, 30000); CloseHandle(k); } - check(up && !IsGameUsingWrongGPU(game), "the owning process died: no stale marker, not in use"); - DeleteFileW(ready.c_str()); + check(up && QueryGameUse(game) == GameUse::NotRunning && OperationGuard(game, 1000).result() == GuardResult::Ok, + "the game died: no stale marker, NotRunning, the guard lets the operation run"); + DeleteFileW(out.c_str()); + } + + // ---- registration against a running operation: no slipping in between + { + const std::wstring out = JoinPath(root, L"reg-2"); + ULONGLONG released = 0; + HANDLE k = nullptr; + { + OperationGuard op(game, 1000); // the launcher's operation starts (lock held, no game) + const bool ok = op.result() == GuardResult::Ok; + k = Spawn(L"--child-register " + Q(game) + L" 2000 " + Q(out)); // the game starts during it + Sleep(800); + check(ok && !Exists(out) && QueryGameUse(game) == GameUse::NotRunning, "during the operation the starting game cannot register (it waits; nothing is loaded)"); + released = Now(); + } // the operation ends: the lock is released + const bool got = k && WaitFile(out, 10000); + const std::string r = ReadText(out); + check(got && r.rfind("ok", 0) == 0 && QueryGameUse(game) == GameUse::Running, "after the operation the game registers (it waited, bounded)"); + check(released > 0 && std::strtoul(r.c_str() + 3, nullptr, 10) >= 500, "the registration came only after the operation released the lock"); + if (k) { TerminateProcess(k, 9); WaitForSingleObject(k, 30000); CloseHandle(k); } + DeleteFileW(out.c_str()); + // a registration that cannot wait that long gives up in time and touches nothing + const std::wstring out2 = JoinPath(root, L"reg-3"); + HANDLE k2 = nullptr; + { + OperationGuard op(game, 1000); + k2 = Spawn(L"--child-register " + Q(game) + L" 300 " + Q(out2)); + const bool got2 = k2 && WaitFile(out2, 10000); + const std::string r2 = ReadText(out2); + check(op.result() == GuardResult::Ok && got2 && r2.rfind("no", 0) == 0 && r2.find("not free in time") != std::string::npos && + std::strtoul(r2.c_str() + 3, nullptr, 10) < 1500 && QueryGameUse(game) == GameUse::NotRunning, + "a registration while an operation runs gives up after its bounded wait: no marker, defaults, nothing blocked"); + } + if (k2) WaitExit(k2); + DeleteFileW(out2.c_str()); } // cleanup (own files only) - for (const auto& n : List(StateDirOf(game))) DeleteFileW(JoinPath(StateDirOf(game), n).c_str()); - RemoveDirectoryW(StateDirOf(game).c_str()); + for (const auto& n : List(state)) DeleteFileW(JoinPath(state, n).c_str()); + RemoveDirectoryW(state.c_str()); + RemoveDirectoryW(JoinPath(root, L"GameJunction").c_str()); // the junction itself (its target is not touched) RemoveDirectoryW(game.c_str()); - RemoveDirectoryW(JoinPath(root, L"Other").c_str()); - DeleteFileW(JoinPath(root, L"ready-hold").c_str()); - DeleteFileW(JoinPath(root, L"ready-die").c_str()); - DeleteFileW(JoinPath(root, L"go-die").c_str()); RemoveDirectoryW(root.c_str()); std::printf("wg_state: %d passed, %d failed\n", g_pass, g_fail); return g_fail ? 1 : 0; From ea2d7eaa43de0b0872e98d999928894416b4ac24 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:37:50 -0500 Subject: [PATCH 4/7] Shared: wg_state.h re-check fixes (marker before the lock, Recheck, LockDenied, write outcomes) 1. The game's marker no longer waits for the state lock: LoadedRegistration makes the marker at once, then tries the lock within the rest of its budget (state_ok() only when had). A game that starts during an operation is visible at once; OperationGuard::Recheck() (no file-system call) is meant for every destructive step and turns the result to GameRunning. 2. A state lock this process may not open is LockDenied (SetSettings and OperationGuard), apart from Busy (a timeout); StateLock tells timedOut() from denied(). 3. WriteAtomic returns a WriteResult and SetSettings a SetOutcome carrying the first failure and every secondary one (a close after an earlier failure, a failed cleanup with its error and the file left); words() says all of them. 4. The whole registration is bounded (kRegisterBudgetMs, about 2 s): the folder identity lookup runs on a helper thread within the budget, the lock wait gets the rest; never from DllMain; nothing throws out of it. Tests: secondary close and cleanup failures; LockDenied; a game starting mid-operation (marker seen by Recheck, state given up within the budget, still visible to a later operation); registration with and without a running operation; a 300 ms budget ends within it. Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/include/wg_state.h | 356 +++++++++++++++++-------- clean/wgshared/tests/test_wg_state.cpp | 163 +++++++---- 2 files changed, 350 insertions(+), 169 deletions(-) diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 64f55842..a331062f 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -22,25 +22,34 @@ // the next taker gets it, and because writes are atomic (below) the files are whole: the old version or the new one. A // temporary file such a holder left is never read as state (IsTempName) and goes with the uninstall. // -// THE LOADED PROTOCOL (no check-then-act race between a game starting and the launcher changing the game's files): -// - The game: every WrongGPU module that is loaded in the game registers BEFORE it reads or writes any state -// (LoadedRegistration): it takes the state lock (bounded wait, kRegisterWaitMs), opens its LoadedMarker -// (Global\WrongGPU-loaded--, held OPEN for as long as the module is loaded, never owned) and -// releases the lock. When the lock is not had in time (a long uninstall, repair or update is running) or the marker cannot -// be made, ok() is false: the module logs it and runs with the defaults, reading and writing no state that session. It -// never blocks the game for longer than the bounded wait. -// - The launcher: an uninstall, repair or update holds an OperationGuard for its WHOLE run: it takes the state lock, then -// asks QueryGameUse, and refuses unless the answer is NotRunning (Running and Unknown both refuse). The lock stays held -// until the operation ends, so no game can register in between. The guard is taken by the process that changes the -// files (the elevated worker when there is one), never by a parent waiting for it. +// THE LOADED PROTOCOL (a game is never invisible to an operation that changes its files): +// - The game: every WrongGPU module loaded in the game registers (LoadedRegistration) at its init, BEFORE it reads or writes +// any state, and keeps the registration for as long as it is loaded: +// 1. its LOADED MARKER first, at once, with no wait: Global\WrongGPU-loaded-- (same identity as +// the state lock), a named object held OPEN, never owned. While the game runs the marker exists, whatever happens next; +// 2. only then the state lock, with a bounded wait: had in time = no launcher operation is running, the module may use the +// state (each later use takes the lock again); not had in time (an uninstall, repair or update is running) = the module +// runs with the defaults and reads and writes no state this session (state_ok() false; why() says so for the log). +// The whole registration is bounded by kRegisterBudgetMs (about 2 s): the folder identity lookup (a file-system call that a +// network folder can stall) runs on a helper thread within that budget, the lock wait gets the rest; a lookup that does not +// finish in time gives no marker and no state (and the launcher, which needs the same lookup, refuses: Unknown). Register +// from the module's init (InitializeASI, the first call), NEVER from DllMain (the helper thread needs the loader lock). +// A marker that cannot be made (marker() false) is logged; the module then uses no state either. +// - The launcher: an uninstall, repair or update holds an OperationGuard for its WHOLE run: it takes the state lock (a +// timeout is Busy, access denied is LockDenied), then queries the marker and refuses unless the answer is NotRunning +// (Running and Unknown both refuse). A game that starts DURING the operation still creates its marker at once (it then +// waits for the lock, and gives up on state): so the operation calls Recheck() before EACH destructive step (each file it +// deletes or replaces) and stops with "close the game first" when the marker appeared. The guard is taken by the process +// that changes the files (the elevated worker when there is one), never by a parent waiting for it. // The marker object exists exactly while some process has it open; the OS closes every handle of a process that ends, crashes // or is killed, so a dead game leaves no stale marker and no PID is ever compared. // // Writes are atomic (WriteAtomic): a new temporary file in the same folder (.wgtmp--, created only where // nothing is), written in checked chunks, flushed and closed (both checked), then MoveFileExW(REPLACE_EXISTING | -// WRITE_THROUGH) over the file. On a failure the temporary file is deleted when possible; a temporary file that could not be -// deleted is reported (*tempLeft). A reader sees the old file or the new one, never part of one. State files are small: -// more than kMaxStateBytes is refused. +// WRITE_THROUGH) over the file. A reader sees the old file or the new one, never part of one. On a failure the temporary file +// is deleted when possible; the result (WriteResult, and SetOutcome for SetSettings) carries the first failure AND every +// secondary one: a close that failed after an earlier failure, a cleanup that failed (its error and the file left). words() +// says all of them. State files are small: more than kMaxStateBytes is refused. // Paths: every helper turns its path into the \\?\ form (full path; \\?\UNC\ for a share), so a game deeper than MAX_PATH // works without the long-path setting. // @@ -75,7 +84,8 @@ constexpr const wchar_t* kSettingsFile = L"settings.ini"; constexpr const wchar_t* kModelChoiceFile = L"model-choice.ini"; constexpr const wchar_t* kTempMark = L".wgtmp-"; // .wgtmp--: a write in progress (or one a crash left) constexpr DWORD kDefaultWaitMs = 5000; // the launcher's waits -constexpr DWORD kRegisterWaitMs = 2000; // the game's registration: never longer +constexpr DWORD kRegisterBudgetMs = 2000; // the game's whole registration (lookup + lock wait): never longer +constexpr DWORD kRegisterWaitMs = kRegisterBudgetMs; // (the name earlier code used) constexpr size_t kMaxStateBytes = 1u << 20; // no state file is larger constexpr DWORD kChunk = 64u * 1024u; @@ -139,6 +149,9 @@ inline bool LockNameFor(const std::wstring& gameDir, std::wstring* name, DWORD* *name = buf; return true; } +/// The names of a game folder's identity: Global\WrongGPU-state- (the lock) and Global\WrongGPU-loaded- (the marker). +constexpr const wchar_t* kLoadedPrefix = L"Global\\WrongGPU-loaded-"; +inline std::wstring MarkerNameOf(const std::wstring& lockName) { return std::wstring(kLoadedPrefix) + lockName.substr(lockName.find(L"-state-") + 7); } // Another per-game name of the same identity: prefix + "-". inline bool NameFor(const wchar_t* prefix, const std::wstring& gameDir, std::wstring* name, DWORD* err) { std::wstring lock; @@ -146,6 +159,41 @@ inline bool NameFor(const wchar_t* prefix, const std::wstring& gameDir, std::wst *name = std::wstring(prefix) + lock.substr(lock.find(L"-state-") + 7); return true; } +// LockNameFor within budgetMs: the lookup (a file-system call a network folder can stall) runs on a helper thread; a lookup +// that does not finish in time gives false with *err = WAIT_TIMEOUT (the thread finishes on its own and frees its data). +// Never from DllMain. Never throws. +namespace detail { +struct LookupJob { + std::wstring dir, name; + DWORD err = 0; + bool ok = false; + volatile LONG refs = 2; +}; +inline DWORD WINAPI LookupThread(void* p) { + LookupJob* j = static_cast(p); + try { j->ok = LockNameFor(j->dir, &j->name, &j->err); } catch (...) { j->ok = false; j->err = ERROR_OUTOFMEMORY; } + if (InterlockedDecrement(&j->refs) == 0) delete j; + return 0; +} +} // namespace detail +inline bool LockNameWithin(const std::wstring& gameDir, DWORD budgetMs, std::wstring* name, DWORD* err) { + detail::LookupJob* j = nullptr; + try { j = new detail::LookupJob; j->dir = gameDir; } catch (...) { delete j; if (err) *err = ERROR_OUTOFMEMORY; return false; } + HANDLE t = CreateThread(nullptr, 0, &detail::LookupThread, j, 0, nullptr); + if (!t) { if (err) *err = GetLastError(); delete j; return false; } + const DWORD w = WaitForSingleObject(t, budgetMs); + CloseHandle(t); + bool ok = false; + if (w == WAIT_OBJECT_0) { + ok = j->ok; + if (err) *err = j->err; + if (ok) { try { *name = j->name; } catch (...) { ok = false; if (err) *err = ERROR_OUTOFMEMORY; } } + } else if (err) { + *err = WAIT_TIMEOUT; + } + if (InterlockedDecrement(&j->refs) == 0) delete j; + return ok; +} // A named mutex every integrity level may open (created, or opened when it exists); nullptr with GetLastError on failure. inline HANDLE CreateSharedMutex(const std::wstring& name) { PSECURITY_DESCRIPTOR sd = nullptr; @@ -161,19 +209,17 @@ inline HANDLE CreateSharedMutex(const std::wstring& name) { return m; } -// The game's state lock, held from construction (when held()) to destruction. Bounded wait: not held after waitMs. +// The game's state lock, held from construction (when held()) to destruction. Bounded wait: not held after waitMs; why: +// timedOut() (another holder), denied() (this process may not open the folder or the lock: ERROR_ACCESS_DENIED), else error(). class StateLock { public: + struct ByName {}; // the lock of an already known name (LockNameFor), no file-system call explicit StateLock(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) { std::wstring name; if (!LockNameFor(gameDir, &name, &err_)) return; - mutex_ = CreateSharedMutex(name); - if (!mutex_) { err_ = GetLastError(); return; } - const DWORD w = WaitForSingleObject(mutex_, waitMs); - held_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; - abandoned_ = w == WAIT_ABANDONED; - if (!held_) err_ = w == WAIT_TIMEOUT ? WAIT_TIMEOUT : GetLastError(); + Take(name, waitMs); } + StateLock(ByName, const std::wstring& lockName, DWORD waitMs) { Take(lockName, waitMs); } ~StateLock() { if (held_) ReleaseMutex(mutex_); if (mutex_) CloseHandle(mutex_); @@ -183,25 +229,35 @@ class StateLock { bool held() const { return held_; } // the previous holder ended without releasing it: informational (re-read the state from disk, as every holder must) bool abandoned() const { return abandoned_; } - DWORD error() const { return err_; } // why not held: WAIT_TIMEOUT, or the Win32 error + bool timedOut() const { return !held_ && err_ == WAIT_TIMEOUT; } + bool denied() const { return !held_ && err_ == ERROR_ACCESS_DENIED; } + DWORD error() const { return err_; } // why not held: WAIT_TIMEOUT, ERROR_ACCESS_DENIED, or another Win32 error private: + void Take(const std::wstring& name, DWORD waitMs) { + mutex_ = CreateSharedMutex(name); + if (!mutex_) { err_ = GetLastError(); return; } + const DWORD w = WaitForSingleObject(mutex_, waitMs); + held_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; + abandoned_ = w == WAIT_ABANDONED; + if (!held_) err_ = w == WAIT_TIMEOUT ? WAIT_TIMEOUT : GetLastError(); + } HANDLE mutex_ = nullptr; bool held_ = false, abandoned_ = false; DWORD err_ = 0; }; // ---- the loaded protocol ------------------------------------------------------------------------------------------ -constexpr const wchar_t* kLoadedPrefix = L"Global\\WrongGPU-loaded-"; -// The marker alone (held open, never owned). Use it through LoadedRegistration, which takes the state lock around it. +// The marker alone (held open, never owned). Games use it through LoadedRegistration. class LoadedMarker { public: explicit LoadedMarker(const std::wstring& gameDir) { std::wstring name; if (!NameFor(kLoadedPrefix, gameDir, &name, &err_)) return; - handle_ = CreateSharedMutex(name); - if (!handle_) err_ = GetLastError(); + Open(name); } + struct ByName {}; + LoadedMarker(ByName, const std::wstring& markerName) { Open(markerName); } ~LoadedMarker() { if (handle_) CloseHandle(handle_); } LoadedMarker(const LoadedMarker&) = delete; LoadedMarker& operator=(const LoadedMarker&) = delete; @@ -209,6 +265,10 @@ class LoadedMarker { DWORD error() const { return err_; } private: + void Open(const std::wstring& name) { + handle_ = CreateSharedMutex(name); + if (!handle_) err_ = GetLastError(); + } HANDLE handle_ = nullptr; DWORD err_ = 0; }; @@ -218,9 +278,18 @@ inline const char* GameUseWords(GameUse u) { return u == GameUse::NotRunning ? "not running" : u == GameUse::Running ? "the game is running with WrongGPU loaded" : "WrongGPU could not tell whether the game is running"; } +// The marker of a known name: Running (it exists, also when it is not ours to open), NotRunning (it does not exist), Unknown. +inline GameUse QueryMarker(const std::wstring& markerName, DWORD* err = nullptr) { + HANDLE h = OpenMutexW(SYNCHRONIZE, FALSE, markerName.c_str()); + if (h) { CloseHandle(h); return GameUse::Running; } + const DWORD e = GetLastError(); + if (err) *err = e; + if (e == ERROR_FILE_NOT_FOUND) return GameUse::NotRunning; + return e == ERROR_ACCESS_DENIED ? GameUse::Running : GameUse::Unknown; // there but not ours to open: in use +} // Whether a running process has WrongGPU loaded for the game folder gameDir. NotRunning ONLY when that is established: the // folder is gone (nothing can run from it), or its marker does not exist. Any error on the way is Unknown (*err). Never -// creates the marker. Ask it under the state lock (OperationGuard does). +// creates the marker. inline GameUse QueryGameUse(const std::wstring& gameDir, DWORD* err = nullptr) { std::wstring name; DWORD e = 0; @@ -228,71 +297,106 @@ inline GameUse QueryGameUse(const std::wstring& gameDir, DWORD* err = nullptr) { if (err) *err = e; return e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND ? GameUse::NotRunning : GameUse::Unknown; } - HANDLE h = OpenMutexW(SYNCHRONIZE, FALSE, name.c_str()); - if (h) { CloseHandle(h); return GameUse::Running; } - e = GetLastError(); - if (err) *err = e; - if (e == ERROR_FILE_NOT_FOUND) return GameUse::NotRunning; - return e == ERROR_ACCESS_DENIED ? GameUse::Running : GameUse::Unknown; // there but not ours to open: in use + return QueryMarker(name, err); } -// The game's side: register under the state lock before any state is read. ok() false: run with the defaults and touch no -// state this session (why() says what to log). Keep the object for as long as the module is loaded. +// The game's side (see THE LOADED PROTOCOL above): the marker at once, then the state lock within the rest of the budget. +// marker(): the game is visible to the launcher. state_ok(): the module may use the state (each use takes the lock again). +// why(): for the log when either is false. Keep the object for as long as the module is loaded. Never throws; bounded by +// budgetMs (at most kRegisterBudgetMs) in total; never from DllMain. class LoadedRegistration { public: - explicit LoadedRegistration(const std::wstring& gameDir, DWORD waitMs = kRegisterWaitMs) { - StateLock lock(gameDir, waitMs > kRegisterWaitMs ? kRegisterWaitMs : waitMs); - if (!lock.held()) { - err_ = lock.error(); - why_ = err_ == WAIT_TIMEOUT ? "the game's state lock was not free in time (an uninstall, repair or update of WrongGPU is running)" - : "the game's state lock could not be taken"; + explicit LoadedRegistration(const std::wstring& gameDir, DWORD budgetMs = kRegisterBudgetMs) { + if (budgetMs > kRegisterBudgetMs) budgetMs = kRegisterBudgetMs; + const ULONGLONG t0 = GetTickCount64(); + std::wstring lockName; + if (!LockNameWithin(gameDir, budgetMs, &lockName, &err_)) { + why_ = err_ == WAIT_TIMEOUT ? "the game folder's identity could not be read in time (no marker, no state this session)" + : "the game folder's identity could not be read (no marker, no state this session)"; return; } - marker_.reset(new LoadedMarker(gameDir)); - if (!marker_->held()) { - err_ = marker_->error(); - why_ = "the loaded marker could not be made"; + try { + marker_.reset(new LoadedMarker(LoadedMarker::ByName{}, MarkerNameOf(lockName))); // 1. visible at once, no wait + } catch (...) { + marker_.reset(); + } + if (!marker_ || !marker_->held()) { + err_ = marker_ ? marker_->error() : ERROR_OUTOFMEMORY; + why_ = "the loaded marker could not be made (no state this session)"; marker_.reset(); + return; + } + const ULONGLONG spent = GetTickCount64() - t0; + StateLock lock(StateLock::ByName{}, lockName, spent >= budgetMs ? 0 : static_cast(budgetMs - spent)); // 2. bounded + if (!lock.held()) { + err_ = lock.error(); + why_ = lock.timedOut() ? "the game's state lock was not free in time (an uninstall, repair or update of WrongGPU is running): the defaults, no state this session" + : lock.denied() ? "the game's state lock may not be used (access denied): the defaults, no state this session" + : "the game's state lock could not be taken: the defaults, no state this session"; + return; } + stateOk_ = true; } - bool ok() const { return marker_ != nullptr; } - const char* why() const { return why_; } // "" when ok + bool marker() const { return marker_ != nullptr; } + bool state_ok() const { return stateOk_; } + bool ok() const { return stateOk_; } // (state_ok) + const char* why() const { return why_; } // "" when both are fine DWORD error() const { return err_; } private: std::unique_ptr marker_; + bool stateOk_ = false; const char* why_ = ""; DWORD err_ = 0; }; -// The launcher's side: hold for the whole uninstall, repair or update. Ok only when the lock is held and no game uses WrongGPU. -enum class GuardResult { Ok, Busy, GameRunning, Unknown }; +// The launcher's side: hold for the whole uninstall, repair or update, and call Recheck() before each destructive step. +// Ok only when the lock is held and no game uses WrongGPU. The lock: a timeout is Busy, access denied is LockDenied. +enum class GuardResult { Ok, Busy, LockDenied, GameRunning, Unknown }; +inline const char* GuardWords(GuardResult r) { + switch (r) { + case GuardResult::Ok: return ""; + case GuardResult::Busy: return "another WrongGPU program is changing this game's WrongGPU state right now; try again in a moment"; + case GuardResult::LockDenied: return "WrongGPU may not use this game's state lock (access denied); run the launcher's repair as administrator"; + case GuardResult::GameRunning: return "the game is running with WrongGPU loaded; close the game first"; + case GuardResult::Unknown: return "WrongGPU could not tell whether the game is running; close the game and try again"; + } + return "?"; +} class OperationGuard { public: - explicit OperationGuard(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) : lock_(gameDir, waitMs) { - if (!lock_.held()) { - err_ = lock_.error(); - const PathState s = DirectoryState(gameDir); - result_ = s == PathState::Missing ? GuardResult::Ok : err_ == WAIT_TIMEOUT ? GuardResult::Busy : GuardResult::Unknown; // (gone: nothing to guard) + explicit OperationGuard(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) { + std::wstring lockName; + if (!LockNameFor(gameDir, &lockName, &err_)) { + const bool gone = err_ == ERROR_FILE_NOT_FOUND || err_ == ERROR_PATH_NOT_FOUND; + result_ = gone ? GuardResult::Ok : GuardResult::Unknown; // gone: nothing to guard; any other lookup error: Unknown + return; + } + markerName_ = MarkerNameOf(lockName); + lock_.reset(new StateLock(StateLock::ByName{}, lockName, waitMs)); + if (!lock_->held()) { + err_ = lock_->error(); + result_ = lock_->timedOut() ? GuardResult::Busy : lock_->denied() ? GuardResult::LockDenied : GuardResult::Unknown; return; } - const GameUse u = QueryGameUse(gameDir, &err_); + Recheck(); + } + // Before each destructive step: the marker again (no file-system call). A game that started meanwhile turns the result to + // GameRunning (or Unknown); the caller stops there. Returns result(). + GuardResult Recheck() { + if (!lock_ || !lock_->held()) return result_; + const GameUse u = QueryMarker(markerName_, &err_); result_ = u == GameUse::NotRunning ? GuardResult::Ok : u == GameUse::Running ? GuardResult::GameRunning : GuardResult::Unknown; + return result_; } + bool ok() const { return result_ == GuardResult::Ok; } GuardResult result() const { return result_; } DWORD error() const { return err_; } - const char* words() const { - switch (result_) { - case GuardResult::Ok: return ""; - case GuardResult::Busy: return "another WrongGPU program is changing this game's WrongGPU state right now; try again in a moment"; - case GuardResult::GameRunning: return "the game is running with WrongGPU loaded; close the game first"; - case GuardResult::Unknown: return "WrongGPU could not tell whether the game is running; close the game and try again"; - } - return "?"; - } + const char* words() const { return GuardWords(result_); } private: - StateLock lock_; + std::unique_ptr lock_; + std::wstring markerName_; GuardResult result_ = GuardResult::Unknown; DWORD err_ = 0; }; @@ -324,55 +428,70 @@ inline bool ReadBytes(const std::wstring& path, std::string* out, bool* missing return ok; } -// The atomic replace described above. false: the file is as it was; *err the error of the step that failed -// (ERROR_FILE_TOO_LARGE: over kMaxStateBytes; ERROR_WRITE_FAULT: a short write). *tempLeft: a temporary file that could not -// be deleted after the failure ("" when none). -inline bool WriteAtomic(const std::wstring& path, const std::string& bytes, DWORD* err = nullptr, std::wstring* tempLeft = nullptr) { +/// The outcome of WriteAtomic: ok, or the first failure (error) AND every secondary failure: a close that failed after an +// earlier failure (closeError), a cleanup that failed (cleanupError, with the file left in tempLeft). words() says all of them. +struct WriteResult { + bool ok = false; + DWORD error = 0; // the first failure (ERROR_FILE_TOO_LARGE: over kMaxStateBytes; ERROR_WRITE_FAULT: a short write) + DWORD closeError = 0; // the temporary file's close failed (also after an earlier failure) + DWORD cleanupError = 0; // the temporary file could not be deleted after the failure + std::wstring tempLeft; // ... and is still there under this name + std::string words() const { + if (ok) return "written"; + std::string w = "not written (error " + std::to_string(error) + ")"; + if (closeError && closeError != error) w += "; closing the temporary file also failed (error " + std::to_string(closeError) + ")"; + if (cleanupError) w += "; the temporary file could not be deleted (error " + std::to_string(cleanupError) + "), it is left next to the file"; + return w; + } +}; + +// The atomic replace described above. On a failure the file is as it was. +inline WriteResult WriteAtomic(const std::wstring& path, const std::string& bytes) { static volatile LONG counter = 0; - if (tempLeft) tempLeft->clear(); - if (bytes.size() > kMaxStateBytes) { if (err) *err = ERROR_FILE_TOO_LARGE; return false; } + WriteResult r; + if (bytes.size() > kMaxStateBytes) { r.error = ERROR_FILE_TOO_LARGE; return r; } const std::wstring target = ExtendedPath(path); - DWORD e = 0; for (int attempt = 0; attempt < 16; ++attempt) { const std::wstring tmp = target + kTempMark + std::to_wstring(GetCurrentProcessId()) + L"-" + std::to_wstring(InterlockedIncrement(&counter)); HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) { - e = GetLastError(); - if (e == ERROR_FILE_EXISTS || e == ERROR_ALREADY_EXISTS) continue; - break; + r.error = GetLastError(); + if (r.error == ERROR_FILE_EXISTS || r.error == ERROR_ALREADY_EXISTS) continue; + return r; } bool ok = true; for (size_t done = 0; ok && done < bytes.size();) { const DWORD want = static_cast(bytes.size() - done < kChunk ? bytes.size() - done : kChunk); DWORD put = 0; - if (Faulted("write")) { ok = false; e = ERROR_WRITE_FAULT; } - else if (!WriteFile(h, bytes.data() + done, want, &put, nullptr)) { ok = false; e = GetLastError(); } - else if (put != want) { ok = false; e = ERROR_WRITE_FAULT; } // a short write: always this error + if (Faulted("write")) { ok = false; r.error = ERROR_WRITE_FAULT; } + else if (!WriteFile(h, bytes.data() + done, want, &put, nullptr)) { ok = false; r.error = GetLastError(); } + else if (put != want) { ok = false; r.error = ERROR_WRITE_FAULT; } // a short write: always this error else done += put; } if (ok) { - if (Faulted("flush")) { ok = false; e = ERROR_WRITE_FAULT; } - else if (!FlushFileBuffers(h)) { ok = false; e = GetLastError(); } + if (Faulted("flush")) { ok = false; r.error = ERROR_WRITE_FAULT; } + else if (!FlushFileBuffers(h)) { ok = false; r.error = GetLastError(); } } - if (Faulted("close")) { - CloseHandle(h); // (the handle is closed all the same; the step reports the failure) - if (ok) { ok = false; e = ERROR_WRITE_FAULT; } - } else if (!CloseHandle(h) && ok) { - ok = false; - e = GetLastError(); + const bool faultClose = Faulted("close"); + const BOOL closed = CloseHandle(h); // (closed in every case; a failure is reported, also after an earlier one) + if (faultClose || !closed) { + r.closeError = faultClose ? ERROR_WRITE_FAULT : GetLastError(); + if (ok) { ok = false; r.error = r.closeError; } } if (ok) { - if (Faulted("move")) { ok = false; e = ERROR_WRITE_FAULT; } - else if (!MoveFileExW(tmp.c_str(), target.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { ok = false; e = GetLastError(); } + if (Faulted("move")) { ok = false; r.error = ERROR_WRITE_FAULT; } + else if (!MoveFileExW(tmp.c_str(), target.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { ok = false; r.error = GetLastError(); } } - if (ok) return true; - if (Faulted("delete") || !DeleteFileW(tmp.c_str())) { - if (tempLeft) *tempLeft = tmp; // deleted when possible; reported otherwise + if (ok) { r.ok = true; r.error = 0; return r; } + const bool faultDelete = Faulted("delete"); + if (faultDelete || !DeleteFileW(tmp.c_str())) { // deleted when possible; reported otherwise + r.cleanupError = faultDelete ? ERROR_WRITE_FAULT : GetLastError(); + r.tempLeft = tmp; } - break; + return r; } - if (err) *err = e ? e : ERROR_FILE_EXISTS; - return false; + if (!r.error) r.error = ERROR_FILE_EXISTS; + return r; } // ---- settings.ini ------------------------------------------------------------------------------------------------- @@ -459,13 +578,14 @@ inline Settings ReadSettings(const std::wstring& gameDir) { return ParseSettings(text); } -enum class SetResult { Ok, NoStateFolder, StateFolderUnknown, Busy, Unreadable, Invalid, AccessDenied, WriteFailed }; +enum class SetResult { Ok, NoStateFolder, StateFolderUnknown, Busy, LockDenied, Unreadable, Invalid, AccessDenied, WriteFailed }; inline const char* SetResultWords(SetResult r) { switch (r) { case SetResult::Ok: return "saved"; case SetResult::NoStateFolder: return "no WrongGPU state folder for this game (not installed by the launcher)"; case SetResult::StateFolderUnknown: return "WrongGPU's state folder of this game could not be checked"; case SetResult::Busy: return "another WrongGPU program kept the game's state lock"; + case SetResult::LockDenied: return "WrongGPU may not use this game's state lock (access denied); run the launcher's repair as administrator"; case SetResult::Unreadable: return "the settings file could not be read (left as it is)"; case SetResult::Invalid: return "not a valid key or value"; case SetResult::AccessDenied: return "WrongGPU can't write to the game folder; run the launcher's repair as administrator"; @@ -473,38 +593,52 @@ inline const char* SetResultWords(SetResult r) { } return "?"; } +// The outcome of SetSettings: the result, its Win32 error, and (a failed write) the write's secondary failures. words() says +// everything a consumer must show, including a temporary file that could not be deleted. +struct SetOutcome { + SetResult result = SetResult::Ok; + DWORD error = 0; + WriteResult write; // the write's outcome when one was attempted (secondary close / cleanup failures) + bool ok() const { return result == SetResult::Ok; } + std::string words() const { + std::string w = SetResultWords(result); + if (result != SetResult::Ok && error && error != WAIT_TIMEOUT) w += " (error " + std::to_string(error) + ")"; + if (write.closeError && write.closeError != write.error) w += "; closing the temporary file also failed (error " + std::to_string(write.closeError) + ")"; + if (write.cleanupError) w += "; a temporary file could not be deleted (error " + std::to_string(write.cleanupError) + ") and is left in the state folder"; + return w; + } +}; // The read-modify-write of settings.ini under the game's state lock: the file re-read from disk after the lock is taken, the // changes applied (a corrupt file starts empty; an unreadable one is never overwritten), written atomically. The state folder -// is never created here. AccessDenied is its own result (the game folder is not writable for this process): consumers say -// so and offer the launcher's elevated repair. *err: the Win32 error of a failure; *tempLeft as in WriteAtomic. -inline SetResult SetSettings(const std::wstring& gameDir, const std::vector>& changes, - DWORD waitMs = kDefaultWaitMs, DWORD* err = nullptr, std::wstring* tempLeft = nullptr) { - for (const auto& c : changes) if (!ValidKey(c.first) || !ValidValue(c.second)) return SetResult::Invalid; +// is never created here. Distinct results for a consumer to show: AccessDenied (the game folder is not writable for this +// process) and LockDenied (the lock may not be opened) both point to the launcher's elevated repair; Busy is contention. +inline SetOutcome SetSettings(const std::wstring& gameDir, const std::vector>& changes, DWORD waitMs = kDefaultWaitMs) { + SetOutcome o; + auto fail = [&](SetResult r, DWORD e) { o.result = r; o.error = e; return o; }; + for (const auto& c : changes) if (!ValidKey(c.first) || !ValidValue(c.second)) return fail(SetResult::Invalid, 0); DWORD e = 0; switch (DirectoryState(StateDirOf(gameDir), &e)) { case PathState::Present: break; - case PathState::Missing: return SetResult::NoStateFolder; - case PathState::Unknown: if (err) *err = e; return e == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::StateFolderUnknown; + case PathState::Missing: return fail(SetResult::NoStateFolder, 0); + case PathState::Unknown: return fail(e == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::StateFolderUnknown, e); } StateLock lock(gameDir, waitMs); - if (!lock.held()) { if (err) *err = lock.error(); return SetResult::Busy; } + if (!lock.held()) return fail(lock.timedOut() ? SetResult::Busy : lock.denied() ? SetResult::LockDenied : SetResult::StateFolderUnknown, lock.error()); std::string text; bool missing = false; Settings s; if (ReadBytes(SettingsPathOf(gameDir), &text, &missing, &e)) s = ParseSettings(text); - else if (!missing) { if (err) *err = e; return e == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::Unreadable; } + else if (!missing) return fail(e == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::Unreadable, e); if (s.corrupt) s = Settings(); bool changed = !s.present; for (const auto& c : changes) { const std::string* now = Get(s, c.first); if (!now || *now != c.second) { Set(s, c.first, c.second); changed = true; } } - if (!changed) return SetResult::Ok; - if (!WriteAtomic(SettingsPathOf(gameDir), RenderSettings(s), &e, tempLeft)) { - if (err) *err = e; - return e == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::WriteFailed; - } - return SetResult::Ok; + if (!changed) return o; + o.write = WriteAtomic(SettingsPathOf(gameDir), RenderSettings(s)); + if (!o.write.ok) return fail(o.write.error == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::WriteFailed, o.write.error); + return o; } } // namespace wgstate diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp index 93a8fcb2..14bb65b4 100644 --- a/clean/wgshared/tests/test_wg_state.cpp +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -10,8 +10,10 @@ // - a busy lock (bounded wait, nothing written), a holder that dies in the middle of a write (abandoned: the next holder // re-reads the old whole file; the half-written temporary file is never read as state); // - the loaded protocol: QueryGameUse NotRunning / Running / Unknown (lookup errors are Unknown, never NotRunning), a -// registered child, a killed child (no stale marker), the launcher's OperationGuard refusing on Running and Unknown, a -// registration that waits for a running operation and gets in only after it, and one that gives up in time. +// registered child, a killed child (no stale marker), the launcher's OperationGuard refusing on Running, Unknown and a +// lock it may not open (LockDenied); a game starting DURING an operation (its marker at once, the operation's Recheck +// stops it, the game gives up on state within its ~2 s budget and stays visible to later operations), and the +// registration budget bounding the whole registration. // Written for this project. #include #include @@ -111,7 +113,7 @@ static int Child(int argc, wchar_t** argv) { Settings w = s; Set(w, "counter", std::to_string(c + 1)); Sleep(0); // widen the window a lost update would need - if (!WriteAtomic(SettingsPathOf(game), RenderSettings(w))) return 4; + if (!WriteAtomic(SettingsPathOf(game), RenderSettings(w)).ok) return 4; } return 0; } @@ -138,11 +140,13 @@ static int Child(int argc, wchar_t** argv) { WaitFile(argv[4]); // the parent keeps a handle to the mutex now ExitProcess(0); } - if (mode == L"--child-register" && argc >= 5) { // the game's registration (wait ms), then stays loaded until killed + if (mode == L"--child-register" && argc >= 5) { // the game's registration (budget ms), then stays loaded until killed const ULONGLONG t0 = Now(); LoadedRegistration reg(game, static_cast(_wtoi(argv[3]))); - WriteText(argv[4], (reg.ok() ? "ok " : "no ") + std::to_string(Now() - t0) + " " + reg.why()); - if (!reg.ok()) return 0; + // "marker=<0|1> state=<0|1> ms= " + WriteText(argv[4], "marker=" + std::to_string(reg.marker() ? 1 : 0) + " state=" + std::to_string(reg.state_ok() ? 1 : 0) + + " ms=" + std::to_string(Now() - t0) + " " + reg.why()); + if (!reg.marker()) return 0; Sleep(120000); return 0; } @@ -175,57 +179,78 @@ int wmain(int argc, wchar_t** argv) { // ---- atomic writes const std::wstring state = StateDirOf(game); { - check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::NoStateFolder && DirectoryState(state) == PathState::Missing, + check(SetSettings(game, {{"rr_mode", "fast"}}).result == SetResult::NoStateFolder && DirectoryState(state) == PathState::Missing, "no state folder: NoStateFolder, the folder is not created"); CreateDirectoryW(state.c_str(), nullptr); const std::wstring f = SettingsPathOf(game); - check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::Ok && *Get(ReadSettings(game), "rr_mode") == "fast", "SetSettings writes the file"); + check(SetSettings(game, {{"rr_mode", "fast"}}).ok() && *Get(ReadSettings(game), "rr_mode") == "fast", "SetSettings writes the file"); const std::string before = ReadText(f); - DWORD e = 0; - check(!WriteAtomic(f, std::string(kMaxStateBytes + 1, 'x'), &e) && e == ERROR_FILE_TOO_LARGE && ReadText(f) == before, "over kMaxStateBytes: refused, the file unchanged"); + WriteResult w = WriteAtomic(f, std::string(kMaxStateBytes + 1, 'x')); + check(!w.ok && w.error == ERROR_FILE_TOO_LARGE && ReadText(f) == before, "over kMaxStateBytes: refused, the file unchanged"); bool steps = true; + static const char* failAt = nullptr; for (const char* step : {"write", "flush", "close", "move"}) { - static const char* failAt = nullptr; failAt = step; TestFault() = [](const char* s) { return std::strcmp(s, failAt) == 0; }; - std::wstring left; - e = 0; - const bool ok = WriteAtomic(f, "rr_mode=exact\r\n", &e, &left); + w = WriteAtomic(f, "rr_mode=exact\r\n"); TestFault() = nullptr; - const bool good = !ok && e == ERROR_WRITE_FAULT && left.empty() && ReadText(f) == before && List(state).size() == 1; - if (!good) std::printf(" (failure at %s: ok %d, error %lu, left %d, files %zu)\n", step, ok, e, !left.empty(), List(state).size()); + const bool good = !w.ok && w.error == ERROR_WRITE_FAULT && w.tempLeft.empty() && !w.cleanupError && ReadText(f) == before && List(state).size() == 1; + if (!good) std::printf(" (failure at %s: ok %d, error %lu, left %d, files %zu)\n", step, w.ok, w.error, !w.tempLeft.empty(), List(state).size()); steps = steps && good; } - check(steps, "a failure at write / flush / close / move (after the temporary file exists): false, the file unchanged, no temporary file left"); + check(steps, "a failure at write / flush / close / move (after the temporary file exists): not written, the file unchanged, no temporary file left"); + // secondary failures are reported with the first one: a close that fails after a failed write; a cleanup that fails + TestFault() = [](const char* s) { return std::strcmp(s, "write") == 0 || std::strcmp(s, "close") == 0; }; + w = WriteAtomic(f, "rr_mode=exact\r\n"); + TestFault() = nullptr; + check(!w.ok && w.error == ERROR_WRITE_FAULT && w.closeError == ERROR_WRITE_FAULT && + ReadText(f) == before && List(state).size() == 1, + "a close that fails after a failed write: closeError reported beside the first error"); TestFault() = [](const char* s) { return std::strcmp(s, "move") == 0 || std::strcmp(s, "delete") == 0; }; - std::wstring left; - const bool ok = WriteAtomic(f, "rr_mode=exact\r\n", &e, &left); + w = WriteAtomic(f, "rr_mode=exact\r\n"); TestFault() = nullptr; - check(!ok && !left.empty() && Exists(left) && IsTempName(left) && ReadText(f) == before, "a cleanup that fails: reported (tempLeft), the file unchanged"); - if (!left.empty()) DeleteFileW(left.c_str()); - check(!WriteAtomic(JoinPath(JoinPath(root, L"missing-folder"), L"x.ini"), "x", &e) && e != 0, "a write into a missing folder fails with its error"); + check(!w.ok && w.cleanupError == ERROR_WRITE_FAULT && !w.tempLeft.empty() && Exists(w.tempLeft) && IsTempName(w.tempLeft) && + w.words().find("could not be deleted") != std::string::npos && ReadText(f) == before, + "a cleanup that fails: its error and the file left are reported (words say so), the file unchanged"); + if (!w.tempLeft.empty()) DeleteFileW(w.tempLeft.c_str()); + w = WriteAtomic(JoinPath(JoinPath(root, L"missing-folder"), L"x.ini"), "x"); + check(!w.ok && w.error != 0, "a write into a missing folder fails with its error"); // corrupt, unreadable WriteText(f, "rr_mode = fast\r\n"); check(ReadSettings(game).corrupt && ReadSettings(game).kv.empty(), "a corrupt file reads as corrupt, no keys"); - check(SetSettings(game, {{"rr_mode", "accurate"}}) == SetResult::Ok && ReadSettings(game).kv.size() == 1, "a corrupt file is replaced by the next write"); + check(SetSettings(game, {{"rr_mode", "accurate"}}).ok() && ReadSettings(game).kv.size() == 1, "a corrupt file is replaced by the next write"); const std::string b2 = ReadText(f); HANDLE h = CreateFileW(f.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - DWORD err = 0; - const SetResult r = SetSettings(game, {{"rr_mode", "exact"}}, kDefaultWaitMs, &err); + SetOutcome o = SetSettings(game, {{"rr_mode", "exact"}}); CloseHandle(h); - check(r == SetResult::Unreadable && err != 0 && ReadText(f) == b2 && List(state).size() == 1, "an unreadable file: Unreadable, left as it was"); + check(o.result == SetResult::Unreadable && o.error != 0 && ReadText(f) == b2 && List(state).size() == 1, "an unreadable file: Unreadable, left as it was"); // a state folder this process may not write: AccessDenied (its own result, for the elevated repair) PSECURITY_DESCRIPTOR ro = nullptr, rw = nullptr; ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;0x1200a9;;;WD)", SDDL_REVISION_1, &ro, nullptr); // read and list only ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;WD)", SDDL_REVISION_1, &rw, nullptr); const bool locked = ro && SetFileSecurityW(state.c_str(), DACL_SECURITY_INFORMATION, ro); - err = 0; - const SetResult denied = SetSettings(game, {{"rr_mode", "exact"}}, kDefaultWaitMs, &err); + o = SetSettings(game, {{"rr_mode", "exact"}}); if (rw) SetFileSecurityW(state.c_str(), DACL_SECURITY_INFORMATION, rw); // the owner may always change the DACL back if (ro) LocalFree(ro); if (rw) LocalFree(rw); - check(locked && denied == SetResult::AccessDenied && err == ERROR_ACCESS_DENIED && ReadText(f) == b2, "a folder this process may not write: AccessDenied, nothing written"); - check(std::string(SetResultWords(SetResult::AccessDenied)).find("administrator") != std::string::npos, "AccessDenied's words name the elevated repair"); + check(locked && o.result == SetResult::AccessDenied && o.error == ERROR_ACCESS_DENIED && ReadText(f) == b2 && o.words().find("administrator") != std::string::npos, + "a folder this process may not write: AccessDenied (words name the elevated repair), nothing written"); + // the state lock may not be opened (an object under its name that denies everyone): LockDenied, not contention + { + std::wstring lockName; + LockNameFor(game, &lockName); + PSECURITY_DESCRIPTOR denyAll = nullptr; + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(D;;GA;;;WD)", SDDL_REVISION_1, &denyAll, nullptr); + SECURITY_ATTRIBUTES sa{sizeof(sa), denyAll, FALSE}; + HANDLE squat = CreateMutexW(&sa, FALSE, lockName.c_str()); + o = SetSettings(game, {{"rr_mode", "exact"}}, 300); + OperationGuard g(game, 300); + check(squat && o.result == SetResult::LockDenied && o.error == ERROR_ACCESS_DENIED && ReadText(f) == b2 && + g.result() == GuardResult::LockDenied && std::string(g.words()).find("access denied") != std::string::npos, + "a state lock this process may not open: LockDenied (SetSettings and the guard), not Busy; nothing written"); + if (squat) CloseHandle(squat); + if (denyAll) LocalFree(denyAll); + } WriteText(f, "counter=0\r\n"); } @@ -276,7 +301,7 @@ int wmain(int argc, wchar_t** argv) { } std::wstring dn; CreateDirectoryW(ExtendedPath(StateDirOf(deep)).c_str(), nullptr); - check(LockNameFor(deep, &dn) && Narrow(dn) != names[0] && SetSettings(deep, {{"k", "v"}}) == SetResult::Ok && *Get(ReadSettings(deep), "k") == "v", + check(LockNameFor(deep, &dn) && Narrow(dn) != names[0] && SetSettings(deep, {{"k", "v"}}).ok() && *Get(ReadSettings(deep), "k") == "v", "a game folder deeper than MAX_PATH: lock name, write and read work"); const std::wstring dout = JoinPath(root, L"name-deep"); HANDLE k = Spawn(L"--child-lockname " + Q(deep) + L" " + Q(dout)); @@ -309,9 +334,8 @@ int wmain(int argc, wchar_t** argv) { HANDLE k = Spawn(L"--child-hold " + Q(game) + L" 3000 " + Q(ready)); const bool up = k && WaitFile(ready); const std::string before = ReadText(SettingsPathOf(game)); - DWORD err = 0; - const SetResult r = SetSettings(game, {{"rr_mode", "fast"}}, 200, &err); - check(up && r == SetResult::Busy && err == WAIT_TIMEOUT && ReadText(SettingsPathOf(game)) == before, "lock held elsewhere: Busy after the bounded wait, nothing written"); + const SetOutcome r = SetSettings(game, {{"rr_mode", "fast"}}, 200); + check(up && r.result == SetResult::Busy && r.error == WAIT_TIMEOUT && ReadText(SettingsPathOf(game)) == before, "lock held elsewhere: Busy after the bounded wait, nothing written"); if (k) WaitExit(k); DeleteFileW(ready.c_str()); } @@ -335,7 +359,7 @@ int wmain(int argc, wchar_t** argv) { std::wstring temp; for (auto& n : List(state)) if (IsTempName(n)) temp = n; check(!temp.empty(), "the half-written temporary file is there and named as a temporary file (never read as state)"); - check(SetSettings(game, {{"counter", "8"}}) == SetResult::Ok && *Get(ReadSettings(game), "counter") == "8", "a write under the abandoned-then-taken lock works"); + check(SetSettings(game, {{"counter", "8"}}).ok() && *Get(ReadSettings(game), "counter") == "8", "a write under the abandoned-then-taken lock works"); if (!temp.empty()) DeleteFileW(JoinPath(state, temp).c_str()); } if (keep) CloseHandle(keep); @@ -350,7 +374,7 @@ int wmain(int argc, wchar_t** argv) { check(QueryGameUse(JoinPath(root, L"gone")) == GameUse::NotRunning, "a folder that does not exist: NotRunning (nothing can run from it)"); { LoadedRegistration reg(game); - check(reg.ok() && QueryGameUse(aliases.back()) == GameUse::Running, "registered in this process: Running (asked through another alias)"); + check(reg.marker() && reg.state_ok() && QueryGameUse(aliases.back()) == GameUse::Running, "registered in this process: Running (asked through another alias)"); } check(QueryGameUse(game) == GameUse::NotRunning, "the registration ended: NotRunning"); // a lookup error is Unknown, never NotRunning: an object of another type under the marker's name @@ -398,7 +422,7 @@ int wmain(int argc, wchar_t** argv) { // a registered game in another process; then it crashes const std::wstring out = JoinPath(root, L"reg-1"); HANDLE k = Spawn(L"--child-register " + Q(game) + L" 2000 " + Q(out)); - const bool up = k && WaitFile(out) && ReadText(out).rfind("ok", 0) == 0; + const bool up = k && WaitFile(out) && ReadText(out).rfind("marker=1 state=1", 0) == 0; OperationGuard* g = new OperationGuard(game, 1000); check(up && QueryGameUse(game) == GameUse::Running && g->result() == GuardResult::GameRunning && std::string(g->words()).find("close the game") != std::string::npos, "a game registered in another process: Running, the guard refuses (GameRunning)"); @@ -413,39 +437,62 @@ int wmain(int argc, wchar_t** argv) { DeleteFileW(out.c_str()); } - // ---- registration against a running operation: no slipping in between + // ---- a game that starts DURING an operation: its marker appears at once, the operation's Recheck sees it and stops; the + // game gives up on state after its bounded registration (about 2 s) and stays visible to every later operation { const std::wstring out = JoinPath(root, L"reg-2"); - ULONGLONG released = 0; HANDLE k = nullptr; + bool sawGame = false; + ULONGLONG seenAfter = 0; { - OperationGuard op(game, 1000); // the launcher's operation starts (lock held, no game) - const bool ok = op.result() == GuardResult::Ok; + OperationGuard op(game, 1000); // the launcher's operation starts (lock held, no game yet) + const bool ok = op.ok(); + const ULONGLONG t0 = Now(); k = Spawn(L"--child-register " + Q(game) + L" 2000 " + Q(out)); // the game starts during it - Sleep(800); - check(ok && !Exists(out) && QueryGameUse(game) == GameUse::NotRunning, "during the operation the starting game cannot register (it waits; nothing is loaded)"); - released = Now(); - } // the operation ends: the lock is released - const bool got = k && WaitFile(out, 10000); + for (int i = 0; i < 150 && !sawGame; ++i) { // the operation's steps: Recheck before each one + if (op.Recheck() == GuardResult::GameRunning) sawGame = true; + else Sleep(20); + } + seenAfter = Now() - t0; + check(ok && sawGame && !op.ok() && std::string(op.words()).find("close the game first") != std::string::npos, + "a game starting mid-operation: its marker appears at once, the next Recheck says GameRunning (close the game first)"); + // the operation keeps the lock (it stops cleanly): the game's registration runs out of budget on the lock, not on the marker + check(k && WaitFile(out, 10000), "the starting game finished its registration while the operation held the lock"); + } // the operation ends (stopped) const std::string r = ReadText(out); - check(got && r.rfind("ok", 0) == 0 && QueryGameUse(game) == GameUse::Running, "after the operation the game registers (it waited, bounded)"); - check(released > 0 && std::strtoul(r.c_str() + 3, nullptr, 10) >= 500, "the registration came only after the operation released the lock"); + const unsigned long ms = std::strtoul(r.c_str() + r.find("ms=") + 3, nullptr, 10); + check(r.rfind("marker=1 state=0", 0) == 0 && r.find("not free in time") != std::string::npos && ms >= 1500 && ms < 3000, + "that game: marker made, state given up after the bounded wait (about 2 s, never longer): defaults, no state this session"); + check(seenAfter < 2000, "the marker was there before the game's lock wait ended (seen within its registration)"); + { + OperationGuard later(game, 1000); + check(QueryGameUse(game) == GameUse::Running && later.result() == GuardResult::GameRunning, + "after that operation the game is still visible: a later operation refuses too"); + } if (k) { TerminateProcess(k, 9); WaitForSingleObject(k, 30000); CloseHandle(k); } DeleteFileW(out.c_str()); - // a registration that cannot wait that long gives up in time and touches nothing + // a game whose registration starts while no operation runs gets marker and state at once const std::wstring out2 = JoinPath(root, L"reg-3"); - HANDLE k2 = nullptr; + HANDLE k2 = Spawn(L"--child-register " + Q(game) + L" 2000 " + Q(out2)); + const bool got2 = k2 && WaitFile(out2, 10000); + const std::string r2 = ReadText(out2); + check(got2 && r2.rfind("marker=1 state=1", 0) == 0 && std::strtoul(r2.c_str() + r2.find("ms=") + 3, nullptr, 10) < 1500, + "no operation running: marker and state at once, well inside the budget"); + if (k2) { TerminateProcess(k2, 9); WaitForSingleObject(k2, 30000); CloseHandle(k2); } + DeleteFileW(out2.c_str()); + // the budget bounds the whole registration: a budget of 300 ms while an operation runs ends within it + const std::wstring out3 = JoinPath(root, L"reg-4"); { OperationGuard op(game, 1000); - k2 = Spawn(L"--child-register " + Q(game) + L" 300 " + Q(out2)); - const bool got2 = k2 && WaitFile(out2, 10000); - const std::string r2 = ReadText(out2); - check(op.result() == GuardResult::Ok && got2 && r2.rfind("no", 0) == 0 && r2.find("not free in time") != std::string::npos && - std::strtoul(r2.c_str() + 3, nullptr, 10) < 1500 && QueryGameUse(game) == GameUse::NotRunning, - "a registration while an operation runs gives up after its bounded wait: no marker, defaults, nothing blocked"); + HANDLE k3 = Spawn(L"--child-register " + Q(game) + L" 300 " + Q(out3)); + const bool got3 = k3 && WaitFile(out3, 10000); + const std::string r3 = ReadText(out3); + check(op.ok() && got3 && r3.rfind("marker=1 state=0", 0) == 0 && std::strtoul(r3.c_str() + r3.find("ms=") + 3, nullptr, 10) < 1000, + "a 300 ms registration budget while an operation runs: done within it (marker, no state)"); + if (k3) { TerminateProcess(k3, 9); WaitForSingleObject(k3, 30000); CloseHandle(k3); } } - if (k2) WaitExit(k2); - DeleteFileW(out2.c_str()); + DeleteFileW(out3.c_str()); + check(QueryGameUse(game) == GameUse::NotRunning, "every game ended: NotRunning"); } // cleanup (own files only) From 184c703482219157188da89421f5846515652365 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:54:14 -0500 Subject: [PATCH 5/7] Shared: wg_state.h decides "game uses WrongGPU" through Windows (exclusive binary handles) The loaded marker, its registration and the helper thread are gone; the game registers nothing. The launcher's OperationGuard takes the state lock, then opens every WrongGPU binary of the install with DELETE | GENERIC_READ | FILE_WRITE_DATA and share mode 0: ERROR_SHARING_VIOLATION = loaded in a process (GameRunning), any other error = Unknown, a missing file is skipped. It holds those handles for the whole operation, so a game that starts meanwhile cannot load WrongGPU (its LoadLibrary fails). Deletes go through the held handle (DeleteHeld: FileDispositionInfoEx POSIX delete, classic delete-on-close as the fallback); Release hands one file back at the step that replaces it. FILE_WRITE_DATA is needed: a loaded image keeps no open handle, so an open with DELETE | GENERIC_READ and share mode 0 SUCCEEDS on a loaded DLL (seen in this test before the flag was added); Windows refuses an open for writing a loaded image's data. Tests (a real test DLL under WrongGPU's binary names): nothing loaded = Ok with every binary held; a held guard makes LoadLibrary fail here and in another process; DeleteHeld; Release; a binary loaded in another process / in this one = GameRunning; that process killed = Ok; a binary the guard may not open = Unknown; the lock busy = Busy; LockDenied as before. Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/CMakeLists.txt | 4 + clean/wgshared/include/wg_state.h | 299 +++++++-------------- clean/wgshared/tests/test_wg_state.cpp | 221 +++++++-------- clean/wgshared/tests/test_wg_state_dll.cpp | 8 + 4 files changed, 197 insertions(+), 335 deletions(-) create mode 100644 clean/wgshared/tests/test_wg_state_dll.cpp diff --git a/clean/wgshared/CMakeLists.txt b/clean/wgshared/CMakeLists.txt index 00721c49..6a0aebfc 100644 --- a/clean/wgshared/CMakeLists.txt +++ b/clean/wgshared/CMakeLists.txt @@ -56,6 +56,10 @@ if(WIN32) target_compile_options(test_wg_state PRIVATE -Wall -Wextra -municode) target_link_options(test_wg_state PRIVATE -static -municode) endif() + # a real DLL the test loads (a WrongGPU binary a game has loaded), next to the test + add_library(wg_state_test_dll SHARED ${CMAKE_CURRENT_LIST_DIR}/tests/test_wg_state_dll.cpp) + set_target_properties(wg_state_test_dll PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" PREFIX "") + add_dependencies(test_wg_state wg_state_test_dll) add_test(NAME wgshared_state COMMAND test_wg_state) endif() diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index a331062f..1f8b1ef0 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -22,27 +22,19 @@ // the next taker gets it, and because writes are atomic (below) the files are whole: the old version or the new one. A // temporary file such a holder left is never read as state (IsTempName) and goes with the uninstall. // -// THE LOADED PROTOCOL (a game is never invisible to an operation that changes its files): -// - The game: every WrongGPU module loaded in the game registers (LoadedRegistration) at its init, BEFORE it reads or writes -// any state, and keeps the registration for as long as it is loaded: -// 1. its LOADED MARKER first, at once, with no wait: Global\WrongGPU-loaded-- (same identity as -// the state lock), a named object held OPEN, never owned. While the game runs the marker exists, whatever happens next; -// 2. only then the state lock, with a bounded wait: had in time = no launcher operation is running, the module may use the -// state (each later use takes the lock again); not had in time (an uninstall, repair or update is running) = the module -// runs with the defaults and reads and writes no state this session (state_ok() false; why() says so for the log). -// The whole registration is bounded by kRegisterBudgetMs (about 2 s): the folder identity lookup (a file-system call that a -// network folder can stall) runs on a helper thread within that budget, the lock wait gets the rest; a lookup that does not -// finish in time gives no marker and no state (and the launcher, which needs the same lookup, refuses: Unknown). Register -// from the module's init (InitializeASI, the first call), NEVER from DllMain (the helper thread needs the loader lock). -// A marker that cannot be made (marker() false) is logged; the module then uses no state either. -// - The launcher: an uninstall, repair or update holds an OperationGuard for its WHOLE run: it takes the state lock (a -// timeout is Busy, access denied is LockDenied), then queries the marker and refuses unless the answer is NotRunning -// (Running and Unknown both refuse). A game that starts DURING the operation still creates its marker at once (it then -// waits for the lock, and gives up on state): so the operation calls Recheck() before EACH destructive step (each file it -// deletes or replaces) and stops with "close the game first" when the marker appeared. The guard is taken by the process -// that changes the files (the elevated worker when there is one), never by a parent waiting for it. -// The marker object exists exactly while some process has it open; the OS closes every handle of a process that ends, crashes -// or is killed, so a dead game leaves no stale marker and no PID is ever compared. +// THE OPERATION GUARD (a game that uses WrongGPU is never changed under it; Windows itself decides, nothing is registered): +// - The game registers nothing. A WrongGPU binary the game has loaded (the front end, the menu plugin, the RR plugin, the +// runtime) is an image section of that process, and Windows refuses an exclusive open of it. +// - The launcher: an uninstall, repair or update holds an OperationGuard for its WHOLE run. It takes the state lock (a timeout +// is Busy, access denied is LockDenied), then opens EVERY WrongGPU binary of the install with DELETE | GENERIC_READ | +// FILE_WRITE_DATA and share mode 0 (a loaded image has no open handle, so share mode 0 alone does not see it; Windows refuses +// an open for writing its data; nothing is ever written through the handle; a read-only binary is therefore Unknown): +// ERROR_SHARING_VIOLATION = a process has it loaded (GameRunning: refuse); any other open error = Unknown (refuse); a +// file that does not exist is skipped; all opened = nobody has WrongGPU loaded. The guard HOLDS those exclusive handles to +// the end, so a game that starts meanwhile cannot load WrongGPU (its LoadLibrary fails; OptiScaler carries on without it). +// The operation deletes a held binary through the guard's own handle (DeleteHeld), or releases that one handle right at +// the step that replaces the file (Release). The guard is taken by the process that changes the files (the elevated worker +// when there is one), never by a parent waiting for it. // // Writes are atomic (WriteAtomic): a new temporary file in the same folder (.wgtmp--, created only where // nothing is), written in checked chunks, flushed and closed (both checked), then MoveFileExW(REPLACE_EXISTING | @@ -84,8 +76,6 @@ constexpr const wchar_t* kSettingsFile = L"settings.ini"; constexpr const wchar_t* kModelChoiceFile = L"model-choice.ini"; constexpr const wchar_t* kTempMark = L".wgtmp-"; // .wgtmp--: a write in progress (or one a crash left) constexpr DWORD kDefaultWaitMs = 5000; // the launcher's waits -constexpr DWORD kRegisterBudgetMs = 2000; // the game's whole registration (lookup + lock wait): never longer -constexpr DWORD kRegisterWaitMs = kRegisterBudgetMs; // (the name earlier code used) constexpr size_t kMaxStateBytes = 1u << 20; // no state file is larger constexpr DWORD kChunk = 64u * 1024u; @@ -149,52 +139,7 @@ inline bool LockNameFor(const std::wstring& gameDir, std::wstring* name, DWORD* *name = buf; return true; } -/// The names of a game folder's identity: Global\WrongGPU-state- (the lock) and Global\WrongGPU-loaded- (the marker). -constexpr const wchar_t* kLoadedPrefix = L"Global\\WrongGPU-loaded-"; -inline std::wstring MarkerNameOf(const std::wstring& lockName) { return std::wstring(kLoadedPrefix) + lockName.substr(lockName.find(L"-state-") + 7); } -// Another per-game name of the same identity: prefix + "-". -inline bool NameFor(const wchar_t* prefix, const std::wstring& gameDir, std::wstring* name, DWORD* err) { - std::wstring lock; - if (!LockNameFor(gameDir, &lock, err)) return false; - *name = std::wstring(prefix) + lock.substr(lock.find(L"-state-") + 7); - return true; -} -// LockNameFor within budgetMs: the lookup (a file-system call a network folder can stall) runs on a helper thread; a lookup -// that does not finish in time gives false with *err = WAIT_TIMEOUT (the thread finishes on its own and frees its data). -// Never from DllMain. Never throws. -namespace detail { -struct LookupJob { - std::wstring dir, name; - DWORD err = 0; - bool ok = false; - volatile LONG refs = 2; -}; -inline DWORD WINAPI LookupThread(void* p) { - LookupJob* j = static_cast(p); - try { j->ok = LockNameFor(j->dir, &j->name, &j->err); } catch (...) { j->ok = false; j->err = ERROR_OUTOFMEMORY; } - if (InterlockedDecrement(&j->refs) == 0) delete j; - return 0; -} -} // namespace detail -inline bool LockNameWithin(const std::wstring& gameDir, DWORD budgetMs, std::wstring* name, DWORD* err) { - detail::LookupJob* j = nullptr; - try { j = new detail::LookupJob; j->dir = gameDir; } catch (...) { delete j; if (err) *err = ERROR_OUTOFMEMORY; return false; } - HANDLE t = CreateThread(nullptr, 0, &detail::LookupThread, j, 0, nullptr); - if (!t) { if (err) *err = GetLastError(); delete j; return false; } - const DWORD w = WaitForSingleObject(t, budgetMs); - CloseHandle(t); - bool ok = false; - if (w == WAIT_OBJECT_0) { - ok = j->ok; - if (err) *err = j->err; - if (ok) { try { *name = j->name; } catch (...) { ok = false; if (err) *err = ERROR_OUTOFMEMORY; } } - } else if (err) { - *err = WAIT_TIMEOUT; - } - if (InterlockedDecrement(&j->refs) == 0) delete j; - return ok; -} -// A named mutex every integrity level may open (created, or opened when it exists); nullptr with GetLastError on failure. +/// A named mutex every integrity level may open (created, or opened when it exists); nullptr with GetLastError on failure. inline HANDLE CreateSharedMutex(const std::wstring& name) { PSECURITY_DESCRIPTOR sd = nullptr; SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, FALSE}; @@ -213,13 +158,16 @@ inline HANDLE CreateSharedMutex(const std::wstring& name) { // timedOut() (another holder), denied() (this process may not open the folder or the lock: ERROR_ACCESS_DENIED), else error(). class StateLock { public: - struct ByName {}; // the lock of an already known name (LockNameFor), no file-system call explicit StateLock(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) { std::wstring name; if (!LockNameFor(gameDir, &name, &err_)) return; - Take(name, waitMs); + mutex_ = CreateSharedMutex(name); + if (!mutex_) { err_ = GetLastError(); return; } + const DWORD w = WaitForSingleObject(mutex_, waitMs); + held_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; + abandoned_ = w == WAIT_ABANDONED; + if (!held_) err_ = w == WAIT_TIMEOUT ? WAIT_TIMEOUT : GetLastError(); } - StateLock(ByName, const std::wstring& lockName, DWORD waitMs) { Take(lockName, waitMs); } ~StateLock() { if (held_) ReleaseMutex(mutex_); if (mutex_) CloseHandle(mutex_); @@ -234,124 +182,16 @@ class StateLock { DWORD error() const { return err_; } // why not held: WAIT_TIMEOUT, ERROR_ACCESS_DENIED, or another Win32 error private: - void Take(const std::wstring& name, DWORD waitMs) { - mutex_ = CreateSharedMutex(name); - if (!mutex_) { err_ = GetLastError(); return; } - const DWORD w = WaitForSingleObject(mutex_, waitMs); - held_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; - abandoned_ = w == WAIT_ABANDONED; - if (!held_) err_ = w == WAIT_TIMEOUT ? WAIT_TIMEOUT : GetLastError(); - } HANDLE mutex_ = nullptr; bool held_ = false, abandoned_ = false; DWORD err_ = 0; }; -// ---- the loaded protocol ------------------------------------------------------------------------------------------ -// The marker alone (held open, never owned). Games use it through LoadedRegistration. -class LoadedMarker { -public: - explicit LoadedMarker(const std::wstring& gameDir) { - std::wstring name; - if (!NameFor(kLoadedPrefix, gameDir, &name, &err_)) return; - Open(name); - } - struct ByName {}; - LoadedMarker(ByName, const std::wstring& markerName) { Open(markerName); } - ~LoadedMarker() { if (handle_) CloseHandle(handle_); } - LoadedMarker(const LoadedMarker&) = delete; - LoadedMarker& operator=(const LoadedMarker&) = delete; - bool held() const { return handle_ != nullptr; } - DWORD error() const { return err_; } - -private: - void Open(const std::wstring& name) { - handle_ = CreateSharedMutex(name); - if (!handle_) err_ = GetLastError(); - } - HANDLE handle_ = nullptr; - DWORD err_ = 0; -}; - -enum class GameUse { NotRunning, Running, Unknown }; -inline const char* GameUseWords(GameUse u) { - return u == GameUse::NotRunning ? "not running" : u == GameUse::Running ? "the game is running with WrongGPU loaded" - : "WrongGPU could not tell whether the game is running"; -} -// The marker of a known name: Running (it exists, also when it is not ours to open), NotRunning (it does not exist), Unknown. -inline GameUse QueryMarker(const std::wstring& markerName, DWORD* err = nullptr) { - HANDLE h = OpenMutexW(SYNCHRONIZE, FALSE, markerName.c_str()); - if (h) { CloseHandle(h); return GameUse::Running; } - const DWORD e = GetLastError(); - if (err) *err = e; - if (e == ERROR_FILE_NOT_FOUND) return GameUse::NotRunning; - return e == ERROR_ACCESS_DENIED ? GameUse::Running : GameUse::Unknown; // there but not ours to open: in use -} -// Whether a running process has WrongGPU loaded for the game folder gameDir. NotRunning ONLY when that is established: the -// folder is gone (nothing can run from it), or its marker does not exist. Any error on the way is Unknown (*err). Never -// creates the marker. -inline GameUse QueryGameUse(const std::wstring& gameDir, DWORD* err = nullptr) { - std::wstring name; - DWORD e = 0; - if (!NameFor(kLoadedPrefix, gameDir, &name, &e)) { - if (err) *err = e; - return e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND ? GameUse::NotRunning : GameUse::Unknown; - } - return QueryMarker(name, err); -} - -// The game's side (see THE LOADED PROTOCOL above): the marker at once, then the state lock within the rest of the budget. -// marker(): the game is visible to the launcher. state_ok(): the module may use the state (each use takes the lock again). -// why(): for the log when either is false. Keep the object for as long as the module is loaded. Never throws; bounded by -// budgetMs (at most kRegisterBudgetMs) in total; never from DllMain. -class LoadedRegistration { -public: - explicit LoadedRegistration(const std::wstring& gameDir, DWORD budgetMs = kRegisterBudgetMs) { - if (budgetMs > kRegisterBudgetMs) budgetMs = kRegisterBudgetMs; - const ULONGLONG t0 = GetTickCount64(); - std::wstring lockName; - if (!LockNameWithin(gameDir, budgetMs, &lockName, &err_)) { - why_ = err_ == WAIT_TIMEOUT ? "the game folder's identity could not be read in time (no marker, no state this session)" - : "the game folder's identity could not be read (no marker, no state this session)"; - return; - } - try { - marker_.reset(new LoadedMarker(LoadedMarker::ByName{}, MarkerNameOf(lockName))); // 1. visible at once, no wait - } catch (...) { - marker_.reset(); - } - if (!marker_ || !marker_->held()) { - err_ = marker_ ? marker_->error() : ERROR_OUTOFMEMORY; - why_ = "the loaded marker could not be made (no state this session)"; - marker_.reset(); - return; - } - const ULONGLONG spent = GetTickCount64() - t0; - StateLock lock(StateLock::ByName{}, lockName, spent >= budgetMs ? 0 : static_cast(budgetMs - spent)); // 2. bounded - if (!lock.held()) { - err_ = lock.error(); - why_ = lock.timedOut() ? "the game's state lock was not free in time (an uninstall, repair or update of WrongGPU is running): the defaults, no state this session" - : lock.denied() ? "the game's state lock may not be used (access denied): the defaults, no state this session" - : "the game's state lock could not be taken: the defaults, no state this session"; - return; - } - stateOk_ = true; - } - bool marker() const { return marker_ != nullptr; } - bool state_ok() const { return stateOk_; } - bool ok() const { return stateOk_; } // (state_ok) - const char* why() const { return why_; } // "" when both are fine - DWORD error() const { return err_; } - -private: - std::unique_ptr marker_; - bool stateOk_ = false; - const char* why_ = ""; - DWORD err_ = 0; -}; - -// The launcher's side: hold for the whole uninstall, repair or update, and call Recheck() before each destructive step. -// Ok only when the lock is held and no game uses WrongGPU. The lock: a timeout is Busy, access denied is LockDenied. +// ---- the operation guard ------------------------------------------------------------------------------------------- +// The launcher's side of an uninstall, repair or update (see THE OPERATION GUARD above). Ok only when the state lock is held +// and every WrongGPU binary that exists is held exclusively. A timeout of the lock is Busy, access denied is LockDenied; a +// binary loaded in a process (ERROR_SHARING_VIOLATION) is GameRunning; any other open error is Unknown. Keep it for the +// whole operation, on the thread that took it. enum class GuardResult { Ok, Busy, LockDenied, GameRunning, Unknown }; inline const char* GuardWords(GuardResult r) { switch (r) { @@ -359,44 +199,91 @@ inline const char* GuardWords(GuardResult r) { case GuardResult::Busy: return "another WrongGPU program is changing this game's WrongGPU state right now; try again in a moment"; case GuardResult::LockDenied: return "WrongGPU may not use this game's state lock (access denied); run the launcher's repair as administrator"; case GuardResult::GameRunning: return "the game is running with WrongGPU loaded; close the game first"; - case GuardResult::Unknown: return "WrongGPU could not tell whether the game is running; close the game and try again"; + case GuardResult::Unknown: return "WrongGPU could not tell whether the game is using its files; close the game and try again"; } return "?"; } class OperationGuard { public: - explicit OperationGuard(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) { - std::wstring lockName; - if (!LockNameFor(gameDir, &lockName, &err_)) { - const bool gone = err_ == ERROR_FILE_NOT_FOUND || err_ == ERROR_PATH_NOT_FOUND; - result_ = gone ? GuardResult::Ok : GuardResult::Unknown; // gone: nothing to guard; any other lookup error: Unknown - return; - } - markerName_ = MarkerNameOf(lockName); - lock_.reset(new StateLock(StateLock::ByName{}, lockName, waitMs)); + // binaries: every WrongGPU binary of the install (the front end, the menu and RR plugins, the runtime), full paths; one that + // does not exist is skipped (nothing can have it loaded). + OperationGuard(const std::wstring& gameDir, const std::vector& binaries, DWORD waitMs = kDefaultWaitMs) { + lock_.reset(new StateLock(gameDir, waitMs)); if (!lock_->held()) { err_ = lock_->error(); - result_ = lock_->timedOut() ? GuardResult::Busy : lock_->denied() ? GuardResult::LockDenied : GuardResult::Unknown; + const bool gone = err_ == ERROR_FILE_NOT_FOUND || err_ == ERROR_PATH_NOT_FOUND; // the game folder is gone: nothing to guard + result_ = gone ? GuardResult::Ok : lock_->timedOut() ? GuardResult::Busy : lock_->denied() ? GuardResult::LockDenied : GuardResult::Unknown; return; } - Recheck(); - } - // Before each destructive step: the marker again (no file-system call). A game that started meanwhile turns the result to - // GameRunning (or Unknown); the caller stops there. Returns result(). - GuardResult Recheck() { - if (!lock_ || !lock_->held()) return result_; - const GameUse u = QueryMarker(markerName_, &err_); - result_ = u == GameUse::NotRunning ? GuardResult::Ok : u == GameUse::Running ? GuardResult::GameRunning : GuardResult::Unknown; - return result_; + for (const std::wstring& b : binaries) { + const std::wstring p = ExtendedPath(b); + // FILE_WRITE_DATA is what a loaded image refuses (the image section holds no open handle, so share mode 0 alone + // would not conflict with it); nothing is ever written through this handle + HANDLE h = CreateFileW(p.c_str(), DELETE | GENERIC_READ | FILE_WRITE_DATA, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + const DWORD e = GetLastError(); + if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) continue; // not there: nothing has it loaded + err_ = e; + which_ = b; + result_ = e == ERROR_SHARING_VIOLATION ? GuardResult::GameRunning : GuardResult::Unknown; + CloseAll(); + return; + } + held_.push_back({p, h}); + } + result_ = GuardResult::Ok; } + ~OperationGuard() { CloseAll(); } + OperationGuard(const OperationGuard&) = delete; + OperationGuard& operator=(const OperationGuard&) = delete; bool ok() const { return result_ == GuardResult::Ok; } GuardResult result() const { return result_; } DWORD error() const { return err_; } + const std::wstring& which() const { return which_; } // the binary that decided GameRunning / Unknown const char* words() const { return GuardWords(result_); } + // Whether the guard holds `path` (a binary it was given). + bool Holds(const std::wstring& path) const { return Find(path) >= 0; } + // Closes the guard's handle of `path` right before the operation replaces that file itself (the file is then open to + // others again: do it at the step, never earlier). True when it was held. + bool Release(const std::wstring& path) { + const int i = Find(path); + if (i < 0) return false; + CloseHandle(held_[i].h); + held_.erase(held_.begin() + i); + return true; + } + // Deletes `path` through the guard's own handle (no window in which another process can open or load it), then closes the + // handle. ERROR_SUCCESS, ERROR_NOT_FOUND (not held), or the error of the delete (the handle is kept then). + DWORD DeleteHeld(const std::wstring& path) { + const int i = Find(path); + if (i < 0) return ERROR_NOT_FOUND; + struct DispositionEx { DWORD Flags; } ex{0x1u | 0x2u}; // FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS + BOOL done = SetFileInformationByHandle(held_[i].h, static_cast(21) /* FileDispositionInfoEx */, &ex, sizeof ex); + if (!done) { // (a file system without the POSIX form: the classic delete-on-close) + FILE_DISPOSITION_INFO classic{TRUE}; + done = SetFileInformationByHandle(held_[i].h, FileDispositionInfo, &classic, sizeof classic); + } + if (!done) return GetLastError(); + CloseHandle(held_[i].h); + held_.erase(held_.begin() + i); + return ERROR_SUCCESS; + } private: + struct Held { std::wstring path; HANDLE h; }; + int Find(const std::wstring& path) const { + const std::wstring p = ExtendedPath(path); + for (size_t i = 0; i < held_.size(); ++i) + if (CompareStringOrdinal(held_[i].path.c_str(), -1, p.c_str(), -1, TRUE) == CSTR_EQUAL) return static_cast(i); + return -1; + } + void CloseAll() { + for (auto& x : held_) CloseHandle(x.h); + held_.clear(); + } std::unique_ptr lock_; - std::wstring markerName_; + std::vector held_; + std::wstring which_; GuardResult result_ = GuardResult::Unknown; DWORD err_ = 0; }; diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp index 14bb65b4..8c1003ab 100644 --- a/clean/wgshared/tests/test_wg_state.cpp +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -// Tests of wg_state.h (the per-game state folder, its lock, the loaded protocol and atomic writes) on real files and real +// Tests of wg_state.h (the per-game state folder, its lock, the operation guard and atomic writes) on real files and real // processes. The test runs itself as the child process (--child-...). Scratch files go to the TMP folder of the run. // - the strict settings.ini format (a bare or embedded CR is corrupt); // - atomic writes: oversized input refused, a failure at every step after the temporary file exists (write, flush, close, @@ -9,11 +9,11 @@ // than MAX_PATH), each computed in a SEPARATE process, and mutual exclusion across processes that use different aliases; // - a busy lock (bounded wait, nothing written), a holder that dies in the middle of a write (abandoned: the next holder // re-reads the old whole file; the half-written temporary file is never read as state); -// - the loaded protocol: QueryGameUse NotRunning / Running / Unknown (lookup errors are Unknown, never NotRunning), a -// registered child, a killed child (no stale marker), the launcher's OperationGuard refusing on Running, Unknown and a -// lock it may not open (LockDenied); a game starting DURING an operation (its marker at once, the operation's Recheck -// stops it, the game gives up on state within its ~2 s budget and stays visible to later operations), and the -// registration budget bounding the whole registration. +// - the operation guard, with a real DLL (wg_state_test_dll) under WrongGPU's binary names: nothing loaded = Ok with every +// existing binary held exclusively; a held guard makes LoadLibrary of the file fail (here and in another process); +// deletes through the held handle; Release; a binary loaded in another process or in this one = GameRunning; that +// process killed = Ok again; a binary the guard may not open = Unknown; the lock busy = Busy; a lock it may not open = +// LockDenied. // Written for this project. #include #include @@ -97,7 +97,6 @@ static std::string Narrow(const std::wstring& w) { for (wchar_t c : w) s.push_back(c < 0x80 ? static_cast(c) : '?'); return s; } -static ULONGLONG Now() { return GetTickCount64(); } // ---- child modes static int Child(int argc, wchar_t** argv) { @@ -140,16 +139,19 @@ static int Child(int argc, wchar_t** argv) { WaitFile(argv[4]); // the parent keeps a handle to the mutex now ExitProcess(0); } - if (mode == L"--child-register" && argc >= 5) { // the game's registration (budget ms), then stays loaded until killed - const ULONGLONG t0 = Now(); - LoadedRegistration reg(game, static_cast(_wtoi(argv[3]))); - // "marker=<0|1> state=<0|1> ms= " - WriteText(argv[4], "marker=" + std::to_string(reg.marker() ? 1 : 0) + " state=" + std::to_string(reg.state_ok() ? 1 : 0) + - " ms=" + std::to_string(Now() - t0) + " " + reg.why()); - if (!reg.marker()) return 0; + if (mode == L"--child-load" && argc >= 4) { // a "game" that loaded a WrongGPU binary (argv[2]), until it is killed + const HMODULE m = LoadLibraryW(game.c_str()); + WriteText(argv[3], m ? "loaded" : "error " + std::to_string(GetLastError())); + if (!m) return 3; Sleep(120000); return 0; } + if (mode == L"--child-tryload" && argc >= 4) { // tries to load argv[2] once: "ok" or "error " + const HMODULE m = LoadLibraryW(game.c_str()); + WriteText(argv[3], m ? std::string("ok") : "error " + std::to_string(GetLastError())); + if (m) FreeLibrary(m); + return 0; + } return 2; } @@ -244,7 +246,7 @@ int wmain(int argc, wchar_t** argv) { SECURITY_ATTRIBUTES sa{sizeof(sa), denyAll, FALSE}; HANDLE squat = CreateMutexW(&sa, FALSE, lockName.c_str()); o = SetSettings(game, {{"rr_mode", "exact"}}, 300); - OperationGuard g(game, 300); + OperationGuard g(game, {}, 300); check(squat && o.result == SetResult::LockDenied && o.error == ERROR_ACCESS_DENIED && ReadText(f) == b2 && g.result() == GuardResult::LockDenied && std::string(g.words()).find("access denied") != std::string::npos, "a state lock this process may not open: LockDenied (SetSettings and the guard), not Busy; nothing written"); @@ -367,132 +369,93 @@ int wmain(int argc, wchar_t** argv) { DeleteFileW(go.c_str()); } - // ---- the loaded protocol + // ---- the operation guard: Windows decides whether a WrongGPU binary is loaded (an exclusive open of a loaded image fails) { - DWORD err = 0; - check(QueryGameUse(game, &err) == GameUse::NotRunning && QueryGameUse(game) == GameUse::NotRunning, "no marker: NotRunning (and the query creates none)"); - check(QueryGameUse(JoinPath(root, L"gone")) == GameUse::NotRunning, "a folder that does not exist: NotRunning (nothing can run from it)"); + wchar_t me[MAX_PATH * 2]; + const DWORD n = GetModuleFileNameW(nullptr, me, MAX_PATH * 2); + std::wstring exeDir(me, n); + exeDir = exeDir.substr(0, exeDir.find_last_of(L'\\')); + const std::wstring testDll = JoinPath(exeDir, L"wg_state_test_dll.dll"); + const std::wstring plugins = JoinPath(game, L"plugins"); + CreateDirectoryW(plugins.c_str(), nullptr); + const std::wstring bin = JoinPath(plugins, L"WrongGPU-RR.asi"), bin2 = JoinPath(game, L"wronggpu_runtime.dll"); + const bool copied = CopyFileW(testDll.c_str(), bin.c_str(), FALSE) && CopyFileW(testDll.c_str(), bin2.c_str(), FALSE); + check(copied, "two real DLLs in the game folder (the test DLL under WrongGPU's binary names)"); + const std::vector bins{bin, bin2, JoinPath(game, L"wronggpu_ffx_dx12.dll") /* not there: skipped */}; { - LoadedRegistration reg(game); - check(reg.marker() && reg.state_ok() && QueryGameUse(aliases.back()) == GameUse::Running, "registered in this process: Running (asked through another alias)"); + OperationGuard g(game, bins, 1000); + check(g.ok() && g.Holds(bin) && g.Holds(bin2) && !g.Holds(bins[2]), "nothing loaded: Ok, every existing binary held exclusively, a missing one skipped"); + // a held guard blocks a load of the file, in this process and in another one + const HMODULE m = LoadLibraryW(bin.c_str()); + const DWORD le = m ? 0 : GetLastError(); + if (m) FreeLibrary(m); + const std::wstring out = JoinPath(root, L"tryload"); + HANDLE k = Spawn(L"--child-tryload " + Q(bin) + L" " + Q(out)); + if (k) WaitExit(k); + const std::string r = ReadText(out); + check(!m && le == ERROR_SHARING_VIOLATION && r.rfind("error ", 0) == 0, "while the guard holds a binary, LoadLibrary of it fails (here and in another process): a game cannot load WrongGPU mid-operation"); + DeleteFileW(out.c_str()); + // deletes go through the held handle; Release hands one file back at its own step + check(g.DeleteHeld(bin2) == ERROR_SUCCESS && !Exists(bin2) && !g.Holds(bin2), "DeleteHeld: the binary deleted through the guard's own handle"); + check(g.DeleteHeld(bin2) == ERROR_NOT_FOUND, "DeleteHeld of a file the guard does not hold: ERROR_NOT_FOUND"); + check(g.Release(bin) && !g.Holds(bin), "Release: the guard closes its handle of that one file"); + HANDLE h = CreateFileW(bin.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + check(h != INVALID_HANDLE_VALUE, "after Release the operation can open (and replace) the file itself"); + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); } - check(QueryGameUse(game) == GameUse::NotRunning, "the registration ended: NotRunning"); - // a lookup error is Unknown, never NotRunning: an object of another type under the marker's name + CopyFileW(testDll.c_str(), bin2.c_str(), FALSE); + // a binary loaded in another process: GameRunning, nothing held; that process killed: Ok + const std::wstring ready = JoinPath(root, L"ready-load"); + HANDLE k = Spawn(L"--child-load " + Q(bin) + L" " + Q(ready)); + const bool up = k && WaitFile(ready) && ReadText(ready) == "loaded"; { - std::wstring markerName; - NameFor(kLoadedPrefix, game, &markerName, nullptr); - HANDLE ev = CreateEventW(nullptr, TRUE, FALSE, markerName.c_str()); - err = 0; - const GameUse u = QueryGameUse(game, &err); - OperationGuard g(game, 1000); - check(ev && u == GameUse::Unknown && err != 0 && g.result() == GuardResult::Unknown && std::string(g.words()).find("could not tell") != std::string::npos, - "a marker lookup that fails: Unknown, and the launcher's guard refuses (Unknown)"); - if (ev) CloseHandle(ev); + OperationGuard g(game, bins, 1000); + check(up && g.result() == GuardResult::GameRunning && g.error() == ERROR_SHARING_VIOLATION && g.which() == bin && !g.Holds(bin2) && + std::string(g.words()).find("close the game first") != std::string::npos, + "a binary loaded in another process: GameRunning (sharing violation, names the file), nothing held"); } - // a game folder this process cannot open: Unknown, the guard refuses + if (k) { TerminateProcess(k, 9); WaitForSingleObject(k, 30000); CloseHandle(k); } + DeleteFileW(ready.c_str()); + check(OperationGuard(game, bins, 1000).ok(), "that process ended (killed): Ok again, nothing stale"); + // loaded in this process { - const std::wstring locked = JoinPath(root, L"Locked"); - CreateDirectoryW(locked.c_str(), nullptr); - PSECURITY_DESCRIPTOR deny = nullptr, allow = nullptr, parentDeny = nullptr, parentAllow = nullptr; - ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(D;;FA;;;WD)", SDDL_REVISION_1, &deny, nullptr); - ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;WD)", SDDL_REVISION_1, &allow, nullptr); - // the parent must not grant listing either (listing a folder lets its entries' attributes be read) - const std::wstring parent = JoinPath(root, L"LockedParent"); - CreateDirectoryW(parent.c_str(), nullptr); - const std::wstring inner = JoinPath(parent, L"Game"); - CreateDirectoryW(inner.c_str(), nullptr); - ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(D;;0x1;;;WD)(A;;FA;;;WD)", SDDL_REVISION_1, &parentDeny, nullptr); - ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;WD)", SDDL_REVISION_1, &parentAllow, nullptr); - const bool set = deny && parentDeny && SetFileSecurityW(inner.c_str(), DACL_SECURITY_INFORMATION, deny) && - SetFileSecurityW(parent.c_str(), DACL_SECURITY_INFORMATION, parentDeny); - err = 0; - const GameUse u = QueryGameUse(inner, &err); - const GuardResult gr = OperationGuard(inner, 500).result(); - if (allow) SetFileSecurityW(inner.c_str(), DACL_SECURITY_INFORMATION, allow); - if (parentAllow) SetFileSecurityW(parent.c_str(), DACL_SECURITY_INFORMATION, parentAllow); - for (PSECURITY_DESCRIPTOR p : {deny, allow, parentDeny, parentAllow}) if (p) LocalFree(p); - if (!(set && u == GameUse::Unknown && err == ERROR_ACCESS_DENIED && gr == GuardResult::Unknown)) - std::printf(" (access-denied lookup: set %d, use %d, error %lu, guard %d)\n", set, static_cast(u), err, static_cast(gr)); - check(set && u == GameUse::Unknown && err == ERROR_ACCESS_DENIED && gr == GuardResult::Unknown, - "a game folder whose identity cannot be read (access denied): Unknown, the guard refuses"); - RemoveDirectoryW(inner.c_str()); - RemoveDirectoryW(parent.c_str()); - RemoveDirectoryW(locked.c_str()); + const HMODULE m = LoadLibraryW(bin2.c_str()); + OperationGuard g(game, bins, 1000); + check(m && g.result() == GuardResult::GameRunning && g.which() == bin2, "a binary loaded in this process: GameRunning"); + if (m) FreeLibrary(m); } - // a registered game in another process; then it crashes - const std::wstring out = JoinPath(root, L"reg-1"); - HANDLE k = Spawn(L"--child-register " + Q(game) + L" 2000 " + Q(out)); - const bool up = k && WaitFile(out) && ReadText(out).rfind("marker=1 state=1", 0) == 0; - OperationGuard* g = new OperationGuard(game, 1000); - check(up && QueryGameUse(game) == GameUse::Running && g->result() == GuardResult::GameRunning && std::string(g->words()).find("close the game") != std::string::npos, - "a game registered in another process: Running, the guard refuses (GameRunning)"); - delete g; - if (k) { - TerminateProcess(k, 9); // the game crashes - WaitForSingleObject(k, 30000); - CloseHandle(k); - } - check(up && QueryGameUse(game) == GameUse::NotRunning && OperationGuard(game, 1000).result() == GuardResult::Ok, - "the game died: no stale marker, NotRunning, the guard lets the operation run"); - DeleteFileW(out.c_str()); - } - - // ---- a game that starts DURING an operation: its marker appears at once, the operation's Recheck sees it and stops; the - // game gives up on state after its bounded registration (about 2 s) and stays visible to every later operation - { - const std::wstring out = JoinPath(root, L"reg-2"); - HANDLE k = nullptr; - bool sawGame = false; - ULONGLONG seenAfter = 0; + // a binary this process may not open: Unknown (refuse), never Ok { - OperationGuard op(game, 1000); // the launcher's operation starts (lock held, no game yet) - const bool ok = op.ok(); - const ULONGLONG t0 = Now(); - k = Spawn(L"--child-register " + Q(game) + L" 2000 " + Q(out)); // the game starts during it - for (int i = 0; i < 150 && !sawGame; ++i) { // the operation's steps: Recheck before each one - if (op.Recheck() == GuardResult::GameRunning) sawGame = true; - else Sleep(20); + PSECURITY_DESCRIPTOR deny = nullptr, allow = nullptr; + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(D;;FA;;;WD)", SDDL_REVISION_1, &deny, nullptr); + ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;;FA;;;WD)", SDDL_REVISION_1, &allow, nullptr); + const bool set = deny && SetFileSecurityW(bin2.c_str(), DACL_SECURITY_INFORMATION, deny); + GuardResult gr; + DWORD ge; + { + OperationGuard g(game, bins, 1000); + gr = g.result(); + ge = g.error(); } - seenAfter = Now() - t0; - check(ok && sawGame && !op.ok() && std::string(op.words()).find("close the game first") != std::string::npos, - "a game starting mid-operation: its marker appears at once, the next Recheck says GameRunning (close the game first)"); - // the operation keeps the lock (it stops cleanly): the game's registration runs out of budget on the lock, not on the marker - check(k && WaitFile(out, 10000), "the starting game finished its registration while the operation held the lock"); - } // the operation ends (stopped) - const std::string r = ReadText(out); - const unsigned long ms = std::strtoul(r.c_str() + r.find("ms=") + 3, nullptr, 10); - check(r.rfind("marker=1 state=0", 0) == 0 && r.find("not free in time") != std::string::npos && ms >= 1500 && ms < 3000, - "that game: marker made, state given up after the bounded wait (about 2 s, never longer): defaults, no state this session"); - check(seenAfter < 2000, "the marker was there before the game's lock wait ended (seen within its registration)"); - { - OperationGuard later(game, 1000); - check(QueryGameUse(game) == GameUse::Running && later.result() == GuardResult::GameRunning, - "after that operation the game is still visible: a later operation refuses too"); + if (allow) SetFileSecurityW(bin2.c_str(), DACL_SECURITY_INFORMATION, allow); // the owner may always change the DACL back + for (PSECURITY_DESCRIPTOR p : {deny, allow}) if (p) LocalFree(p); + check(set && gr == GuardResult::Unknown && ge == ERROR_ACCESS_DENIED, "a binary the guard may not open (access denied): Unknown, the operation refuses"); } - if (k) { TerminateProcess(k, 9); WaitForSingleObject(k, 30000); CloseHandle(k); } - DeleteFileW(out.c_str()); - // a game whose registration starts while no operation runs gets marker and state at once - const std::wstring out2 = JoinPath(root, L"reg-3"); - HANDLE k2 = Spawn(L"--child-register " + Q(game) + L" 2000 " + Q(out2)); - const bool got2 = k2 && WaitFile(out2, 10000); - const std::string r2 = ReadText(out2); - check(got2 && r2.rfind("marker=1 state=1", 0) == 0 && std::strtoul(r2.c_str() + r2.find("ms=") + 3, nullptr, 10) < 1500, - "no operation running: marker and state at once, well inside the budget"); - if (k2) { TerminateProcess(k2, 9); WaitForSingleObject(k2, 30000); CloseHandle(k2); } - DeleteFileW(out2.c_str()); - // the budget bounds the whole registration: a budget of 300 ms while an operation runs ends within it - const std::wstring out3 = JoinPath(root, L"reg-4"); + // the state lock busy: Busy (the binaries are not even opened) { - OperationGuard op(game, 1000); - HANDLE k3 = Spawn(L"--child-register " + Q(game) + L" 300 " + Q(out3)); - const bool got3 = k3 && WaitFile(out3, 10000); - const std::string r3 = ReadText(out3); - check(op.ok() && got3 && r3.rfind("marker=1 state=0", 0) == 0 && std::strtoul(r3.c_str() + r3.find("ms=") + 3, nullptr, 10) < 1000, - "a 300 ms registration budget while an operation runs: done within it (marker, no state)"); - if (k3) { TerminateProcess(k3, 9); WaitForSingleObject(k3, 30000); CloseHandle(k3); } + const std::wstring ready2 = JoinPath(root, L"ready-hold2"); + HANDLE h2 = Spawn(L"--child-hold " + Q(game) + L" 2000 " + Q(ready2)); + const bool up2 = h2 && WaitFile(ready2); + OperationGuard* g = new OperationGuard(game, bins, 200); + check(up2 && g->result() == GuardResult::Busy && !g->Holds(bin), "the state lock held elsewhere: Busy, no binary held"); + delete g; + if (h2) WaitExit(h2); + DeleteFileW(ready2.c_str()); } - DeleteFileW(out3.c_str()); - check(QueryGameUse(game) == GameUse::NotRunning, "every game ended: NotRunning"); + check(OperationGuard(JoinPath(root, L"gone"), {}, 1000).ok(), "a game folder that is gone: nothing to guard (Ok)"); + DeleteFileW(bin.c_str()); + DeleteFileW(bin2.c_str()); + RemoveDirectoryW(plugins.c_str()); } // cleanup (own files only) diff --git a/clean/wgshared/tests/test_wg_state_dll.cpp b/clean/wgshared/tests/test_wg_state_dll.cpp new file mode 100644 index 00000000..63f11357 --- /dev/null +++ b/clean/wgshared/tests/test_wg_state_dll.cpp @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT +// A tiny DLL for test_wg_state: a real image that a process can load, standing in for a WrongGPU binary the game has loaded. +// Written for this project. +#include + +extern "C" __declspec(dllexport) int WgStateTestDll() { return 219; } + +BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID) { return TRUE; } From 6fdebcd6d4161f66f43448f6ac6eecb3746a5618 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:04:15 -0500 Subject: [PATCH 6/7] Shared: the operation guard shares reads (the operation can still read the binaries it holds) The guard's handles (DELETE | GENERIC_READ | FILE_WRITE_DATA) now share reads. A game's LoadLibrary still fails against them (it does not share writes), and a loaded image still refuses the open, but the launcher's own reads during the operation (hashes, version resources, opened sharing writes and deletes) work. Test: a held binary can be read; LoadLibrary still fails. Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/include/wg_state.h | 18 ++++++++++-------- clean/wgshared/tests/test_wg_state.cpp | 9 +++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 1f8b1ef0..686c7248 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -24,14 +24,16 @@ // // THE OPERATION GUARD (a game that uses WrongGPU is never changed under it; Windows itself decides, nothing is registered): // - The game registers nothing. A WrongGPU binary the game has loaded (the front end, the menu plugin, the RR plugin, the -// runtime) is an image section of that process, and Windows refuses an exclusive open of it. +// runtime) is an image section of that process, and Windows refuses an open of it for writing its data. // - The launcher: an uninstall, repair or update holds an OperationGuard for its WHOLE run. It takes the state lock (a timeout // is Busy, access denied is LockDenied), then opens EVERY WrongGPU binary of the install with DELETE | GENERIC_READ | -// FILE_WRITE_DATA and share mode 0 (a loaded image has no open handle, so share mode 0 alone does not see it; Windows refuses -// an open for writing its data; nothing is ever written through the handle; a read-only binary is therefore Unknown): +// FILE_WRITE_DATA, sharing reads only (a loaded image has no open handle, so share modes alone do not see it; Windows refuses +// the open for writing its data; nothing is ever written through the handle; a read-only binary is therefore Unknown): // ERROR_SHARING_VIOLATION = a process has it loaded (GameRunning: refuse); any other open error = Unknown (refuse); a -// file that does not exist is skipped; all opened = nobody has WrongGPU loaded. The guard HOLDS those exclusive handles to -// the end, so a game that starts meanwhile cannot load WrongGPU (its LoadLibrary fails; OptiScaler carries on without it). +// file that does not exist is skipped; all opened = nobody has WrongGPU loaded. The guard HOLDS those handles to the end: +// a game that starts meanwhile cannot load WrongGPU (LoadLibrary does not share writes, so it fails against the guard's +// write access; OptiScaler carries on without it), while the operation itself can still read the files (hashes, version +// resources) with an open that shares writes and deletes. // The operation deletes a held binary through the guard's own handle (DeleteHeld), or releases that one handle right at // the step that replaces the file (Release). The guard is taken by the process that changes the files (the elevated worker // when there is one), never by a parent waiting for it. @@ -189,7 +191,7 @@ class StateLock { // ---- the operation guard ------------------------------------------------------------------------------------------- // The launcher's side of an uninstall, repair or update (see THE OPERATION GUARD above). Ok only when the state lock is held -// and every WrongGPU binary that exists is held exclusively. A timeout of the lock is Busy, access denied is LockDenied; a +// and every WrongGPU binary that exists is held (write access, reads shared). A timeout of the lock is Busy, access denied is LockDenied; a // binary loaded in a process (ERROR_SHARING_VIOLATION) is GameRunning; any other open error is Unknown. Keep it for the // whole operation, on the thread that took it. enum class GuardResult { Ok, Busy, LockDenied, GameRunning, Unknown }; @@ -217,9 +219,9 @@ class OperationGuard { } for (const std::wstring& b : binaries) { const std::wstring p = ExtendedPath(b); - // FILE_WRITE_DATA is what a loaded image refuses (the image section holds no open handle, so share mode 0 alone + // FILE_WRITE_DATA is what a loaded image refuses (the image section holds no open handle, so share modes alone // would not conflict with it); nothing is ever written through this handle - HANDLE h = CreateFileW(p.c_str(), DELETE | GENERIC_READ | FILE_WRITE_DATA, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE h = CreateFileW(p.c_str(), DELETE | GENERIC_READ | FILE_WRITE_DATA, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) { const DWORD e = GetLastError(); if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) continue; // not there: nothing has it loaded diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp index 8c1003ab..eab80465 100644 --- a/clean/wgshared/tests/test_wg_state.cpp +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -395,6 +395,15 @@ int wmain(int argc, wchar_t** argv) { const std::string r = ReadText(out); check(!m && le == ERROR_SHARING_VIOLATION && r.rfind("error ", 0) == 0, "while the guard holds a binary, LoadLibrary of it fails (here and in another process): a game cannot load WrongGPU mid-operation"); DeleteFileW(out.c_str()); + // the operation itself can still read a held binary (hash it, read its version) with an open that shares writes and deletes + { + HANDLE rd = CreateFileW(bin.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, 0, nullptr); + char head[2] = {0, 0}; + DWORD got = 0; + const bool read = rd != INVALID_HANDLE_VALUE && ReadFile(rd, head, 2, &got, nullptr) && got == 2 && head[0] == 'M' && head[1] == 'Z'; + if (rd != INVALID_HANDLE_VALUE) CloseHandle(rd); + check(read, "while the guard holds a binary, the operation can still read it (an open sharing writes and deletes)"); + } // deletes go through the held handle; Release hands one file back at its own step check(g.DeleteHeld(bin2) == ERROR_SUCCESS && !Exists(bin2) && !g.Holds(bin2), "DeleteHeld: the binary deleted through the guard's own handle"); check(g.DeleteHeld(bin2) == ERROR_NOT_FOUND, "DeleteHeld of a file the guard does not hold: ERROR_NOT_FOUND"); From f9f372ef9e5266a48818708284c21bd10c6bade8 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:10:18 -0500 Subject: [PATCH 7/7] Shared: the guard replaces held binaries without a release window (PutHeld) Release is gone. PutHeld / PutHeldFrom rename the held old binary away through its own handle (.wronggpu-old, the next free name when taken), rename the complete new file into place from a flushed temporary file, hold it at once, then delete the old file through its handle; files the operation creates take the same rename-in-then-hold path. A load in the moment before the hold gets the complete new file and stops the operation (sharing violation, GameRunning). Renames go through the NT form of the full path. GameRunning's words no longer claim it is the game: in use by the game or another program (for example antivirus). Tests: two builds of the test DLL (219, 220); 20 replaces while another process loads the file in a loop (complete binaries or refusals only, never another error); no .wronggpu-old or temporary file left; a taken .wronggpu-old name; PutHeld of a new file. Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/CMakeLists.txt | 5 +- clean/wgshared/include/wg_state.h | 132 ++++++++++++++++++--- clean/wgshared/tests/test_wg_state.cpp | 94 +++++++++++++-- clean/wgshared/tests/test_wg_state_dll.cpp | 9 +- 4 files changed, 211 insertions(+), 29 deletions(-) diff --git a/clean/wgshared/CMakeLists.txt b/clean/wgshared/CMakeLists.txt index 6a0aebfc..4087aee1 100644 --- a/clean/wgshared/CMakeLists.txt +++ b/clean/wgshared/CMakeLists.txt @@ -59,7 +59,10 @@ if(WIN32) # a real DLL the test loads (a WrongGPU binary a game has loaded), next to the test add_library(wg_state_test_dll SHARED ${CMAKE_CURRENT_LIST_DIR}/tests/test_wg_state_dll.cpp) set_target_properties(wg_state_test_dll PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" PREFIX "") - add_dependencies(test_wg_state wg_state_test_dll) + add_library(wg_state_test_dll2 SHARED ${CMAKE_CURRENT_LIST_DIR}/tests/test_wg_state_dll.cpp) # the "new" binary of a replace + target_compile_definitions(wg_state_test_dll2 PRIVATE WG_TEST_DLL_VALUE=220) + set_target_properties(wg_state_test_dll2 PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" PREFIX "") + add_dependencies(test_wg_state wg_state_test_dll wg_state_test_dll2) add_test(NAME wgshared_state COMMAND test_wg_state) endif() diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 686c7248..7693cf1a 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -34,9 +34,12 @@ // a game that starts meanwhile cannot load WrongGPU (LoadLibrary does not share writes, so it fails against the guard's // write access; OptiScaler carries on without it), while the operation itself can still read the files (hashes, version // resources) with an open that shares writes and deletes. -// The operation deletes a held binary through the guard's own handle (DeleteHeld), or releases that one handle right at -// the step that replaces the file (Release). The guard is taken by the process that changes the files (the elevated worker -// when there is one), never by a parent waiting for it. +// The operation deletes a held binary through the guard's own handle (DeleteHeld). It replaces one (or creates a new one) +// with PutHeld, never releasing it: the held old file is renamed away through its handle, the complete new file is renamed +// into place and held at once, the old one is deleted through its handle; a process can at most load the complete new file. +// A sharing violation is not always the game: the words say "in use by the game or another program (for example +// antivirus)". The guard is taken by the process that changes the files (the elevated worker when there is one), never by +// a parent waiting for it. // // Writes are atomic (WriteAtomic): a new temporary file in the same folder (.wgtmp--, created only where // nothing is), written in checked chunks, flushed and closed (both checked), then MoveFileExW(REPLACE_EXISTING | @@ -54,6 +57,7 @@ // is corrupt); ASCII only. // Written for this project; Windows API and the C++ standard library only. #include +#include #include #include #include @@ -200,7 +204,7 @@ inline const char* GuardWords(GuardResult r) { case GuardResult::Ok: return ""; case GuardResult::Busy: return "another WrongGPU program is changing this game's WrongGPU state right now; try again in a moment"; case GuardResult::LockDenied: return "WrongGPU may not use this game's state lock (access denied); run the launcher's repair as administrator"; - case GuardResult::GameRunning: return "the game is running with WrongGPU loaded; close the game first"; + case GuardResult::GameRunning: return "WrongGPU's files are in use by the game or another program (for example antivirus). Close the game and try again"; case GuardResult::Unknown: return "WrongGPU could not tell whether the game is using its files; close the game and try again"; } return "?"; @@ -245,33 +249,125 @@ class OperationGuard { const char* words() const { return GuardWords(result_); } // Whether the guard holds `path` (a binary it was given). bool Holds(const std::wstring& path) const { return Find(path) >= 0; } - // Closes the guard's handle of `path` right before the operation replaces that file itself (the file is then open to - // others again: do it at the step, never earlier). True when it was held. - bool Release(const std::wstring& path) { + // Puts the complete new bytes at `path` with no window in which a process can load a partial file or the guard holds + // nothing: (1) the held old binary, if any, is renamed away through its own handle to .wronggpu-old (the next free + // .wronggpu-old- when that name is taken; nothing is deleted by name); (2) the new bytes are written to a temporary + // file in the same folder, flushed, closed and renamed into place (only where nothing is); (3) the new file is opened and + // held like the others at once; (4) the old file is deleted through its held handle. A process can at most load the complete + // new file in the moment between (2) and (3): then the result is ERROR_SHARING_VIOLATION, the new file stays, and the guard's + // result turns to GameRunning (the operation stops). Files the operation creates (no old binary) take steps 2 and 3. + // ERROR_SUCCESS, or the error of the step that failed: before (2) completes nothing changed (the old file is renamed back); + // *oldLeft names an old file that could not be deleted after a successful replace (it stays, under its .wronggpu-old name). + DWORD PutHeld(const std::wstring& path, const void* data, size_t size, std::wstring* oldLeft = nullptr) { + if (oldLeft) oldLeft->clear(); + const std::wstring target = ExtendedPath(path); const int i = Find(path); - if (i < 0) return false; - CloseHandle(held_[i].h); - held_.erase(held_.begin() + i); - return true; + HANDLE old = i >= 0 ? held_[i].h : INVALID_HANDLE_VALUE; + std::wstring oldName; + if (old != INVALID_HANDLE_VALUE) { + const std::wstring folder = target.substr(0, target.find_last_of(L'\\') + 1), base = target.substr(target.find_last_of(L'\\') + 1); + DWORD e = ERROR_FILE_EXISTS; + for (int n = 0; n < 1000 && (e == ERROR_FILE_EXISTS || e == ERROR_ALREADY_EXISTS); ++n) { + oldName = base + L".wronggpu-old" + (n ? L"-" + std::to_wstring(n) : std::wstring()); + e = RenameHandle(old, folder + oldName, false); + } + if (e) return e; // nothing changed + held_.erase(held_.begin() + i); + } + auto renameBack = [&]() { if (old != INVALID_HANDLE_VALUE) { RenameHandle(old, target, false); held_.push_back({target, old}); } }; + DWORD e = PutComplete(target, data, size); + if (e) { renameBack(); return e; } // the old file back under its name, still held + HANDLE h = CreateFileW(target.c_str(), DELETE | GENERIC_READ | FILE_WRITE_DATA, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD heldErr = 0; + if (h == INVALID_HANDLE_VALUE) { + heldErr = GetLastError(); + which_ = path; + err_ = heldErr; + result_ = heldErr == ERROR_SHARING_VIOLATION ? GuardResult::GameRunning : GuardResult::Unknown; + } else { + held_.push_back({target, h}); + } + if (old != INVALID_HANDLE_VALUE) { + if (DeleteThrough(old)) { + CloseHandle(old); + } else { + if (oldLeft) *oldLeft = target.substr(0, target.find_last_of(L'\\') + 1) + oldName; + CloseHandle(old); + } + } + return heldErr; + } + // The same from a file (`source`, read whole; for payload files the launcher has on disk). + DWORD PutHeldFrom(const std::wstring& path, const std::wstring& source, std::wstring* oldLeft = nullptr) { + std::string bytes; + HANDLE s = CreateFileW(ExtendedPath(source).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, 0, nullptr); + if (s == INVALID_HANDLE_VALUE) return GetLastError(); + char buf[64 * 1024]; + DWORD got = 0; + DWORD e = 0; + for (;;) { + if (!ReadFile(s, buf, sizeof buf, &got, nullptr)) { e = GetLastError(); break; } + if (!got) break; + try { bytes.append(buf, got); } catch (...) { e = ERROR_OUTOFMEMORY; break; } + } + CloseHandle(s); + if (e) return e; + return PutHeld(path, bytes.data(), bytes.size(), oldLeft); } // Deletes `path` through the guard's own handle (no window in which another process can open or load it), then closes the // handle. ERROR_SUCCESS, ERROR_NOT_FOUND (not held), or the error of the delete (the handle is kept then). DWORD DeleteHeld(const std::wstring& path) { const int i = Find(path); if (i < 0) return ERROR_NOT_FOUND; - struct DispositionEx { DWORD Flags; } ex{0x1u | 0x2u}; // FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS - BOOL done = SetFileInformationByHandle(held_[i].h, static_cast(21) /* FileDispositionInfoEx */, &ex, sizeof ex); - if (!done) { // (a file system without the POSIX form: the classic delete-on-close) - FILE_DISPOSITION_INFO classic{TRUE}; - done = SetFileInformationByHandle(held_[i].h, FileDispositionInfo, &classic, sizeof classic); - } - if (!done) return GetLastError(); + if (!DeleteThrough(held_[i].h)) return GetLastError(); CloseHandle(held_[i].h); held_.erase(held_.begin() + i); return ERROR_SUCCESS; } private: + // Marks the file of `h` for deletion (POSIX delete: the name goes at once; the classic delete-on-close as the fallback). + static bool DeleteThrough(HANDLE h) { + struct DispositionEx { DWORD Flags; } ex{0x1u | 0x2u}; // FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS + if (SetFileInformationByHandle(h, static_cast(21) /* FileDispositionInfoEx */, &ex, sizeof ex)) return true; + FILE_DISPOSITION_INFO classic{TRUE}; + return SetFileInformationByHandle(h, FileDispositionInfo, &classic, sizeof classic) != 0; + } + // Renames the file of `h` (held with DELETE access) to `newPath` (the \\?\ form, the same folder). 0 or the error. The name + // goes to the file system in its NT form (\??\...): a plain name would be taken against the current folder. + static DWORD RenameHandle(HANDLE h, const std::wstring& newPath, bool replace) { + const std::wstring newName = newPath.rfind(L"\\\\?\\", 0) == 0 ? L"\\??\\" + newPath.substr(4) : newPath; + const size_t bytes = sizeof(FILE_RENAME_INFO) + newName.size() * sizeof(wchar_t); + std::vector buf(bytes, 0); + FILE_RENAME_INFO* info = reinterpret_cast(buf.data()); + info->ReplaceIfExists = replace ? TRUE : FALSE; + info->RootDirectory = nullptr; + info->FileNameLength = static_cast(newName.size() * sizeof(wchar_t)); + memcpy(info->FileName, newName.c_str(), newName.size() * sizeof(wchar_t)); + return SetFileInformationByHandle(h, FileRenameInfo, info, static_cast(bytes)) ? 0 : GetLastError(); + } + // The complete bytes at `target` (a new temporary file in its folder, written in checked chunks, flushed, closed, then + // renamed into place only where nothing is). 0 or the error; the temporary file is deleted on a failure. + static DWORD PutComplete(const std::wstring& target, const void* data, size_t size) { + static volatile LONG counter = 0; + const std::wstring tmp = target + kTempMark + std::to_wstring(GetCurrentProcessId()) + L"-g" + std::to_wstring(InterlockedIncrement(&counter)); + HANDLE t = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (t == INVALID_HANDLE_VALUE) return GetLastError(); + DWORD e = 0; + const char* p = static_cast(data); + for (size_t done = 0; !e && done < size;) { + const DWORD want = static_cast(size - done < kChunk ? size - done : kChunk); + DWORD put = 0; + if (!WriteFile(t, p + done, want, &put, nullptr)) e = GetLastError(); + else if (put != want) e = ERROR_WRITE_FAULT; + else done += put; + } + if (!e && !FlushFileBuffers(t)) e = GetLastError(); + if (!CloseHandle(t) && !e) e = GetLastError(); + if (!e && !MoveFileExW(tmp.c_str(), target.c_str(), MOVEFILE_WRITE_THROUGH)) e = GetLastError(); + if (e) DeleteFileW(tmp.c_str()); + return e; + } struct Held { std::wstring path; HANDLE h; }; int Find(const std::wstring& path) const { const std::wstring p = ExtendedPath(path); diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp index eab80465..cc9c18f2 100644 --- a/clean/wgshared/tests/test_wg_state.cpp +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -11,7 +11,9 @@ // re-reads the old whole file; the half-written temporary file is never read as state); // - the operation guard, with a real DLL (wg_state_test_dll) under WrongGPU's binary names: nothing loaded = Ok with every // existing binary held exclusively; a held guard makes LoadLibrary of the file fail (here and in another process); -// deletes through the held handle; Release; a binary loaded in another process or in this one = GameRunning; that +// deletes through the held handle; PutHeld of a new file and replaces of a held one while another process keeps loading +// it (complete old or new binary, or a refusal; never partial; no leftovers); a binary loaded in another process or in +// this one = GameRunning; that // process killed = Ok again; a binary the guard may not open = Unknown; the lock busy = Busy; a lock it may not open = // LockDenied. // Written for this project. @@ -146,6 +148,36 @@ static int Child(int argc, wchar_t** argv) { Sleep(120000); return 0; } + if (mode == L"--child-loadloop" && argc >= 6) { // once exists: loads argv[2] again and again for , then a summary + WaitFile(argv[4]); + const ULONGLONG end = GetTickCount64() + static_cast(_wtoi(argv[5])); + int loads = 0, refused = 0; + bool v219 = false, v220 = false, vOther = false; + std::string other; + while (GetTickCount64() < end) { + const HMODULE m = LoadLibraryW(game.c_str()); + if (m) { + ++loads; + typedef int (*Fn)(); + const Fn f = reinterpret_cast(GetProcAddress(m, "WgStateTestDll")); + const int v = f ? f() : 0; + if (v == 219) v219 = true; + else if (v == 220) v220 = true; + else vOther = true; // loaded but not a complete binary of either version + FreeLibrary(m); + } else { + const DWORD e = GetLastError(); + // refusals: the guard holds the file (sharing violation), or the name is between the rename-away and the rename-in + if (e == ERROR_SHARING_VIOLATION || e == ERROR_MOD_NOT_FOUND || e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND || e == ERROR_ACCESS_DENIED) ++refused; + else if (other.find(std::to_string(e)) == std::string::npos) other += (other.empty() ? "" : ",") + std::to_string(e); // e.g. a bad image: partial + } + } + std::string values = std::string(v219 ? "219" : "") + (v220 ? (v219 ? ",220" : "220") : ""); + if (vOther) values += values.empty() ? "partial" : ",partial"; + WriteText(argv[3], "loads=" + std::to_string(loads) + " values=" + (values.empty() ? "none" : values) + " refused=" + std::to_string(refused) + + " other=" + (other.empty() ? "-" : other)); + return 0; + } if (mode == L"--child-tryload" && argc >= 4) { // tries to load argv[2] once: "ok" or "error " const HMODULE m = LoadLibraryW(game.c_str()); WriteText(argv[3], m ? std::string("ok") : "error " + std::to_string(GetLastError())); @@ -375,7 +407,7 @@ int wmain(int argc, wchar_t** argv) { const DWORD n = GetModuleFileNameW(nullptr, me, MAX_PATH * 2); std::wstring exeDir(me, n); exeDir = exeDir.substr(0, exeDir.find_last_of(L'\\')); - const std::wstring testDll = JoinPath(exeDir, L"wg_state_test_dll.dll"); + const std::wstring testDll = JoinPath(exeDir, L"wg_state_test_dll.dll"), testDll2 = JoinPath(exeDir, L"wg_state_test_dll2.dll"); const std::wstring plugins = JoinPath(game, L"plugins"); CreateDirectoryW(plugins.c_str(), nullptr); const std::wstring bin = JoinPath(plugins, L"WrongGPU-RR.asi"), bin2 = JoinPath(game, L"wronggpu_runtime.dll"); @@ -404,15 +436,61 @@ int wmain(int argc, wchar_t** argv) { if (rd != INVALID_HANDLE_VALUE) CloseHandle(rd); check(read, "while the guard holds a binary, the operation can still read it (an open sharing writes and deletes)"); } - // deletes go through the held handle; Release hands one file back at its own step + // deletes go through the held handle check(g.DeleteHeld(bin2) == ERROR_SUCCESS && !Exists(bin2) && !g.Holds(bin2), "DeleteHeld: the binary deleted through the guard's own handle"); check(g.DeleteHeld(bin2) == ERROR_NOT_FOUND, "DeleteHeld of a file the guard does not hold: ERROR_NOT_FOUND"); - check(g.Release(bin) && !g.Holds(bin), "Release: the guard closes its handle of that one file"); - HANDLE h = CreateFileW(bin.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); - check(h != INVALID_HANDLE_VALUE, "after Release the operation can open (and replace) the file itself"); - if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + // a file the operation creates: renamed in complete, then held + const std::string newBytes = ReadText(testDll2); + check(g.PutHeld(bin2, newBytes.data(), newBytes.size()) == ERROR_SUCCESS && g.Holds(bin2) && ReadText(bin2) == newBytes, + "PutHeld of a new file: the complete file renamed into place and held at once"); } CopyFileW(testDll.c_str(), bin2.c_str(), FALSE); + // ---- a replace while another process keeps trying to load the file: it gets the old or the new COMPLETE binary, or a + // refusal, never a partial one; no .wronggpu-old and no temporary file stays + { + const std::string newBytes = ReadText(testDll2); + const std::wstring out = JoinPath(root, L"loadloop"), go = JoinPath(root, L"go-loadloop"); + // the old file loaded once before the guard (the loop's first load), then the loop runs against the guard + OperationGuard g(game, bins, 1000); + const bool held = g.ok() && g.Holds(bin); + HANDLE k = Spawn(L"--child-loadloop " + Q(bin) + L" " + Q(out) + L" " + Q(go) + L" 3000"); + Sleep(500); // the loop is running (refused while the old file is held) + WriteText(go, "go"); + std::wstring oldLeft; + DWORD e = ERROR_SUCCESS; + for (int i = 0; i < 20 && e == ERROR_SUCCESS; ++i) { // replace back and forth: 220, 219, 220, ... + const std::string& bytes = (i % 2 == 0) ? newBytes : ReadText(testDll); + const std::string copy = bytes; + e = g.PutHeld(bin, copy.data(), copy.size(), &oldLeft); + Sleep(25); + } + const DWORD replaced = e; + if (k) WaitExit(k, 60000); + const std::string r = ReadText(out); // "loads= values= refused= other=" + bool onlyComplete = r.find("other=-") != std::string::npos; + for (const char* bad : {"values=0", "partial"}) onlyComplete = onlyComplete && r.find(bad) == std::string::npos; + std::printf(" (load loop during replaces: %s; last PutHeld %lu)\n", r.c_str(), replaced); + check(held && (replaced == ERROR_SUCCESS || replaced == ERROR_SHARING_VIOLATION) && !r.empty() && onlyComplete, + "replaces while another process keeps loading the file: every load got a complete old or new binary, or a refusal; never a partial file"); + bool leftovers = false; + for (auto& name : List(plugins)) leftovers = leftovers || name.find(L".wronggpu-old") != std::wstring::npos || IsTempName(name); + check(oldLeft.empty() && !leftovers, "after the replaces: no .wronggpu-old and no temporary file left (the old files were deleted through their handles)"); + DeleteFileW(out.c_str()); + DeleteFileW(go.c_str()); + } + // a .wronggpu-old name already taken (a file of an earlier crash): the next free name is used, the earlier file stays + { + const std::wstring taken = bin + L".wronggpu-old"; + WriteText(taken, "an earlier file"); + const std::string newBytes = ReadText(testDll2); + OperationGuard g(game, bins, 1000); + std::wstring oldLeft; + const DWORD e = g.PutHeld(bin, newBytes.data(), newBytes.size(), &oldLeft); + check(g.ok() && e == ERROR_SUCCESS && ReadText(bin) == newBytes && ReadText(taken) == "an earlier file" && !Exists(bin + L".wronggpu-old-1") && oldLeft.empty(), + "a taken .wronggpu-old name: the next free name used and cleaned up, the earlier file untouched (nothing deleted by name)"); + DeleteFileW(taken.c_str()); + } + CopyFileW(testDll.c_str(), bin.c_str(), FALSE); // a binary loaded in another process: GameRunning, nothing held; that process killed: Ok const std::wstring ready = JoinPath(root, L"ready-load"); HANDLE k = Spawn(L"--child-load " + Q(bin) + L" " + Q(ready)); @@ -420,7 +498,7 @@ int wmain(int argc, wchar_t** argv) { { OperationGuard g(game, bins, 1000); check(up && g.result() == GuardResult::GameRunning && g.error() == ERROR_SHARING_VIOLATION && g.which() == bin && !g.Holds(bin2) && - std::string(g.words()).find("close the game first") != std::string::npos, + std::string(g.words()).find("in use by the game or another program") != std::string::npos, "a binary loaded in another process: GameRunning (sharing violation, names the file), nothing held"); } if (k) { TerminateProcess(k, 9); WaitForSingleObject(k, 30000); CloseHandle(k); } diff --git a/clean/wgshared/tests/test_wg_state_dll.cpp b/clean/wgshared/tests/test_wg_state_dll.cpp index 63f11357..a705cf8b 100644 --- a/clean/wgshared/tests/test_wg_state_dll.cpp +++ b/clean/wgshared/tests/test_wg_state_dll.cpp @@ -1,8 +1,13 @@ // SPDX-License-Identifier: MIT // A tiny DLL for test_wg_state: a real image that a process can load, standing in for a WrongGPU binary the game has loaded. -// Written for this project. +// Built twice: WG_TEST_DLL_VALUE 219 (the "old" binary) and 220 (the "new" one), so a test can tell which complete file a +// process loaded. Written for this project. #include -extern "C" __declspec(dllexport) int WgStateTestDll() { return 219; } +#ifndef WG_TEST_DLL_VALUE +#define WG_TEST_DLL_VALUE 219 +#endif + +extern "C" __declspec(dllexport) int WgStateTestDll() { return WG_TEST_DLL_VALUE; } BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID) { return TRUE; }