diff --git a/clean/fsr/src/config.cpp b/clean/fsr/src/config.cpp index 7574bdbe..62ad2301 100644 --- a/clean/fsr/src/config.cpp +++ b/clean/fsr/src/config.cpp @@ -398,6 +398,30 @@ std::string Config::BackendOptions() const { return extra.empty() ? std::string(buffer) : std::string(buffer) + ";" + extra; } +void ApplyStateSettings(Config& c, const std::vector>& kv, std::string* notes) { + auto note = [&](const std::string& s) { if (notes) *notes += s + "\n"; }; + std::string items; + for (const auto& p : kv) { + const std::string& key = p.first; + const std::string lv = Lower(p.second); + if (key == "upscaler") { + if (lv == "network") c.upscaler = UpscalerChoice::Network; + else if (lv == "amd") c.upscaler = UpscalerChoice::Amd; + else if (lv == "standin" || lv == "stand-in") c.upscaler = UpscalerChoice::StandIn; + else { note("settings.ini: bad value \"" + p.second + "\" for upscaler (wronggpu.ini's kept)"); continue; } + note("settings.ini: upscaler = " + lv + " (over wronggpu.ini)"); + } else if (key.rfind("rr_", 0) == 0 || key == "model") { + continue; // the RR plugin's keys and the model choice record's: not the front end's + } else if (IsRuntimeOptionKey(key)) { + items += (items.empty() ? "" : ";") + key + "=" + p.second; + note("settings.ini: " + key + " = " + p.second + " (over wronggpu.ini)"); + } else { + note("settings.ini: unknown key \"" + key + "\" (ignored)"); + } + } + if (!items.empty()) c.runtimeOptions = NormalizeOptions(c.runtimeOptions + ";" + items); +} + std::string OptionValue(const std::string& options, const char* key, bool* found) { std::string value; bool any = false; diff --git a/clean/fsr/src/config.h b/clean/fsr/src/config.h index 54b76ce2..e91422f5 100644 --- a/clean/fsr/src/config.h +++ b/clean/fsr/src/config.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include "model_k.h" @@ -129,6 +130,14 @@ struct Config { // (runtime_keys.h, e.g. "network = fused") is appended to runtime_options as "network=fused", with a warning. Config ParseConfig(const std::string& text, std::string* warnings); +// #219 (0.6.5): the settings chosen in the WrongGPU launcher are in the game's state folder, \ +// wronggpu-setup\settings.ini (clean/wgshared/include/wg_state.h), and take precedence over wronggpu.ini (the install's +// defaults, the player's to edit; the launcher never rewrites it). Applied over a parsed Config: `upscaler` (network, amd, +// standin) and every runtime option key (runtime_keys.h) as an item appended to runtime_options (the runtime takes a key's +// last value). The RR plugin's keys (rr_*) and `model` (the model choice record's) are not the front end's and are skipped; +// any other key is reported in *notes and ignored. *notes gets one line per applied key. +void ApplyStateSettings(Config& c, const std::vector>& kv, std::string* notes); + // Windows virtual-key code of an overlay_key value ("insert", "f9", "0x2d", ...); 0 when not recognised. int OverlayKeyCode(const std::string& name); diff --git a/clean/fsr/src/win_util.cpp b/clean/fsr/src/win_util.cpp index dcb3ae99..a1b98cc6 100644 --- a/clean/fsr/src/win_util.cpp +++ b/clean/fsr/src/win_util.cpp @@ -12,6 +12,7 @@ #include "amd_provider.h" #include "settings_bridge.h" #include "wg_settings_io.h" +#include "../../wgshared/include/wg_state.h" // #219: the game's state folder (settings.ini) #include "standin_d3d12.h" #include "provider_label.h" @@ -462,6 +463,20 @@ wgfsr::Config ReadSettings(const std::string& tag) { } std::string warnings; wgfsr::Config config = wgfsr::ParseConfig(text, &warnings); + // #219: the settings chosen in the launcher (the game's state folder beside wronggpu.ini) over wronggpu.ini's defaults + { + const std::wstring iniDir = path.substr(0, path.find_last_of(L"\\/")); + const wgstate::Settings st = wgstate::ReadSettings(iniDir); + if (st.corrupt || !st.why.empty()) + L().WriteLine(tag + "settings: " + Narrow(wgstate::SettingsPathOf(iniDir)) + " not used: " + st.why + " (wronggpu.ini's values apply)"); + std::string notes; + wgfsr::ApplyStateSettings(config, st.kv, ¬es); + for (size_t a = 0; a < notes.size();) { + const size_t e = notes.find('\n', a); + L().WriteLine(tag + notes.substr(a, e - a)); + a = e == std::string::npos ? notes.size() : e + 1; + } + } // Registry options the front end reads (clean/wgshared; [wronggpu] keys, block and environment first): set there, // they decide over the [fsr] keys of the same meaning. { diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index 2db49e57..e38a0c55 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -3472,6 +3472,29 @@ static void TestWithoutModelL() { } #endif +// #219: the launcher's settings in the game's state folder (settings.ini) over wronggpu.ini (config.h ApplyStateSettings) +static void TestStateSettings() { + std::string w; + Config c = ParseConfig("upscaler = amd\nruntime_options = executor=hip;sync=pipelined;output_filter=analytic\n", &w); + std::string notes; + ApplyStateSettings(c, {{"upscaler", "network"}, {"executor", "dx12"}, {"output_filter", "default"}, {"sparkle_guard", "off"}, + {"rr_mode", "fast"}, {"model", "L"}, {"no_such_key", "1"}}, + ¬es); + CHECK(c.upscaler == UpscalerChoice::Network); // the state's upscaler decides + // the runtime takes a key's last value: the state's items come after wronggpu.ini's + CHECK(c.runtimeOptions == "executor=hip;sync=pipelined;output_filter=analytic;executor=dx12;output_filter=default;sparkle_guard=off"); + CHECK(OptionValue(c.runtimeOptions, "sync", nullptr) == "pipelined"); // a key the state does not hold stays as the file has it + CHECK(c.runtimeOptions.find("rr_mode") == std::string::npos && c.runtimeOptions.find("model=") == std::string::npos); // not the front end's + CHECK(notes.find("unknown key \"no_such_key\"") != std::string::npos && notes.find("upscaler = network") != std::string::npos); + Config d = ParseConfig("upscaler = network\n", &w); + notes.clear(); + ApplyStateSettings(d, {{"upscaler", "turbo"}}, ¬es); + CHECK(d.upscaler == UpscalerChoice::Network && notes.find("bad value") != std::string::npos); // a bad value: the file's kept + Config e = ParseConfig("upscaler = amd\n", &w); + ApplyStateSettings(e, {}, nullptr); + CHECK(e.upscaler == UpscalerChoice::Amd && e.runtimeOptions.empty()); // no state: wronggpu.ini as it is +} + int main() { TestCustomSlotFailedCreate(); TestCustomSlotFailureKeyHasSize(); @@ -3559,6 +3582,7 @@ int main() { TestLogThinning(); TestHosted(); TestHostVersionHandling(); + TestStateSettings(); if (const char* dump = std::getenv("WG_TEST_DUMP_LOG")) { (void)dump; for (const auto& line : g_log) std::printf("%s\n", line.c_str()); diff --git a/clean/installer/README.md b/clean/installer/README.md index 7bd1e98f..94f011ca 100644 --- a/clean/installer/README.md +++ b/clean/installer/README.md @@ -29,9 +29,11 @@ payload file built with the front end) for every game and sets OptiScaler.ini `[ `Path=auto` (the section is added when the player's ini has none). On the OptiScaler builds the plugin recognises, "WrongGPU" is then an entry of OptiScaler's main upscaler list and its default, and OptiScaler's FSR 3.X/4 entry is AMD's upscaler; on any other build the plugin changes nothing and WrongGPU stays the first entry of the FFX box. -`Dx12Upscaler=fsr31`, `FfxDx12SRPath` and `UpscalerIndex=0` stay as before. Uninstall removes the plugin, its folder -when the install made it, and its files (`wronggpu-asi.log`, `wronggpu-asi.ini` in the OptiScaler folder), and puts the -player's OptiScaler.ini back. Tests: `test_asi_plugin`. +`Dx12Upscaler=fsr31`, `FfxDx12SRPath` and `UpscalerIndex=0` stay as before. Uninstall removes the plugin and its folder +when the install made it, and puts the player's OptiScaler.ini back. The plugin's starting entry `wronggpu-asi.ini` (a +Preset K build writes it) is one of the install's recorded files (#219): an uninstall removes it while it is unchanged +and keeps it, listed, once the plugin's menu or the player changed it (an update keeps such a file as it is). The +plugin's log `wronggpu-asi.log` is not recorded and stays, listed. Tests: `test_asi_plugin`. Other setups' plugins (0.6.1, `ForeignPlugins`): `.asi` files in `plugins\`, `OptiScaler\plugins\` or `wronggpu-plugins\` that the install record doesn't name with that hash. In a Ray Reconstruction game WrongGPU's RR stays out by default (they may hook RR too; the result says so); with the player's OK (the window's question, `--switch-plugins`) they are moved aside @@ -245,8 +247,9 @@ With the defaults nothing of this section changes the installer. - **What the launcher removes or overwrites: the file-ownership rule** (0.6.1; the restore, uninstall, repair, update, move out of a wrong folder and the state-folder cleanup; `src/wg_core/record.h`). In the game's folders, a file is deleted or overwritten only when its current bytes are WrongGPU's: the hash the install record says WrongGPU last - wrote there (every write of the launcher to `wronggpu.ini`, `OptiScaler.ini` and the RR plugin's settings updates that - hash). Nothing else proves it: not the file's name, not a file next to it, not an ini key, not "it is a log", not "the + wrote there (every write of the launcher to `OptiScaler.ini` updates that hash; `wronggpu.ini` and the RR plugin's + `WrongGPU\wronggpu.ini` are written once, by the install, and never rewritten after it: see the saved settings below). + Nothing else proves it: not the file's name, not a file next to it, not an ini key, not "it is a log", not "the install created that path". A file that is not in the record is not touched, whatever its name (`wronggpu-*`, `OptiScaler.log`, `fakenvapi.log`, ...). - **Two policies, stated here on purpose.** Files in WrongGPU's FSR slot that identify as WrongGPU (the version @@ -267,8 +270,15 @@ With the defaults nothing of this section changes the installer. where a hash is known, its bytes are those. The backups the record lists go while they match the entry's hash; the previous version's files that `previous.txt` lists go while they match the hashes it states (a changed one stays and is listed); `owned-files.json` goes while it is byte for byte what WrongGPU makes of the record. The record, - `previous.txt`, `uninstall.exe`, `setup.log` and `profile.ini` carry no recorded hash and go by their fixed names (the one - place the rule is by name). The player's Engine.ini copy (`rr-config`) goes only through the Engine.ini revert. Any other + `previous.txt`, `uninstall.exe`, `setup.log` and `profile.ini` carry no recorded hash and go by their fixed names. + The saved settings `settings.ini` and `model-choice.ini` go only while their bytes carry WrongGPU's stamp: a last + line `; wronggpu-written ` whose check covers every byte before it, the file's own name and this install's id + (the record's `install-id`, kept by repair and update). WrongGPU stamps a state file it creates and keeps the stamp + only while nobody else changes the file. A file the player edited or made, a copy under another name (a temporary + file among them) or from another install stays and is listed. Repair and update keep them. A save never overwrites + a change made meanwhile: the file is held from the read to the move, and a change in the last moment refuses the save. + A failed install, repair or update takes back only what that run made (written down before each create); everything + else in the state folder stays and is listed. The player's Engine.ini copy (`rr-config`) goes only through the Engine.ini revert. Any other file stays, the folder stays with it, and the result lists what was left. The same applies when an install is moved out of a wrong folder. The shared folder `%LOCALAPPDATA%\WrongGPU` is not in a game's folder; see Uninstall. - **A settings file in a build without Preset K.** The plugin's `wronggpu-asi.ini` is rewritten (its `selection=wronggpu-k` @@ -284,6 +294,23 @@ With the defaults nothing of this section changes the installer. any file); the game's FSR DLL, in the one step where WrongGPU's DLL is deleted and the game's file takes its name, is held until deleted and the move that follows creates the name only if free; the install, repair and update steps that write into the game folder and the Engine.ini edit that adds the line are not covered by this (tracked separately). + - **The saved settings** (#219; `clean/wgshared/include/wg_state.h`). Settings you change in the launcher or the in-game + menu are saved in `wronggpu-setup\settings.ini` and take precedence over `wronggpu.ini` (the FSR front end reads the + upscaler and its runtime option keys from there, the RR plugin `rr_*`). `wronggpu.ini` and `WrongGPU\wronggpu.ini` + keep the install's defaults and are the player's to edit; no launcher operation and no plugin rewrites them after the + install, so a save in the game never makes them look edited, and an uninstall after a save leaves nothing behind. + Every write of `settings.ini` takes the game's state lock (one named mutex per game folder, shared by the launcher, + the front end and the plugins) and replaces the file whole (`WriteAtomic`); a write that cannot take the lock or + cannot be made is reported, never silent (the launcher stops with "Settings not applied: ...", the RR menu logs + "not saved: ..."). An install from before #219 whose `WrongGPU\wronggpu.ini` differs from the record (an older + plugin's save or the player's edit) is the player's: its `rr_mode` and `rr_overlay` are copied into `settings.ini` + once and the file is kept. + - **Uninstall, repair and update refuse while WrongGPU is in use.** For the whole operation the launcher holds the + record's WrongGPU binaries (`.dll`, `.asi`) open for writing and deleting (`OperationGuard`); a binary the game has + loaded, or another program has open without sharing writes (antivirus, a backup tool), cannot be opened that way, so + the operation stops before anything changes: "Nothing was changed: WrongGPU's files are in use by the game or another + program (for example antivirus). Close the game and try again ()." A binary the operation replaces or creates + is renamed in complete and held at once; the old one is deleted through its handle. - **Roll back** holds every payload file it changes through one handle (as above), compares its bytes with the hash the record says WrongGPU installed, keeps the current files for a later update by copying them out through those handles into a new swap folder, and then overwrites through them. The earlier files are held and hashed too, all of them before @@ -449,12 +476,13 @@ Basic tier: `wronggpu` (on | off: `[fsr] upscaler = network | amd`), `executor` original), `sparkle_guard` (off | on | a rate in (0, 1)), `fps_overlay` (keep | on | off: OptiScaler's `[Menu] ShowFps`, written only when that key exists in the game's OptiScaler.ini). On the game page Use WrongGPU is in view; Runs on, Output filter, Pre-exposure and Sparkle guard are under "Advanced settings (4)", shown when one of them is off its default, unsaved or changed outside the launcher (`AdvancedWanted`). Every value is checked before -anything is written. `wronggpu.ini` gets only what differs from the defaults: the managed runtime items are removed -from `runtime_options` (and from lines of their own, which the front end appends) and the non-default ones appended -in a fixed order, one line without spaces; other items, comments, unknown keys and sections stay. A value in the -files that differs from both its default and the profile is an outside edit (Keep / Revert). After every install, -update and repair the profile is written into the files again; the record learns the new hashes of `wronggpu.ini` -and `OptiScaler.ini`, so an uninstall can still prove they are WrongGPU's. +anything is written. The front end's settings go into `wronggpu-setup\settings.ini` (#219): `upscaler` and every +managed runtime key, defaults too, so they decide over `wronggpu.ini`, which keeps the install's defaults and is not +rewritten (the front end puts the state's keys over the file's `runtime_options`, last value wins). The Model L/K +choice is not one of these keys (`model-choice.ini`). A value in the effective settings that differs from both its +default and the profile is an outside edit (Keep / Revert). After every install, update and repair the profile is +written again (`settings.ini`, `OptiScaler.ini`); the record learns the new hash of `OptiScaler.ini`, so an uninstall +can still prove it is WrongGPU's. **Record v2** (`WRONGGPU-RECORD 2`, `src/wg_core/record.*`): the v1 lines plus `payload`, `proxy` and one `owner` line per action (`wg`, `wg-optibundle`, `adopted`, `moved`); action lines keep their five fields, so a 0.5.x uninstaller diff --git a/clean/installer/src/app/cli.cpp b/clean/installer/src/app/cli.cpp index c07b9215..1d739319 100644 --- a/clean/installer/src/app/cli.cpp +++ b/clean/installer/src/app/cli.cpp @@ -847,7 +847,7 @@ int Verb(const wstring& verb, const Args& a, Output& o) { if (res.code) return res.code; } string wini, oini; - ReadAll(Join(dir, L"wronggpu.ini"), wini); + wini = EffectiveWronggpuIni(dir); // (#219: the state folder over the file) ReadAll(Join(dir, L"OptiScaler.ini"), oini); auto eff = EffectiveSettings(wini, oini); if (const RrFileState rs = ReadRrSettings(dir); rs.present) { // Ray Reconstruction: the RR plugin's settings file diff --git a/clean/installer/src/app/launcher_ui.cpp b/clean/installer/src/app/launcher_ui.cpp index 649553f5..ff05b4e5 100644 --- a/clean/installer/src/app/launcher_ui.cpp +++ b/clean/installer/src/app/launcher_ui.cpp @@ -325,7 +325,7 @@ PageData ReadPageData(const GameEntry& e, const Profile& defaults) { d.saved = e.hasRecord ? GameProfile(e.dir) : defaults; d.opti = ReadOpti(e); string wini, oini; - ReadAll(Join(e.dir, L"wronggpu.ini"), wini); + wini = EffectiveWronggpuIni(e.dir); // (#219: the state folder over the file) ReadAll(Join(e.dir, L"OptiScaler.ini"), oini); d.outside = e.hasRecord ? OutsideEdits(d.saved, wini, oini) : std::vector{}; if (const RrConfigGame* rg = e.hasRecord ? RrConfigGameFor(e.exe) : nullptr) { diff --git a/clean/installer/src/app/ui_checks.cpp b/clean/installer/src/app/ui_checks.cpp index 0a7df4d9..11d36322 100644 --- a/clean/installer/src/app/ui_checks.cpp +++ b/clean/installer/src/app/ui_checks.cpp @@ -108,7 +108,7 @@ void FirstRunChecks(HWND hwnd, const GlobalSettings& gs, const wstring& dll, boo std::vector pn; if (!IsFile(ProfilePath(e.dir))) { string wini, oini; - ReadAll(Join(e.dir, L"wronggpu.ini"), wini); + wini = EffectiveWronggpuIni(e.dir); // (#219: the state folder over the file) ReadAll(Join(e.dir, L"OptiScaler.ini"), oini); ImportProfile(wini, oini, &pn); } diff --git a/clean/installer/src/wg_core/install.cpp b/clean/installer/src/wg_core/install.cpp index f224aac8..e67d4ff0 100644 --- a/clean/installer/src/wg_core/install.cpp +++ b/clean/installer/src/wg_core/install.cpp @@ -12,6 +12,8 @@ #include "rr.h" #include "settings.h" +#include + namespace wg { // The install routes (setup_route.h of the installer). Two routes. Hosted: the player's OptiScaler next to the game @@ -401,19 +403,20 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod // 2. An older WrongGPU install with a record, then an earlier install of this version: back to the original files. if (!target.conflicts.legacyRecordDir.empty()) for (auto& w : LegacyRestore(ctx, target.conflicts.legacyRecordDir, ui)) warnings.push_back(w); RemoveEarlierDirect(ctx, target, ui, warnings); - // Once the earlier installation is removed, a failure leaves the game's original files and no install: what is - // left of its state folder (the uninstaller, which has no record any more) goes too. rc6 L4: never the player's settings - // there (profile.ini, previous\ for Roll back, rr-config\): an update or repair that fails keeps them for the next try, - // as does a failed install where they were before it (a profile the launcher saved first). + // Once the earlier installation is removed, a failure leaves the game's original files and no install. The state folder + // then loses only what THIS run made (the run journal: written down before each create); everything else there (the + // player's settings, profile.ini, previous\ for Roll back, rr-config\, a file the player keeps there, what an earlier + // uninstall kept and listed) stays and is listed. Never a removal of the whole folder. const bool keepSettings = StateHasSettings(dir) || IsFile(RecordPath(dir)); + RunJournal journal; struct EarlierGone { - const wstring& dir; Ui& ui; bool armed = false; + Context& ctx; const wstring& dir; Ui& ui; RunJournal& journal; bool armed = false; ~EarlierGone() { if (!armed || IsFile(RecordPath(dir))) return; - RemoveStateKeepingSettings(dir); + if (!journal.done) RollbackCreated(ctx, StateDir(dir), journal); ui.log(L"The earlier installation was removed and the game's original files are back; the new version was not installed (your settings were kept)."); } - } earlierGone{dir, ui}; + } earlierGone{ctx, dir, ui, journal}; std::map keptByRestore; // recorded files the restore left in place (changed since the install), with its warning string carriedIni; // the earlier install's wronggpu.ini when it was WrongGPU's: the new one starts from it bool haveCarried = false; @@ -458,7 +461,9 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod return opti && IEq(f.rel, L"amd_fidelityfx_dx12.dll") ? wstring(slot ? kOptiSlotFrontEnd : kOptiFrontEnd) : opti && IEq(f.rel, kAsiPlugin) ? pluginRel : wstring(f.rel); }; // OptiScaler's files (OptiScaler.dll as the proxy, OptiScaler.ini set up for WrongGPU from a temporary copy) - struct OptiFile { wstring rel, src; }; + // seed: a file the install creates only where nothing is (the plugin's wronggpu-asi.ini, WrongGPU\wronggpu.ini): one that + // appears before it is written is the player's (kept as it is, not recorded); kept: so found, not written + struct OptiFile { wstring rel, src; bool seed = false, kept = false; }; std::vector optiFiles; wstring proxy, proxyReason; CoexistReport co; @@ -475,8 +480,14 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod string selectedOptions, selectedSection; IniGetFrontEnd(selectedIni, "runtime_options", &selectedOptions, &selectedSection); #if WRONGGPU_PRESET_K - selectedOptions += selectedOptions.empty() ? "" : ";"; - selectedOptions += ctx.presetK ? "model=K" : "model=M"; + { // #219: the earlier model items out first, so a repair or update writes the same wronggpu.ini again (the launcher no + // longer rewrites it after the install) + std::vector> kept; + for (auto& kv : SplitOptions(selectedOptions)) + if (_stricmp(kv.first.c_str(), "model") != 0) kept.push_back(kv); + kept.push_back({"model", ctx.presetK ? "K" : "M"}); + selectedOptions = JoinOptions(kept); + } #else if (target.presetK) { // the launcher asked first (PresetKText); the command line says it in the log const wstring w = L"Preset K isn't in this version of WrongGPU: " + target.name + L" now starts on Model M."; @@ -508,6 +519,21 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod const wstring selectedIniSrc = Join(OptiTempDir(ctx), L"WrongGPU.selected.ini"); WriteFileAtomic(selectedIniSrc, selectedIni.data(), selectedIni.size()); optiFiles.push_back({L"wronggpu.ini", selectedIniSrc}); +#if WRONGGPU_PRESET_K + if (opti && !slot) { // the menu plugin's starting entry (optiscaler.h AsiSelectionText), one of the install's recorded files + // (#219: a wronggpu-asi.ini still there after the restore is not WrongGPU's, the plugin's menu or the player changed it: + // left as it is and not recorded, so an uninstall keeps it and lists it) + if (Exists(Join(dir, L"wronggpu-asi.ini"))) { + LogLine(ctx, L"OptiScaler plugin: wronggpu-asi.ini kept as it is (its entry last selected; not WrongGPU's file)"); + } else { + const string asiText = AsiSelectionText(ctx.presetK); + const wstring asiSrc = Join(OptiTempDir(ctx), L"wronggpu-asi.ini"); + WriteFileAtomic(asiSrc, asiText.data(), asiText.size()); + optiFiles.push_back({L"wronggpu-asi.ini", asiSrc, true}); + LogLine(ctx, wstring(L"OptiScaler plugin: starts on WrongGPU (Model ") + (ctx.presetK ? L"K" : L"M") + L") (wronggpu-asi.ini)"); + } + } +#endif // Where the game's Ray Reconstruction needs the host to restore the game's command-list state (plugin interface 5, // gamerules.h), OptiScaler must be WrongGPU's edition of OptiScaler (optiedition.h: the launcher downloads it; never // shipped with WrongGPU). With another OptiScaler (the player's own download, used when the edition couldn't be @@ -666,12 +692,18 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod const wstring rsrc = Join(tmp, kRrIni); WriteFileAtomic(rsrc, rini.data(), rini.size()); optiFiles.push_back({kRrIni, rsrc}); - Profile rp = DefaultProfile(); - if (!LoadProfile(ProfilePath(dir), rp)) rp = DefaultProfile(); - const string sini = RenderRrSettings(rp, rrData, ""); - const wstring ssrc = Join(tmp, L"wronggpu.ini"); - WriteFileAtomic(ssrc, sini.data(), sini.size()); - optiFiles.push_back({kRrSettings, ssrc}); + // #219: WrongGPU\wronggpu.ini holds the install's defaults (the player's choices are in the state folder, which decides + // over it), so a repair or update writes the same file again. One still there after the restore is not WrongGPU's + // (the player's edit, an older plugin's save: its mode was copied into the state folder, MigrateRrState): left as it is + // and not recorded, so an uninstall keeps it and lists it + if (Exists(Join(dir, kRrSettings))) { + LogLine(ctx, wstring(kRrSettings) + L" kept as it is (not WrongGPU's file; the saved settings decide over it)"); + } else { + const string sini = RenderRrSettings(DefaultProfile(), rrData, ""); + const wstring ssrc = Join(tmp, L"wronggpu.ini"); + WriteFileAtomic(ssrc, sini.data(), sini.size()); + optiFiles.push_back({kRrSettings, ssrc, true}); + } LogLine(ctx, L"Ray Reconstruction: " + Join(Parent(pluginRel), kRrPluginName) + L", " + kRrRuntime + L" (the RR runtime is part of it), " + kRrIni + L" (data " + RrDataFile() + (rrData ? L")" : L", not converted yet: RR off)") + L", " + kRrSettings); } @@ -684,6 +716,9 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod // the earlier install moved aside or replaced with the player's OK (its disable entries, its copies over a file that // was there): those go aside again below on that OK.) Record m; m.version = ctx.data->version; m.game = dir; m.exe = target.exe; + // this install's id: the earlier install's (a repair or update keeps it, so WrongGPU's stamped state files stay its own), a + // new one otherwise + m.installId = target.installed && !target.record.installId.empty() ? target.record.installId : NewInstallId(); m.status = target.validated ? L"validated" : L"experimental"; m.regkey = ctx.perGameEntry ? RegKeyFor(dir) : L""; m.model = ModelFile(ctx); m.modelM = modelM.outcome; LogLine(ctx, L"target " + target.exe + L" | install folder " + dir + L" | status " + m.status); // Folders the payload needs that do not exist yet (shallow first). @@ -710,10 +745,18 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod if (Exists(tp)) { e.existed = true; e.orig = Sha256File(tp); if (e.orig.empty()) Fail(L"Cannot read the existing file " + tp); } m.e.push_back(e); } + RestoreStep("seed-planned"); // (tests: a seed file appears here, after its check and before the record) for (auto& of : optiFiles) { Entry e; e.action = L"copy"; e.rel = of.rel; e.inst = Sha256File(of.src); if (e.inst.empty()) Fail(L"Cannot read OptiScaler's " + of.rel); wstring tp = Target(dir, e.rel); + if (of.seed && Exists(tp)) { // appeared since the check: the player's; not recorded, never written + of.kept = true; + const wstring w = L"Left in place (appeared during the install, not WrongGPU's): " + of.rel; + LogLine(ctx, w); + warnings.push_back(w); + continue; + } if (Exists(tp)) { e.existed = true; e.orig = Sha256File(tp); if (e.orig.empty()) Fail(L"Cannot read the existing file " + tp); } m.e.push_back(e); } @@ -801,19 +844,21 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod ui.step(done, total, L"Backing up existing files"); const wstring state = StateDir(dir), rpath = RecordPath(dir); + JournalCreate(journal, state, true); EnsureDir(state); bool recorded = false; try { for (auto& e : m.e) { if (!e.existed) continue; - wstring b = BackupPath(dir, e.rel); - CopyChecked(Target(dir, e.rel), b); - if (Sha256File(b) != e.orig) Fail(L"Backup verification failed for " + e.rel); + // created only where nothing is: a file an earlier uninstall kept in backup\ stays, this backup takes a new name + CopyBackup(ctx, dir, e, Target(dir, e.rel), &journal, &warnings); ui.step(++done, total, L"Backed up " + e.rel); ui.log(L"backup " + e.rel); } + JournalCreate(journal, rpath, false); SaveRecord(rpath, m); // written before any change so an interrupted install can still be undone recorded = true; + RestoreStep("seed-recorded"); // (tests: a seed file appears here, after the record and before it is written) for (auto& e : m.e) { const wstring tp = Target(dir, e.rel); if (e.action == L"dir") { @@ -841,7 +886,8 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod ui.step(++done, total, L"Installing " + rel); DWORD sz = 0; const void* d = PayloadData(f, sz); const wstring tp = Target(dir, rel); - WriteFileAtomic(tp, d, sz); + if (IsBinaryName(rel)) PutBinary(tp, d, sz); // #219: renamed in complete, held by the operation's gate (record.h) + else WriteFileAtomic(tp, d, sz); if (Sha256File(tp) != f.sha256) Fail(L"Verification failed after writing " + rel); ui.log(L"installed " + rel); } @@ -849,12 +895,32 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod const bool ours = StartsWithI(BaseName(of.rel), L"wronggpu"); // the settings file and the Ray Reconstruction files ui.step(++done, total, (ours ? L"Installing " : L"Installing OptiScaler: ") + of.rel); const wstring tp = Target(dir, of.rel); - CopyChecked(of.src, tp); + if (of.kept) continue; + if (of.seed) { // created only where nothing is (CopyFileW fail-if-exists): a file that appeared is never replaced + EnsureDir(Parent(tp)); + DWORD err = 0; + if (!CopyNew(of.src, tp, &err)) { + if (err != ERROR_FILE_EXISTS && err != ERROR_ALREADY_EXISTS) Fail(L"Cannot create " + tp + L": " + ErrText(err)); + // the player's file (it appeared after the record was written): kept as it is, out of the record + m.e.erase(std::remove_if(m.e.begin(), m.e.end(), [&](const Entry& x) { return x.action == L"copy" && IEq(x.rel, of.rel); }), m.e.end()); + SaveRecord(rpath, m); + const wstring w = L"Left in place (appeared during the install, not WrongGPU's): " + of.rel; + LogLine(ctx, w); + warnings.push_back(w); + continue; + } + if (Sha256File(tp) != Sha256File(of.src)) Fail(L"Verification failed after writing " + of.rel); + ui.log(L"installed " + of.rel); + continue; + } + if (IsBinaryName(of.rel)) PutBinaryFrom(tp, of.src); // #219 (record.h) + else CopyChecked(of.src, tp); ui.log((ours ? L"installed " : L"installed OptiScaler's ") + of.rel); } for (auto& mr : mirrors) { ui.step(++done, total, L"Installing " + mr.second); - CopyChecked(Target(dir, mr.first), Target(dir, mr.second)); + if (IsBinaryName(mr.second)) PutBinaryFrom(Target(dir, mr.second), Target(dir, mr.first)); // #219 (record.h) + else CopyChecked(Target(dir, mr.first), Target(dir, mr.second)); ui.log(L"installed " + mr.second + L" (REFramework's copy of " + mr.first + L")"); } if (opti) ui.log(L"OptiScaler " + ctx.opti.version + L" is set up for WrongGPU (OptiScaler.dll as " + proxy + @@ -864,16 +930,17 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod // The uninstaller: the small restorer (WrongGPU-Restore.exe) the launcher embeds, else a copy of this program. if (ctx.restorer && ctx.restorerSize) { const wstring un = Join(state, L"uninstall.exe"); + JournalCreate(journal, un, false); WriteFileAtomic(un, ctx.restorer, ctx.restorerSize); if (Sha256File(un) != Sha256Bytes(ctx.restorer, ctx.restorerSize)) Fail(L"Verification failed after writing the uninstaller"); } else { + JournalCreate(journal, Join(state, L"uninstall.exe"), false); CopyChecked(SelfPath(), Join(state, L"uninstall.exe")); } if (ctx.perGameEntry) RegisterUninstall(ctx, m, state, target.name); + JournalCreate(journal, Join(state, L"owned-files.json"), false); WriteOwnedFiles(dir, m); -#if WRONGGPU_PRESET_K - if (opti && !slot) SeedAsiSelection(ctx, dir, ctx.presetK); -#endif + RestoreStep("installed"); // (tests: a failure after everything was written: the rollback takes back what this run made) ui.log(L"WrongGPU installed in " + dir + L" (" + m.status + L"); model data: " + ModelFile(ctx)); ui.step(total, total, L"Done"); } catch (const SetupError& ex) { @@ -881,8 +948,8 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod try { // (rc6 L4: the settings that were there before this install stay: the failed install's record and backup go only) if (recorded) DoRestore(ctx, dir, ui, true, keepSettings); - else if (!keepSettings) RemoveTree(state); - if (keepSettings && !IsFile(rpath)) RemoveStateKeepingSettings(dir); // (a backup DoRestore had to keep stays with its record) + // then what this run made and DoRestore left (the journal); anything else in the state folder stays and is listed + if (!IsFile(rpath)) RollbackCreated(ctx, state, journal); // (a backup DoRestore had to keep stays with its record) ui.log(L"Rollback complete; the game folder is back to its previous state."); } catch (const SetupError& r) { ui.log(L"Rollback problem: " + r.msg); } throw; diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index 1f99aafa..56cfae07 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -24,6 +24,7 @@ #include "pe.h" #include "rr.h" #include "rrconfig.h" +#include "../../../wgshared/include/wg_state.h" // the game's state folder (settings.ini), its lock, atomic writes #ifdef _MSC_VER #pragma comment(lib, "winhttp.lib") @@ -371,7 +372,7 @@ GameEntry EntryFor(Context& ctx, const wstring& exeIn, const wstring& name, cons if (fix == "on" || fix == "ask") try { g.rrConfigProtected = NeedsElevation(g.dir); } catch (...) {} } string wini, oini; - ReadAll(Join(g.dir, L"wronggpu.ini"), wini); + wini = EffectiveWronggpuIni(g.dir); // (#219: the state folder over the file) ReadAll(Join(g.dir, L"OptiScaler.ini"), oini); const bool off = EffectiveSettings(wini, oini)["wronggpu"] == "off"; g.wgOff = off; // kept with a Running status too (the window's Model M data rule) @@ -708,6 +709,7 @@ static void Rollback(Context& ctx, const wstring& dir, Ui& ui, OpResult& res) { Record m; if (!LoadRecord(RecordPath(dir), m) || m.legacy) Fail(L"No WrongGPU installation record was found in " + dir + L".", EXIT_NOT_INSTALLED); if (!m.exe.empty() && GameRunning(m.exe)) Fail(BaseName(m.exe) + L" is running. Close it first.", EXIT_REFUSED); + const auto gate = GuardOperation(dir, &m, false); // #219: the state lock for the whole roll back; its files are held below (record.h) wstring version, txtSha; std::vector files; if (!ReadPrevious(dir, version, files, &txtSha) || files.empty()) Fail(L"There is no earlier version to roll back to in " + dir + L".", EXIT_NOT_INSTALLED); @@ -988,11 +990,51 @@ static bool OptInKey(const wstring& exe, const IniKeyChange& c) { return false; } +std::vector> FrontEndStateKeys(const Profile& p) { + std::vector> r{{"upscaler", p.get("wronggpu") == "off" ? "amd" : "network"}}; + for (size_t i = 0; i < kSettingCount; ++i) + if (kSettings[i].layer == Layer::Rt) r.push_back({kSettings[i].key, p.get(kSettings[i].key)}); // explicit, defaults too + return r; +} + +string WithFrontEndState(const string& wronggpuIni, const std::vector>& state) { + string t = wronggpuIni; + std::vector> items; // the runtime option keys of the state, in its order + for (auto& kv : state) { + if (kv.first == "upscaler") { + string cur, sec; + t = IniGetFrontEnd(t, "upscaler", &cur, &sec) ? IniSet(t, sec, "upscaler", kv.second) : IniSet(t, "fsr", "upscaler", kv.second); + } else if (kv.first.rfind("rr_", 0) != 0 && kv.first != "model") { + items.push_back(kv); + } + } + if (items.empty()) return t; + string options, section; + const bool had = IniGetFrontEnd(t, "runtime_options", &options, §ion); + std::vector> kept; + for (auto& kv : SplitOptions(options)) { + string k = LowerA(kv.first); + if (k == "backend") k = "executor"; + bool overridden = false; + for (auto& s : items) overridden = overridden || s.first == k; + if (!overridden) kept.push_back(kv); + } + for (auto& s : items) { t = IniRemoveFrontEnd(t, s.first); kept.push_back(s); } + return IniSet(t, had ? section : "fsr", "runtime_options", JoinOptions(kept)); +} + +string EffectiveWronggpuIni(const wstring& dir) { + string text; + ReadAll(Join(dir, L"wronggpu.ini"), text); + const wgstate::Settings s = wgstate::ReadSettings(dir); + return s.kv.empty() ? text : WithFrontEndState(text, s.kv); +} + Profile GameProfile(const wstring& dir) { Profile p; if (!LoadProfile(ProfilePath(dir), p)) { string wini, oini; - ReadAll(Join(dir, L"wronggpu.ini"), wini); + wini = EffectiveWronggpuIni(dir); // (#219: the state folder over the file) ReadAll(Join(dir, L"OptiScaler.ini"), oini); p = ImportProfile(wini, oini); } @@ -1005,6 +1047,10 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto if (!LoadRecord(RecordPath(dir), m) || m.legacy) Fail(L"WrongGPU is not installed in " + dir + L".", EXIT_NOT_INSTALLED); InferOwners(ctx, m); bool recordChanged = m.format < 2; + Profile before; // the launcher's choice as saved before this apply: RR's mode is written only when it changes (rr.h WriteRrState) + const bool hadBefore = LoadProfile(ProfilePath(dir), before); + const string prevMode = before.get("rr_mode").empty() ? string("fast") : before.get("rr_mode"); + MigrateRrState(ctx, dir); // #219: an older plugin's or the player's edit of WrongGPU\wronggpu.ini: its mode into the state folder // Model L (or Model K, a build with its choice) saved while its data on this PC is not ready (removed since, or an install // of a game set to it before the data was converted): the game's files say Model M until it is; the profile keeps the // player's choice @@ -1040,20 +1086,24 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto for (auto& e : m.e) if (e.action == L"copy" && IEq(e.rel, name) && e.inst != h) { e.inst = h; recordChanged = true; } notes.push_back(wstring(name) + L" written"); }; - renderFile(L"wronggpu.ini", false); + // #219: the front end's settings go into the game's state folder (wg_state.h), which the front end reads over wronggpu.ini: + // wronggpu.ini holds the install's defaults, is the player's to edit, and is never rewritten after the install. (The model + // choice is not among these keys: it is the model choice record's, model-choice.ini.) + { + string unused; + wstring why; + if (!RenderWronggpuIni(q, "", unused, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); // (validates every setting) + const int w = WriteStateKeys(ctx, dir, FrontEndStateKeys(q), &why); + if (w < 0) Fail(L"Settings not applied: " + why, EXIT_REFUSED); + if (w > 0) notes.push_back(Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L" written"); + } if (HostedRecord(m)) renderFile(L"OptiScaler.ini", true); - if (RecordHasRr(m)) { // Ray Reconstruction (rr.h): the RR plugin's settings file (RR stays off while its data is not ready) - const wstring path = Join(dir, kRrSettings); - string in; - ReadAll(path, in); - const string out = RenderRrSettings(p, RrDataValid(ctx), in); - if (out != in) { - EnsureDir(Parent(path)); - WriteFileAtomic(path, out.data(), out.size()); - const wstring h = Sha256Bytes(out.data(), out.size()); - for (auto& e : m.e) if (e.action == L"copy" && IEq(e.rel, kRrSettings) && e.inst != h) { e.inst = h; recordChanged = true; } - notes.push_back(wstring(kRrSettings) + L" written"); - } + if (RecordHasRr(m)) { // Ray Reconstruction (rr.h): into the game's state folder (RR stays off while its data is not ready); + // WrongGPU\wronggpu.ini (the install's defaults, the player's to edit) is never rewritten + wstring why; + const int w = WriteRrState(ctx, dir, p, RrDataValid(ctx), &why, hadBefore ? &prevMode : nullptr); + if (w < 0) Fail(L"Settings not applied: " + why, EXIT_REFUSED); + if (w > 0) notes.push_back(Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L" written (Ray Reconstruction)"); } if (RrConfigGameFor(m.exe)) { // Borderlands 4, Hogwarts Legacy: the game's Engine.ini follows rr_config_fix (rrconfig.h) std::vector w; @@ -1171,7 +1221,7 @@ std::vector AdoptInstall(Context& ctx, const wstring& dir, bool* repair } if (!IsFile(ProfilePath(dir))) { string wini, oini; - ReadAll(Join(dir, L"wronggpu.ini"), wini); + wini = EffectiveWronggpuIni(dir); // (#219: the state folder over the file) ReadAll(Join(dir, L"OptiScaler.ini"), oini); std::vector pn; const Profile p = ImportProfile(wini, oini, &pn); @@ -1221,6 +1271,8 @@ static void InstallOp(Context& ctx, const OpRequest& r, Ui& ui, OpResult& res) { GameTarget target = InspectGame(ctx, gameExe); const wstring dir = target.dir; LogLine(ctx, wstring(L"launcher ") + OpName(r.op) + L": " + target.exe + L" (" + (target.validated ? L"validated" : L"experimental") + L"), install folder " + dir); + // #219: a repair or update (an install over a recorded one) holds the game's state lock from here to its end (record.h) + const auto gate = IsFile(RecordPath(dir)) ? GuardOperation(dir, target.installed ? &target.record : nullptr) : nullptr; // the rules table (design section 5): DLSS-NR on AMD, DXVK / vkd3d-proton, two OptiScaler copies, not D3D12, anti-cheat if (const Finding* no = target.coexist.refusal()) Fail(no->tool == Tool::AntiCheat ? AntiCheatMessage(no->evidence) : no->what + L": " + no->message, no->code ? no->code : EXIT_REFUSED); @@ -1284,10 +1336,11 @@ static void InstallOp(Context& ctx, const OpRequest& r, Ui& ui, OpResult& res) { bool haveProfile = LoadProfile(ProfilePath(dir), profile); if (!haveProfile) { string wini, oini; - if (ReadAll(Join(dir, L"wronggpu.ini"), wini)) { ReadAll(Join(dir, L"OptiScaler.ini"), oini); profile = ImportProfile(wini, oini); haveProfile = true; } + if (IsFile(Join(dir, L"wronggpu.ini"))) { wini = EffectiveWronggpuIni(dir); ReadAll(Join(dir, L"OptiScaler.ini"), oini); profile = ImportProfile(wini, oini); haveProfile = true; } } if (!haveProfile) profile = r.hasProfile ? r.profile : DefaultProfile(); - FoldRrFromGame(dir, profile); // a Ray Reconstruction mode chosen in the game stays (the install below rewrites its file) + MigrateRrState(ctx, dir); // #219: an older plugin's or the player's edit of WrongGPU\wronggpu.ini: its mode into the state folder + FoldRrFromGame(dir, profile); // a Ray Reconstruction mode chosen in the game stays (the state folder keeps it through the install) if (target.installed && !target.record.version.empty() && ctx.data && !IEq(target.record.version, ctx.data->version)) SavePrevious(ctx, dir, target.record, ui); std::vector oldJournal = target.installed ? target.record.inikeys : !wrongDir.empty() ? wrong.inikeys : std::vector{}; // a game's opt-in keys follow its setting (ApplyProfile), not the old file @@ -1324,7 +1377,13 @@ static void InstallOp(Context& ctx, const OpRequest& r, Ui& ui, OpResult& res) { Record m; if (LoadRecord(RecordPath(dir), m)) { m.rrconfig = keepFix; - if (keepFix.backup) { EnsureDir(Parent(RrConfigBackupPath(dir))); WriteFileAtomic(RrConfigBackupPath(dir), keepBackup.data(), keepBackup.size()); } + if (keepFix.backup) { // created only where nothing is: a file already there stays (the revert then leaves Engine.ini's + // copy as it is and says so) + EnsureDir(Parent(RrConfigBackupPath(dir))); + PinnedFile pf; + if (pf.Create(RrConfigBackupPath(dir))) { if (!pf.OverwriteBytes(keepBackup.data(), keepBackup.size())) pf.Delete(); pf.Close(); } + else LogLine(ctx, L"kept " + RrConfigBackupPath(dir) + L" (there already, not this install's copy: not overwritten)"); + } SaveRecord(RecordPath(dir), m); } } diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index 4b9d91a3..aa97acc0 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -212,6 +212,20 @@ bool NeedsElevation(const wstring& dir); // warnings: what could not be done that the player should hear (rr_config_fix: the game's Engine.ini, rrconfig.h). void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings = nullptr); Profile GameProfile(const wstring& dir); // profile.ini, else the profile its wronggpu.ini implies +// #219 (0.6.5): the launcher never rewrites the game's wronggpu.ini after the install (the install's defaults, the player's to +// edit). The front end's settings it manages go into the game's state folder, wronggpu-setup\settings.ini (wg_state.h), which +// the front end reads over wronggpu.ini: upscaler (network / amd, from the profile's wronggpu on / off) and every runtime key +// of the schema (executor, output_filter, pre_exposure, sparkle_guard), written explicitly, defaults too. Not the model: the +// model choice is the model choice record's (model-choice.ini). +std::vector> FrontEndStateKeys(const Profile& p); +// wronggpu.ini's text as the front end sees it with the state's keys over it: upscaler set in its section (else [fsr]); the +// runtime keys out of runtime_options and off their own lines, then appended to runtime_options (the RR keys rr_* and a model +// key are not the front end's and stay out). +string WithFrontEndState(const string& wronggpuIni, const std::vector>& state); +// The game's wronggpu.ini as in effect: the file with the state folder's settings over it (WithFrontEndState). Every reader +// of the launcher's settings (get, status, the game page, the import of a profile) reads this, so a key the state holds +// shadows the file's. +string EffectiveWronggpuIni(const wstring& dir); // The OptiScaler tab: reset / keep / edits of OpRequest written into the installed OptiScaler.ini with the inikey // journal in the record. Nothing to do: no change. void ApplyOptiTab(Context& ctx, const wstring& dir, const OpRequest& r, std::vector& notes); diff --git a/clean/installer/src/wg_core/leftovers.cpp b/clean/installer/src/wg_core/leftovers.cpp index 5c54e8e9..cd46b8de 100644 --- a/clean/installer/src/wg_core/leftovers.cpp +++ b/clean/installer/src/wg_core/leftovers.cpp @@ -232,8 +232,7 @@ std::vector AdoptLeftovers(Context& ctx, const wstring& exe, const wstr r.inst = Sha256File(orig); r.owner = L"moved"; m.e.insert(m.e.begin(), r); e.existed = true; e.orig = r.inst; - CopyChecked(orig, BackupPath(dir, f.rel)); - if (Sha256File(BackupPath(dir, f.rel)) != e.orig) Fail(L"Backup verification failed for " + f.rel); + CopyBackup(ctx, dir, e, orig, nullptr, nullptr); // (only where nothing is: a kept file there stays, logged) } } m.e.push_back(e); diff --git a/clean/installer/src/wg_core/logs.cpp b/clean/installer/src/wg_core/logs.cpp index 2efe402a..85a2431b 100644 --- a/clean/installer/src/wg_core/logs.cpp +++ b/clean/installer/src/wg_core/logs.cpp @@ -284,6 +284,7 @@ Bundle CollectLogs(Context& ctx, const wstring& dirIn, const wstring& outZip, co take(RecordPath(dir), L"install\\install.record"); take(Join(StateDir(dir), L"setup.log"), L"install\\setup.log"); take(Join(dir, kRrSettings), L"ray-reconstruction\\wronggpu.ini"); // the RR plugin's settings file (rr.h) + take(Join(StateDir(dir), L"settings.ini"), L"install\\settings.ini"); // #219: the settings chosen since (over the defaults above) take(Join(RrDataDir(), L"model-source.txt"), L"ray-reconstruction\\model-source.txt"); const bool reportK = WRONGGPU_PRESET_K && installed && IEq(FullPath(m.model), FullPath(Join(Join(ModelBaseDir(), L"K"), L"model.wgcm"))); const wstring reportModelDir = reportK ? Join(ModelBaseDir(), L"K") : ModelBaseDir(); diff --git a/clean/installer/src/wg_core/optiscaler.h b/clean/installer/src/wg_core/optiscaler.h index 15c10d20..2a426d5d 100644 --- a/clean/installer/src/wg_core/optiscaler.h +++ b/clean/installer/src/wg_core/optiscaler.h @@ -64,9 +64,10 @@ inline const GameNotice kGameNotices[] = { // // Install record: the plugin is a "copy" entry and the plugins folder (when new) a "dir" entry; OptiScaler.ini is // installed as a whole file with a backup of the player's, so an uninstall removes the plugin and its folder and -// puts the player's OptiScaler.ini back byte for byte. The plugin's own files (wronggpu-asi.log, wronggpu-asi.ini: -// the entry last selected) are written into the OptiScaler folder, named wronggpu-*. The install does not record them, so an -// uninstall leaves them in place and lists them (UnrecordedRuntimeFiles). +// puts the player's OptiScaler.ini back byte for byte. The plugin's own log (wronggpu-asi.log) is written into the +// OptiScaler folder; the install does not record it, so an uninstall leaves it in place and lists it +// (UnrecordedRuntimeFiles). Its settings file (wronggpu-asi.ini, the entry last selected) is one of the install's recorded +// files in a Preset K build (AsiSelectionText below). // OptiScaler.ini keys for the plugin (entries of kOptiIni). Path=auto: OptiScaler's "plugins" folder next to itself. #define WRONGGPU_ASI_INI {"Plugins", "LoadAsiPlugins", "true"}, {"Plugins", "Path", "auto"}, @@ -78,16 +79,14 @@ inline bool OptiOnlyPayload(const std::wstring& rel) { return _wcsicmp(rel.c_str // The entry the plugin starts on (0.5.0, an installer with Preset K): the plugin's wronggpu-asi.ini in the OptiScaler // folder, in the plugin's own format (FormatSelection, clean/fsr/asi/asi_thunk.h). With the plugin hooked, its entry // decides over wronggpu.ini's model=, so without this file a Preset K install would start on Model M (the plugin's -// default). Preset K: "selection=wronggpu-k" (WrongGPU (Model K)); Model M: "selection=wronggpu". Written after the -// install succeeded and not recorded: it is one of the plugin's own files (wronggpu-*), which an uninstall leaves in place -// and lists (UnrecordedRuntimeFiles; nothing proves it WrongGPU's), and which this write replaces on an update. -inline void SeedAsiSelection(Context& ctx, const std::wstring& dir, bool presetK) { - const std::string text = std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n" - "; (wronggpu or amd). Deleting this file selects WrongGPU.\r\nselection=") + - (presetK ? "wronggpu-k" : "wronggpu") + "\r\n"; - const std::wstring path = Join(dir, L"wronggpu-asi.ini"); - WriteFileAtomic(path, text.data(), text.size()); - LogLine(ctx, std::wstring(L"OptiScaler plugin: starts on WrongGPU (Model ") + (presetK ? L"K" : L"M") + L") (" + path + L")"); +// default). Preset K: "selection=wronggpu-k" (WrongGPU (Model K)); Model M: "selection=wronggpu". #219: installed as one of +// the install's files (recorded with its hash, a file already there backed up), so an uninstall removes it while it is +// unchanged and keeps it, listed, once the plugin's menu or the player changed it; an update keeps such a changed file's +// bytes (install.cpp). +inline std::string AsiSelectionText(bool presetK) { + return std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n" + "; (wronggpu or amd). Deleting this file selects WrongGPU.\r\nselection=") + + (presetK ? "wronggpu-k" : "wronggpu") + "\r\n"; } // OptiScaler.ini for WrongGPU; FfxDx12SRPath (empty here) gets the full path of kOptiFrontEnd at install time. inline const OptiKey kOptiIni[] = { diff --git a/clean/installer/src/wg_core/record.cpp b/clean/installer/src/wg_core/record.cpp index 2bf865a3..ac992e7f 100644 --- a/clean/installer/src/wg_core/record.cpp +++ b/clean/installer/src/wg_core/record.cpp @@ -6,6 +6,12 @@ #include #include #include +#include +#include +#ifdef WRONGGPU_TESTING +#include +#pragma comment(lib, "rstrtmgr.lib") +#endif #include "detect.h" #include "fingerprint.h" @@ -18,12 +24,14 @@ #include "rr.h" #include "rrconfig.h" #include "settings.h" +#include "../../../wgshared/include/wg_state.h" // the game's state files (settings.ini, model-choice.ini) and the state lock namespace wg { wstring StateDir(const wstring& dir) { return Join(dir, kStateDirName); } wstring RecordPath(const wstring& dir) { return Join(StateDir(dir), L"install.record"); } wstring BackupPath(const wstring& dir, const wstring& rel) { return Join(Join(StateDir(dir), L"backup"), rel); } +wstring EntryBackupPath(const wstring& dir, const Entry& e) { return BackupPath(dir, e.backup.empty() ? e.rel : e.backup); } wstring LegacyStateDir(const wstring& dir) { return Join(dir, kLegacyStateDir); } wstring LegacyRecordPath(const wstring& dir) { return Join(LegacyStateDir(dir), L"install.manifest"); } wstring LegacyBackupPath(const wstring& dir, const wstring& rel) { return Join(Join(LegacyStateDir(dir), L"backup"), rel); } @@ -65,9 +73,10 @@ static void RebaseRecord(Record& m, const wstring& dir) { bool LoadRecord(const wstring& path, Record& m) { string raw; if (!ReadAll(path, raw)) return false; + m = Record(); // the file's record alone (#219: a second load into the same Record listed every entry again) wstring text = FromUtf8(raw); size_t pos = 0; bool header = false; - std::vector> owners; + std::vector> owners, backups; while (pos < text.size()) { size_t nl = text.find(L'\n', pos); wstring line = text.substr(pos, nl == wstring::npos ? wstring::npos : nl - pos); @@ -106,6 +115,7 @@ bool LoadRecord(const wstring& path, Record& m) { else if (f[0] == L"regkey") m.regkey = f[1]; else if (f[0] == L"model") m.model = f[1]; else if (f[0] == L"model-m") m.modelM = f[1]; + else if (!m.legacy && f[0] == L"install-id") m.installId = f[1]; else if (!m.legacy && f[0] == L"rrconfig-backup") m.rrconfig.backupSha = f[1]; else if (!m.legacy) m.extra.push_back(line); } else if (f.size() == 5 && (f[0] == L"copy" || f[0] == L"disable" || (!m.legacy && (f[0] == L"rename" || f[0] == L"dir")))) { @@ -130,6 +140,8 @@ bool LoadRecord(const wstring& path, Record& m) { x.folder = f[4] == L"-" ? wstring() : f[4]; } else if (!m.legacy && f[0] == L"owner" && f.size() == 4) { owners.push_back({f[1], f[2], f[3]}); + } else if (!m.legacy && f[0] == L"backup" && f.size() == 4 && f[3].find(L"..") == wstring::npos && f[3].find_first_of(L"/:") == wstring::npos) { + backups.push_back({f[1], f[2], f[3]}); } else if (!m.legacy && f[0] == L"runtime" && f.size() == 3 && StartsWithI(f[2], L"wronggpu-") && f[2].find_first_of(L"\\/:") == wstring::npos) { m.runtime.push_back({f[1], f[2]}); } else if (!m.legacy) { @@ -138,6 +150,8 @@ bool LoadRecord(const wstring& path, Record& m) { } for (auto& o : owners) // owner lines name an action line by its action and path for (auto& e : m.e) if (e.owner.empty() && e.action == o[0] && IEq(e.rel, o[1])) { e.owner = o[2]; break; } + for (auto& o : backups) // backup lines too: the entry's backup under another name + for (auto& e : m.e) if (e.backup.empty() && e.action == o[0] && IEq(e.rel, o[1])) { e.backup = o[2]; break; } // rc6 L1: the record of a game folder that was moved names the old folder; read from \wronggpu-setup\install.record // it is the record of dir (its entries are relative to it, its backup is next to it): rebased to dir if (header && !m.game.empty() && !m.legacy && IEq(BaseName(path), L"install.record") && IEq(BaseName(Parent(path)), kStateDirName)) @@ -149,6 +163,7 @@ void SaveRecord(const wstring& path, const Record& m) { wstring t = L"WRONGGPU-RECORD 2\r\nversion\t" + m.version + L"\r\ngame\t" + m.game + L"\r\nexe\t" + m.exe + L"\r\nstatus\t" + m.status + L"\r\nregkey\t" + m.regkey + L"\r\nmodel\t" + m.model + L"\r\n"; if (!m.modelM.empty()) t += L"model-m\t" + m.modelM + L"\r\n"; + if (!m.installId.empty()) t += L"install-id\t" + m.installId + L"\r\n"; auto dash = [](const wstring& s) { return s.empty() ? wstring(L"-") : s; }; if (!m.payloadVersion.empty()) t += L"payload\t" + m.payloadVersion + L"\t" + dash(m.runtimeSha) + L"\t" + dash(m.frontEndSha) + L"\t" + dash(m.pluginSha) + @@ -171,6 +186,8 @@ void SaveRecord(const wstring& path, const Record& m) { t += e.action + L"\t" + (e.existed ? L"1" : L"0") + L"\t" + (e.orig.empty() ? L"-" : e.orig) + L"\t" + (e.inst.empty() ? L"-" : e.inst) + L"\t" + e.rel + L"\r\n"; for (auto& e : m.e) if (!e.owner.empty()) t += L"owner\t" + e.action + L"\t" + e.rel + L"\t" + e.owner + L"\r\n"; + for (auto& e : m.e) + if (!e.backup.empty()) t += L"backup\t" + e.action + L"\t" + e.rel + L"\t" + e.backup + L"\r\n"; string u = ToUtf8(t); EnsureDir(Parent(path)); WriteFileAtomic(path, u.data(), u.size()); @@ -409,10 +426,15 @@ static wstring LowerRel(wstring r) { static std::function StateOwned(const wstring& dir, const Record* m) { auto names = std::make_shared>(); for (const wchar_t* n : {L"install.record", L"uninstall.exe", L"setup.log", L"profile.ini"}) (*names)[n] = L""; + // #219: the game's state files (wg_state.h: settings chosen in the launcher or a WrongGPU menu in the game, the model choice + // record) are WrongGPU's only while they carry WrongGPU's stamp valid for THEIR OWN NAME and THIS INSTALL's id (the record's + // install-id; wg_state.h StampedByWrongGPU). An edited file, a copy under another name (a temporary file among them) or + // from another install, a file without the stamp: not WrongGPU's, it stays and is listed (below, in the returned test) + const string installId = m ? ToUtf8(m->installId) : string(); if (m) { const string json = OwnedFilesJson(*m); (*names)[L"owned-files.json"] = Sha256Bytes(json.data(), json.size()); - for (auto& e : m->e) if (e.action != L"dir" && !e.orig.empty()) (*names)[LowerRel(L"backup\\" + e.rel)] = Lower(e.orig); + for (auto& e : m->e) if (e.action != L"dir" && !e.orig.empty()) (*names)[LowerRel(L"backup\\" + (e.backup.empty() ? e.rel : e.backup))] = Lower(e.orig); } string raw; if (ReadAll(Join(Join(StateDir(dir), L"previous"), L"previous.txt"), raw)) { // the kept version: "file=|" lines @@ -428,8 +450,13 @@ static std::function StateOwned(const wstring (*names)[LowerRel(L"previous\\" + FromUtf8(line.substr(bar + 1)))] = Lower(FromUtf8(line.substr(5, bar - 5))); } } - return [names](const wstring& rel, PinnedFile& f) { - const auto it = names->find(LowerRel(rel)); + return [names, installId](const wstring& rel, PinnedFile& f) { + const wstring low = LowerRel(rel); + if (low == wgstate::kSettingsFile || low == wgstate::kModelChoiceFile) { + string bytes; // (read through the handle that holds the file until it is deleted) + return f.ReadBytes(bytes) && wgstate::StampedByWrongGPU(bytes, ToUtf8(low), installId); + } + const auto it = names->find(low); return it != names->end() && (it->second.empty() || IEq(f.Sha256(), it->second)); }; } @@ -537,6 +564,20 @@ void RestoreStep(const char* name) { if (g_restoreStepHook) g_restoreStepHook(name); #ifdef WRONGGPU_TESTING if (EnvVar(L"WRONGGPU_TEST_STOP_AT") == FromUtf8(name)) ExitProcess(99); // tests: the process stops here, as if killed + // tests: the operation fails here (as a failed write would), so its rollback runs + if (EnvVar(L"WRONGGPU_TEST_FAIL_AT") == FromUtf8(name)) Fail(L"Test failure at " + FromUtf8(name) + L" (WRONGGPU_TEST_FAIL_AT)"); + // tests: a file appears here (another program or the player creating it at this moment), where nothing is + if (EnvVar(L"WRONGGPU_TEST_CREATE_AT") == FromUtf8(name) && !EnvVar(L"WRONGGPU_TEST_CREATE_FILE").empty()) { + const wstring f = EnvVar(L"WRONGGPU_TEST_CREATE_FILE"); + EnsureDir(Parent(f)); + const HANDLE h = CreateFileW(f.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h != INVALID_HANDLE_VALUE) { + static const char kText[] = "; made by the player during the install (test)\r\n"; + DWORD w = 0; + WriteFile(h, kText, sizeof kText - 1, &w, nullptr); + CloseHandle(h); + } + } #endif } @@ -597,10 +638,116 @@ static bool Replaceable(const wstring& path) { return true; } +// A WrongGPU binary: what a game loads (DLLs and the OptiScaler plugins). +bool IsBinaryName(const wstring& rel) { return EndsWithI(rel, L".dll") || EndsWithI(rel, L".asi"); } + +// The binaries of an install the operation guard holds: every copy entry of WrongGPU's (owner wg / wg-optibundle) that is a +// binary, at its path in the game folder (whatever is there now: a file the guard cannot open refuses the operation). +static std::vector GuardedBinaries(const wstring& dir, const Record& m) { + std::vector r; + for (auto& e : m.e) + if (e.action == L"copy" && (e.owner == L"wg" || e.owner == L"wg-optibundle" || e.owner.empty()) && IsBinaryName(e.rel)) { + const wstring p = Target(dir, e.rel); + bool seen = false; // each file once: a second open of a held file would refuse the operation against its own hold + for (auto& q : r) seen = seen || IEq(FullPath(q), FullPath(p)); + if (!seen) r.push_back(p); + } + return r; +} + +static thread_local OperationGate* t_gate = nullptr; // the innermost gate of this thread +OperationGate::OperationGate(const wstring& d, const std::vector& binaries) : dir(d), guard(d, binaries), prev(t_gate) { t_gate = this; } +OperationGate::~OperationGate() { t_gate = prev; } + +#ifdef WRONGGPU_TESTING +// Test builds: which processes have a file open (Restart Manager), for the log when the gate refuses. +static wstring HoldersOf(const wstring& path) { + DWORD session = 0; + WCHAR key[CCH_RM_SESSION_KEY + 1] = {}; + if (RmStartSession(&session, 0, key) != ERROR_SUCCESS) return L"?"; + LPCWSTR files[] = {path.c_str()}; + wstring out; + if (RmRegisterResources(session, 1, files, 0, nullptr, 0, nullptr) == ERROR_SUCCESS) { + UINT needed = 0, n = 16; + RM_PROCESS_INFO info[16]; + DWORD reasons = 0; + if (RmGetList(session, &needed, &n, info, &reasons) == ERROR_SUCCESS) + for (UINT i = 0; i < n; ++i) + out += L" pid " + std::to_wstring(info[i].Process.dwProcessId) + (info[i].Process.dwProcessId == GetCurrentProcessId() ? L" (this process)" : L"") + + L" " + info[i].strAppName + L";"; + } + RmEndSession(session); + return out.empty() ? L" none listed" : out; +} +#endif + +std::unique_ptr GuardOperation(const wstring& dir, const Record* m, bool holdBinaries) { + if (t_gate && IEq(FullPath(t_gate->dir), FullPath(dir))) return nullptr; // this thread's operation holds the gate already + Record loaded; + if (!m && LoadRecord(RecordPath(dir), loaded) && !loaded.legacy) m = &loaded; + auto gate = std::make_unique(dir, m && holdBinaries ? GuardedBinaries(dir, *m) : std::vector{}); + if (!gate->guard.ok()) { + wstring which = gate->guard.which().empty() ? wstring() : L" (" + BaseName(gate->guard.which()) + L")"; +#ifdef WRONGGPU_TESTING + if (!gate->guard.which().empty()) which += L" [test build, holders:" + HoldersOf(gate->guard.which()) + L"]"; +#endif + Fail(L"Nothing was changed: " + FromUtf8(gate->guard.words()) + which + L".", EXIT_REFUSED); + } + return gate; +} + +bool GateHolds(const wstring& path) { return t_gate && t_gate->guard.Holds(path); } + +// A binary written (or replaced) by the operation: through the gate (PutHeld: renamed in complete, then held) when this thread +// holds one, else plainly. Throws on failure; a load in the gap (sharing violation) stops the operation. +static void FailPut(const wstring& path, DWORD e) { + if (e == ERROR_SHARING_VIOLATION) + Fail(L"Stopped: " + FromUtf8(wgstate::GuardWords(wgstate::GuardResult::GameRunning)) + L" (" + BaseName(path) + + L"). What was done so far stays recorded; run it again once the game is closed.", EXIT_REFUSED); + Fail(L"Cannot write " + path + L": " + ErrText(e)); +} +// A file at the path that the gate does not hold (one the install decided to replace that the record did not list, such as +// an earlier copy in REFramework's mirror): opened as the gate opens its binaries (a program that has it loaded, or open +// without sharing writes, stops the operation) and deleted through that handle, so the new file can be renamed in and held. +static DWORD FreeUnheld(const wstring& path) { + if (GateHolds(path) || !Exists(path)) return ERROR_SUCCESS; + const HANDLE h = CreateFileW(wgstate::ExtendedPath(path).c_str(), DELETE | GENERIC_READ | FILE_WRITE_DATA, FILE_SHARE_READ, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return GetLastError(); + FILE_DISPOSITION_INFO_EX d{}; + d.Flags = FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS; + const DWORD e = SetFileInformationByHandle(h, FileDispositionInfoEx, &d, sizeof d) ? ERROR_SUCCESS : GetLastError(); + CloseHandle(h); + return e; +} +void PutBinary(const wstring& path, const void* data, size_t size) { + if (!t_gate) { WriteFileAtomic(path, data, size); return; } + EnsureDir(Parent(path)); + if (const DWORD fe = FreeUnheld(path)) FailPut(path, fe); + std::wstring oldLeft; + const DWORD e = t_gate->guard.PutHeld(path, data, size, &oldLeft); + if (e == ERROR_SUCCESS && !oldLeft.empty()) t_gate->oldLeft.push_back(oldLeft); + if (e == ERROR_SUCCESS) return; + FailPut(path, e); +} +void PutBinaryFrom(const wstring& path, const wstring& source) { + if (!t_gate) { CopyChecked(source, path); return; } + EnsureDir(Parent(path)); + if (const DWORD fe = FreeUnheld(path)) FailPut(path, fe); + std::wstring oldLeft; + const DWORD e = t_gate->guard.PutHeldFrom(path, source, &oldLeft); + if (e == ERROR_SUCCESS && !oldLeft.empty()) t_gate->oldLeft.push_back(oldLeft); + if (e == ERROR_SUCCESS) return; + FailPut(path, e); +} +DWORD DeleteHeldBinary(const wstring& path) { return t_gate ? t_gate->guard.DeleteHeld(path) : ERROR_NOT_FOUND; } std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool failedInstall, bool keepState, std::map* keptWarnings) { Record m; if (!LoadRecord(RecordPath(dir), m) || m.legacy) Fail(L"No WrongGPU installation record was found in " + dir + L".", EXIT_NOT_INSTALLED); if (!IEq(m.game, dir)) Fail(L"The installation record belongs to a different folder: " + m.game); + // #219: never while a running program has WrongGPU loaded (wg_state.h, the loaded protocol: the state lock is held for the + // whole restore, so no game registers in between; a failed install's own restore runs under its install's guard) + const auto gate = failedInstall ? nullptr : GuardOperation(dir, &m); std::vector warnings; int total = (int)m.e.size() + 2, done = 0; @@ -609,7 +756,9 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa struct Plan { Do what = Do::Nothing; wstring now, source; bool keep = false; }; // now: the hash the decision was made on std::vector plan(m.e.size()); auto leaveWarning = [&](const Entry& e, const wstring& t, const wstring& keptAt, bool linked = false) { - const Fingerprint fp = e.action == L"copy" && !IsSlotName(e.rel) ? IdentifyFile(t) : Fingerprint(); + // (not WrongGPU's settings files: the headers WrongGPU writes in WrongGPU\wronggpu.ini and wronggpu-asi.ini name OptiScaler) + const bool settingsFile = IsRrSettingsFile(e.rel) || IEq(BaseName(e.rel), L"wronggpu-asi.ini"); + const Fingerprint fp = e.action == L"copy" && !IsSlotName(e.rel) && !settingsFile ? IdentifyFile(t) : Fingerprint(); wstring w; if (linked) w = L"Left in place (the file has another name, a hard link; writing through it would change that name too): " + e.rel; else if (e.action == L"copy" && IsSlotName(e.rel)) w = L"The game replaced " + e.rel + L" (probably an update); its new file was kept."; @@ -626,7 +775,7 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa const Entry& e = m.e[i]; Plan& p = plan[i]; if (e.action == L"dir") continue; - const wstring t = Target(dir, e.rel), b = BackupPath(dir, e.rel); + const wstring t = Target(dir, e.rel), b = EntryBackupPath(dir, e); // the player's original: the backup, or (a game FSR DLL) its renamed copy beside WrongGPU's const bool hasOriginal = e.existed || e.action == L"disable"; if (hasOriginal) { @@ -656,7 +805,7 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa case Holds::Original: p.what = Do::Nothing; break; case Holds::Other: p.what = Do::Leave; p.keep = hasOriginal; break; } - if ((p.what == Do::Remove || p.what == Do::PutBack) && Exists(t) && !Replaceable(t)) + if ((p.what == Do::Remove || p.what == Do::PutBack) && Exists(t) && !GateHolds(t) && !Replaceable(t)) // (a held binary: the gate changes it) Fail(L"Cannot change " + e.rel + L": another program has it open (the game?). Close it and try again. Nothing was changed.", EXIT_REFUSED); } } else { @@ -667,7 +816,7 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa const Entry& e = m.e[i]; Plan& p = plan[i]; if (e.action == L"dir" || e.action == L"rename") continue; - p.source = BackupPath(dir, e.rel); + p.source = EntryBackupPath(dir, e); if (e.action == L"copy" && e.owner == L"adopted") continue; const bool hasOriginal = e.action == L"disable" || e.existed; const wstring t = Target(dir, e.rel); @@ -715,7 +864,15 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa // below keeps the game's file). A name that is empty (a stop between the two steps, or the DLL removed) gets it. PinnedFile held; DWORD err = 0; - if (held.Open(slot, false, &err)) { + if (GateHolds(slot)) { // #219: WrongGPU's DLL in the slot is held by the operation's gate: deleted through it + if (ClassifySlot(*sl, slot, nullptr, info) == FFX_OURS) { + const DWORD de = DeleteHeldBinary(slot); + if (de != ERROR_SUCCESS) Fail(L"Cannot put " + wstring(sl->name) + L" back: " + ErrText(de)); + if (MoveFileExW(t.c_str(), slot.c_str(), MOVEFILE_WRITE_THROUGH)) ui.log(L"restored " + wstring(sl->name) + L" from " + e.rel); + else if (GetLastError() != ERROR_ALREADY_EXISTS && GetLastError() != ERROR_FILE_EXISTS) + Fail(L"Cannot put " + wstring(sl->name) + L" back: " + ErrText(GetLastError())); + } + } else if (held.Open(slot, false, &err)) { if (ClassifySlot(*sl, slot, nullptr, info) == FFX_OURS) { RestoreStep("locked"); if (!held.Delete(&err)) Fail(L"Cannot put " + wstring(sl->name) + L" back: " + ErrText(err)); @@ -765,6 +922,27 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa Fail(L"Cannot change " + e.rel + L": another program has it open (the game?). Close it and try again.", EXIT_REFUSED); Fail(L"Cannot change " + e.rel + L": " + ErrText(err)); }; + if (GateHolds(t)) { // #219: a binary the operation's gate holds (nothing could change it since the plan hashed it) + RestoreStep("locked"); // (held and checked: the tests try to change it here, and cannot) + if (p.what == Do::Remove) { + const DWORD de = DeleteHeldBinary(t); + if (de != ERROR_SUCCESS) Fail(L"Cannot delete " + t + L": " + ErrText(de)); + ui.log(L"removed " + e.rel); + } else { // PutBack: WrongGPU's file deleted through its handle, then the original copied in, only if the name is free; + // the original is the game's or the player's file, so the gate does not hold it (a later step of the same + // operation, such as the install of a repair, may rename it); a failed copy leaves the backup for another run + if (failedInstall && !Exists(p.source)) continue; + const DWORD de = DeleteHeldBinary(t); + if (de != ERROR_SUCCESS) Fail(L"Cannot delete " + t + L": " + ErrText(de)); + if (!CopyFileW(p.source.c_str(), t.c_str(), TRUE)) { + const DWORD ce = GetLastError(); + Fail(L"Cannot put back " + t + L": " + ErrText(ce) + L" Its original is kept in " + p.source + L"; run the uninstall again."); + } + if (!failedInstall && !IEq(Sha256File(t), e.orig)) Fail(L"Restore verification failed for " + e.rel); + ui.log(L"restored " + e.rel); + } + continue; + } PinnedFile held; DWORD err = 0; const bool opened = held.Open(t, p.what == Do::PutBack, &err); @@ -913,7 +1091,8 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa } static bool SettingsName(const wstring& name, bool folder) { - return folder ? IEq(name, L"previous") || IEq(name, L"rr-config") : IEq(name, L"profile.ini"); + return folder ? IEq(name, L"previous") || IEq(name, L"rr-config") + : IEq(name, L"profile.ini") || IEq(name, wgstate::kSettingsFile) || IEq(name, wgstate::kModelChoiceFile); // (#219: the state files) } bool StateHasSettings(const wstring& dir) { const wstring state = StateDir(dir); @@ -921,12 +1100,63 @@ bool StateHasSettings(const wstring& dir) { for (auto& d : ListDirs(state)) if (SettingsName(BaseName(d), true)) return true; return false; } -void RemoveStateKeepingSettings(const wstring& dir) { - const wstring state = StateDir(dir); - for (auto& f : ListFiles(state, L"*")) // never throws (a destructor calls it) - if (!SettingsName(BaseName(f), false)) { SetFileAttributesW(f.c_str(), FILE_ATTRIBUTE_NORMAL); DeleteFileW(f.c_str()); } - for (auto& d : ListDirs(state)) if (!SettingsName(BaseName(d), true)) RemoveTree(d); - RemoveDirectoryW(state.c_str()); // only when empty +wstring CopyBackup(Context& ctx, const wstring& dir, Entry& e, const wstring& source, RunJournal* j, std::vector* warnings) { + for (int n = 0; n < 100; ++n) { + const wstring name = n == 0 ? e.rel : e.rel + L"." + std::to_wstring(n); + const wstring b = BackupPath(dir, name); + if (Exists(b)) continue; // something is there that this install did not make: never overwritten + const size_t mark = j ? j->created.size() : 0; + if (j) JournalCreate(*j, b, false); + EnsureDir(Parent(b)); + DWORD err = 0; + if (!CopyNew(source, b, &err)) { + if (j && j->created.size() > mark && j->created.back().first == b) j->created.pop_back(); // (not this run's: not created) + if (err == ERROR_FILE_EXISTS || err == ERROR_ALREADY_EXISTS) continue; // it appeared a moment ago: the next name + Fail(L"Cannot copy " + source + L" to " + b + L": " + ErrText(err)); + } + if (Sha256File(b) != e.orig) Fail(L"Backup verification failed for " + e.rel); + e.backup = n == 0 ? wstring() : name; + if (n) { + const wstring w = L"Left in place (not this install's; an earlier uninstall kept it): " + Join(Join(kStateDirName, L"backup"), e.rel) + + L"; this install's backup of " + e.rel + L" is " + Join(Join(kStateDirName, L"backup"), name); + LogLine(ctx, w); + if (warnings) warnings->push_back(w); + } + return b; + } + Fail(L"No free name for the backup of " + e.rel + L" in " + Join(StateDir(dir), L"backup")); +} +wstring NewInstallId() { + std::random_device rd; // (the CRT's system random source) + wchar_t buf[33] = {}; + for (int i = 0; i < 4; ++i) swprintf(buf + i * 8, 9, L"%08x", static_cast(rd())); + return buf; +} +void JournalCreate(RunJournal& j, const wstring& path, bool folder) { + if (Exists(path)) return; // there before this run: never this run's + const wstring up = Parent(path); + if (!up.empty() && up != path && !Exists(up)) JournalCreate(j, up, true); + j.created.push_back({path, folder}); +} +std::vector RollbackCreated(Context& ctx, const wstring& state, RunJournal& j) { + std::vector left; + try { + for (auto it = j.created.rbegin(); it != j.created.rend(); ++it) { + if (it->second) RemoveDirectoryW(it->first.c_str()); // (only when empty: anything else in it stays) + else if (IsFile(it->first)) { SetFileAttributesW(it->first.c_str(), FILE_ATTRIBUTE_NORMAL); DeleteFileW(it->first.c_str()); } + } + j.created.clear(); + j.done = true; + std::vector stack{state}; + while (!stack.empty()) { + const wstring d = stack.back(); + stack.pop_back(); + for (auto& f : ListFiles(d, L"*")) left.push_back(f.substr(state.size() + 1)); + for (auto& s : ListDirs(d)) stack.push_back(s); + } + for (auto& f : left) LogLine(ctx, L"kept " + Join(state, f) + L" (not made by this run: the rollback takes back only what it made)"); + } catch (...) {} + return left; } // Byte-exact removal of a WrongGPU 0.1.x/0.2.x ("DLSS 4.5 AMD") install from its own record and backup: the same @@ -1132,7 +1362,11 @@ bool UpgradeRecord(Context& ctx, const wstring& dir, std::vector* notes Record m; if (!LoadRecord(RecordPath(dir), m) || m.legacy) return false; if (m.format >= 2) return false; - CopyChecked(RecordPath(dir), RecordPath(dir) + L".v1"); + { // the 0.5.x record kept beside it, created only where nothing is (a file an earlier uninstall kept there stays) + bool kept = false; + for (int n = 0; n < 100 && !kept; ++n) kept = CopyNew(RecordPath(dir), RecordPath(dir) + L".v1" + (n ? L"." + std::to_wstring(n) : wstring())); + if (!kept) Fail(L"Cannot keep a copy of the earlier record " + RecordPath(dir)); + } InferOwners(ctx, m); if (m.payloadVersion.empty()) { // what the 0.5.x install wrote: its version, the hashes from its own entries m.payloadVersion = m.version; diff --git a/clean/installer/src/wg_core/record.h b/clean/installer/src/wg_core/record.h index b8bff4da..17143d21 100644 --- a/clean/installer/src/wg_core/record.h +++ b/clean/installer/src/wg_core/record.h @@ -2,8 +2,10 @@ // WrongGPU launcher core: the install record (v1), the "Apps & features" entry and the restore / uninstall engine. // Written for this project. #pragma once +#include #include "context.h" #include "optikeys.h" +#include "../../../wgshared/include/wg_state.h" // the game's state folder, its lock and the loaded protocol (#219) namespace wg { @@ -43,7 +45,9 @@ namespace wg { // renamed aside and put back byte for byte). Action lines keep their five fields, so a 0.5.x uninstaller still reads a // v2 record (it skips the lines it does not know). Lines of a later version are kept as they are. // ------------------------------------------------------------------------------------------------ -struct Entry { wstring action, rel; bool existed = false; wstring orig, inst, owner; }; +// backup: the entry's backup below wronggpu-setup\backup when it is not `rel` (a file that an earlier uninstall kept was at +// that name: the new backup went to .; the record's "backup" line). Empty: backup\. +struct Entry { wstring action, rel; bool existed = false; wstring orig, inst, owner, backup; }; // The rrconfig line (rrconfig.h): what "Fix it for me" did to the game's Engine.ini, so that =off and the uninstall undo it. struct RrConfigFix { bool present = false; @@ -60,6 +64,7 @@ struct RrConfigFix { inline const wchar_t* const kRuntimeGameRoot = L""; struct Record { wstring version, game, exe, status, regkey, model, modelM; + wstring installId; // this install's id (32 hex digits; kept by repair and update): WrongGPU's stamp on its state files names it std::vector e; bool legacy = false; int format = 1; // 1: 0.5.x setup, 2: the launcher @@ -105,6 +110,14 @@ void RemoveManagedGame(const wstring& dir); wstring StateDir(const wstring& dir); wstring RecordPath(const wstring& dir); wstring BackupPath(const wstring& dir, const wstring& rel); +// The entry's backup file (its recorded name, else backup\). +wstring EntryBackupPath(const wstring& dir, const Entry& e); +struct RunJournal; +// The backup of `source` for entry e, created ONLY where nothing is (CopyFileW fail-if-exists): backup\, or, when a file +// is there already (one an earlier uninstall kept: never overwritten), the first free backup\., which goes into +// e.backup (and so into the record). The kept file stays; it is logged and (warnings) listed. Checked against e.orig. +// j: the run journal (each create written down before it). Returns the backup's path. +wstring CopyBackup(Context& ctx, const wstring& dir, Entry& e, const wstring& source, RunJournal* j, std::vector* warnings); wstring LegacyStateDir(const wstring& dir); wstring LegacyRecordPath(const wstring& dir); wstring LegacyBackupPath(const wstring& dir, const wstring& rel); @@ -151,11 +164,13 @@ bool OptiIniWrittenByUs(const wstring& dir, const Record& m); // with its hash, or the ini is the one WrongGPU last wrote. Used only to decide what the scan reports and asks about (the // switch question) and which menu-saved values carry over; never to delete or overwrite a file. bool OptiSetupIsOurs(const wstring& dir, const Record& m); -// Test hook: called at the named steps of DoRestore ("restored", "kept", "record-removed"), of the rollback ("rollback-absent": +// Test hook: called at the named steps of DoRestore ("restored", "kept", "record-removed"), of the install ("seed-planned": the +// seed files checked absent, the record not yet made; "seed-recorded": the record written, the seeds not yet), of the rollback ("rollback-absent": // about to create the missing payload files; "rollback-held": every payload file held and checked) and of the Engine.ini restore ("rrconfig-held": Engine.ini held and read; // "rrconfig-absent": about to create it; "rrconfig-replace": the corrected copy written, the handle closed, about to replace // it); a test stops the operation there (as a killed process would) or tries to change -// the file. Test builds also stop the process at the step named by WRONGGPU_TEST_STOP_AT. +// the file. Test builds also stop the process at the step named by WRONGGPU_TEST_STOP_AT, and create the file +// WRONGGPU_TEST_CREATE_FILE (where nothing is) at the step named by WRONGGPU_TEST_CREATE_AT. void SetRestoreStepHook(std::function hook); void RestoreStep(const char* name); // calls the hook (above) // Test seam: a write fault at a named step ("rollback-write": before each payload file Roll back writes; "rrconfig-write": the @@ -218,7 +233,8 @@ wstring StartCleanup(Context& ctx, const wstring& state, const wstring& self, co // when it is WrongGPU's and, where a hash is known, its bytes are those: the backups the record lists (the entry's hash), the // previous version's files that previous.txt lists with their hashes, owned-files.json (the bytes WrongGPU makes of the record). // The record, previous.txt, uninstall.exe, setup.log and profile.ini carry no recorded hash and go by their fixed names (stated -// in the README). Anything else, or a listed file whose bytes changed, stays with the folder and the result lists it +// in the README). settings.ini, model-choice.ini and their .wgtmp-* files go only while they carry WrongGPU's valid +// stamp (wg_state.h StampedByWrongGPU). Anything else, or a listed file whose bytes changed, stays with the folder and the result lists it // (kLeftUnrecorded); only a folder that holds nothing else is removed. // RemoveStateFolder: the state folder of `dir` (relocation: the restore has removed the backup); m: the record the install had // (the hashes of its backups and of owned-files.json come from it; without it those two are left). keepFile: the running uninstaller. Returns what stays, below the folder. @@ -234,12 +250,47 @@ wstring LeftText(const wstring& where, const std::vector& rels); // path or in the kept folder. keepState (update, repair, a move): the state folder stays (record and backup cleared). // keptWarnings: the warning of each recorded file left in place, by its path (the update path replaces the warning of a // file it then moves aside with the player's OK). +// #219: the gate of an uninstall, repair, update, roll back or move of the install in `dir` (wg_state.h OperationGuard): the +// game's state lock, then every WrongGPU binary of the install (the record's copy entries of WrongGPU's that are .dll / .asi) +// held with write access, so Windows itself says whether a process has one loaded, and no game can load one while the +// operation runs. Keep the returned gate for the whole operation, on the thread that took it; a nested GuardOperation for the +// same folder on the same thread returns nullptr (the outer gate covers it). Refuses (EXIT_REFUSED, "Nothing was changed: +// ...", naming the file) while a binary is in use by the game or another program, while that cannot be told, and while +// another WrongGPU program holds the lock or it may not be opened. Inside it, the operation writes binaries with PutBinary / +// PutBinaryFrom (renamed in complete and held at once; a load in that moment stops the operation) and deletes held ones with +// DeleteHeldBinary; GateHolds tells which files the gate holds (their reads still work; their writes go through the gate). +// The state files (settings.ini, model-choice.ini) are written inside the same hold (the state lock is recursive per thread). +struct OperationGate { + OperationGate(const wstring& dir, const std::vector& binaries); + ~OperationGate(); + OperationGate(const OperationGate&) = delete; + OperationGate& operator=(const OperationGate&) = delete; + wstring dir; + wgstate::OperationGuard guard; + OperationGate* prev; + std::vector oldLeft; // old binaries a replace could not delete (each stays under its .wronggpu-old name) +}; +// holdBinaries false: the state lock only, for an operation that holds every file it changes itself with write access (Roll +// back, PinnedFile: a loaded file refuses that open, and a held file cannot be loaded), the same guarantee. +std::unique_ptr GuardOperation(const wstring& dir, const Record* m, bool holdBinaries = true); +bool IsBinaryName(const wstring& rel); // .dll / .asi: what a game loads +bool GateHolds(const wstring& path); +void PutBinary(const wstring& path, const void* data, size_t size); +void PutBinaryFrom(const wstring& path, const wstring& source); +DWORD DeleteHeldBinary(const wstring& path); // ERROR_SUCCESS, ERROR_NOT_FOUND (not held), or the delete's error std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool failedInstall, bool keepState, std::map* keptWarnings = nullptr); // rc6 L4: the player's things in the state folder that a failed install or update never removes when they were there before -// it: profile.ini (the game's settings), previous\ (the version Roll back goes to) and rr-config\ (the Engine.ini fix's backup). +// it: profile.ini (the game's settings), previous\ (the version Roll back goes to) and rr-config\ (the Engine.ini fix's backup); +// since 0.6.5 also the state files settings.ini and model-choice.ini (wg_state.h). bool StateHasSettings(const wstring& dir); -// The state folder emptied of everything else (the record, the backup, the uninstaller, logs); removed when nothing is left. -void RemoveStateKeepingSettings(const wstring& dir); +// A new install id (32 lower-case hex digits, from the system's random source). +wstring NewInstallId(); +// What an install run creates, written down BEFORE each create (a file or a folder that was not there), so a failed run takes +// back only what it made: RollbackCreated deletes those files (newest first) and removes those folders when empty. Everything +// else stays: it is logged and returned (paths relative to `state`). Never throws (a destructor calls it). +struct RunJournal { std::vector> created; bool done = false; }; // (path, is a folder); done: rolled back +void JournalCreate(RunJournal& j, const wstring& path, bool folder); // only when nothing is at path; parents first +std::vector RollbackCreated(Context& ctx, const wstring& state, RunJournal& j); std::vector LegacyRestore(Context& ctx, const wstring& dir, Ui& ui); } // namespace wg diff --git a/clean/installer/src/wg_core/rr.cpp b/clean/installer/src/wg_core/rr.cpp index a7d4d550..7699aba5 100644 --- a/clean/installer/src/wg_core/rr.cpp +++ b/clean/installer/src/wg_core/rr.cpp @@ -12,6 +12,7 @@ #include "payload.h" #include "pe.h" #include "settings.h" +#include "../../../wgshared/include/wg_state.h" // the game's state folder: settings.ini, the state lock, atomic writes namespace wg { @@ -472,7 +473,9 @@ RrFileState ParseRrSettings(const string& text) { RrFileState s; s.present = true; string sec; - for (size_t a = 0; a < text.size();) { + // a UTF-8 BOM before the first line (a 0.6.0 file saved by an editor; the plugin's reader skips it too) + const size_t from = text.size() >= 3 && (unsigned char)text[0] == 0xEF && (unsigned char)text[1] == 0xBB && (unsigned char)text[2] == 0xBF ? 3 : 0; + for (size_t a = from; a < text.size();) { size_t e = text.find('\n', a); if (e == string::npos) e = text.size(); const string t = TrimA(text.substr(a, e - a)); @@ -490,8 +493,89 @@ RrFileState ParseRrSettings(const string& text) { } RrFileState ReadRrSettings(const wstring& dir) { string text; - if (!ReadAll(Join(dir, kRrSettings), text)) return RrFileState(); - return ParseRrSettings(text); + RrFileState s; + if (ReadAll(Join(dir, kRrSettings), text)) s = ParseRrSettings(text); + const wgstate::Settings st = wgstate::ReadSettings(dir); // the state folder's keys over the install's defaults + if (const string* v = wgstate::Get(st, "rr_enabled")) { s.present = true; s.enabled = !(*v == "0" || *v == "off" || *v == "false"); } + if (const string* v = wgstate::Get(st, "rr_mode"); v && (*v == "exact" || *v == "accurate" || *v == "fast")) { s.present = true; s.mode = *v; } + return s; +} + +std::vector> RrStateKeys(const Profile& p, bool dataReady) { + const string mode = p.get("rr_mode").empty() ? string("fast") : p.get("rr_mode"); + return {{"rr_enabled", p.get("rr_enabled") != "off" && dataReady ? "1" : "0"}, {"rr_mode", mode}, {"rr_exact_allowed", mode == "exact" ? "1" : "0"}}; +} + +// (the launcher's state writes, rr.h WriteStateKeys): 1 written, 0 nothing differed, -1 not saved (in words) +static int StateWriteResult(Context& ctx, const wstring& dir, const wgstate::SetOutcome& o, wstring* why) { + if (o.ok()) return o.written ? 1 : 0; + // every failure in words, the access-denied ones with the elevated repair (wg_state.h SetOutcome::words) + const wstring w = L"the game's WrongGPU settings (" + Join(Join(dir, wgstate::kStateFolder), wgstate::kSettingsFile) + L") were not saved: " + + FromUtf8(o.words()); + LogLine(ctx, w); + if (why) *why = w; + return -1; +} +int WriteStateKeys(Context& ctx, const wstring& dir, const std::vector>& keys, wstring* why) { + // the comparison and the write both under the state lock (wg_state.h UpdateSettings): only keys that differ now are written + return StateWriteResult(ctx, dir, wgstate::SetSettings(dir, keys, wgstate::kDefaultWaitMs), why); +} + +int WriteRrState(Context& ctx, const wstring& dir, const Profile& p, bool dataReady, wstring* why, const string* prevMode) { + const string want = p.get("rr_mode").empty() ? string("fast") : p.get("rr_mode"); + const string enabled = p.get("rr_enabled") != "off" && dataReady ? "1" : "0"; + // decided under the state lock from the file as it is now (wg_state.h UpdateSettings), so a mode the game's menu saved + // after the launcher read the settings is never replaced by the launcher's older view: the mode is written only when the + // file has none, or when the launcher's own choice changed (prevMode: the profile's mode before this apply; none: a + // refresh, which never changes a saved mode). rr_exact_allowed follows the mode that stays. + const wgstate::SetOutcome o = wgstate::UpdateSettings(dir, [&](const wgstate::Settings& now, std::vector>* out) { + const string* cur = wgstate::Get(now, "rr_mode"); + const bool curValid = cur && (*cur == "exact" || *cur == "accurate" || *cur == "fast"); + const bool writeMode = !curValid || (prevMode && want != *prevMode); + const string mode = writeMode ? want : *cur; + out->push_back({"rr_enabled", enabled}); + if (writeMode) out->push_back({"rr_mode", mode}); + out->push_back({"rr_exact_allowed", mode == "exact" ? "1" : "0"}); + }, wgstate::kDefaultWaitMs); + return StateWriteResult(ctx, dir, o, why); +} + +bool MigrateRrState(Context& ctx, const wstring& dir) { + Record m; + if (!LoadRecord(RecordPath(dir), m) || m.legacy || !RecordHasRr(m)) return false; + if (wgstate::Get(wgstate::ReadSettings(dir), "rr_mode")) return false; // the state folder has the mode already + const Entry* e = nullptr; + for (auto& x : m.e) if (x.action == L"copy" && IEq(x.rel, kRrSettings)) e = &x; + string text; + if (!e || e->inst.empty() || !ReadAll(Join(dir, kRrSettings), text)) return false; + if (IEq(Sha256Bytes(text.data(), text.size()), e->inst)) return false; // WrongGPU's own file, unchanged: nothing to carry + // changed since the launcher last wrote it (an older RR plugin's save, or the player's edit): the player's file from now on; + // its mode carries over into the state folder so nothing changes in the game + std::vector> keys; + const RrFileState s = ParseRrSettings(text); + if (!s.mode.empty()) keys.push_back({"rr_mode", s.mode}); + string sec; + const size_t bom = text.size() >= 3 && (unsigned char)text[0] == 0xEF && (unsigned char)text[1] == 0xBB && (unsigned char)text[2] == 0xBF ? 3 : 0; + for (size_t a = bom; a < text.size();) { // rr_overlay too, when the file has one ([wronggpu], a plain value; after a BOM) + size_t n = text.find('\n', a); + if (n == string::npos) n = text.size(); + const string t = TrimA(text.substr(a, n - a)); + a = n + 1; + if (!t.empty() && t[0] == '[') { sec = LowerA(t); continue; } + const size_t eq = t.find('='); + if (sec == "[wronggpu]" && eq != string::npos && LowerA(TrimA(t.substr(0, eq))) == "rr_overlay" && wgstate::ValidValue(TrimA(t.substr(eq + 1)))) + keys.push_back({"rr_overlay", TrimA(t.substr(eq + 1))}); + } + if (keys.empty()) return false; + wstring why; + // under the state lock: only while the state folder still has no mode (a save in between wins) + const wgstate::SetOutcome o = wgstate::UpdateSettings(dir, [&](const wgstate::Settings& now, std::vector>* out) { + if (!wgstate::Get(now, "rr_mode")) *out = keys; + }, wgstate::kDefaultWaitMs); + if (StateWriteResult(ctx, dir, o, &why) <= 0) return false; + LogLine(ctx, wstring(kRrSettings) + L" was changed since the install (an older RR plugin or the player): it is the player's file now; its mode was " + L"copied into " + Join(wgstate::kStateFolder, wgstate::kSettingsFile)); + return true; } string RenderRrSettings(const Profile& p, bool dataReady, const string& in) { @@ -520,24 +604,12 @@ bool FoldRrFromGame(const wstring& dir, Profile& p) { int RefreshRrSettings(Context& ctx, const wstring& dir, bool dataReady, wstring* why) { Record m; if (!LoadRecord(RecordPath(dir), m) || m.legacy || !RecordHasRr(m)) return 0; + MigrateRrState(ctx, dir); Profile p = GameProfile(dir); - string in; - ReadAll(Join(dir, kRrSettings), in); - const string out = RenderRrSettings(p, dataReady, in); - if (out == in) return 0; - try { // the file and the record that follows it (a protected folder refuses both: the caller elevates) - WriteFileAtomic(Join(dir, kRrSettings), out.data(), out.size()); - const wstring h = Sha256Bytes(out.data(), out.size()); - for (auto& e : m.e) if (e.action == L"copy" && IEq(e.rel, kRrSettings)) e.inst = h; - SaveRecord(RecordPath(dir), m); - WriteOwnedFiles(dir, m); - } catch (const SetupError& e) { - LogLine(ctx, L"RR settings of " + dir + L" not written: " + e.msg); - if (why) *why = e.msg; - return -1; - } - LogLine(ctx, L"RR settings of " + dir + L" written for the Ray Reconstruction data's state"); - return 1; + FoldRrFromGame(dir, p); // (the mode last chosen in the game stays) + const int r = WriteRrState(ctx, dir, p, dataReady, why); // the state folder only: WrongGPU\wronggpu.ini is never rewritten + if (r > 0) LogLine(ctx, L"RR settings of " + dir + L" written for the Ray Reconstruction data's state"); + return r; } std::vector RefreshAllRrSettings(Context& ctx, const wstring& except) { diff --git a/clean/installer/src/wg_core/rr.h b/clean/installer/src/wg_core/rr.h index 30145970..ae1db764 100644 --- a/clean/installer/src/wg_core/rr.h +++ b/clean/installer/src/wg_core/rr.h @@ -4,9 +4,10 @@ // RR model file), or is one of the few games known to call it directly. For those games a WrongGPU install also places // the RR files of this build: WrongGPU's RR plugin (an .asi OptiScaler loads from its plugins folder, beside WrongGPU's // own plugin), the RR runtime next to the game exe, wronggpu-rr.ini (rr_model: the RR data) and the plugin's settings -// file WrongGPU\wronggpu.ini ([wronggpu] rr_enabled, rr_mode, rr_exact_allowed; the plugin saves rr_mode there when the -// player switches it in OptiScaler's menu). Every one is an entry of the install record (staging, rollback, uninstall -// byte for byte); the two settings files go at uninstall even after the plugin rewrote them. +// file WrongGPU\wronggpu.ini ([wronggpu] rr_enabled, rr_mode, rr_exact_allowed: the install's defaults; the plugin saves +// the rr_mode the player switches to in OptiScaler's menu in the state folder). Every one is an entry of the install record (staging, rollback, uninstall +// byte for byte). Since 0.6.5 (#219) neither the launcher nor the plugin rewrites WrongGPU\wronggpu.ini after the install: +// later changes go into the state folder's settings.ini (see "settings" below), which an uninstall removes with the folder. // The RR data (preset F) is converted once per PC from the player's own RR model file with WrongGPU's converter, as the // model data is (model.h), into %LOCALAPPDATA%\WrongGPU\model\F\model.wgcm: shared by every game (a game whose own file is // too old uses it too). The file is never copied or changed, and never downloaded or shipped. Written for this project. @@ -124,20 +125,44 @@ bool ConvertRrData(Context& ctx, const wstring& dll, const std::vector\wronggpu-setup\settings.ini (clean/wgshared/include/wg_state.h: the state lock and atomic writes shared +// with the plugin and the model choice record), whose keys take precedence over wronggpu.ini's [wronggpu] keys. +// The RR keys there: rr_enabled (1/0), rr_mode (exact/accurate/fast), rr_exact_allowed (1/0). +// +// WrongGPU\wronggpu.ini as an install writes it from the profile (rr_enabled, rr_mode; rr_exact_allowed = 1 only while the +// mode is exact: the plugin runs Exact only with it). RR stays off (rr_enabled=0) while the RR data is not ready, whatever +// the profile says; other lines and keys of `in` stay as they are. string RenderRrSettings(const Profile& p, bool dataReady, const string& in); string RrIniText(const wstring& dataFile); // wronggpu-rr.ini as an install writes it struct RrFileState { bool present = false, enabled = true; string mode; }; RrFileState ParseRrSettings(const string& text); +// The settings in effect: WrongGPU\wronggpu.ini's [wronggpu] keys, then the state folder's settings.ini over them. RrFileState ReadRrSettings(const wstring& dir); -// The mode the player chose in the game (OptiScaler's menu saves it into WrongGPU\wronggpu.ini) becomes the profile's: +// The launcher's write of `keys` into the game's settings.ini (wg_state.h SetSettings: compared and written under the state +// lock). 1: written; 0: the file had these values already; -1: refused (*why in words, logged: no state folder, the lock kept +// by another WrongGPU program, the file unreadable, not text WrongGPU can keep (never replaced), or not written). +int WriteStateKeys(Context& ctx, const wstring& dir, const std::vector>& keys, wstring* why = nullptr); +// The state keys a launcher write puts in settings.ini for the profile and the RR data's state. +std::vector> RrStateKeys(const Profile& p, bool dataReady); +// The launcher's RR settings into the state folder, decided under the game's state lock from the file as it is then. The +// mode is written only when the file has none or when the launcher's own choice changed (prevMode: the profile's mode before +// this apply; null: a refresh, which never changes a saved mode), so a mode the game's menu saved meanwhile stays. +// 1: written; 0: nothing to write (the same values); -1: refused (*why: as WriteStateKeys). +int WriteRrState(Context& ctx, const wstring& dir, const Profile& p, bool dataReady, wstring* why = nullptr, const string* prevMode = nullptr); +// Upgrade of an install whose WrongGPU\wronggpu.ini an older RR plugin (or the player) changed: while settings.ini has no +// rr_mode, a WrongGPU\wronggpu.ini whose bytes differ from the record's hash is the player's (it stays, as every changed +// file), and its rr_mode (and rr_overlay) are copied into settings.ini, so the game keeps running as before. A file with the +// record's bytes, or none: nothing. True when it wrote settings.ini. +bool MigrateRrState(Context& ctx, const wstring& dir); +// The mode the player chose in the game (OptiScaler's menu saves it into the state folder) becomes the profile's: // the page shows it and an update keeps it. True when it changed `p`. bool FoldRrFromGame(const wstring& dir, Profile& p); -// WrongGPU\wronggpu.ini of an installed RR game written again for the RR data's state (after a conversion: RR turns on -// where the profile wants it; `dataReady`: RrDataValid, read once by the caller). The record's hash follows. 1: written; -// 0: nothing to write (not an RR install, the same text); -1: the folder refused it (*why). +// The state folder's RR settings of an installed RR game written again for the RR data's state (after a conversion: RR +// turns on where the profile wants it; `dataReady`: RrDataValid, read once by the caller). 1: written; 0: nothing to write +// (not an RR install, the same values); -1: refused (*why). int RefreshRrSettings(Context& ctx, const wstring& dir, bool dataReady, wstring* why = nullptr); // Every managed RR game's settings file (but `except`'s, which its own operation writes) brought to the RR data's state: // after the data was converted, the games installed before it get RR. Returns the ones that could not be written. diff --git a/clean/installer/src/wg_core/rrconfig.cpp b/clean/installer/src/wg_core/rrconfig.cpp index 51f6362f..cc1c6017 100644 --- a/clean/installer/src/wg_core/rrconfig.cpp +++ b/clean/installer/src/wg_core/rrconfig.cpp @@ -322,7 +322,19 @@ bool ApplyRrConfig(Context& ctx, const wstring& dir, Record& m, std::vectorname) + L": " + b + + L" is there and is not a copy this fix made (left as it is). Move it away, then Apply again."); + LogLine(ctx, L"rr_config_fix: " + b + L" is there (not this fix's): nothing written"); + return moved; + } + if (!pf.OverwriteBytes(in.data(), in.size(), &err)) { pf.Delete(); Fail(L"Cannot keep a copy of " + file + L": " + ErrText(err)); } + pf.Close(); next.backup = true; next.backupSha = Sha256Bytes(in.data(), in.size()); // (the revert deletes the backup only while it is these bytes) } diff --git a/clean/installer/tests/launcher_core_tests.cpp b/clean/installer/tests/launcher_core_tests.cpp index 691047d5..66368d23 100644 --- a/clean/installer/tests/launcher_core_tests.cpp +++ b/clean/installer/tests/launcher_core_tests.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -687,12 +688,18 @@ int main() { // overwritten. { auto said = [](const std::vector& ws, const wstring& what) { for (auto& x : ws) if (x == what) return true; return false; }; - { // 1. a recorded file to delete, swapped for another program's bytes before it is held + { // 1. a recorded binary to delete: #219, the operation's gate holds it from before the plan (wg_state.h + // OperationGuard), so another program cannot swap it between the check and the delete; it goes as checked const wstring d = ownGame(L"Swap remove", {{L"wronggpu_runtime.dll", L"copy", "", W, W}}); - SetRestoreStepHook([&](const char* s) { if (string(s) == "kept") file(Join(d, L"wronggpu_runtime.dll"), C); }); + bool swapped = false, tried = false; + SetRestoreStepHook([&](const char* s) { + if (string(s) != "kept") return; + tried = true; + try { file(Join(d, L"wronggpu_runtime.dll"), C); swapped = true; } catch (const SetupError&) {} + }); std::vector w; - require(restore(d, false, &w) && read(Join(d, L"wronggpu_runtime.dll")) == C && said(w, L"Left in place (changed since install): wronggpu_runtime.dll"), - "swap: a recorded file swapped for other bytes between the check and the delete is not deleted, and the result says so"); + require(restore(d, false, &w) && tried && !swapped && !IsFile(Join(d, L"wronggpu_runtime.dll")) && !said(w, L"Left in place (changed since install): wronggpu_runtime.dll"), + "swap: a recorded binary is held by the operation's gate; a swap between the check and the delete fails, and the checked file goes"); } { // 2. the same before an original goes back over a file WrongGPU installed const wstring d = ownGame(L"Swap put back", {{L"wronggpu.ini", L"copy", A, W, W}}); @@ -1584,25 +1591,90 @@ int main() { require(cpEntries == 1, "the scan lists the game once: the wrong-place install's entry, not the game a second time"); RemoveTree(cp); RemoveManagedGame(cp); - // ---- rc6 L4: what a failed install or update leaves in the state folder: the player's settings only ---------------- + // ---- a failed install or update takes back only what THIS run made (the run journal, written before each create); + // everything else in the state folder stays and is listed: never a removal of the whole folder ---------------------- const wstring fs = Join(dir, L"failed-state"); require(!StateHasSettings(fs), "L4: no state folder, no settings"); - file(Join(StateDir(fs), L"uninstall.exe"), "MZ"); - file(Join(StateDir(fs), L"owned-files.json"), "{}"); - file(Join(StateDir(fs), L"backup\\x.dll"), "x"); - require(!StateHasSettings(fs), "L4: an uninstaller and a backup are no settings"); - RemoveStateKeepingSettings(fs); - require(!IsDir(StateDir(fs)), "L4: without settings the state folder goes"); - file(Join(StateDir(fs), L"uninstall.exe"), "MZ"); - file(ProfilePath(fs), "[profile]\r\n"); - file(Join(StateDir(fs), L"previous\\previous.txt"), "version=0.5.9\r\n"); - file(Join(StateDir(fs), L"rr-config\\Engine.ini"), "[x]\r\n"); - file(Join(StateDir(fs), L"backup\\x.dll"), "x"); - require(StateHasSettings(fs), "L4: profile.ini, previous\\ and rr-config\\ are settings"); - RemoveStateKeepingSettings(fs); - require(IsFile(ProfilePath(fs)) && IsFile(Join(StateDir(fs), L"previous\\previous.txt")) && IsFile(Join(StateDir(fs), L"rr-config\\Engine.ini")) && - !IsFile(Join(StateDir(fs), L"uninstall.exe")) && !IsDir(Join(StateDir(fs), L"backup")), - "L4: the settings stay, the rest goes"); + { + RunJournal j; + JournalCreate(j, Join(StateDir(fs), L"backup\\x.dll"), false); // (the state folder and backup\ first: not there yet) + file(Join(StateDir(fs), L"backup\\x.dll"), "x"); + JournalCreate(j, Join(StateDir(fs), L"uninstall.exe"), false); + file(Join(StateDir(fs), L"uninstall.exe"), "MZ"); + const auto left = RollbackCreated(mc, StateDir(fs), j); + require(j.created.size() == 0 && left.empty() && !IsDir(StateDir(fs)), "rollback: a state folder this run made, with only what it made: all of it goes"); + } + { + // there before the run: the player's settings, files an earlier uninstall kept and listed, a folder of the player's, + // an earlier uninstaller (not this run's) + const std::vector> before = { + {ProfilePath(fs), "[profile]\r\n"}, {Join(StateDir(fs), L"previous\\previous.txt"), "version=0.5.9\r\n"}, + {Join(StateDir(fs), L"rr-config\\Engine.ini"), "[x]\r\n"}, {Join(StateDir(fs), L"settings.ini.wgtmp-player"), "player_key=1\r\n"}, + {Join(StateDir(fs), L"notes\\mine.txt"), "the player's"}, {Join(StateDir(fs), L"uninstall.exe"), "MZ earlier"}}; + for (auto& f : before) file(f.first, f.second); + RunJournal j; + JournalCreate(j, StateDir(fs), true); // (there: not written down) + JournalCreate(j, Join(StateDir(fs), L"backup\\y.dll"), false); // backup\ and the file: this run's + file(Join(StateDir(fs), L"backup\\y.dll"), "y"); + JournalCreate(j, Join(StateDir(fs), L"owned-files.json"), false); + file(Join(StateDir(fs), L"owned-files.json"), "{}"); + JournalCreate(j, Join(StateDir(fs), L"uninstall.exe"), false); // (there: an overwrite later is not a create) + const auto left = RollbackCreated(mc, StateDir(fs), j); + bool same = true; + for (auto& f : before) { string b; same = same && ReadAll(f.first, b) && b == f.second; } + require(same && left.size() == before.size() && !IsDir(Join(StateDir(fs), L"backup")) && !IsFile(Join(StateDir(fs), L"owned-files.json")), + "rollback: only what this run made goes (backup\\y.dll, backup\\, owned-files.json); the player's settings, a kept temporary file, " + "the player's folder and the earlier uninstaller stay byte for byte and are listed"); + RemoveTree(StateDir(fs)); + } + { + // a backup never overwrites a file an earlier uninstall kept in wronggpu-setup\backup: a new recorded name + const wstring bg = Join(dir, L"backup-collision"); + const string kept = "the player's file an earlier uninstall kept", game = "the game's wronggpu.ini (the player's settings)"; + file(BackupPath(bg, L"wronggpu.ini"), kept); + file(Join(bg, L"wronggpu.ini"), game); + Entry e; e.action = L"copy"; e.rel = L"wronggpu.ini"; e.existed = true; e.orig = Sha256Bytes(game.data(), game.size()); + RunJournal j; + std::vector w; + const wstring b = CopyBackup(mc, bg, e, Join(bg, L"wronggpu.ini"), &j, &w); + string k, nb; + require(ReadAll(BackupPath(bg, L"wronggpu.ini"), k) && k == kept && ReadAll(b, nb) && nb == game && e.backup == L"wronggpu.ini.1" && + IEq(b, EntryBackupPath(bg, e)) && w.size() == 1 && w[0].find(L"backup\\wronggpu.ini") != wstring::npos && + j.created.size() == 1 && IEq(j.created[0].first, b), + "backup collision: the kept backup\\wronggpu.ini stays byte for byte; the new backup is wronggpu.ini.1 (created only where nothing " + "was, written down in the run journal alone), listed"); + Record br; + br.version = L"0.6.5"; br.game = bg; br.exe = Join(bg, L"Game.exe"); br.format = 2; br.e.push_back(e); + SaveRecord(RecordPath(bg), br); + Record back; + require(LoadRecord(RecordPath(bg), back) && back.e.size() == 1 && back.e[0].backup == L"wronggpu.ini.1" && IEq(EntryBackupPath(bg, back.e[0]), b), + "backup collision: the record keeps the backup's name (its backup line), so the restore reads that file"); + Entry e2 = e; + e2.backup.clear(); + CopyBackup(mc, bg, e2, Join(bg, L"wronggpu.ini"), nullptr, nullptr); + require(e2.backup == L"wronggpu.ini.2", "backup collision: the next free name when .1 is taken too"); + RemoveTree(bg); + } + { + // the tests' failure and file hooks exist in WRONGGPU_TESTING builds only: in a release build the variables + // change nothing (CI runs this test in its release-flag builds) + const wstring made = Join(dir, L"hook-made.txt"); + SetEnvironmentVariableW(L"WRONGGPU_TEST_FAIL_AT", L"hook-fail"); + SetEnvironmentVariableW(L"WRONGGPU_TEST_CREATE_AT", L"hook-make"); + SetEnvironmentVariableW(L"WRONGGPU_TEST_CREATE_FILE", made.c_str()); + bool threw = false; + RestoreStep("hook-make"); // (each hook at its own step: the failure would stop the step before the file) + try { RestoreStep("hook-fail"); } catch (const SetupError&) { threw = true; } + SetEnvironmentVariableW(L"WRONGGPU_TEST_FAIL_AT", nullptr); + SetEnvironmentVariableW(L"WRONGGPU_TEST_CREATE_AT", nullptr); + SetEnvironmentVariableW(L"WRONGGPU_TEST_CREATE_FILE", nullptr); +#ifdef WRONGGPU_TESTING + require(threw && IsFile(made), "testing build: WRONGGPU_TEST_FAIL_AT fails the operation at its step, WRONGGPU_TEST_CREATE_AT makes the file (the tests' hooks)"); +#else + require(!threw && !IsFile(made), "release build: WRONGGPU_TEST_FAIL_AT and WRONGGPU_TEST_CREATE_AT change nothing (the hooks are compiled out)"); +#endif + DeleteFileW(made.c_str()); + } SetEnvironmentVariableW(L"LOCALAPPDATA", oldLad.c_str()); } @@ -1929,6 +2001,210 @@ int main() { require(FoldRrFromGame(rg, fold) && fold.get("rr_mode") == "accurate" && !FoldRrFromGame(rg, fold), "the game's rr_mode folds into the profile once"); require(ReadRrSettings(rg).present && ReadRrSettings(Join(dir, L"nothing")).present == false, "ReadRrSettings: present only with the file"); + // #219: the launcher's settings go into the game's state folder (wg_state.h), read over the install's defaults + { + auto put = [](const wstring& p, const string& t) { EnsureDir(Parent(p)); WriteFileAtomic(p, t.data(), t.size()); }; + Context sctx; + // the keys the launcher writes + const auto rk = RrStateKeys(acc, true); + require(rk.size() == 3 && rk[0].second == "1" && rk[1] == std::make_pair(string("rr_mode"), string("accurate")) && rk[2].second == "0", + "RrStateKeys: rr_enabled=1, rr_mode, rr_exact_allowed=0 (Accurate, data ready)"); + require(RrStateKeys(acc, false)[0].second == "0", "RrStateKeys: no RR data: rr_enabled=0"); + Profile fe = DefaultProfile(); + const auto fk = FrontEndStateKeys(fe); + require(!fk.empty() && fk[0] == std::make_pair(string("upscaler"), string("network")) && + std::all_of(fk.begin(), fk.end(), [](const std::pair& kv) { return kv.first != "model" && kv.first.rfind("rr_", 0) != 0; }) && + std::any_of(fk.begin(), fk.end(), [](const std::pair& kv) { return kv.first == "executor"; }), + "FrontEndStateKeys: upscaler first, every runtime key of the schema explicitly, never model or rr_*"); + SetSetting(fe, "wronggpu", "off", nullptr); + require(FrontEndStateKeys(fe)[0].second == "amd", "FrontEndStateKeys: WrongGPU off = upscaler=amd"); + // the effective wronggpu.ini: the state's keys over the file's + const string fileIni = "[fsr]\r\nupscaler = network\r\nruntime_options = executor=hip;sync=pipelined;model=L\r\n"; + const string eff = WithFrontEndState(fileIni, {{"upscaler", "amd"}, {"executor", "dx12"}, {"rr_mode", "fast"}, {"model", "K"}}); + string v, sec; + require(IniGetFrontEnd(eff, "upscaler", &v, &sec) && v == "amd", "WithFrontEndState: the state's upscaler over the file's"); + require(IniGetFrontEnd(eff, "runtime_options", &v, &sec) && v.find("executor=dx12") != string::npos && v.find("executor=hip") == string::npos && + v.find("sync=pipelined") != string::npos && v.find("model=L") != string::npos && v.find("model=K") == string::npos && v.find("rr_mode") == string::npos, + "WithFrontEndState: a runtime key replaced, the others kept; rr_* and model of the state left out"); + require(WithFrontEndState(fileIni, {}) == fileIni, "WithFrontEndState: no state keys: the file as it is"); + // a game folder with an RR install record: the effective RR settings, the upgrade path, never a write of wronggpu.ini + const wstring sg = Join(dir, L"state-game"); + EnsureDir(StateDir(sg)); + const string defaults = RenderRrSettings(acc, true, ""); // what the install wrote (rr_mode=accurate) + put(Join(sg, kRrSettings), defaults); + Record rm; + rm.version = L"0.6.5"; rm.game = sg; rm.exe = Join(sg, L"Game.exe"); rm.format = 2; + rm.installId = L"0123456789abcdef0123456789abcdef"; // (the state files' stamps name it) + const string sid = ToUtf8(rm.installId); + auto entry = [](const wstring& rel, const wstring& inst) { Entry e; e.action = L"copy"; e.rel = rel; e.inst = inst; e.owner = L"wg"; return e; }; + rm.e.push_back(entry(L"plugins\\WrongGPU-RR.asi", L"aa")); + rm.e.push_back(entry(kRrSettings, Sha256Bytes(defaults.data(), defaults.size()))); + SaveRecord(RecordPath(sg), rm); + { + Record twice; + require(LoadRecord(RecordPath(sg), twice) && LoadRecord(RecordPath(sg), twice) && twice.e.size() == rm.e.size(), + "LoadRecord into a Record loaded before: the file's entries once (no entry listed twice)"); + } + require(ReadRrSettings(sg).mode == "accurate", "ReadRrSettings: the install's defaults without state"); + require(!MigrateRrState(sctx, sg) && !IsFile(wgstate::SettingsPathOf(sg)), "upgrade: wronggpu.ini with the record's bytes: nothing copied, no state written"); + require(WriteStateKeys(sctx, sg, {{"rr_mode", "fast"}}) == 1 && ReadRrSettings(sg).mode == "fast" && !ParseRrSettings(defaults).mode.empty(), + "the state's rr_mode decides over wronggpu.ini's"); + string after; + ReadAll(Join(sg, kRrSettings), after); + require(after == defaults, "a state write never touches WrongGPU\\wronggpu.ini"); + require(WriteStateKeys(sctx, sg, {{"rr_mode", "fast"}}) == 0, "the same values again: nothing written (0)"); + // upgrade from an older plugin's save (or the player's edit): LF and CRLF, with and without a UTF-8 BOM (a 0.6.0 + // file an editor saved), each with a mode other than the install's (accurate): the file's mode carried, the file kept + require(ParseRrSettings("\xEF\xBB\xBF[wronggpu]\r\nrr_mode=exact\r\n").mode == "exact" && ParseRrSettings("\xEF\xBB\xBF[wronggpu]\nrr_mode=fast\n").mode == "fast", + "ParseRrSettings: a UTF-8 BOM before [wronggpu] (CRLF and LF): the section and its mode are read"); + for (const char* edited : {"[wronggpu]\nrr_enabled=1\nrr_mode = exact\nrr_overlay=1\n", "[wronggpu]\r\nrr_mode=fast\r\n", + "\xEF\xBB\xBF[wronggpu]\nrr_mode=exact\n", "\xEF\xBB\xBF[wronggpu]\r\nrr_mode=fast\r\nrr_overlay=1\r\n"}) { + DeleteFileW(wgstate::SettingsPathOf(sg).c_str()); + put(Join(sg, kRrSettings), edited); + const bool moved = MigrateRrState(sctx, sg); + const wgstate::Settings st = wgstate::ReadSettings(sg); + string kept; + ReadAll(Join(sg, kRrSettings), kept); + const string want = ParseRrSettings(edited).mode; + require(moved && wgstate::Get(st, "rr_mode") && *wgstate::Get(st, "rr_mode") == want && kept == edited && + (string(edited).find("rr_overlay") == string::npos || (wgstate::Get(st, "rr_overlay") && *wgstate::Get(st, "rr_overlay") == "1")), + "upgrade: a changed WrongGPU\\wronggpu.ini (" + string(string(edited).find("\r\n") == string::npos ? "LF" : "CRLF") + + (edited[0] == '\xEF' ? ", BOM" : "") + ", rr_mode " + want + ") is the player's: kept as it is, its rr_mode (and rr_overlay) copied into the state folder"); + require(!MigrateRrState(sctx, sg), "upgrade: once the state has rr_mode, nothing more is copied"); + } + // the RR mode decided under the state lock (rr.h WriteRrState), forced interleavings: the launcher's view is older + // than the menu's save (the menu saved accurate after the launcher read fast) + { + Profile stale = DefaultProfile(); + stale.v["rr_mode"] = "fast"; + const string fastPrev = "fast"; + DeleteFileW(wgstate::SettingsPathOf(sg).c_str()); + require(wgstate::SetSettings(sg, {{"rr_mode", "accurate"}}).ok(), "(interleaving: the menu saved accurate)"); + require(WriteRrState(sctx, sg, stale, true, nullptr, nullptr) >= 0 && ReadRrSettings(sg).mode == "accurate" && + *wgstate::Get(wgstate::ReadSettings(sg), "rr_exact_allowed") == "0", + "an RR refresh with the launcher's older view (fast): the menu's newer accurate stays (a refresh never changes a saved mode)"); + require(WriteRrState(sctx, sg, stale, true, nullptr, &fastPrev) >= 0 && ReadRrSettings(sg).mode == "accurate", + "an apply whose own mode did not change (fast before, fast now): the menu's newer accurate stays (an unchanged field is not written)"); + Profile chosen = DefaultProfile(); + chosen.v["rr_mode"] = "exact"; + require(WriteRrState(sctx, sg, chosen, true, nullptr, &fastPrev) == 1 && ReadRrSettings(sg).mode == "exact" && + *wgstate::Get(wgstate::ReadSettings(sg), "rr_exact_allowed") == "1", + "an apply where the player changed the mode in the launcher (fast -> exact): written, rr_exact_allowed follows"); + DeleteFileW(wgstate::SettingsPathOf(sg).c_str()); + require(WriteRrState(sctx, sg, stale, true, nullptr, nullptr) == 1 && ReadRrSettings(sg).mode == "fast", + "no mode saved yet: the launcher's mode is written"); + // the menu saves while the launcher's write waits for the lock: the decision is made from the menu's save + require(wgstate::SetSettings(sg, {{"rr_mode", "fast"}}).ok(), "(interleaving 2: fast saved)"); + HANDLE held = CreateEventW(nullptr, TRUE, FALSE, nullptr); + std::thread menu([&] { + wgstate::StateLock lock(sg, 2000); + SetEvent(held); + Sleep(300); + wgstate::Settings now = wgstate::ReadSettings(sg); + wgstate::Set(now, "rr_mode", "accurate"); + wgstate::WriteAtomic(wgstate::SettingsPathOf(sg), wgstate::Stamped(wgstate::RenderSettings(now), "settings.ini", sid)); + }); + WaitForSingleObject(held, 5000); + const int w = WriteRrState(sctx, sg, stale, true, nullptr, &fastPrev); // the launcher read fast before the menu's save + menu.join(); + CloseHandle(held); + require(w >= 0 && ReadRrSettings(sg).mode == "accurate", + "the menu saves accurate while the launcher's write waits for the state lock: the launcher decides under the lock and accurate stays"); + } + // the state files go with the state folder only while their stamp is valid for their own name and this install + // (wg_state.h): a file the player edited or made, an unknown one, a copy under another name (temporary files among + // them) or from another install stay and are listed + DeleteFileW(wgstate::SettingsPathOf(sg).c_str()); + require(wgstate::SetSettings(sg, {{"rr_mode", "fast"}}).ok() && wgstate::StampedByWrongGPU([&] { string b; ReadAll(wgstate::SettingsPathOf(sg), b); return b; }(), "settings.ini", sid), + "(settings.ini written by WrongGPU: stamped for its name and this install's id from the record)"); + put(Join(StateDir(sg), L"model-choice.ini"), wgstate::Stamped("model=M\r\n", "model-choice.ini", sid)); // (as its writer makes it) + put(Join(StateDir(sg), L"settings.ini.wgtmp-1-2"), wgstate::Stamped("rr_mode=fast\r\n", "settings.ini", sid)); // a complete write a crash left + put(Join(StateDir(sg), L"player-note.txt"), "mine"); + auto stay = RemoveStateFolder(sg, &rm); + require(!IsFile(wgstate::SettingsPathOf(sg)) && !IsFile(Join(StateDir(sg), L"model-choice.ini")) && + IsFile(Join(StateDir(sg), L"settings.ini.wgtmp-1-2")) && IsFile(Join(StateDir(sg), L"player-note.txt")) && stay.size() == 2, + "uninstall: settings.ini and model-choice.ini with their valid stamps go; a temporary file (another name) and the player's file stay (listed)"); + DeleteFileW(Join(StateDir(sg), L"settings.ini.wgtmp-1-2").c_str()); + DeleteFileW(Join(StateDir(sg), L"player-note.txt").c_str()); + // negative controls, each alone: the file stays byte for byte and is listed + struct Control { const wchar_t* name; string bytes; const char* what; }; + const string ours = wgstate::Stamped("rr_mode=fast\r\n", "settings.ini", sid); + for (const Control& c : {Control{L"settings.ini", ours + "player_key=1\r\n", "settings.ini WrongGPU wrote, the player added a key after it"}, + Control{L"settings.ini", ours.substr(0, 8) + "accurate" + ours.substr(12), "settings.ini WrongGPU wrote, a value edited (the stamp no longer matches)"}, + Control{L"settings.ini", "rr_mode=fast\r\n", "settings.ini the player made (no stamp)"}, + Control{L"settings.ini", "rr_mode=fast\r\n; wronggpu-written 0123456789abcdef\r\n", "settings.ini with a stamp that does not match"}, + Control{L"model-choice.ini", "model=L\r\n", "model-choice.ini without WrongGPU's stamp (unknown)"}, + Control{L"settings.ini.wgtmp-9-9", "player_key=1\r\n", "a file named like a temporary file, not WrongGPU's"}, + Control{L"settings.ini.wgtmp-backup", ours, "a copy of WrongGPU's settings.ini under another name (its stamp names settings.ini)"}, + Control{L"settings-copy.ini", ours, "a copy of WrongGPU's settings.ini as settings-copy.ini"}, + Control{L"model-choice.ini", wgstate::Stamped("model=M\r\n", "settings.ini", sid), "settings.ini's bytes copied to model-choice.ini"}, + Control{L"settings.ini", wgstate::Stamped("rr_mode=fast\r\n", "settings.ini", "fedcba9876543210fedcba9876543210"), + "a settings.ini copied from another install (its stamp names that install)"}}) { + const wstring f = Join(StateDir(sg), c.name); + put(f, c.bytes); + stay = RemoveStateFolder(sg, &rm); + string back; + require(ReadAll(f, back) && back == c.bytes && stay.size() == 1, string("uninstall keeps ") + c.what + " byte for byte and lists it"); + DeleteFileW(f.c_str()); + } + + // the operation gate (wg_state.h OperationGuard): the record's binaries held, writes and deletes through it, + // refused while a binary is in use, one gate per folder and thread + const wstring gg = Join(dir, L"gate-game"); + EnsureDir(StateDir(gg)); + const wstring bin = Join(gg, L"wronggpu_runtime.dll"); + put(bin, "MZ old"); + Record gm; + gm.version = L"0.6.5"; gm.game = gg; gm.exe = Join(gg, L"Game.exe"); gm.format = 2; + gm.e.push_back(entry(L"wronggpu_runtime.dll", Sha256Bytes("MZ old", 6))); + gm.e.push_back(entry(L"wronggpu.ini", L"bb")); // not a binary: never held + SaveRecord(RecordPath(gg), gm); + { + auto gate = GuardOperation(gg, &gm); + require(gate && GateHolds(bin) && !GateHolds(Join(gg, L"wronggpu.ini")), "gate: the record's binaries held, an ini not"); + require(GuardOperation(gg, &gm) == nullptr, "gate: a nested gate for the same folder on the same thread is the outer one"); + string r; + require(ReadAll(bin, r) && r == "MZ old", "gate: a held binary can still be read by the operation"); + PutBinary(bin, "MZ new", 6); + require(ReadAll(bin, r) && r == "MZ new" && GateHolds(bin), "gate: PutBinary replaces the held binary (renamed in complete) and holds the new one"); + bool blocked = false; + try { put(bin, "MZ someone else"); } catch (const SetupError&) { blocked = true; } + require(blocked && ReadAll(bin, r) && r == "MZ new", "gate: another writer cannot replace a held binary"); + require(DeleteHeldBinary(bin) == ERROR_SUCCESS && !IsFile(bin), "gate: DeleteHeldBinary deletes through the held handle"); + PutBinary(Join(gg, L"plugins\\WrongGPU.asi"), "MZ plugin", 9); + require(GateHolds(Join(gg, L"plugins\\WrongGPU.asi")), "gate: a binary the operation creates is renamed in and held"); + // a file there that the gate does not hold (an earlier mirror copy the record did not list): replaced and held, + // unless another program has it open without sharing writes (then the operation stops, the file as it was) + const wstring mirror = Join(gg, L"_storage_\\dxgi.dll"); + put(mirror, "MZ earlier copy"); + PutBinary(mirror, "MZ this copy", 12); + require(ReadAll(mirror, r) && r == "MZ this copy" && GateHolds(mirror), "gate: an unheld file at the path is replaced and the new one held"); + const wstring other = Join(gg, L"_storage_\\wronggpu-amd-compare.dll"); + put(other, "MZ in use"); + HANDLE busy = CreateFileW(other.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + string stopped; + try { PutBinary(other, "MZ new", 6); } catch (const SetupError& ex) { stopped = ToUtf8(ex.msg); } + if (busy != INVALID_HANDLE_VALUE) CloseHandle(busy); + require(stopped.find("Stopped") != string::npos && ReadAll(other, r) && r == "MZ in use" && !GateHolds(other), + "gate: an unheld file another program has open: the operation stops, the file as it was"); + } + put(bin, "MZ old"); + DeleteFileW(Join(gg, L"plugins\\WrongGPU.asi").c_str()); + { + HANDLE inUse = CreateFileW(bin.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); // another program, no write sharing + string msg; + try { auto gate = GuardOperation(gg, &gm); } catch (const SetupError& ex) { msg = ToUtf8(ex.msg); } + if (inUse != INVALID_HANDLE_VALUE) CloseHandle(inUse); + require(msg.find("Nothing was changed") != string::npos && msg.find("in use by the game or another program") != string::npos && + msg.find("wronggpu_runtime.dll") != string::npos, + "gate: a binary in use by another program: refused, nothing changed, the file named"); + } + { + auto gate = GuardOperation(gg, &gm); + require(gate != nullptr, "gate: once the file is free again, the operation runs"); + } + } + // which games: the RR files next to the exe, deeper in the game's folder, a game known to call it, none auto file = [](const wstring& p) { EnsureDir(Parent(p)); WriteFileAtomic(p, "x", 1); }; const wstring a = Join(dir, L"rr-a"), b = Join(dir, L"rr-b"), c = Join(dir, L"rr-c"), d = Join(dir, L"rr-d"); diff --git a/clean/installer/tests/launcher_state_cases.py b/clean/installer/tests/launcher_state_cases.py new file mode 100644 index 00000000..fa18be24 --- /dev/null +++ b/clean/installer/tests/launcher_state_cases.py @@ -0,0 +1,365 @@ +# SPDX-License-Identifier: MIT +"""#219: the game's state folder (wronggpu-setup\\settings.ini, wg_state.h) for run_launcher_tests.py, which calls run() in +its place in the suite (this file keeps that suite below the 256 KB source limit, as launcher_edition_cases.py does). +wronggpu.ini and WrongGPU\\wronggpu.ini hold the install's defaults and are the player's: no launcher operation rewrites them +after the install. What the launcher and the in-game menu save goes into the state folder, which decides over them, which is +WrongGPU's by its bytes (WrongGPU's stamp: uninstall removes a stamped file, keeps an edited or unknown one), and which +uninstall, repair and update only change while no other program has WrongGPU's files open. The in-game menu's save is written +here the way the RR plugin writes it (wg_state.h SetSettings: the key set, the other lines kept, the stamp kept on a file that +was WrongGPU's: menu_save); the plugin's own save is tested with the real plugin in clean/rr_f/proxy/tests/test_hook_dll.cpp. +The install's seed files (wronggpu-asi.ini, WrongGPU\\wronggpu.ini) are created only where nothing is: a file that appears +at either boundary (after the check, after the record: WRONGGPU_TEST_CREATE_AT) is the player's. Written for this project.""" +import os +import shutil +import subprocess +import sys + +from run_installer_tests import read, sha, snapshot, diff, write, kept_runtime, unrecorded_wronggpu_files + +HOLD = r""" +import ctypes, sys +k = ctypes.WinDLL("kernel32", use_last_error=True) +k.CreateFileW.restype = ctypes.c_void_p +k.LoadLibraryExW.restype = ctypes.c_void_p +path, how = sys.argv[1], sys.argv[2] +if how == "open": # another program (antivirus, a backup tool) reads the file without sharing writes + h = k.CreateFileW(path, 0x80000000, 1, None, 3, 0, None) + ok = h not in (None, ctypes.c_void_p(-1).value) +else: # the game has it loaded (mapped as an image; nothing of it runs) + h = k.LoadLibraryExW(path, None, 0x1) or k.LoadLibraryExW(path, None, 0x20) + ok = bool(h) +print("held" if ok else "failed %d" % ctypes.get_last_error(), flush=True) +sys.stdin.read() +""" + + +STAMP = b"; wronggpu-written " + + +def stamp_check(body, name, install_id): + """wg_state.h StampCheck: FNV-1a 64 of the bytes, then of "\\n\\n"; 16 lower-case hex digits.""" + h = 1469598103934665603 + for c in body + b"\n" + name.lower().encode() + b"\n" + install_id: + h = ((h ^ c) * 1099511628211) & 0xFFFFFFFFFFFFFFFF + return b"%016x" % h + + +def install_id(state_dir): + """The record's install-id (wg_state.h InstallIdOf); b"" when none.""" + rp = os.path.join(state_dir, "install.record") + for line in (read(rp).split(b"\r\n") if os.path.isfile(rp) else []): + if line.startswith(b"install-id\t"): + return line[len(b"install-id\t"):] + return b"" + + +def stamped_by_wronggpu(data, name, iid): + if not iid: + return False + t = data[:-1] if data.endswith(b"\n") else data + t = t[:-1] if t.endswith(b"\r") else t + start = t.rfind(b"\n") + 1 + last = t[start:] + return last.startswith(STAMP) and len(last) == len(STAMP) + 16 and last[len(STAMP):] == stamp_check(data[:start], name, iid) + + +def menu_save(path, k, v): + """The in-game menu's save as wg_state.h SetSettings makes it: k=v set (its line rewritten, or added at the end), every + other line kept with its own line end, only the valid stamp taken off, put back only on a file that was WrongGPU's (or new) + of an install with an id.""" + name, iid = os.path.basename(path), install_id(os.path.dirname(path)) + data = read(path) if os.path.isfile(path) else None + ours = bool(iid) and (data is None or stamped_by_wronggpu(data, name, iid)) + text = (data or b"").decode("utf-8") + if data is not None and stamped_by_wronggpu(data, name, iid): + text = text[:text.rstrip("\r\n").rfind("\n") + 1] # (the valid stamp line off) + lines = text.splitlines(keepends=True) + keys = [l.split("=", 1)[0].strip() if "=" in l and not l.lstrip().startswith((";", "#", "[")) else None for l in lines] + if k in keys: + i = keys.index(k) + lines[i] = k + "=" + v + lines[i][len(lines[i].rstrip("\r\n")):] + else: + if lines and not lines[-1].endswith("\n"): + lines[-1] += "\r\n" + lines.append(k + "=" + v + "\r\n") + body = "".join(lines).encode("utf-8") + write(path, body + STAMP + stamp_check(body, name, iid) + b"\r\n" if ours else body) + + +def seed_appears(t, m, name, rel, extra=None): + """A seed file that appears during the install (WRONGGPU_TEST_CREATE_AT: after its check, after the record is written): kept + byte for byte, not recorded, said; the uninstall keeps it and lists it.""" + inst = ("--opti=" + t.opti, "--noscan", "--force", "--experimental") + made = b"; made by the player during the install (test)\r\n" # (record.cpp RestoreStep writes these bytes) + for step in ("seed-planned", "seed-recorded"): + root, b, exe = m.game(t, "State Seed %s %s" % (name, step), extra=extra) + before = snapshot(root) + f = os.path.join(b, rel) + t.env["WRONGGPU_TEST_CREATE_AT"], t.env["WRONGGPU_TEST_CREATE_FILE"] = step, f + try: + rc = t.run("install", exe, *inst) + finally: + t.env.pop("WRONGGPU_TEST_CREATE_AT", None) + t.env.pop("WRONGGPU_TEST_CREATE_FILE", None) + t.check("%s appears during the install (%s): the install keeps it byte for byte, does not record it, and says so" % (rel, step), + rc == 0 and os.path.isfile(f) and read(f) == made and m.record_entry_sha(b, rel) is None and + any(w.startswith("Left in place (appeared during the install") and rel in w for w in t.j.get("warnings", [])), + (rc, read(f) if os.path.isfile(f) else None, m.record_entry_sha(b, rel), t.j.get("warnings"), t.logtail(800))) + left = kept_runtime(before, root, os.path.join("bin", "x64", rel), *unrecorded_wronggpu_files(root)) + rc = t.run("uninstall", exe) + t.check("...and the uninstall keeps it (the player's) byte for byte; everything else as before", + rc == 0 and read(f) == made and snapshot(root) == left, (rc, diff(left, snapshot(root)), t.j.get("warnings"))) + shutil.rmtree(root, ignore_errors=True) + + +def record_060(t, m, b): + """The install record as 0.6.0 wrote it for this install, built from this install's record in 0.6.0's format: the + WrongGPU 0.6.0 source (commit f3aa109, clean/installer/src/wg_core/record.cpp SaveRecord, line 141) writes no install-id + line, and 0.6.0 seeded wronggpu-asi.ini without recording it (clean/installer/src/wg_core/optiscaler.h, lines 77-87): so + version 0.6.0, no install-id, no wronggpu-asi.ini entry; and 0.6.0 had no state files (settings.ini goes).""" + rp = os.path.join(b, "wronggpu-setup", "install.record") + lines = read(rp).decode("utf-8").split("\r\n") + lines = ["version\t0.6.0" if l.startswith("version\t") else l for l in lines + if not l.endswith("\twronggpu-asi.ini") and not l.startswith("install-id\t")] + write(rp, "\r\n".join(lines).encode("utf-8")) + for f in ("settings.ini", "model-choice.ini"): + if os.path.isfile(os.path.join(b, "wronggpu-setup", f)): + os.remove(os.path.join(b, "wronggpu-setup", f)) + + +def kept_backup(t, m): + """A file an earlier uninstall kept in wronggpu-setup\\backup (here backup\\wronggpu.ini) and a later install that backs up + the game's wronggpu.ini: the kept file stays byte for byte, the new backup takes a recorded new name, the uninstall puts the + game's file back from that name and keeps (and lists) the old one.""" + inst = ("--opti=" + t.opti, "--noscan", "--force", "--experimental") + root, b, exe = m.game(t, "State Kept Backup") + players, kept = b"[fsr]\r\n; the player's own wronggpu.ini\r\n", b"; an earlier backup the uninstall kept (changed since)\r\n" + write(os.path.join(b, "wronggpu.ini"), players) + kb = os.path.join(b, "wronggpu-setup", "backup", "wronggpu.ini") + write(kb, kept) + before = snapshot(root) + rc = t.run("install", exe, *inst) + rec = read(os.path.join(b, "wronggpu-setup", "install.record")).decode("utf-8", "replace") if rc == 0 else "" + nb = os.path.join(b, "wronggpu-setup", "backup", "wronggpu.ini.1") + t.check("install with a kept backup\\wronggpu.ini: it stays byte for byte; the game's wronggpu.ini is backed up as wronggpu.ini.1 (recorded), the kept file listed", + rc == 0 and read(kb) == kept and os.path.isfile(nb) and read(nb) == players and "\nbackup\tcopy\twronggpu.ini\twronggpu.ini.1\r\n" in rec and + any("backup\\wronggpu.ini" in w and w.startswith("Left in place") for w in t.j.get("warnings", [])), + (rc, read(kb) == kept, os.path.isfile(nb), [l for l in rec.split("\r\n") if l.startswith("backup\t")], t.j.get("warnings"))) + rc = t.run("uninstall", exe) + left = kept_runtime(before, root, *unrecorded_wronggpu_files(root)) + t.check("...the uninstall restores the game's wronggpu.ini from the recorded name; the kept backup stays (listed); the folder as before", + rc == 0 and read(os.path.join(b, "wronggpu.ini")) == players and read(kb) == kept and not os.path.exists(nb) and snapshot(root) == left, + (rc, diff(left, snapshot(root)), t.j.get("warnings"))) + shutil.rmtree(root, ignore_errors=True) + + +def failed_runs(t, m): + """A repair or install that fails takes back only what it made (the run journal): the player's files in the state folder + (a note, a folder, a kept temporary file, a copy of the settings file) stay byte for byte, whichever way the run fails.""" + inst = ("--opti=" + t.opti, "--noscan", "--force", "--experimental") + root, b, exe = m.game(t, "State Failed Runs") + st = os.path.join(b, "wronggpu-setup") + rc = t.run("install", exe, *inst) + mine = {"notes.txt": b"the player's notes", os.path.join("mine", "x.txt"): b"a folder of the player's", + "settings.ini.wgtmp-player": b"player_key=1\r\n"} + for rel, data in mine.items(): + write(os.path.join(st, rel), data) + if os.path.isfile(os.path.join(st, "settings.ini")): + mine["settings-copy.ini"] = read(os.path.join(st, "settings.ini")) # (a copy of WrongGPU's file: the player's) + write(os.path.join(st, "settings-copy.ini"), mine["settings-copy.ini"]) + + def same(): + return all(os.path.isfile(os.path.join(st, r)) and read(os.path.join(st, r)) == d for r, d in mine.items()) + for how, step in (("a repair that fails after everything was written", "installed"), + ("a repair that fails before its record (the earlier install already removed)", "seed-planned")): + t.env["WRONGGPU_TEST_FAIL_AT"] = step + try: + rc2 = t.run("repair", exe, *inst) + finally: + t.env.pop("WRONGGPU_TEST_FAIL_AT", None) + t.check("%s: refused, the player's files in the state folder stay byte for byte" % how, + rc == 0 and rc2 != 0 and same(), (rc, rc2, [r for r, d in mine.items() if not os.path.isfile(os.path.join(st, r))], t.logtail(1200))) + rc = t.run("install", exe, *inst) # (installed again for the next case) + rc = t.run("uninstall", exe) + t.check("...the uninstall keeps them too (listed)", rc == 0 and same(), (rc, t.j.get("warnings"))) + t.env["WRONGGPU_TEST_FAIL_AT"] = "seed-planned" + try: + rc2 = t.run("install", exe, *inst) # a new install into the state folder those files are in + finally: + t.env.pop("WRONGGPU_TEST_FAIL_AT", None) + t.check("an install that fails where an earlier uninstall kept the player's files: they stay byte for byte (never a removal of the folder)", + rc2 != 0 and same() and not os.path.isfile(os.path.join(st, "install.record")), (rc2, os.listdir(st) if os.path.isdir(st) else None)) + shutil.rmtree(root, ignore_errors=True) + + +def hold(path, how): + p = subprocess.Popen([sys.executable, "-c", HOLD, path, how], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + creationflags=0x08000000) + return p, p.stdout.readline().decode().strip() + + +def release(p): + p.stdin.close() + p.wait(30) + + +def asi_seed_cases(t, opti, m): + """The OptiScaler plugin's starting entry (wronggpu-asi.ini, written by a Preset K build on the hosted route): one of the + install's recorded files, removed by an uninstall while unchanged, kept and listed once the plugin's menu changed it.""" + inst = ("--opti=" + opti, "--noscan", "--force", "--experimental") + root, b, exe = m.game(t, "State Asi") + before = snapshot(root) + asi = os.path.join(b, "wronggpu-asi.ini") + rc = t.run("install", exe, *inst) + if rc != 0 or not os.path.isfile(asi): + t.check("install (hosted route)", rc == 0, (rc, t.j.get("message"))) + print(" skipped: the plugin's wronggpu-asi.ini (a build without Preset K writes none)") + return + seeded = read(asi) + t.check("Preset K build: the plugin's wronggpu-asi.ini is one of the install's recorded files, with its hash", + m.record_entry_sha(b, "wronggpu-asi.ini") == sha(seeded) and b"selection=wronggpu" in seeded, (m.record_entry_sha(b, "wronggpu-asi.ini"), seeded)) + left = kept_runtime(before, root, *unrecorded_wronggpu_files(root)) + rc = t.run("uninstall", exe) + t.check("wronggpu-asi.ini unchanged: the uninstall removes it, the folder byte for byte as before, nothing listed for it", + rc == 0 and not os.path.exists(asi) and snapshot(root) == left and not any("wronggpu-asi.ini" in w for w in t.j.get("warnings", [])), + (rc, diff(left, snapshot(root)), t.j.get("warnings"))) + rel = os.path.join("bin", "x64", "wronggpu-asi.ini") + rc = t.run("install", exe, *inst) + menu = b"; WrongGPU OptiScaler plugin\r\nselection=amd\r\n" # the plugin's menu: AMD chosen + write(asi, menu) + left = kept_runtime(before, root, rel, *unrecorded_wronggpu_files(root)) + rc2 = t.run("uninstall", exe) + t.check("wronggpu-asi.ini changed by the plugin's menu: the uninstall keeps it as it is and lists it (changed since install); everything else as before", + rc == 0 and rc2 == 0 and read(asi) == menu and snapshot(root) == left and + any(w.startswith("Left in place (changed since install)") and "wronggpu-asi.ini" in w for w in t.j.get("warnings", [])), + (rc, rc2, diff(left, snapshot(root)), t.j.get("warnings"))) + # the player's file there at the next install: kept as it is, not recorded (a repair keeps it too); the uninstall lists it + rc = t.run("install", exe, *inst) + rc2 = t.run("repair", exe, *inst) + t.check("the player's wronggpu-asi.ini at an install and a repair: kept byte for byte, not in the record", + rc == 0 and rc2 == 0 and read(asi) == menu and m.record_entry_sha(b, "wronggpu-asi.ini") is None, (rc, rc2, read(asi))) + left = kept_runtime(before, root, rel, *unrecorded_wronggpu_files(root)) + rc = t.run("uninstall", exe) + t.check("...and the uninstall keeps it and lists it; everything else as before", + rc == 0 and read(asi) == menu and snapshot(root) == left and any("wronggpu-asi.ini" in w and w.startswith("Left in place") for w in t.j.get("warnings", [])), + (rc, diff(left, snapshot(root)), t.j.get("warnings"))) + # an update over a 0.6.0 install: its record has no wronggpu-asi.ini entry; the file (0.6.0's seed, or the plugin's menu + # save since) is not WrongGPU's: the update keeps it byte for byte and does not record it, the uninstall keeps and lists it + for label, asi_bytes in (("0.6.0's seed bytes", seeded), ("changed by the plugin's menu", menu)): + rc = t.run("install", exe, *inst) + write(asi, asi_bytes) + record_060(t, m, b) + rc2 = t.run("update", exe, *inst) + t.check("update over a 0.6.0 record without the seed entry (wronggpu-asi.ini %s): kept byte for byte, not recorded" % label, + rc == 0 and rc2 == 0 and read(asi) == asi_bytes and m.record_entry_sha(b, "wronggpu-asi.ini") is None, + (rc, rc2, read(asi), m.record_entry_sha(b, "wronggpu-asi.ini"), t.j.get("message"))) + rc3 = t.run("status", exe) + said = str(t.j.get("game", {})) + str(t.j.get("warnings", [])) + t.check("...a status (what the launcher shows at every start) does not list it", rc3 == 0 and "wronggpu-asi.ini" not in said, said[-600:]) + left = kept_runtime(before, root, rel, *unrecorded_wronggpu_files(root)) + rc = t.run("uninstall", exe) + t.check("...the uninstall keeps it and lists it once; everything else as before", + rc == 0 and read(asi) == asi_bytes and snapshot(root) == left and sum("wronggpu-asi.ini" in w for w in t.j.get("warnings", [])) == 1, + (rc, diff(left, snapshot(root)), t.j.get("warnings"))) + os.remove(asi) + shutil.rmtree(root, ignore_errors=True) # (the later sections, the window's library among them, see only their own games) + seed_appears(t, m, "Asi", "wronggpu-asi.ini") + + +def run(t, opti, m): + """m: the suite's module (its helpers: game, ini, state_kv, state_set, rr_ini, record_entry_sha, RR_SETTINGS, STATE).""" + print("\n[state] #219: the saved settings in the state folder, wronggpu.ini never rewritten, uninstall/repair/update refused while in use") + t.opti = opti + asi_seed_cases(t, opti, m) + rr_files = {"bin/x64/nvngx_dlssd.dll": b"MZ synthetic stand-in, not a usable RR model file " * 64, + "bin/x64/sl.dlss_d.dll": b"MZ synthetic stand-in"} # the DLSS RR plugin stand-in + seed_appears(t, m, "RR", m.RR_SETTINGS, extra=rr_files) + failed_runs(t, m) + kept_backup(t, m) + inst = ("--opti=" + opti, "--noscan", "--force", "--experimental") + root, b, exe = m.game(t, "State Game", extra=rr_files) + before = snapshot(root) + rc = t.run("install", exe, *inst) + rrs = os.path.join(b, m.RR_SETTINGS) + t.check("install of an RR game", rc == 0 and os.path.isfile(rrs), (rc, t.j.get("message"), t.logtail())) + if rc != 0 or not os.path.isfile(rrs): + return + wini0, rr0 = read(os.path.join(b, "wronggpu.ini")), read(rrs) + + # 1. the in-game menu saves Fast, then uninstall: nothing of WrongGPU is left (the #219 case: the save made the repair and + # the uninstall take WrongGPU\wronggpu.ini for the player's) + m.state_set(b, "rr_mode", "fast") + rc = t.run("status", exe) + t.check("in-game save (state rr_mode=fast): status shows Fast, WrongGPU\\wronggpu.ini as installed", + rc == 0 and t.j.get("game", {}).get("rr_mode") == "fast" and read(rrs) == rr0, t.j.get("game")) + rc = t.run("repair", exe, *inst) + t.check("repair after the in-game save: Fast kept (state), both wronggpu.ini files as installed, nothing 'left in place'", + rc == 0 and m.rr_ini(b).get("rr_mode") == "fast" and read(rrs) == rr0 and read(os.path.join(b, "wronggpu.ini")) == wini0 and + not any("Left in place" in w for w in t.j.get("warnings", [])), + (rc, m.rr_ini(b), t.j.get("warnings"), read(rrs) == rr0, read(os.path.join(b, "wronggpu.ini")) == wini0)) + left = kept_runtime(before, root, *unrecorded_wronggpu_files(root)) + rc = t.run("uninstall", exe) + t.check("uninstall after the in-game save: the folder byte for byte as before (the state folder gone, no settings file left)", + rc == 0 and snapshot(root) == left and not os.path.exists(os.path.join(b, "wronggpu-setup")), (rc, diff(left, snapshot(root)), t.j.get("warnings"))) + + # 2. a player's edit of wronggpu.ini, then the launcher's Apply: the edit stays, the launcher's change goes into the state + rc = t.run("install", exe, *inst) + t.check("install again", rc == 0, (rc, t.j.get("message"))) + wp = os.path.join(b, "wronggpu.ini") + edited = read(wp) + b"; the player's note\r\n" + write(wp, edited) + rc = t.run("set", exe, "output_filter=quality5") + t.check("a player's edit of wronggpu.ini, then set: wronggpu.ini kept byte for byte, output_filter=quality5 in the state", + rc == 0 and read(wp) == edited and m.state_kv(b).get("output_filter") == "quality5" and "output_filter=quality5" in (m.options_line(m.eff_ini(b)) or ""), + (rc, m.state_kv(b), t.j.get("message"))) + rc = t.run("set", exe, "rr_mode=accurate") + t.check("set rr_mode=accurate: in the state, WrongGPU\\wronggpu.ini as installed", rc == 0 and m.state_kv(b).get("rr_mode") == "accurate" and read(rrs) == rr0, + (rc, m.state_kv(b))) + + # 3. the player edits WrongGPU\wronggpu.ini by hand, then the in-game menu saves: the save decides, the hand edit stays + hand = rr0.replace(b"rr_mode=fast", b"rr_mode=exact") + b"; mine\r\n" + write(rrs, hand) + m.state_set(b, "rr_mode", "fast") + rc = t.run("status", exe) + t.check("hand edit then in-game save: the save decides (Fast), the hand-edited file kept", rc == 0 and t.j.get("game", {}).get("rr_mode") == "fast" and read(rrs) == hand, + t.j.get("game")) + + # 4. uninstall, repair and update refused while another program has a WrongGPU file open or the game has it loaded + for rel, how in (("plugins\\WrongGPU-RR.asi", "open"), ("wronggpu_runtime.dll", "load")): + p, state = hold(os.path.join(b, rel), how) + try: + if state != "held": + print(" skipped: %s %s (%s)" % (how, rel, state)) + continue + snap = snapshot(root) + for op in ("uninstall", "repair", "update"): + rc = t.run(op, exe, *(() if op == "uninstall" else inst)) + msg = t.j.get("message", "") + t.j.get("error", "") + t.check("%s while %s is %s: refused (exit 2), nothing changed, the file named" % (op, rel, "open in another program" if how == "open" else "loaded"), + rc == 2 and "in use by the game or another program" in msg and os.path.basename(rel) in msg and snapshot(root) == snap, + (rc, msg, diff(snap, snapshot(root)))) + finally: + release(p) + + # 5. an older install (before #219): its WrongGPU\wronggpu.ini rewritten by the older plugin's save; the next repair + # carries the mode into the state and keeps the file; an unchanged file carries nothing + os.remove(os.path.join(b, m.STATE)) + write(rrs, rr0) + rc = t.run("repair", exe, *inst) + t.check("upgrade, WrongGPU\\wronggpu.ini unchanged: nothing carried over (no rr_mode from the file in the state), the file as installed", + rc == 0 and read(rrs) == rr0 and m.record_entry_sha(b, m.RR_SETTINGS) == sha(rr0), (rc, m.state_kv(b))) + os.remove(os.path.join(b, m.STATE)) + older = rr0.replace(b"\r\n", b"\n").replace(b"rr_mode=fast", b"rr_mode = exact\nrr_overlay=1") # an older plugin's save (LF) + write(rrs, older) + rc = t.run("repair", exe, *inst) + sk = m.state_kv(b) + t.check("upgrade, WrongGPU\\wronggpu.ini saved by an older plugin (LF): rr_mode and rr_overlay carried into the state, the file kept", + rc == 0 and sk.get("rr_mode") == "exact" and sk.get("rr_overlay") == "1" and read(rrs) == older, (rc, sk)) + left = kept_runtime(before, root, *unrecorded_wronggpu_files(root)) # the unrecorded files, with their bytes now + rc = t.run("uninstall", exe) + # the player's two files: WrongGPU\wronggpu.ini kept through the repairs as it is; wronggpu.ini (the install wrote WrongGPU's + # version of it and kept the player's in the backup) back as the player saved it + left = kept_runtime(left, root, os.path.join("bin", "x64", m.RR_SETTINGS), os.path.join("bin", "x64", "wronggpu.ini")) + t.check("uninstall: the player's WrongGPU\\wronggpu.ini and wronggpu.ini stay as the player saved them; everything else as before, the state folder gone", + rc == 0 and snapshot(root) == left and read(rrs) == older and read(wp) == edited, (rc, diff(left, snapshot(root)), t.j.get("warnings"))) + shutil.rmtree(root, ignore_errors=True) diff --git a/clean/installer/tests/run_launcher_tests.py b/clean/installer/tests/run_launcher_tests.py index f4bbe0e2..129b4b64 100644 --- a/clean/installer/tests/run_launcher_tests.py +++ b/clean/installer/tests/run_launcher_tests.py @@ -169,6 +169,36 @@ def ini(b, name="wronggpu.ini"): return read(p).decode("utf-8", "replace") if os.path.isfile(p) else "" +STATE = os.path.join("wronggpu-setup", "settings.ini") # #219: what the launcher and the in-game menu save (key=value), over wronggpu.ini + + +def state_kv(b): + return dict(l.split("=", 1) for l in ini(b, STATE).split("\r\n") if "=" in l) + + +def state_set(b, k, v): + """The in-game menu's save of the state, as wg_state.h SetSettings makes it (launcher_state_cases.menu_save).""" + __import__("launcher_state_cases").menu_save(os.path.join(b, STATE), k, v) + + +def eff_ini(b): + """wronggpu.ini as the front end sees it: the state's upscaler and runtime option keys over the file's (WithFrontEndState).""" + kv = {k: v for k, v in state_kv(b).items() if not k.startswith("rr_") and k != "model"} + items = {k: v for k, v in kv.items() if k != "upscaler"} + out, opts = [], False + for line in ini(b).replace("\r", "").split("\n"): + k = line.split("=", 1)[0].strip().lower() if "=" in line and not line.lstrip().startswith(("#", ";")) else "" + if k == "upscaler" and "upscaler" in kv: + line = "upscaler = " + kv["upscaler"] + elif k in items: + continue + elif k == "runtime_options" and items: + kept = [p for p in line.split("=", 1)[1].strip().split(";") if p and p.split("=")[0].strip().lower().replace("backend", "executor") not in items] + line, opts = "runtime_options=" + ";".join(kept + [a + "=" + c for a, c in items.items()]), True + out.append(line) + return "\r\n".join(out + ([] if opts or not items else ["runtime_options=" + ";".join(a + "=" + c for a, c in items.items())])) + + def options_line(text): for line in text.replace("\r", "").split("\n"): s = line.strip() @@ -322,15 +352,18 @@ def test_install_settings_uninstall(t, opti): t.check("status: installed, record v2, not run yet", rc == 0 and g.get("status") == "installed" and g.get("record_v1") is False and g.get("last_run", {}).get("found") is False, g) # settings + wini0 = ini(b) rc = t.run("set", exe, "output_filter=quality9", "executor=dx12", "sparkle_guard=0.4") - text = ini(b) - t.check("set: exit 0; runtime_options one line without spaces, managed items appended", rc == 0 and - (options_line(text) or "").endswith("executor=dx12;output_filter=quality9;sparkle_guard=0.4") and " " not in (options_line(text) or " "), - (rc, options_line(text), t.j.get("message"))) - t.check("set: the record knows the new wronggpu.ini (uninstall can prove it is ours)", record_entry_sha(b, "wronggpu.ini") == sha(read(os.path.join(b, "wronggpu.ini")))) - before_bad = ini(b) + sk, text = state_kv(b), eff_ini(b) + t.check("set (#219): exit 0; the values in wronggpu-setup\\settings.ini, the front end's view has them on one runtime_options line without spaces", + rc == 0 and sk.get("executor") == "dx12" and sk.get("output_filter") == "quality9" and sk.get("sparkle_guard") == "0.4" and + all(x in (options_line(text) or "").split(";") for x in ("executor=dx12", "output_filter=quality9", "sparkle_guard=0.4")) and " " not in (options_line(text) or " "), + (rc, sk, options_line(text), t.j.get("message"))) + t.check("set (#219): wronggpu.ini never rewritten after install (the record's bytes)", + ini(b) == wini0 and record_entry_sha(b, "wronggpu.ini") == sha(read(os.path.join(b, "wronggpu.ini")))) + before_bad = (ini(b), ini(b, STATE)) rc = t.run("set", exe, "executor=warp") - t.check("set a bad value: exit 10, the file unchanged", rc == 10 and ini(b) == before_bad, (rc, t.j)) + t.check("set a bad value: exit 10, the files unchanged", rc == 10 and (ini(b), ini(b, STATE)) == before_bad, (rc, t.j)) rc = t.run("set", exe, "nosuch=1") t.check("set an unknown key: exit 10", rc == 10, t.j) rc = t.run("set", exe, "fps_overlay=on") @@ -341,12 +374,13 @@ def test_install_settings_uninstall(t, opti): s = t.j.get("settings", {}) t.check("get: profile and file agree", rc == 0 and s.get("output_filter", {}).get("profile") == "quality9" and s.get("output_filter", {}).get("file") == "quality9" and s.get("fps_overlay", {}).get("file") == "on", s) - # an edit outside the launcher - write(os.path.join(b, "wronggpu.ini"), ini(b).replace("sparkle_guard=0.4", "sparkle_guard=0.4;pre_exposure=original")) + # an edit outside the launcher (of the saved settings) + state_set(b, "pre_exposure", "original") rc = t.run("get", exe) t.check("an outside edit is reported (pre_exposure=original)", rc == 0 and any(x["key"] == "pre_exposure" and x["file"] == "original" for x in t.j.get("outside_edits", [])), t.j.get("outside_edits")) rc = t.run("set", exe, "pre_exposure=scale") # revert: the profile wins - t.check("revert: the file follows the profile again", rc == 0 and "pre_exposure" not in (options_line(ini(b)) or ""), options_line(ini(b))) + t.check("revert: the settings follow the profile again", rc == 0 and "pre_exposure=original" not in (options_line(eff_ini(b)) or "") and ini(b) == wini0, + options_line(eff_ini(b))) # the log tail write(os.path.join(b, "wronggpu-fsr.log"), "[11:00:00.000 9] [amd_fidelityfx_dx12] ==== session start: Cyberpunk2077.exe (process 9) ====\r\n" @@ -404,15 +438,15 @@ def test_install_settings_uninstall(t, opti): asi_ini = os.path.join(b, "wronggpu-asi.ini") # (the plugin's settings file is not in the record: nothing proves it WrongGPU's, so it is not rewritten; the result says so) t.check("update of a Preset K install (no Preset K in this build): starts on Model M, the log says so; the plugin's settings file is left as it is and the result says so", - rc == 0 and "now starts on Model M" in t.logtail(20000) and "model=M" in (options_line(ini(b)) or "") and + rc == 0 and "now starts on Model M" in t.logtail(20000) and "model=M" in (options_line(eff_ini(b)) or "") and read(asi_ini) == b"; WrongGPU OptiScaler plugin\r\nselection=wronggpu-k\r\n" and any(w.startswith("Left in place (the plugin's settings file selects an entry this version lacks)") for w in t.j.get("warnings", [])), - (rc, options_line(ini(b)), t.j.get("warnings"), t.logtail(1500))) + (rc, options_line(eff_ini(b)), t.j.get("warnings"), t.logtail(1500))) prev_txt = os.path.join(b, "wronggpu-setup", "previous", "previous.txt") t.check("update: exit 0; the earlier version kept in previous\\", rc == 0 and os.path.isfile(prev_txt) and "version=0.5.1" in read(prev_txt).decode(), (rc, t.j.get("message"), t.logtail())) rec = record_text(b) - t.check("update: the settings survive (profile re-applied)", "output_filter=quality9" in (options_line(ini(b)) or "") and "ShowFps=true" in ini(b, "OptiScaler.ini"), - (options_line(ini(b)), ini(b, "OptiScaler.ini"))) + t.check("update: the settings survive (profile re-applied)", "output_filter=quality9" in (options_line(eff_ini(b)) or "") and "ShowFps=true" in ini(b, "OptiScaler.ini"), + (options_line(eff_ini(b)), ini(b, "OptiScaler.ini"))) t.check("update: record at this version", "\nversion\t0.5.1" not in rec, rec[:300]) rc = t.run("rollback", exe) rec = record_text(b) @@ -421,7 +455,7 @@ def test_install_settings_uninstall(t, opti): rc = t.run("rollback", exe) t.check("roll back again: back to the newer version", rc == 0 and "\nversion\t0.5.1\r\n" not in record_text(b), t.j.get("message")) rc = t.run("repair", exe, "--opti=" + opti, "--noscan", "--force") - t.check("repair: exit 0, settings kept", rc == 0 and "output_filter=quality9" in (options_line(ini(b)) or ""), (rc, t.j.get("message"))) + t.check("repair: exit 0, settings kept", rc == 0 and "output_filter=quality9" in (options_line(eff_ini(b)) or ""), (rc, t.j.get("message"))) # a missing settings file is one problem, said once (the record lists wronggpu.ini as a file of the install too) os.remove(os.path.join(b, "wronggpu.ini")) rc = t.run("status", exe) @@ -433,7 +467,7 @@ def test_install_settings_uninstall(t, opti): write(rec_path, "\r\n".join("version\t0.5.1" if l.startswith("version\t") else l for l in lines)) rc = t.run("repair", exe, "--opti=" + opti, "--noscan", "--force") t.check("repair of an older version: wronggpu.ini back with the settings, the message says it updated from 0.5.1", - rc == 0 and "output_filter=quality9" in (options_line(ini(b)) or "") and "updated from 0.5.1 to" in t.j.get("message", ""), (rc, t.j.get("message"))) + rc == 0 and "output_filter=quality9" in (options_line(eff_ini(b)) or "") and "updated from 0.5.1 to" in t.j.get("message", ""), (rc, t.j.get("message"))) # the elevated worker's job (run here without elevation: the same code path) job = os.path.join(t.work, "job.txt") result = os.path.join(t.work, "result.txt") @@ -441,7 +475,7 @@ def test_install_settings_uninstall(t, opti): rc = t.run("apply", "--job=" + job, "--result=" + result) res = read(result).decode("utf-8", "replace") if os.path.isfile(result) else "" t.check("apply --job: the worker writes the result; the job's settings are in the files", rc == 0 and "code=0" in res and - "output_filter=analytic" in (options_line(ini(b)) or "") and "ShowFps=false" in ini(b, "OptiScaler.ini"), (rc, res)) + "output_filter=analytic" in (options_line(eff_ini(b)) or "") and "ShowFps=false" in ini(b, "OptiScaler.ini"), (rc, res)) write(job, "op=apply\r\ndir=relative\\folder\r\nlocalappdata=%s\r\n" % t.env["LOCALAPPDATA"]) rc = t.run("apply", "--job=" + job, "--result=" + result) t.check("apply --job with a relative path: refused (exit 10)", rc == 10 and "code=10" in read(result).decode(), rc) @@ -459,7 +493,7 @@ def test_install_settings_uninstall(t, opti): rc = t.run("apply", "--batch=" + batch) res = [read(f).decode("utf-8", "replace") if os.path.isfile(f) else "" for f in results] t.check("apply --batch: both jobs run in order, each writes its result (the last one's settings are in the files)", - rc == 0 and all("code=0" in r for r in res) and t.j.get("ran") == 2 and "output_filter=analytic" in (options_line(ini(b)) or ""), (rc, res, t.j)) + rc == 0 and all("code=0" in r for r in res) and t.j.get("ran") == 2 and "output_filter=analytic" in (options_line(eff_ini(b)) or ""), (rc, res, t.j)) for f in results: if os.path.exists(f): os.remove(f) @@ -468,7 +502,7 @@ def test_install_settings_uninstall(t, opti): rc = t.run("apply", "--batch=" + batch) res = [read(f).decode("utf-8", "replace") if os.path.isfile(f) else "" for f in results] t.check("apply --batch with stop=1: the first fails (exit 10), the second is not run and its result says so (code -1, the files unchanged)", - rc == 10 and "code=10" in res[0] and "code=-1" in res[1] and t.j.get("ran") == 1 and "output_filter=analytic" in (options_line(ini(b)) or ""), (rc, res, t.j)) + rc == 10 and "code=10" in res[0] and "code=-1" in res[1] and t.j.get("ran") == 1 and "output_filter=analytic" in (options_line(eff_ini(b)) or ""), (rc, res, t.j)) # collect logs zpath = os.path.join(t.work, "support.zip") rc = t.run("collect", exe, "--zip=" + zpath) @@ -705,9 +739,9 @@ def test_rc6_hunt(t, opti): state = os.path.join(b, "wronggpu-setup") t.check("L4: the update failed after the earlier install was removed: no record, the game's files back", rc == 0 and rc2 == 0 and rc3 != 0 and not os.path.isfile(rp) and not os.path.isfile(os.path.join(b, "wronggpu_runtime.dll")), (rc, rc2, rc3, t.j.get("message"))) - t.check("L4: profile.ini and previous\\ (Roll back) are kept; the uninstaller without a record is gone", + t.check("L4: profile.ini, previous\\ (Roll back) and all the failed run did not make stay (the earlier uninstaller too)", os.path.isfile(os.path.join(state, "profile.ini")) and os.path.isfile(os.path.join(state, "previous", "previous.txt")) and - not os.path.isfile(os.path.join(state, "uninstall.exe")), sorted(os.listdir(state)) if os.path.isdir(state) else None) + os.path.isfile(os.path.join(state, "uninstall.exe")), sorted(os.listdir(state)) if os.path.isdir(state) else None) rc = t.run("install", exe, "--opti=" + opti, "--noscan", "--force") rc2 = t.run("get", exe) t.check("L4: the next install starts with the kept settings", rc == 0 and rc2 == 0 and @@ -1009,7 +1043,7 @@ def synth_f_dll(folder): def rr_ini(b): - """The RR plugin's settings file ([wronggpu] key=value) as a dict, lower-cased keys.""" + """The RR plugin's effective settings ([wronggpu] key=value of its file, then the state's rr_* keys), lower-cased keys.""" out, sec = {}, "" for line in ini(b, RR_SETTINGS).replace("\r", "").split("\n"): s = line.strip() @@ -1018,6 +1052,7 @@ def rr_ini(b): elif sec == "[wronggpu]" and "=" in s and not s.startswith(("#", ";")): k, v = s.split("=", 1) out[k.strip().lower()] = v.strip() + out.update({k: v for k, v in state_kv(b).items() if k.startswith("rr_")}) # #219: the saved settings over the file return out @@ -1061,6 +1096,7 @@ def test_rr(t, opti, synth_f): rc == 0 and all(os.path.isfile(p) for p in files.values()) and os.path.isfile(os.path.join(b, "plugins", "WrongGPU.asi")), (rc, t.j.get("message"), t.logtail())) if rc != 0: return + rr0 = read(files["settings"]) # #219: never rewritten after install; later changes go into the state folder t.check("install: every RR file is an entry of the record (copy, its hash)", all(record_entry_sha(b, rel) for rel in ("plugins\\WrongGPU-RR.asi", "wronggpu_runtime.dll", "wronggpu-rr.ini", RR_SETTINGS)) and "wronggpu_rr_runtime.dll" not in rec, rec[:2500]) t.check("install: wronggpu-rr.ini names the shared RR data file", ("rr_model=" + fdata).lower() in ini(b, "wronggpu-rr.ini").lower(), ini(b, "wronggpu-rr.ini")) @@ -1087,8 +1123,9 @@ def test_rr(t, opti, synth_f): t.check("rr-data convert: the RR data written and valid, its source named, the source file untouched", rc == 0 and rd.get("valid") is True and os.path.isfile(fdata) and rd.get("source", "").lower() == src.lower() and read(src) == src_bytes, (rc, t.j, t.logtail())) s = rr_ini(b) - t.check("after the conversion: the installed RR game's settings file turns RR on, the record follows", - s.get("rr_enabled") == "1" and record_entry_sha(b, RR_SETTINGS) == sha(read(files["settings"])), (s, record_entry_sha(b, RR_SETTINGS))) + t.check("after the conversion: the installed RR game's saved settings turn RR on (state), its WrongGPU\\wronggpu.ini and record entry as installed", + s.get("rr_enabled") == "1" and state_kv(b).get("rr_enabled") == "1" and read(files["settings"]) == rr0 and + record_entry_sha(b, RR_SETTINGS) == sha(rr0), (s, record_entry_sha(b, RR_SETTINGS))) rc = t.run("status", exe) t.check("status: RR on", rc == 0 and t.j.get("game", {}).get("rr_enabled") is True, t.j.get("game")) rc = t.run("rr-data", "status") @@ -1105,9 +1142,9 @@ def test_rr(t, opti, synth_f): rc = t.run("install", exe2, "--opti=" + opti, "--noscan", "--force", "--experimental") warn2 = t.j.get("warnings", []) s1 = rr_ini(b) - t.check("a second RR game's install converts the data from its own file; the RR game installed before it gets RR too (its file and record follow)", + t.check("a second RR game's install converts the data from its own file; the RR game installed before it gets RR too (its saved settings; its file as installed)", rc == 0 and os.path.isfile(fdata) and rr_ini(b2).get("rr_enabled") == "1" and s1.get("rr_enabled") == "1" and - record_entry_sha(b, RR_SETTINGS) == sha(read(files["settings"])) and not any("Ray Reconstruction" in w for w in warn2), + read(files["settings"]) == rr0 and not any("Ray Reconstruction" in w for w in warn2), (rc, s1, rr_ini(b2), warn2, t.logtail())) rc = t.run("status", exe) t.check("status of the game installed before: RR on", rc == 0 and t.j.get("game", {}).get("rr_enabled") is True, t.j.get("game")) @@ -1126,8 +1163,8 @@ def test_rr(t, opti, synth_f): # settings: the profile's rr_enabled and rr_mode into WrongGPU\wronggpu.ini (rr_exact_allowed only with exact) rc = t.run("set", exe, "rr_mode=fast") s = rr_ini(b) - t.check("set rr_mode=fast: written, Exact not allowed, the record follows", rc == 0 and s.get("rr_mode") == "fast" and s.get("rr_exact_allowed") == "0" and - record_entry_sha(b, RR_SETTINGS) == sha(read(files["settings"])), (rc, s, t.j.get("message"))) + t.check("set rr_mode=fast: saved in the state folder, Exact not allowed, WrongGPU\\wronggpu.ini as installed", rc == 0 and s.get("rr_mode") == "fast" and + s.get("rr_exact_allowed") == "0" and state_kv(b).get("rr_mode") == "fast" and read(files["settings"]) == rr0, (rc, s, t.j.get("message"))) rc = t.run("set", exe, "rr_mode=exact") s = rr_ini(b) t.check("set rr_mode=exact: rr_exact_allowed=1 with it", rc == 0 and s.get("rr_mode") == "exact" and s.get("rr_exact_allowed") == "1", (rc, s)) @@ -1157,9 +1194,9 @@ def test_rr(t, opti, synth_f): t.check("update from an older version (rc5): an existing rr_mode=accurate stays, in the profile and the file", rc == 0 and rcg == 0 and t.j.get("settings", {}).get("rr_mode", {}).get("profile") == "accurate" and rr_ini(b).get("rr_mode") == "accurate", (rc, t.j.get("settings", {}).get("rr_mode"), rr_ini(b), t.logtail(800))) - # the player switches it in the game (OptiScaler's menu): the plugin saves rr_mode and its own key; the next scan shows it, - # and an update or repair keeps it - write(files["settings"], read(files["settings"]).replace(b"rr_mode=accurate", b"rr_mode = fast\r\nrr_overlay=1")) + # the player switches it in the game (OptiScaler's menu): the plugin saves rr_mode in the state folder (#219); the next scan + # shows it, and an update or repair keeps it + state_set(b, "rr_mode", "fast") rc = t.run("status", exe) t.check("switched in the game: status shows rr_mode fast", rc == 0 and t.j.get("game", {}).get("rr_mode") == "fast", t.j.get("game")) rc = t.run("repair", exe, "--opti=" + opti, "--noscan", "--force", "--experimental") @@ -1259,15 +1296,18 @@ def test_rr(t, opti, synth_f): rq = t.j.get("rr_recheck", {}) t.check("rr-recheck with the same driver and runtime: not stale (ready), nothing run", rc == 0 and rq.get("stale") is False and rq.get("state_before") == "ready" and rq.get("result") == -1, t.j) - # the plugin rewrote both settings files while the game ran; uninstall still leaves the folder as it was + # the player edited both RR settings files by hand; the state folder holds the saved settings (#219) write(files["ini"], read(files["ini"]) + b"rr_plugin_key=1\r\n") write(files["settings"], read(files["settings"]) + b"rr_last_seen=1\r\n") - # the install created both settings files and the plugin rewrote them: their bytes are no longer the recorded ones, so the - # uninstall leaves them as they are (with the wronggpu-* logs that are not in the record) and says so + stated = os.path.isfile(os.path.join(b, STATE)) + # the install created both settings files and the player changed them: their bytes are no longer the recorded ones, so the + # uninstall leaves them as they are (with the wronggpu-* logs that are not in the record) and says so; the state folder is + # WrongGPU's and goes left = kept_runtime(before, root, *[os.path.relpath(files[k], root) for k in ("ini", "settings")], *unrecorded_wronggpu_files(root)) rc = t.run("uninstall", exe) after = snapshot(root) - t.check("uninstall: exit 0, the RR game's folder as before except the two RR settings files the plugin rewrote and the unrecorded logs, which stay as they are", + t.check("uninstall: exit 0, the RR game's folder as before except the two RR settings files edited by hand and the unrecorded logs, which stay as they are; " + "the saved settings (wronggpu-setup\\settings.ini) gone", stated and rc == 0 and after == left and any(w == "Left in place (changed since install): " + os.path.relpath(files["ini"], b) for w in t.j.get("warnings", [])), (rc, t.j.get("message"), diff(left, after), t.j.get("warnings"))) t.check("uninstall: the shared RR data stays for the other games", os.path.isfile(fdata) == data_on) @@ -1818,7 +1858,10 @@ def set_writable(root): def outside_pre_exposure(b): - # a value changed outside the launcher: pre_exposure=original added to wronggpu.ini's runtime_options line (r3 #1) + # a value changed outside the launcher: pre_exposure=original added to wronggpu.ini's runtime_options line (r3 #1); with + # saved settings (#219: they decide over wronggpu.ini) the change is made there + if os.path.isfile(os.path.join(b, STATE)): + return state_set(b, "pre_exposure", "original") out = [] for line in ini(b).split("\n"): if line.strip().lower().startswith("runtime_options") and "=" in line: @@ -1958,8 +2001,8 @@ def rr_page(tag, env=None, extra=()): ch = changed_keys(game_before, snapshot(root)) t.check("...the window's own apply on the game's page writes Engine.ini alone: only the install record changed in the game folder, " "wronggpu.ini byte for byte with the outside pre_exposure, the page's unsaved change still unsaved (r3 #1)", - ch and all(k.endswith("wronggpu-setup/install.record") for k in ch) and "pre_exposure=original" in (options_line(ini(b)) or "") and - du.get("from_library") is False and du.get("edit_kept") is True, (ch, options_line(ini(b)), du.get("edit_kept"))) + ch and all(k.endswith("wronggpu-setup/install.record") for k in ch) and "pre_exposure=original" in (options_line(eff_ini(b)) or "") and + du.get("from_library") is False and du.get("edit_kept") is True, (ch, options_line(eff_ini(b)), du.get("edit_kept"))) t.check("window opens with the folder there: the choice applied once (Borderlands 4: Windows\\Engine.ini, the 45-byte file, read-only), the toast says so (r2b #1)", rx == 0 and du.get("due") is True and du.get("entry_due") is True and du.get("started") is True and du.get("applied") is True and du.get("state") == 1 and du.get("fixed_after") is True and "has the Ray Reconstruction setting now" in du.get("toast", "") and du.get("again") is False and @@ -1995,18 +2038,21 @@ def rr_page(tag, env=None, extra=()): rx == 0 and du.get("from_library") is True and du.get("started") is True and du.get("applied") is True and du.get("state") == 1 and du.get("asks") == 0 and du.get("edit_kept") is True and read(bl4_ini) == new_file and read_only(bl4_ini) and re.search(r"(?m)^rrconfig\t" + re.escape(bl4_ini) + r"\tcr\tabsent\t-\r?$", record_text(b)) is not None and - ch and all(k.endswith("wronggpu-setup/install.record") for k in ch) and "pre_exposure=original" in (options_line(ini(b)) or ""), - (rx, du, ch, options_line(ini(b)))) - edited = read(os.path.join(b, "wronggpu.ini")) # (changed outside the launcher above: not WrongGPU's bytes any more) + ch and all(k.endswith("wronggpu-setup/install.record") for k in ch) and "pre_exposure=original" in (options_line(eff_ini(b)) or ""), + (rx, du, ch, options_line(eff_ini(b)))) + edited = read(os.path.join(b, "wronggpu.ini")) # (#219: the outside change above is in the saved settings, which go with the state folder) + theirs = sha(edited) != record_entry_sha(b, "wronggpu.ini") rc = t.run("uninstall", exe) - # (0.6.1, the ownership rule: the wronggpu.ini changed outside the launcher stays as it is, the only file left) + # (0.6.1, the ownership rule: a wronggpu.ini changed outside the launcher stays as it is, the only file left) want = dict(before) - want[os.path.relpath(os.path.join(b, "wronggpu.ini"), root).replace("\\", "/").lower()] = sha(edited) + if theirs: + want[os.path.relpath(os.path.join(b, "wronggpu.ini"), root).replace("\\", "/").lower()] = sha(edited) t.check("...uninstall takes that line out: Engine.ini gone, the game's settings folder stays, the game folder as before the install, the outside-edited " "wronggpu.ini left as it is (r3 #1)", rc == 0 and not os.path.exists(bl4_ini) and os.listdir(os.path.dirname(bl4_ini)) == ["GameUserSettings.ini"] and snapshot(root) == want, (rc, msgs(), diff(want, snapshot(root)))) - os.remove(os.path.join(b, "wronggpu.ini")) + if theirs: + os.remove(os.path.join(b, "wronggpu.ini")) os.remove(rr_lib) # r6 #5 / r7 #5: the game without the RR library now, so WrongGPU's RR files don't go in rc = t.run("install", exe, "--opti=" + opti, "--noscan", "--force", "--experimental") t.check("...installed again for the checks below (without WrongGPU's RR files)", rc == 0 and "WrongGPU-RR.asi" not in record_text(b), (rc, t.j.get("message"))) @@ -2053,10 +2099,9 @@ def rr_page(tag, env=None, extra=()): rc == 0 and rc2 == 0 and "WrongGPU-RR.asi" in record_text(b) and os.path.isfile(os.path.join(b, RR_SETTINGS)), (rc, rc2, t.j.get("message"))) def rr_data_ready(): - """RR on in the game's RR settings file, as the RR data's conversion leaves an RR install (RefreshRrSettings): this run has - no RR data, so the install wrote rr_enabled=0 (r6 #5)""" - p = os.path.join(b, RR_SETTINGS) - write(p, re.sub(rb"(?m)^(rr_enabled[ \t]*=[ \t]*)0", rb"\g<1>1", read(p))) + """RR on in the game's saved settings, as the RR data's conversion leaves an RR install (RefreshRrSettings, #219: the state + folder): this run has no RR data, so the install wrote rr_enabled=0 (r6 #5)""" + state_set(b, "rr_enabled", "1") return rr_ini(b).get("rr_enabled") == "1" # r2c: the game in a protected folder (WRONGGPU_TEST_PROTECTED: its folder counts as needing administrator permission). # The window never adds the line by itself there: opening the launcher or the page, or Check again, asks Windows for @@ -2258,7 +2303,7 @@ def set_no_docs(*kv): "byte for byte with the outside pre_exposure; the toast says it is saved (r4 #4)", ch == [k for k in ch if k.endswith("wronggpu-setup/profile.ini")] and len(ch) == 1 and all(l.strip().startswith("rr_config_fix") for l in pdiff) and len(pdiff) == 2 and read(os.path.join(b, "wronggpu.ini")) == wini_before and - "pre_exposure=original" in (options_line(ini(b)) or "") and "Saved: you add" in sa.get("toast", ""), (ch, pdiff, sa.get("toast"))) + "pre_exposure=original" in (options_line(eff_ini(b)) or "") and "Saved: you add" in sa.get("toast", ""), (ch, pdiff, sa.get("toast"))) # r4 #4: Fix it for me, answered from a profile captured before a change (its sparkle_guard differs from the saved one): the # line added, rr_config_fix=on saved alone; the saved sparkle_guard, the outside pre_exposure and every other file stay rc = t.run("set", exe, "rr_config_fix=ask") @@ -2277,7 +2322,7 @@ def set_no_docs(*kv): "line alone) and install.record changed in the game folder; wronggpu.ini byte for byte with the outside pre_exposure (r4 #4)", ch and all(k.endswith("wronggpu-setup/profile.ini") or k.endswith("wronggpu-setup/install.record") for k in ch) and all(l.strip().startswith("rr_config_fix") for l in pdiff) and len(pdiff) == 2 and read(os.path.join(b, "wronggpu.ini")) == wini_before and - "pre_exposure=original" in (options_line(ini(b)) or "") and ff.get("sparkle_guard") != ff.get("stale_sparkle_guard"), (ch, pdiff, ff)) + "pre_exposure=original" in (options_line(eff_ini(b)) or "") and ff.get("sparkle_guard") != ff.get("stale_sparkle_guard"), (ch, pdiff, ff)) rc = t.run("set", exe, "rr_config_fix=off") t.check("...off takes that line out again (Engine.ini gone, no record line)", rc == 0 and not os.path.exists(bl4_ini) and "rrconfig " not in record_text(b), (rc, msgs())) @@ -2609,6 +2654,10 @@ def set_no_docs(*kv): shutil.rmtree(d, ignore_errors=True) +def test_state(t, opti): # #219, in launcher_state_cases.py + __import__("launcher_state_cases").run(t, opti, sys.modules[__name__]) + + def test_edition_download(t, opti): # in launcher_edition_cases.py (this file stays below the 256 KB source limit) __import__("launcher_edition_cases").run(t, opti, game, edition_package, OPTI_INI) @@ -3072,6 +3121,7 @@ def main(): test_install_settings_uninstall(t, opti) test_slot(t) test_rr(t, opti, a.synth_f) + test_state(t, opti) test_re9(t, opti, a.synth_f) test_direct_rr(t, opti, a.synth_f) test_sm2_settings(t, opti) diff --git a/clean/rr_f/proxy/include/wg_settings_reader.h b/clean/rr_f/proxy/include/wg_settings_reader.h index 99573f49..beb9b95e 100644 --- a/clean/rr_f/proxy/include/wg_settings_reader.h +++ b/clean/rr_f/proxy/include/wg_settings_reader.h @@ -30,6 +30,7 @@ #include "../../../wgshared/include/wg_registry_gen.h" #include "../../../wgshared/include/wg_shared_settings.h" +#include "../../../wgshared/include/wg_state.h" // #219: the game's state folder (settings.ini), its lock, the loaded protocol namespace wgss { @@ -148,6 +149,29 @@ inline const std::string* ini_find(const std::vector& ini, const char* return v; } +// ------------------------------------------------------------------------------------------------ the game's state (#219) +// Settings chosen after the install (the launcher, this plugin's menu) live in the game's state folder, +// \wronggpu-setup\settings.ini (wg_state.h), and take precedence over WrongGPU\wronggpu.ini, the install's +// defaults, which this plugin never writes. Game folder: WG_STATE_GAME_DIR when set (tests), else the exe's folder. +inline std::wstring state_game_dir() { + wchar_t buf[MAX_PATH * 2]; + const DWORD n = GetEnvironmentVariableW(L"WG_STATE_GAME_DIR", buf, (DWORD)(sizeof buf / sizeof buf[0])); + if (n > 0 && n < sizeof buf / sizeof buf[0]) return std::wstring(buf, n); + return exe_dir(); +} +// The state folder's settings appended to `ini` as [wronggpu] entries (the last value of a key wins: they decide). +inline void add_state_settings(std::vector* ini) { + const wgstate::Settings s = wgstate::ReadSettings(state_game_dir()); // (whole files only: written atomically) + for (const auto& kv : s.kv) ini->push_back({"wronggpu", kv.first, kv.second}); +} +// WrongGPU\wronggpu.ini, then the state folder's settings over it. False when neither has anything. +inline bool read_rr_settings(std::vector* out) { + const bool have = read_ini(data_dir() + L"wronggpu.ini", out); + const size_t n = out->size(); + add_state_settings(out); + return have || out->size() != n; +} + // ------------------------------------------------------------------------------------------------ registry helpers inline const WgOptionDef* option_by_key(const std::string& key) { for (const WgOptionDef& o : kWgOptions) @@ -429,7 +453,7 @@ class Block { bool have = false; if (!seed_test) { const std::wstring main = data_dir() + L"wronggpu.ini"; - have = read_ini(main, &ini); + have = read_rr_settings(&ini); // (#219: with the state folder's settings over it) used = main; if (!have && !legacy_ini.empty() && read_ini(legacy_ini, &ini)) { have = true; diff --git a/clean/rr_f/proxy/src/rr_enabled.h b/clean/rr_f/proxy/src/rr_enabled.h index e3ac9042..f784794d 100644 --- a/clean/rr_f/proxy/src/rr_enabled.h +++ b/clean/rr_f/proxy/src/rr_enabled.h @@ -6,10 +6,11 @@ // creates RR, so a later change applies at the next game start, as the launcher writes it while the game is closed). // // Where it is read, first hit wins: -// 1. \wronggpu.ini, [wronggpu] rr_enabled (the file the launcher writes; data dir = WG_DATA_DIR or -// \WrongGPU\); -// 2. the plugin's own wronggpu-rr.ini next to the game exe: rr_enabled, or the older 60.9 key wronggpu_rr; -// 3. on. +// 1. the game's state folder, \wronggpu-setup\settings.ini, rr_enabled (where the launcher writes it since +// 0.6.5, #219); +// 2. \wronggpu.ini, [wronggpu] rr_enabled (the install's defaults; data dir = WG_DATA_DIR or \WrongGPU\); +// 3. the plugin's own wronggpu-rr.ini next to the game exe: rr_enabled, or the older 60.9 key wronggpu_rr; +// 4. on. // Values as the registry parses them: 0 / 1, off / on, false / true, no / yes. An unreadable value is ignored (the next // source applies). #pragma once @@ -30,6 +31,15 @@ inline RrEnabled read_rr_enabled(const std::wstring& data_dir_ini, const std::ws const WgOptionDef& o = kWgOptions[WG_OPT_RR_ENABLED]; std::vector ini; int32_t v = 1; + // #219: the launcher's switch as it stands now is in the game's state folder (wronggpu-setup\settings.ini), over the + // install's defaults below (wg_settings_reader.h) + ini.clear(); + wgss::add_state_settings(&ini); + if (wgss::ini_value(ini, o, &v)) { + r.on = v != 0; + r.source = wgss::utf8(wgstate::SettingsPathOf(wgss::state_game_dir())); + return r; + } if (wgss::read_ini(data_dir_ini, &ini) && wgss::ini_value(ini, o, &v)) { r.on = v != 0; r.source = wgss::utf8(data_dir_ini); diff --git a/clean/rr_f/proxy/src/rr_panel.cpp b/clean/rr_f/proxy/src/rr_panel.cpp index 62f360a8..faf6dbf5 100644 --- a/clean/rr_f/proxy/src/rr_panel.cpp +++ b/clean/rr_f/proxy/src/rr_panel.cpp @@ -33,17 +33,19 @@ void log(const std::string& s) { if (g_log) g_log(s); } -std::wstring settings_file() { return wgss::data_dir() + L"wronggpu.ini"; } - -// rr_mode as it stands (block slot, else WG_RR_MODE, else wronggpu.ini, else the default), as a mode id. +// rr_mode as it stands (block slot, else WG_RR_MODE, else the game's settings: the state folder over wronggpu.ini, else the +// default), as a mode id. int32_t current_mode() { return resolved_mode().mode; } +// #219: the mode the player picks is saved in the game's state folder (wronggpu-setup\settings.ini, wg_state.h: under the +// game's state lock, written atomically), never into WrongGPU\wronggpu.ini (the install's defaults, the player's to edit). +// A write that fails (the launcher's operation holds the state lock, the folder is not writable, ...) is logged in words. void choose(int32_t mode) { const bool live = g_block.write_panel_slot(WG_OPT_RR_MODE, mode); - const bool saved = wgss::ini_set(settings_file(), "wronggpu", "rr_mode", kWgRrModeNames[mode]); + const wgstate::SetOutcome o = wgstate::SetSettings(wgss::state_game_dir(), {{"rr_mode", kWgRrModeNames[mode]}}, 1000); + const std::string saved = o.ok() ? std::string("saved to wronggpu-setup\\settings.ini") : "not saved: " + o.words(); log(std::string("menu: rr_mode=") + kWgRrModeNames[mode] + " chosen in OptiScaler's menu (" + - (live ? "from the next frame" : "shared settings unavailable: from the next start") + - (saved ? ", saved to wronggpu.ini)" : ", wronggpu.ini not written)")); + (live ? "from the next frame" : "shared settings unavailable: from the next start") + ", " + saved + ")"); } void draw(void*) { @@ -125,7 +127,7 @@ void start(LogFn log_fn, ActiveFn rr_active, GpuMsFn gpu_ms, PreparingFn prepari wgss::Snapshot snap; const bool have = g_block.present() && g_block.snapshot(WG_READER_RR_PLUGIN, &snap); std::vector ini; - if (!have) wgss::read_ini(settings_file(), &ini); + if (!have) wgss::read_rr_settings(&ini); // (#219: the state folder over wronggpu.ini) const bool allowed = wgss::resolve(kWgOptions[WG_OPT_RR_EXACT_ALLOWED], have ? &snap : nullptr, have ? nullptr : &ini).value != 0; g_exact_allowed.store(allowed); const int32_t mode = current_mode(); @@ -144,7 +146,7 @@ ModeSetting resolved_mode() { wgss::Snapshot snap; m.shared = g_block.present() && g_block.snapshot(WG_READER_RR_PLUGIN, &snap); std::vector ini; - if (!m.shared) wgss::read_ini(settings_file(), &ini); + if (!m.shared) wgss::read_rr_settings(&ini); // (#219: the state folder over wronggpu.ini) const wgss::Resolved r = wgss::resolve(kWgOptions[WG_OPT_RR_MODE], m.shared ? &snap : nullptr, m.shared ? nullptr : &ini, "wronggpu.ini"); m.mode = r.value; diff --git a/clean/rr_f/proxy/tests/test_hook_dll.cpp b/clean/rr_f/proxy/tests/test_hook_dll.cpp index 1adf2968..7c82e216 100644 --- a/clean/rr_f/proxy/tests/test_hook_dll.cpp +++ b/clean/rr_f/proxy/tests/test_hook_dll.cpp @@ -366,6 +366,10 @@ int main(int argc, char** argv) { : legacy_mode ? "[wronggpu]\r\nrr_enabled = 1\r\n" : "[wronggpu]\r\nrr_mode = accurate\r\n"); SetEnvironmentVariableW(L"WG_DATA_DIR", data.c_str()); + // #219: the game's state folder of this run (the menu saves rr_mode there, never into WrongGPU\wronggpu.ini) + CreateDirectoryW((data + L"wronggpu-setup").c_str(), nullptr); + DeleteFileW((data + L"wronggpu-setup\\settings.ini").c_str()); // (an earlier run's save: each run starts from the defaults) + SetEnvironmentVariableW(L"WG_STATE_GAME_DIR", data.c_str()); SetEnvironmentVariableW(L"WG_RR_MODE", nullptr); // the checks below see what the plugin hands over, nothing inherited HANDLE block_squatter = nullptr; // --fast-noblock: the block's name is taken, so no module can create the block if (fast_noblock) { @@ -763,17 +767,18 @@ int main(int argc, char** argv) { CHECK(menu::combo_count == 2 && menu::items[0] == "Accurate" && menu::items[1] == "Fast"); CHECK_EQ(menu::combo_index, 0); // accurate (exact_denied: exact shows as the accurate that runs) } - // the player picks Fast: shared settings + wronggpu.ini, and the box shows it at once + // the player picks Fast: shared settings + the game's state folder (#219), and the box shows it at once + const std::string iniBefore = file_text(data + L"wronggpu.ini"); menu::pick = exact ? 2 : 1; menu::draw(nullptr); - const std::string ini = file_text(data + L"wronggpu.ini"); - CHECK(ini.find("rr_mode=fast") != std::string::npos); - CHECK(ini.find("rr_mode = exact") == std::string::npos && ini.find("rr_mode = accurate") == std::string::npos); + const std::string state = file_text(data + L"wronggpu-setup\\settings.ini"); + CHECK(state.find("rr_mode=fast\r\n") != std::string::npos); + CHECK(file_text(data + L"wronggpu.ini") == iniBefore); // the install's defaults (the player's file) never rewritten menu::reset(); menu::draw(nullptr); CHECK_EQ(menu::combo_index, exact ? 2 : 1); std::vector L = read_lines(log_path); - CHECK(count(L, "menu: rr_mode=fast chosen in OptiScaler's menu (from the next frame, saved to wronggpu.ini)") == 1); + CHECK(count(L, "menu: rr_mode=fast chosen in OptiScaler's menu (from the next frame, saved to wronggpu-setup\\settings.ini)") == 1); } // upgrade-interface is not hooked by the release build: the call reaches the stand-in directly (unchanged slot). void* iface2 = nullptr; diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 7693cf1a..31aebd24 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -6,8 +6,9 @@ // 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 folder is WrongGPU's; its files are WrongGPU's by their bytes, their name and their install (the stamp, below): an +// uninstall removes a state file only while it carries WrongGPU's valid stamp for that name and install (an edited file, +// a copy, an unknown file stays and is listed); 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-- @@ -50,14 +51,16 @@ // 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. +// settings.ini (ParseSettings): key=value lines, key [a-z0-9_] 1..64 chars, value [A-Za-z0-9_.+-] 0..256 chars, spaces +// around '=' allowed; a key's first line counts. Everything else is kept as it is and written back unchanged: a UTF-8 BOM, +// comments (';' or '#', any UTF-8 text), blank lines, sections, unknown or other lines. CRLF or LF. CORRUPT is only text +// WrongGPU cannot keep as it is (a NUL or other control character, a CR that is not part of CRLF, bytes that are not UTF-8): +// readers treat it as empty and say so, and a save is REFUSED (Unparseable): the file is never replaced. Every line keeps +// its own line end; a save adds no final line end to a file that had none (unless the file is WrongGPU's own). // Written for this project; Windows API and the C++ standard library only. #include #include +#include #include #include #include @@ -479,11 +482,89 @@ inline WriteResult WriteAtomic(const std::wstring& path, const std::string& byte return r; } +// ---- WrongGPU's stamp: which state files are WrongGPU's, by their bytes, their name and their install -------------------- +// A state file WrongGPU created and nobody else changed ends with the stamp line "; wronggpu-written ", where +// is a 64-bit FNV-1a (16 lower-case hex digits) of every byte before that line, the file's own name (lower case) and this +// install's id (the record's install-id line, InstallIdOf). It tells WrongGPU's own bytes from an edit, a copy under another +// name and a copy from another install (it is no protection against a forgery). An uninstall deletes a state file only while +// its stamp is valid for its name and this install: an edited file, a copy, a file without the stamp (the player's, a +// temporary file a crash left) stays and is listed. A write keeps a file WrongGPU's only when it was (or nothing was there) +// and the install has an id: a file the player made or changed is written on WITHOUT a stamp and stays the player's. +// Readers see the stamp as a comment. +constexpr const char* kStampPrefix = "; wronggpu-written "; +inline std::string LowerAscii(std::string s) { for (auto& c : s) if (c >= 'A' && c <= 'Z') c = static_cast(c - 'A' + 'a'); return s; } +inline std::string StampCheck(const std::string& body, const std::string& name, const std::string& installId) { + uint64_t h = 1469598103934665603ull; // FNV-1a 64 over the body, then "\n\n" + auto feed = [&](const std::string& s) { for (unsigned char c : s) { h ^= c; h *= 1099511628211ull; } }; + feed(body); + feed("\n" + LowerAscii(name) + "\n" + installId); + static const char* hex = "0123456789abcdef"; + std::string s(16, '0'); + for (int i = 15; i >= 0; --i) { s[static_cast(i)] = hex[h & 15u]; h >>= 4; } + return s; +} +// body + its stamp line for the file `name` of the install `installId` (body ends with a line end, or is empty). +inline std::string Stamped(const std::string& body, const std::string& name, const std::string& installId) { + return body + kStampPrefix + StampCheck(body, name, installId) + "\r\n"; +} +// Where the stamp line starts when bytes end with one valid for `name` and `installId` ("\r\n" or "\n", or none, after it); +// npos: no valid stamp (also when installId is empty: an install without an id stamps nothing). +inline size_t ValidStampAt(const std::string& bytes, const std::string& name, const std::string& installId) { + if (installId.empty()) return std::string::npos; + std::string t = bytes; + if (!t.empty() && t.back() == '\n') t.pop_back(); + if (!t.empty() && t.back() == '\r') t.pop_back(); + const size_t nl = t.rfind('\n'); + const size_t start = nl == std::string::npos ? 0 : nl + 1; + const std::string last = t.substr(start), prefix = kStampPrefix; + if (last.size() != prefix.size() + 16 || last.compare(0, prefix.size(), prefix) != 0) return std::string::npos; + return last.substr(prefix.size()) == StampCheck(bytes.substr(0, start), name, installId) ? start : std::string::npos; +} +inline bool StampedByWrongGPU(const std::string& bytes, const std::string& name, const std::string& installId) { + return ValidStampAt(bytes, name, installId) != std::string::npos; +} +// This install's id: the "install-id" line of the record in the game's state folder (written by the launcher's +// install). Empty: no record, or a record without one (nothing is stamped then). +inline std::string InstallIdOf(const std::wstring& gameDir) { + std::string rec; + if (!ReadBytes(JoinPath(StateDirOf(gameDir), L"install.record"), &rec)) return ""; + const std::string key = "\ninstall-id\t"; + const size_t at = rec.find(key); + if (at == std::string::npos) return ""; + size_t e = at + key.size(); + std::string id; + while (e < rec.size() && ((rec[e] >= '0' && rec[e] <= '9') || (rec[e] >= 'a' && rec[e] <= 'f'))) id += rec[e++]; + return id.size() >= 16 && id.size() <= 64 ? id : ""; +} +inline std::string FileNameOf(const std::wstring& path) { + const size_t s = path.find_last_of(L"\\/"); + std::string n; + for (wchar_t c : path.substr(s == std::wstring::npos ? 0 : s + 1)) n += c < 0x80 ? static_cast(c) : '?'; + return n; +} +// A state file written atomically with WrongGPU's stamp for its name and install (for a writer that makes its file whole, +// such as the model choice record; it takes the state lock first). No install id: written without a stamp. +inline WriteResult WriteStamped(const std::wstring& gameDir, const std::wstring& path, const std::string& body) { + const std::string id = InstallIdOf(gameDir); + return WriteAtomic(path, id.empty() ? body : Stamped(body, FileNameOf(path), id)); +} + // ---- settings.ini ------------------------------------------------------------------------------------------------- +// One line of the file as read: its text (without the line end), its own line end ("\r\n", "\n", or none on a last line +// without one) and, for a key=value line WrongGPU uses, the key. +struct SettingsLine { + std::string text; + std::string key; // empty: a comment, a blank line, a section, or a line kept as it is (not a usable key=value) + std::string eol; +}; struct Settings { - std::vector> kv; // in file order + std::vector> kv; // the usable keys, in file order (a key's first line) + std::vector lines; // every line with its own line end, kept for the write + bool bom = false; // the file started with a UTF-8 BOM (kept) + std::string eol = "\r\n"; // the line end for lines WrongGPU adds (the file's first one) + bool endsWithEol = true; // the last line had a line end (or nothing was there) bool present = false; // the file was there and read - bool corrupt = false; // it was there and not in the format above (kv empty) + bool corrupt = false; // it was there and not text WrongGPU can keep (kv and lines 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 == '_'; } @@ -504,23 +585,71 @@ 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). +// Sets key=value: its line's text rewritten as "key=value" (its line end kept); a key not there: a new line at the end (the +// line before it gets a line end if it had none; the new line ends with one only when the file did). 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; } + for (auto& p : s.kv) + if (p.first == key) { + p.second = value; + for (auto& l : s.lines) if (l.key == key) { l.text = key + "=" + value; break; } + return true; + } s.kv.emplace_back(key, value); + if (!s.lines.empty() && s.lines.back().eol.empty()) s.lines.back().eol = s.eol; + s.lines.push_back({key + "=" + value, key, s.endsWithEol ? s.eol : std::string()}); + return true; +} +inline std::string TrimSpaces(const std::string& t) { + size_t a = 0, b = t.size(); + while (a < b && (t[a] == ' ' || t[a] == '\t')) ++a; + while (b > a && (t[b - 1] == ' ' || t[b - 1] == '\t')) --b; + return t.substr(a, b - a); +} +// Well-formed UTF-8 (no overlong forms, no surrogates, at most U+10FFFF). +inline bool Utf8Ok(const std::string& t) { + for (size_t i = 0; i < t.size();) { + const unsigned char c = static_cast(t[i]); + size_t n = c < 0x80 ? 0 : (c & 0xE0) == 0xC0 ? 1 : (c & 0xF0) == 0xE0 ? 2 : (c & 0xF8) == 0xF0 ? 3 : 9; + if (n == 9 || (n && i + n >= t.size())) return false; + uint32_t cp = n == 0 ? c : n == 1 ? (c & 0x1Fu) : n == 2 ? (c & 0x0Fu) : (c & 0x07u); + for (size_t k = 1; k <= n; ++k) { + const unsigned char d = static_cast(t[i + k]); + if ((d & 0xC0) != 0x80) return false; + cp = (cp << 6) | (d & 0x3Fu); + } + if ((n == 1 && cp < 0x80) || (n == 2 && cp < 0x800) || (n == 3 && (cp < 0x10000 || cp > 0x10FFFF)) || (cp >= 0xD800 && cp <= 0xDFFF)) return false; + i += n + 1; + } 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) { +// Parses settings.ini text tolerantly and keeps every line, with its own line end, for the write. A UTF-8 BOM, comments +// (';' or '#', any UTF-8 text, also one that looks like WrongGPU's stamp), blank lines, sections, spaces around '=' and lines +// WrongGPU does not use (an unknown key in another spelling, a value it does not take, a key's second line) are kept as they +// are; key=value lines with a valid key and value are the usable keys (a key's first line). CORRUPT (no keys, no lines; why +// says where): text WrongGPU cannot keep as it is: a NUL or other control character (a tab is fine), a CR that is not part +// of CRLF, or bytes that are not UTF-8. +inline Settings ParseSettings(const std::string& in) { Settings s; s.present = true; + std::string text = in; + if (text.size() >= 3 && static_cast(text[0]) == 0xEF && static_cast(text[1]) == 0xBB && + static_cast(text[2]) == 0xBF) { + s.bom = true; + text.erase(0, 3); + } auto corrupt = [&](int lineNo, const char* what) { s.kv.clear(); + s.lines.clear(); s.corrupt = true; s.why = "line " + std::to_string(lineNo) + ": " + what; return s; }; + if (!Utf8Ok(text)) return corrupt(0, "not UTF-8 text"); + const size_t firstLf = text.find('\n'); + if (firstLf != std::string::npos) s.eol = firstLf > 0 && text[firstLf - 1] == '\r' ? "\r\n" : "\n"; + s.endsWithEol = text.empty() || text.back() == '\n'; size_t a = 0; int lineNo = 0; while (a < text.size()) { @@ -530,23 +659,32 @@ inline Settings ParseSettings(const std::string& text) { 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 + std::string eol = lf ? "\n" : ""; + if (lf && !line.empty() && line.back() == '\r') { line.pop_back(); eol = "\r\n"; } // 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); + if (static_cast(c) < 0x20 && c != '\t') return corrupt(lineNo, c == '\r' ? "a CR that is not part of CRLF" : "a control character"); + SettingsLine l{line, "", eol}; + const std::string t = TrimSpaces(line); + const size_t eq = t.find('='); + if (!t.empty() && t[0] != ';' && t[0] != '#' && t[0] != '[' && eq != std::string::npos) { + const std::string k = TrimSpaces(t.substr(0, eq)), v = TrimSpaces(t.substr(eq + 1)); + if (ValidKey(k) && ValidValue(v) && !Get(s, k)) { l.key = k; s.kv.emplace_back(k, v); } + } + s.lines.push_back(std::move(l)); } return s; } +// The file's text: a new file (nothing read) starts with a comment saying what it is; a read one keeps its BOM and every line +// with its own line end, the changed keys rewritten and new keys at the end. No stamp (UpdateSettings adds it when the file is +// WrongGPU'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"; + std::string out = s.bom ? "\xEF\xBB\xBF" : ""; + if (!s.present && s.lines.empty()) { + 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; + } + for (const auto& l : s.lines) out += l.text + l.eol; return out; } // settings.ini of the game in gameDir, read now from disk. Missing: present = false, no keys. Unreadable or corrupt: no keys, @@ -563,7 +701,7 @@ inline Settings ReadSettings(const std::wstring& gameDir) { return ParseSettings(text); } -enum class SetResult { Ok, NoStateFolder, StateFolderUnknown, Busy, LockDenied, Unreadable, Invalid, AccessDenied, WriteFailed }; +enum class SetResult { Ok, NoStateFolder, StateFolderUnknown, Busy, LockDenied, Unreadable, Unparseable, Changed, Invalid, AccessDenied, WriteFailed }; inline const char* SetResultWords(SetResult r) { switch (r) { case SetResult::Ok: return "saved"; @@ -572,35 +710,79 @@ inline const char* SetResultWords(SetResult r) { 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::Unparseable: return "the settings file is not text WrongGPU can keep as it is, so nothing was saved (the file is left as it is)"; + case SetResult::Changed: return "another program changed or made the settings file while WrongGPU saved, so nothing was saved (its file is 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. +// The outcome of SetSettings / UpdateSettings: the result, its Win32 error, what was wrong with the file (Unparseable), whether +// a write happened, 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) + std::string why; // Unparseable: where (ParseSettings) + bool written = false; // Ok: a new file was written (false: nothing had changed) + 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 (!why.empty()) w += " (" + why + ")"; 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) { +// What the file is: its identity and its last write, to tell it was not changed or replaced. +struct FileIdentity { + DWORD volume = 0, indexHigh = 0, indexLow = 0, sizeHigh = 0, sizeLow = 0; + FILETIME written{}; + bool operator==(const FileIdentity& o) const { + return volume == o.volume && indexHigh == o.indexHigh && indexLow == o.indexLow && sizeHigh == o.sizeHigh && sizeLow == o.sizeLow && + written.dwLowDateTime == o.written.dwLowDateTime && written.dwHighDateTime == o.written.dwHighDateTime; + } +}; +inline bool IdentityOf(HANDLE h, FileIdentity* id) { + BY_HANDLE_FILE_INFORMATION fi{}; + if (!GetFileInformationByHandle(h, &fi)) return false; + id->volume = fi.dwVolumeSerialNumber; id->indexHigh = fi.nFileIndexHigh; id->indexLow = fi.nFileIndexLow; + id->sizeHigh = fi.nFileSizeHigh; id->sizeLow = fi.nFileSizeLow; id->written = fi.ftLastWriteTime; + return true; +} +// The file at path is still the one with `want`'s identity (opened for attributes only, sharing everything). +inline bool StillIdentity(const std::wstring& path, const FileIdentity& want) { + HANDLE h = CreateFileW(ExtendedPath(path).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) return false; + FileIdentity now; + const bool ok = IdentityOf(h, &now) && now == want; + CloseHandle(h); + return ok; +} +// What to change, decided from the file as it is now (read under the state lock): the keys and values to set. +using SettingsDecision = std::function>* changes)>; +// The read-decide-write of settings.ini under the game's state lock, safe against a player or another program writing the +// file meanwhile (the state lock coordinates WrongGPU's programs only): +// - The file is opened and HELD (reads shared, no writes, no deletes, no replace) from the read to just before the new file +// is moved into place: an editor's save in that time fails with a sharing violation and its bytes never reach the disk. +// - Right before the move, the file's identity and last write are checked once more (StillIdentity): a file changed or +// replaced in that moment refuses the save (Changed). A file that was not there is created only where nothing is +// (MoveFileExW without REPLACE): one that appeared meanwhile refuses the save (Changed). The other program's bytes stay. +// - decide() is called with the file as read under the lock (a decision never rests on a read made before another WrongGPU +// program's write); the changes that differ are applied, nothing differs: no write. +// - Unreadable or Unparseable (text WrongGPU cannot keep): never replaced, refused. Comments, lines WrongGPU does not use and +// every line's own line end are kept; only the file's valid stamp is taken off (and put back when the file stays +// WrongGPU's: it was WrongGPU's or new, and the install has an id). +// - The state folder is never created here. AccessDenied and LockDenied point to the launcher's elevated repair; Busy is +// contention. Test seam: TestFault("replace-held") with the file held, TestFault("replace-check") after it is let go and +// before the identity check (the tests act there; returning false). +inline SetOutcome UpdateSettings(const std::wstring& gameDir, const SettingsDecision& decide, 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; @@ -609,21 +791,88 @@ inline SetOutcome SetSettings(const std::wstring& gameDir, const std::vector kMaxStateBytes) return fail(SetResult::Unreadable, ERROR_FILE_TOO_LARGE); + } + if (!IdentityOf(held.h, &before)) return fail(SetResult::Unreadable, GetLastError()); + s = ParseSettings(text); + if (s.corrupt) { o.why = s.why; return fail(SetResult::Unparseable, 0); } + } + const std::string id = InstallIdOf(gameDir), name = FileNameOf(path); + const size_t stampAt = s.present ? ValidStampAt(text, name, id) : std::string::npos; + const bool ours = !id.empty() && (!s.present || stampAt != std::string::npos); + if (stampAt != std::string::npos) { // the valid stamp is the last line: off for the change (put back below) + s.lines.pop_back(); + s.endsWithEol = true; + } + std::vector> changes; + decide(s, &changes); + for (const auto& c : changes) if (!ValidKey(c.first) || !ValidValue(c.second)) return fail(SetResult::Invalid, 0); + bool changed = false; 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); + std::string body = RenderSettings(s); + if (ours && !body.empty() && body.back() != '\n') body += s.eol; // (WrongGPU's own file: its stamp on a line of its own) + const std::string bytes = ours ? Stamped(body, name, id) : body; + if (bytes.size() > kMaxStateBytes) { o.write.error = ERROR_FILE_TOO_LARGE; return fail(SetResult::WriteFailed, ERROR_FILE_TOO_LARGE); } + // the new file, complete and flushed, beside the held one + static volatile LONG counter = 0; + std::wstring tmp; + HANDLE th = INVALID_HANDLE_VALUE; + for (int attempt = 0; attempt < 16 && th == INVALID_HANDLE_VALUE; ++attempt) { + tmp = target + kTempMark + std::to_wstring(GetCurrentProcessId()) + L"-" + std::to_wstring(InterlockedIncrement(&counter)); + th = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (th == INVALID_HANDLE_VALUE && GetLastError() != ERROR_FILE_EXISTS && GetLastError() != ERROR_ALREADY_EXISTS) break; + } + if (th == INVALID_HANDLE_VALUE) { + o.write.error = GetLastError(); + return fail(o.write.error == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::WriteFailed, o.write.error); + } + DWORD put = 0; + bool ok = WriteFile(th, bytes.data(), static_cast(bytes.size()), &put, nullptr) && put == bytes.size() && FlushFileBuffers(th); + if (!ok) o.write.error = GetLastError() ? GetLastError() : ERROR_WRITE_FAULT; + if (!CloseHandle(th) && ok) { ok = false; o.write.error = o.write.closeError = GetLastError(); } + auto dropTemp = [&]() { if (!DeleteFileW(tmp.c_str())) { o.write.cleanupError = GetLastError(); o.write.tempLeft = tmp; } }; + if (!ok) { dropTemp(); return fail(SetResult::WriteFailed, o.write.error); } + Faulted("replace-held"); // (tests: another program tries to save the held file here; Windows refuses it) + const bool existed = held.h != INVALID_HANDLE_VALUE; + if (existed) { CloseHandle(held.h); held.h = INVALID_HANDLE_VALUE; } + Faulted("replace-check"); // (tests: another program changes or makes the file in this moment) + if (existed ? !StillIdentity(path, before) : false) { dropTemp(); return fail(SetResult::Changed, 0); } + if (!MoveFileExW(tmp.c_str(), target.c_str(), (existed ? MOVEFILE_REPLACE_EXISTING : 0) | MOVEFILE_WRITE_THROUGH)) { + const DWORD me = GetLastError(); + dropTemp(); + if (!existed && (me == ERROR_ALREADY_EXISTS || me == ERROR_FILE_EXISTS)) return fail(SetResult::Changed, 0); // it appeared: the other program's + o.write.error = me; + return fail(me == ERROR_ACCESS_DENIED ? SetResult::AccessDenied : SetResult::WriteFailed, me); + } + o.write.ok = true; + o.written = true; return o; } +// UpdateSettings with fixed changes (a key already at its value is not written again). +inline SetOutcome SetSettings(const std::wstring& gameDir, const std::vector>& changes, DWORD waitMs = kDefaultWaitMs) { + for (const auto& c : changes) + if (!ValidKey(c.first) || !ValidValue(c.second)) { SetOutcome o; o.result = SetResult::Invalid; return o; } + return UpdateSettings(gameDir, [&](const Settings&, std::vector>* out) { *out = changes; }, waitMs); +} } // namespace wgstate diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp index cc9c18f2..6ed6d33e 100644 --- a/clean/wgshared/tests/test_wg_state.cpp +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -1,10 +1,15 @@ // 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); +// - the settings.ini format: tolerant (BOM, comments in any UTF-8, spaces around '=', sections, unknown lines: kept and +// written back), corrupt only for text that cannot be kept (a control character, a CR outside CRLF, not UTF-8); +// - WrongGPU's stamp: a new file is stamped, an edited or player-made file is written on without one; +// - the decision under the state lock (UpdateSettings): a write made while another thread holds the lock is what decide() +// sees (forced interleaving); // - 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; +// - SetSettings: no state folder, a folder this process may not write (AccessDenied, its own result), unreadable, a file it +// cannot keep (Unparseable: refused, the bytes stay), the player's keys and comments kept; // - 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 @@ -21,12 +26,17 @@ #include #include #include +#include #include #include "wg_state.h" using namespace wgstate; +static const char* kId = "abcdef0123456789abcdef0123456789"; // the install id the test's record names +static std::wstring g_hookFile; // the settings file the interleaving hooks act on +static DWORD g_editorWriteError = 0, g_editorMoveError = 0; + static int g_fail = 0, g_pass = 0; static void check(bool ok, const char* what) { if (ok) ++g_pass; @@ -57,7 +67,9 @@ static std::vector List(const std::wstring& dir) { 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)); + do { // (the record with the install id is not counted: the tests count settings.ini and temporary files) + if (wcscmp(f.cFileName, L".") && wcscmp(f.cFileName, L"..") && _wcsicmp(f.cFileName, L"install.record")) out.push_back(f.cFileName); + } while (FindNextFileW(h, &f)); FindClose(h); return out; } @@ -193,17 +205,49 @@ int wmain(int argc, wchar_t** argv) { const std::wstring game = JoinPath(root, L"Game"); CreateDirectoryW(game.c_str(), nullptr); - // ---- the strict format + // ---- the format: tolerant, everything kept; corrupt only for text that cannot be kept { 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"}; + struct { const char* text; const char* key; const char* value; } kept[] = { + {"rr_mode = fast\r\n", "rr_mode", "fast"}, {"[wronggpu]\r\nrr_mode=fast\r\n", "rr_mode", "fast"}, + {"RR_MODE=fast\r\n", nullptr, nullptr}, {"rr_mode=fast\r\nrr_mode=accurate\r\n", "rr_mode", "fast"}, + {"rr_mode\r\n", nullptr, nullptr}, {"rr_mode=fa st\r\n", nullptr, nullptr}, {"=fast\r\n", nullptr, nullptr}, + {"rr_mode=f\xc3\xa4st\r\n", nullptr, nullptr}, {"; \xc3\xa4 a note\r\nrr_mode=exact\r\n", "rr_mode", "exact"}, + {"# hash comment\r\n\trr_mode =\taccurate \r\n", "rr_mode", "accurate"}, {"\xEF\xBB\xBFrr_mode=fast\r\n", "rr_mode", "fast"}}; 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"); + for (const auto& k : kept) { + const Settings x = ParseSettings(k.text); + const bool good = !x.corrupt && (k.key ? (Get(x, k.key) && *Get(x, k.key) == k.value) : x.kv.empty()) && RenderSettings(x) == std::string(k.text); + if (!good) std::printf(" (kept case %s: corrupt %d, keys %zu, render %s)\n", k.text, x.corrupt, x.kv.size(), RenderSettings(x).c_str()); + all = all && good; + } + check(all, "parse: spaces around '=', sections, upper case, a key twice (the first counts), no '=', a value WrongGPU does not take, " + "non-ASCII comments and values, '#' comments, tabs, a BOM: read, and written back byte for byte"); + const std::string nul("rr_mode=fast\r\nnote=a\0b\r\n", 24); + const char* bad[] = {"rr_mode=fast\r", "rr_mode=fa\rst\r\n", "rr_mode=fast\r\r\n", "; a\rb\n", "; \xff\xfe not UTF-8\r\n", "k=v\x01\r\n"}; + bool allBad = ParseSettings(nul).corrupt; + for (const char* b : bad) { const Settings x = ParseSettings(b); allBad = allBad && x.corrupt && x.kv.empty() && x.lines.empty() && !x.why.empty(); } + check(allBad, "parse: a NUL or other control character, a bare or embedded CR, bytes that are not UTF-8: corrupt (nothing WrongGPU could keep)"); check(!ParseSettings("rr_mode=fast").corrupt, "parse: a last line without a line end is fine"); + Settings mixed = ParseSettings("\xEF\xBB\xBF; the player's note \xc3\xa4\nPlayer Key = 1\n[section]\nrr_mode = fast\nother_key=2\n"); + check(Set(mixed, "rr_mode", "exact") && Set(mixed, "new_key", "3") && + RenderSettings(mixed) == "\xEF\xBB\xBF; the player's note \xc3\xa4\nPlayer Key = 1\n[section]\nrr_mode=exact\nother_key=2\nnew_key=3\n", + "a change keeps the BOM, the comments, the unknown lines and the line ends; the changed key rewritten in place, a new one at the end"); + const std::string st = Stamped("rr_mode=fast\r\n", "settings.ini", kId); + check(ParseSettings(st).kv.size() == 1 && StampedByWrongGPU(st, "settings.ini", kId) && StampedByWrongGPU(st, "SETTINGS.INI", kId) && + !StampedByWrongGPU(st + "x=1\r\n", "settings.ini", kId) && !StampedByWrongGPU("rr_mode=fast\r\n; wronggpu-written 0123456789abcdef\r\n", "settings.ini", kId), + "the stamp: a comment to readers, valid only right after the bytes it checks"); + check(!StampedByWrongGPU(st, "settings.ini.wgtmp-backup", kId) && !StampedByWrongGPU(st, "model-choice.ini", kId) && + !StampedByWrongGPU(st, "settings.ini", "fedcba9876543210fedcba9876543210") && !StampedByWrongGPU(st, "settings.ini", ""), + "the stamp names the file and the install: a copy under another name, from another install, or an install without an id does not match"); + // every line keeps its own line end; nothing is added at the end of a file that had none; a stamp-like comment stays + Settings ends = ParseSettings("a=1\r\nb=2\nc=3"); + check(Set(ends, "rr_mode", "fast") && RenderSettings(ends) == "a=1\r\nb=2\nc=3\r\nrr_mode=fast", + "mixed line ends kept line by line; a new key after a last line without a line end: that line gets one, the new one none"); + Settings noEnd = ParseSettings("; wronggpu-written reminder\nrr_mode=fast"); + check(Set(noEnd, "rr_mode", "exact") && RenderSettings(noEnd) == "; wronggpu-written reminder\nrr_mode=exact", + "a player's comment that starts like the stamp stays; a changed key in a file without a final line end gets none"); 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)); @@ -216,6 +260,8 @@ int wmain(int argc, wchar_t** argv) { 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); + WriteText(JoinPath(state, L"install.record"), std::string("WRONGGPU-RECORD 2\r\nversion\t0.6.5\r\ninstall-id\t") + kId + "\r\n"); + check(InstallIdOf(game) == kId, "InstallIdOf: the record's install-id line"); 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); @@ -249,13 +295,37 @@ int wmain(int argc, wchar_t** argv) { 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"); + // the stamp: the file WrongGPU created is stamped and stays so while only WrongGPU writes it + check(StampedByWrongGPU(ReadText(f), "settings.ini", kId), "a file SetSettings created carries WrongGPU's stamp"); + check(SetSettings(game, {{"rr_enabled", "1"}}).ok() && StampedByWrongGPU(ReadText(f), "settings.ini", kId), "...and keeps it through WrongGPU's next write"); + // the player's edits: kept by every write, and the file is the player's from then on (no stamp) + WriteText(f, ReadText(f) + "player_key = 7\r\n; the player's note \xc3\xa4\r\n; wronggpu-written a player's line\r\n"); + SetOutcome o = SetSettings(game, {{"rr_mode", "accurate"}}); + std::string t = ReadText(f); + check(o.ok() && o.written && *Get(ReadSettings(game), "rr_mode") == "accurate" && t.find("player_key = 7\r\n") != std::string::npos && + t.find("; the player's note \xc3\xa4\r\n; wronggpu-written a player's line\r\n") != std::string::npos && !StampedByWrongGPU(t, "settings.ini", kId), + "a file the player edited: the menu's save keeps the player's key and note as they are and writes no stamp (the player's file now)"); + WriteText(f, "\xEF\xBB\xBF# made by the player\r\nRR Mode = Fast\r\n"); + o = SetSettings(game, {{"rr_mode", "fast"}}); + t = ReadText(f); + check(o.ok() && t.rfind("\xEF\xBB\xBF# made by the player\r\nRR Mode = Fast\r\nrr_mode=fast\r\n", 0) == 0 && !StampedByWrongGPU(t, "settings.ini", kId), + "a file the player made (BOM, '#' comment, a key in other spelling): kept as it is, the key added, no stamp"); + // text WrongGPU cannot keep as it is: the save is refused and the bytes stay + const std::string unkeepable = std::string("rr_mode=fast\r\nplayer_key=1\r\nnote=a\0b\r\n", 38); + WriteText(f, unkeepable); + check(ReadSettings(game).corrupt && ReadSettings(game).kv.empty(), "a file WrongGPU cannot keep reads as corrupt, no keys"); + o = SetSettings(game, {{"rr_mode", "accurate"}}); + check(o.result == SetResult::Unparseable && !o.written && ReadText(f) == unkeepable && o.words().find("nothing was saved") != std::string::npos && + List(state).size() == 1, + "...and a save is REFUSED (Unparseable, the reason in words), the bytes left as they are, no temporary file"); + WriteText(f, "\xff\xfeplayer bytes\r\n"); + o = SetSettings(game, {{"rr_mode", "accurate"}}); + check(o.result == SetResult::Unparseable && ReadText(f) == "\xff\xfeplayer bytes\r\n", "bytes that are not UTF-8: refused, left as they are"); + DeleteFileW(f.c_str()); + check(SetSettings(game, {{"rr_mode", "accurate"}}).ok() && StampedByWrongGPU(ReadText(f), "settings.ini", kId), "(a new file again: stamped)"); 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"}}); + 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) @@ -374,6 +444,88 @@ int wmain(int argc, wchar_t** argv) { DeleteFileW(ready.c_str()); } + // ---- the decision under the lock (forced interleaving): another program saves while this one waits for the lock; the + // decision is made from what that program wrote, never from a read made before + { + CreateDirectoryW(state.c_str(), nullptr); + DeleteFileW(SettingsPathOf(game).c_str()); + check(SetSettings(game, {{"rr_mode", "fast"}}).ok(), "(interleaving: the file starts with fast)"); + const std::string staleRead = *Get(ReadSettings(game), "rr_mode"); // a decision would rest on this read: "fast" + HANDLE held = CreateEventW(nullptr, TRUE, FALSE, nullptr); + std::thread menu([&] { // the game's menu: takes the lock, saves accurate a moment later, lets go + StateLock lock(game, 2000); + SetEvent(held); + Sleep(300); + Settings now = ReadSettings(game); + Set(now, "rr_mode", "accurate"); + WriteAtomic(SettingsPathOf(game), Stamped(RenderSettings(now), "settings.ini", kId)); + }); + WaitForSingleObject(held, 5000); + std::string seen; + const SetOutcome o = UpdateSettings(game, [&](const Settings& now, std::vector>* out) { + seen = Get(now, "rr_mode") ? *Get(now, "rr_mode") : ""; + if (seen.empty()) out->push_back({"rr_mode", staleRead}); // only when there is none: a saved mode stays + out->push_back({"rr_exact_allowed", seen == "exact" ? "1" : "0"}); + }, 5000); + menu.join(); + CloseHandle(held); + check(staleRead == "fast" && o.ok() && seen == "accurate" && *Get(ReadSettings(game), "rr_mode") == "accurate" && StampedByWrongGPU(ReadText(SettingsPathOf(game)), "settings.ini", kId), + "UpdateSettings: decide() sees the mode another thread saved while this one waited for the lock (accurate), not the older read " + "(fast); the newer mode stays"); + const std::string before = ReadText(SettingsPathOf(game)); + const SetOutcome same = SetSettings(game, {{"rr_mode", "accurate"}, {"rr_exact_allowed", "0"}}); + check(same.ok() && !same.written && ReadText(SettingsPathOf(game)) == before, "a change to the values already there: nothing written"); + } + + // ---- a player's editor saving while WrongGPU saves (the state lock does not stop it): the file is held from the read to just + // before the move (an editor's save meanwhile fails: Windows refuses it), and a change or a new file in the last moment + // refuses WrongGPU's save; the player's bytes always stay + { + const std::wstring f = SettingsPathOf(game); + g_hookFile = f; + // 1. held: an editor writing the file, or replacing it with its own copy, is refused; WrongGPU's save goes through + WriteText(f, "rr_mode=fast\r\n"); + TestFault() = [](const char* step) { + if (std::strcmp(step, "replace-held") == 0) { + HANDLE h = CreateFileW(ExtendedPath(g_hookFile).c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + g_editorWriteError = h == INVALID_HANDLE_VALUE ? GetLastError() : 0; + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + const std::wstring copy = g_hookFile + L".editor"; + WriteText(copy, "rr_mode=exact\r\n; the editor's copy\r\n"); + g_editorMoveError = MoveFileExW(ExtendedPath(copy).c_str(), ExtendedPath(g_hookFile).c_str(), MOVEFILE_REPLACE_EXISTING) ? 0 : GetLastError(); + DeleteFileW(ExtendedPath(copy).c_str()); + } + return false; + }; + SetOutcome o = SetSettings(game, {{"rr_mode", "accurate"}}); + TestFault() = nullptr; + check(g_editorWriteError == ERROR_SHARING_VIOLATION && g_editorMoveError != 0 && o.ok() && o.written && *Get(ReadSettings(game), "rr_mode") == "accurate", + "while WrongGPU holds the file, an editor's write and an editor's replace are refused by Windows (its bytes never land); WrongGPU's save completes"); + // 2. the last moment (the file let go, before the move): another program changes the file: WrongGPU's save is refused + WriteText(f, "rr_mode=fast\r\n"); + TestFault() = [](const char* step) { + if (std::strcmp(step, "replace-check") == 0) { Sleep(20); WriteText(g_hookFile, "rr_mode=exact\r\n; the player's save\r\n"); } + return false; + }; + o = SetSettings(game, {{"rr_mode", "accurate"}}); + TestFault() = nullptr; + check(o.result == SetResult::Changed && !o.written && ReadText(f) == "rr_mode=exact\r\n; the player's save\r\n" && List(state).size() == 1 && + o.words().find("nothing was saved") != std::string::npos, + "a change in the last moment before the move: WrongGPU's save is refused (Changed, in words), the player's bytes stay, no temporary file"); + // 3. the file was not there: another program makes it before the move: refused, its bytes stay + DeleteFileW(f.c_str()); + TestFault() = [](const char* step) { + if (std::strcmp(step, "replace-held") == 0) WriteText(g_hookFile, "player_made=1\r\n"); + return false; + }; + o = SetSettings(game, {{"rr_mode", "accurate"}}); + TestFault() = nullptr; + check(o.result == SetResult::Changed && ReadText(f) == "player_made=1\r\n" && List(state).size() == 1, + "a file made by another program while WrongGPU saved a new one: refused (Changed), the other program's file stays, no temporary file"); + DeleteFileW(f.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");