diff --git a/clean/wgshared/CMakeLists.txt b/clean/wgshared/CMakeLists.txt index e868fee9..4087aee1 100644 --- a/clean/wgshared/CMakeLists.txt +++ b/clean/wgshared/CMakeLists.txt @@ -45,6 +45,25 @@ 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() + # 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_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() 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..7693cf1a --- /dev/null +++ b/clean/wgshared/include/wg_state.h @@ -0,0 +1,629 @@ +// 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. The launcher creates the +// folder; nothing here creates it. +// +// 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. +// +// 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 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, 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 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). 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 | +// 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. +// +// 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 (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 +#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; // the launcher's waits +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); } +// 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; } + +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(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(); + 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"Global\\WrongGPU-state-%08lX-%016llX", static_cast(info.dwVolumeSerialNumber), index); + *name = buf; + 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; why: +// timedOut() (another holder), denied() (this process may not open the folder or the lock: ERROR_ACCESS_DENIED), else error(). +class StateLock { +public: + 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(); + } + ~StateLock() { + if (held_) ReleaseMutex(mutex_); + if (mutex_) CloseHandle(mutex_); + } + StateLock(const StateLock&) = delete; + StateLock& operator=(const StateLock&) = delete; + 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_; } + 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: + HANDLE mutex_ = nullptr; + bool held_ = false, abandoned_ = false; + DWORD err_ = 0; +}; + +// ---- 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 (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 }; +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 "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 "?"; +} +class OperationGuard { +public: + // 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(); + 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; + } + 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 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, 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 + 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; } + // 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); + 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; + 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); + 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::vector held_; + std::wstring which_; + 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(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(); + 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() > kMaxStateBytes) { ok = false; if (err) *err = ERROR_FILE_TOO_LARGE; break; } + } + CloseHandle(h); + if (!ok) out->clear(); + return ok; +} + +/// 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; + WriteResult r; + if (bytes.size() > kMaxStateBytes) { r.error = ERROR_FILE_TOO_LARGE; return r; } + const std::wstring target = ExtendedPath(path); + 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) { + 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; 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; r.error = ERROR_WRITE_FAULT; } + else if (!FlushFileBuffers(h)) { ok = false; r.error = 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; 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) { 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; + } + return r; + } + if (!r.error) r.error = ERROR_FILE_EXISTS; + return r; +} + +// ---- 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; + 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); + 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 (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) 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; +} +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, 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; + 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, 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"; + case SetResult::WriteFailed: return "the settings file could not be written"; + } + 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. 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 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()) 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) 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 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 new file mode 100644 index 00000000..cc9c18f2 --- /dev/null +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -0,0 +1,556 @@ +// SPDX-License-Identifier: MIT +// 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, +// move) leaves the target as it was and no temporary file, a cleanup that fails is reported; +// - SetSettings: no state folder, a folder this process may not write (AccessDenied, its own result), unreadable, corrupt; +// - one lock name for several aliases of one folder (case, trailing backslash, 8.3 name, \\?\ form, a junction, a path longer +// 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 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; 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. +#include +#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(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(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); + 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 bool WaitFile(const std::wstring& p, DWORD ms = 30000) { + for (DWORD t = 0; t < ms; t += 20) { + 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; +} + +// ---- 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) { // 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); // 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; + Set(w, "counter", std::to_string(c + 1)); + Sleep(0); // widen the window a lost update would need + if (!WriteAtomic(SettingsPathOf(game), RenderSettings(w)).ok) return 4; + } + return 0; + } + 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) { // 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-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 keeps a handle to the mutex now + ExitProcess(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-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())); + if (m) FreeLibrary(m); + 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=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, 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 + const std::wstring state = StateDirOf(game); + { + 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"}}).ok() && *Get(ReadSettings(game), "rr_mode") == "fast", "SetSettings writes the file"); + const std::string before = ReadText(f); + 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"}) { + failAt = step; + TestFault() = [](const char* s) { return std::strcmp(s, failAt) == 0; }; + w = WriteAtomic(f, "rr_mode=exact\r\n"); + TestFault() = nullptr; + 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): 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; }; + w = WriteAtomic(f, "rr_mode=exact\r\n"); + TestFault() = nullptr; + 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"}}).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); + SetOutcome o = SetSettings(game, {{"rr_mode", "exact"}}); + CloseHandle(h); + 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); + 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 && 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"); + } + + // ---- one lock name for every alias of the folder, each in a SEPARATE process + std::vector aliases; + { + aliases.push_back(game); + aliases.push_back(game + L"\\"); + std::wstring upper = game; + for (auto& ch : upper) ch = static_cast(towupper(ch)); + aliases.push_back(upper); + wchar_t shortp[MAX_PATH * 2]; + 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"}}).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 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 " + 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: a bounded wait gives up, nothing written + { + const std::wstring ready = JoinPath(root, L"ready-hold"); + 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)); + 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()); + } + + // ---- abandoned in the middle of a write: the next holder re-reads the old whole file + { + 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 alive past the child's end + WriteText(go, "go"); + if (k) WaitExit(k); + { + StateLock lock(game, 5000); + 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"}}).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); + DeleteFileW(ready.c_str()); + DeleteFileW(go.c_str()); + } + + // ---- the operation guard: Windows decides whether a WrongGPU binary is loaded (an exclusive open of a loaded image fails) + { + 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"), 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"); + 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 */}; + { + 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()); + // 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 + 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"); + // 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)); + const bool up = k && WaitFile(ready) && ReadText(ready) == "loaded"; + { + 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("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); } + DeleteFileW(ready.c_str()); + check(OperationGuard(game, bins, 1000).ok(), "that process ended (killed): Ok again, nothing stale"); + // loaded in this process + { + 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 binary this process may not open: Unknown (refuse), never Ok + { + 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(); + } + 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"); + } + // the state lock busy: Busy (the binaries are not even opened) + { + 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()); + } + 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) + 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(root.c_str()); + std::printf("wg_state: %d passed, %d failed\n", g_pass, g_fail); + return g_fail ? 1 : 0; +} 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..a705cf8b --- /dev/null +++ b/clean/wgshared/tests/test_wg_state_dll.cpp @@ -0,0 +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. +// 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 + +#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; }