Skip to content

Shared: the per-game state folder, its lock and atomic writes (wg_state.h) - #226

Merged
phantoslayer21 merged 9 commits into
mainfrom
shared/wg-state
Nov 15, 2026
Merged

phantoslayer21 merged 9 commits into
mainfrom
shared/wg-state

Conversation

@phantoslayer21

@phantoslayer21 phantoslayer21 commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

What this changes and why

Refs #219 and #213. This adds one shared, header-only module for the per-game state that WrongGPU's user interfaces change after the install, and for the guard of the launcher's destructive operations. It is the library that #224 (all launcher-written settings) and #213 (the model choice record) build on; their reviews check the integration. This PR adds only the module and its tests; nothing uses it yet.

clean/wgshared/include/wg_state.h (namespace wgstate):

  • The state folder: one per game, <game folder>\wronggpu-setup (the launcher's state folder, beside the install record). It holds settings.ini (settings chosen in the launcher or in a WrongGPU menu in the game, read over wronggpu.ini's install defaults) and model-choice.ini (the model choice record). The launcher creates the folder; nothing here creates it.
  • The state lock (StateLock):
    • a named mutex per game folder, Global\WrongGPU-state-<volume serial>-<file index>, taken from the folder's file identity, so every alias gives the same name: case, trailing separator, 8.3 name, \\?\ form, a junction;
    • Global\ gives one name for every session;
    • open to every integrity level;
    • bounded wait; timedOut() and denied() are told apart;
    • a holder that died leaves it abandoned, and the next taker gets it.
    • Every protected operation re-reads its state from disk after taking the lock. StateLock caches nothing.
  • The operation guard (OperationGuard): Windows decides whether the game uses WrongGPU, and the game registers nothing.
    • An uninstall, repair or update holds the guard for its whole run.
    • The guard takes the state lock (a timeout is Busy, access denied is LockDenied). Then it opens every WrongGPU binary of the install with DELETE | GENERIC_READ | FILE_WRITE_DATA, sharing reads only:
      • ERROR_SHARING_VIOLATION: a process has the binary loaded (GameRunning: refuse, naming the file);
      • any other error: Unknown (refuse);
      • a file that does not exist is skipped.
    • The guard holds those handles to the end. A game that starts meanwhile cannot load WrongGPU: LoadLibrary does not share writes, so it fails, and OptiScaler carries on without it. The operation itself can still read the files (hashes, version resources) with an open that shares writes and deletes.
    • DeleteHeld deletes a binary through the held handle (POSIX delete, classic delete-on-close as the fallback).
    • PutHeld / PutHeldFrom replace a binary, or create a new one, without a release window:
      1. the held old file is renamed away through its own handle to <name>.wronggpu-old (the next free name when that is taken; nothing is deleted by name);
      2. the complete new file is written as a temporary file, flushed and renamed into place;
      3. the new file is held at once;
      4. the old file is deleted through its handle.
        A process can at most load the complete new file in the moment before step 3. Then the result is a sharing violation and the guard turns to GameRunning, so the operation stops; a partial file is never loadable.
    • A sharing violation is not always the game. The words say: "WrongGPU's files are in use by the game or another program (for example antivirus). Close the game and try again".
    • Why FILE_WRITE_DATA: a loaded image keeps no open handle, so an open with DELETE | GENERIC_READ and share mode 0 succeeds on a loaded DLL. The test showed this before the flag was added. Windows refuses an open for writing a loaded image's data. Nothing is ever written through the handle; a read-only binary is therefore Unknown.
  • WriteAtomic:
    • a temporary file in the same folder, created only where nothing is;
    • written in checked chunks (a short write is ERROR_WRITE_FAULT), flushed and closed (both checked), then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH);
    • the result (WriteResult; SetOutcome for SetSettings) carries the first failure and every secondary one: a close that failed after an earlier failure, and a cleanup that failed (its error and the file left). words() says all of them;
    • input over 1 MiB is refused.
  • Paths: every helper uses the \\?\ form (full path, \\?\UNC\ for a share), so a game deeper than MAX_PATH works. DirectoryState tells missing from unknown.
  • settings.ini, in a strict format: key=value lines, comments, blank lines, CRLF or LF only (a CR anywhere else, also a bare final CR, is corrupt).
    • Corrupt means no keys; the next write replaces the file.
    • SetSettings is the locked read-modify-write. An unreadable file is never overwritten.
    • Distinct results for consumers to show: AccessDenied (the game folder is not writable for this process) and LockDenied both point to the launcher's elevated repair; Busy is contention.

What each new or substantially changed file is based on

Own design, using the documented Windows API: named mutexes, GetFileInformationByHandle, CreateFileW share modes, SetFileInformationByHandle dispositions, MoveFileExW, SDDL, extended-length paths.

How it was tested

Tested: test_wg_state (ctest wgshared_state, in the existing "Shared settings" CI step and the front end's ctest), on real files and real processes, Windows with MSVC. A small test DLL (wg_state_test_dll) stands in for a WrongGPU binary.

Format and writes

  • the strict format, including a bare final CR and an embedded CR;
  • WriteAtomic:
    • oversized input refused;
    • a failure at write, flush, close and move (each after the temporary file exists): not written, the file unchanged, no temporary file left;
    • a close failing after a failed write is reported as closeError;
    • a failing cleanup reports its error and the file left;
  • SetSettings:
    • no state folder: nothing created;
    • a corrupt file replaced; an unreadable file left as it was;
    • a read-only state folder: AccessDenied;
    • a lock this process may not open: LockDenied (also from the guard), not Busy.

Aliases and locking

  • lock names, each computed in its own process: case, trailing backslash, 8.3 name, \\?\ form and a junction give one name; a folder deeper than MAX_PATH works in both processes;
  • four processes using four different aliases, 50 locked increments each: 200;
  • a busy lock: Busy, nothing written;
  • a holder that dies in the middle of a write: the lock is abandoned and taken, the state re-read is the old whole file, and the half-written temporary file is never read.

The guard

  • nothing loaded: Ok, with every existing binary held and a missing one skipped;
  • while the guard holds a binary, LoadLibrary of it fails, here and in another process, and the operation can still read it;
  • DeleteHeld deletes through the held handle;
  • PutHeld of a new file: the complete file is renamed in and held;
  • 20 replaces back and forth between two DLL builds while another process loads the file in a loop for 3 s: every load got a complete binary (the version it returns is checked) or a refusal, and no other error (no partial image). In one run: 5904 loads, 1026 refusals; a load in the gap stopped the replaces with a sharing violation, as designed. No .wronggpu-old and no temporary file stayed;
  • a .wronggpu-old name already taken: the next free name is used and cleaned up, the earlier file untouched;
  • a binary loaded in another process: GameRunning (sharing violation, names the file), nothing held; that process killed: Ok again;
  • a binary loaded in this process: GameRunning;
  • a binary the guard may not open: Unknown;
  • the lock busy: Busy, no binary held;
  • a game folder that is gone: nothing to guard.

Not tested:

Checklist

  • I make the clean-room statement of CONTRIBUTING.md for this and all my contributions (required once, in my first pull request).
  • Every commit has a Signed-off-by: line (git commit -s; Developer Certificate of Origin 1.1).
  • New source files carry the SPDX licence line for MIT, or are covered in REUSE.toml.
  • No files of the original upscaler (see CONTRIBUTING.md), no model data, game files, captures, screenshots or binaries; no paths, user or machine names of my PC.
  • Any new third-party component is under a permitted licence and listed in THIRD-PARTY-NOTICES and REUSE.toml. (None.)
  • Numbers in documents come with their measurement record. (None.)
  • Kernel or runtime changes: none.

…te.h)

One header-only module for every WrongGPU program that changes per-game state after the
install (the launcher, the front end and its menu plugin, the RR plugin):

- the ONE state folder <game folder>\wronggpu-setup (settings.ini: settings chosen in the
  launcher or a WrongGPU menu in the game, over wronggpu.ini's install defaults;
  model-choice.ini: the model choice record);
- StateLock: a named mutex per game folder, named from the folder's file identity
  (volume serial + file index, so every spelling of the path gives the same name), open to
  every integrity level, bounded wait, abandoned = taken;
- WriteAtomic: temporary file in the same folder (created only where nothing is), flushed,
  MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), the temporary file deleted on any failure;
- settings.ini in a strict key=value format (corrupt = no keys); SetSettings is the locked
  read-modify-write (an unreadable file is never overwritten, the folder never created).

test_wg_state (ctest wgshared_state): the format, real-file writes and cleanup, the lock
name for several spellings, four child processes doing 50 locked increments each of one
counter (200 at the end), a busy lock (bounded wait, nothing written) and a holder that
dies (abandoned, taken).

Refs #219

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
…tate.h

A WrongGPU module loaded in the game keeps a named mutex Local\WrongGPU-loaded-<volume
serial>-<file index> open (never owned) for the game folder; the object exists exactly while
some process has it open, and the OS closes every handle of a process that ends or crashes, so
a dead game leaves no stale marker. IsGameUsingWrongGPU(gameDir) only opens it (never creates).
StateLock and the marker share CreateSharedMutex and NameFor.

Tests: a marker in this process (any spelling of the folder), another folder, a missing
folder, a child process holding it, and that child killed (TerminateProcess): not in use.

Refs #219

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
@phantoslayer21
phantoslayer21 marked this pull request as ready for review November 15, 2026 02:10
@phantoslayer21
phantoslayer21 marked this pull request as draft November 15, 2026 02:13
…ocol)

- The loaded protocol: the game registers under the state lock before it reads any state
  (LoadedRegistration: bounded wait kRegisterWaitMs; not had in time, or no marker: ok() is
  false and the module runs with the defaults, touching no state); the launcher's
  OperationGuard takes the lock, asks QueryGameUse and holds the lock for the whole
  uninstall, repair or update, so nothing registers in between.
- QueryGameUse is tri-state: NotRunning only when established (no marker, or the folder is
  gone); any lookup error is Unknown, and the guard refuses on Running and Unknown.
- Names are Global\ (one per game folder for every session); every protected operation
  re-reads its state after taking the lock (documented; StateLock caches nothing).
- WriteAtomic: input over kMaxStateBytes refused; checked chunks, a short write is
  ERROR_WRITE_FAULT; flush and close checked; the temporary file deleted when possible and
  reported otherwise (tempLeft); a test seam fails each step.
- Paths go through the \\?\ form (full path, \\?\UNC\ for shares); DirectoryState tells
  missing from unknown; SetSettings reports AccessDenied (the game folder is not writable:
  the launcher's elevated repair) apart from other failures.
- The parser rejects a CR that is not part of CRLF (also a bare final CR).

Tests: every step's failure after the temporary file exists, a failed cleanup, oversized
input, AccessDenied on a read-only state folder; lock names of case, trailing backslash,
8.3 name, \\?\ form, a junction and a path over MAX_PATH, each in its own process, and four
processes using different aliases (200 locked increments); a holder dying mid-write
(abandoned, the old whole file re-read); QueryGameUse Unknown on a lookup error and on a
folder whose identity cannot be read (the guard refuses); a registered then killed child;
a registration that waits for a running operation and one that gives up in time.

Refs #219

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
@phantoslayer21
phantoslayer21 marked this pull request as ready for review November 15, 2026 02:30
@phantoslayer21
phantoslayer21 marked this pull request as draft November 15, 2026 02:32
…ockDenied, write outcomes)

1. The game's marker no longer waits for the state lock: LoadedRegistration makes the marker at
   once, then tries the lock within the rest of its budget (state_ok() only when had). A game
   that starts during an operation is visible at once; OperationGuard::Recheck() (no file-system
   call) is meant for every destructive step and turns the result to GameRunning.
2. A state lock this process may not open is LockDenied (SetSettings and OperationGuard), apart
   from Busy (a timeout); StateLock tells timedOut() from denied().
3. WriteAtomic returns a WriteResult and SetSettings a SetOutcome carrying the first failure and
   every secondary one (a close after an earlier failure, a failed cleanup with its error and the
   file left); words() says all of them.
4. The whole registration is bounded (kRegisterBudgetMs, about 2 s): the folder identity lookup
   runs on a helper thread within the budget, the lock wait gets the rest; never from DllMain;
   nothing throws out of it.

Tests: secondary close and cleanup failures; LockDenied; a game starting mid-operation (marker
seen by Recheck, state given up within the budget, still visible to a later operation);
registration with and without a running operation; a 300 ms budget ends within it.

Refs #219

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
phantoslayer21 added a commit that referenced this pull request Nov 15, 2026
Review of #213 (fourth round), cut down as decided:

- The record lives in the game's WrongGPU state folder and uses
  wg_state.h (#226): its state lock (named from the game folder's volume
  and file identity, so every path alias is one lock) and its atomic
  write, retried up to 3 times in the call. #213 has no lock code of its
  own.
- No queued choices. A plugin click or a host selection that cannot be
  saved in time changes nothing: the plugin's entry says "not saved, try
  again", the host event returns "not saved"; the running model stays.
- When the record cannot be read, is corrupt or busy at a create: the
  last choice read this session, else wronggpu.ini's model item, else
  Model M. Never the host's stored entry.
- The launcher's Apply with a model shown is an explicit choice: the
  record is always written (also the same model again) and the index
  set. The launcher holds the state lock across wronggpu.ini, the record
  and OptiScaler.ini; the model is no longer written into wronggpu.ini.
  A game without a record gets one from the profile; the launcher's own
  last choice follows the model's data being ready.
- The upgrade migration reads wronggpu.ini's model item while it holds
  the lock (the file as it is on disk now).
- The host event returns 1 when the model that runs changes (also for a
  re-selection of the same entry), 0 when nothing changes, negative when
  not saved. No session-only choices.
- One shared definition of the entry order (wgshared
  wg_model_entries.h) for the launcher's UpscalerIndex, checked against
  the front end's version list.
- The front end and the menu plugin keep WrongGPU's loaded marker open
  while loaded (wg_state.h), for the launcher's refusal to uninstall,
  repair or update a game in use.
- The record decides on the direct route too.

Tests: two real processes for the migration against a launcher apply
(one dying between wronggpu.ini and the record), a junction and the \\?\
form of one folder as one lock across processes, lock timeout and failed
writes changing nothing, a re-selection of the same entry returning 1,
an explicit launcher choice of an unchanged model winning over a newer
plugin choice, a launcher change of another setting leaving it, the
entry order. Negative controls for the migration read, the fallback, the
event result, the plugin's failed save and the launcher's explicit
choice.

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
phantoslayer21 added a commit that referenced this pull request Nov 15, 2026
The front end and the menu plugin follow wg_state.h's loaded protocol
(#226): each registers under the game's state lock before it reads or
writes any state (LoadedRegistration), keeping its loaded marker open
while loaded. When the registration fails (an uninstall, repair or update
holds the lock), the record is neither read nor written that session:
the front end runs wronggpu.ini's model item (else Model M) and a host
selection returns "not saved"; a plugin click is not saved.

Test: a front end that could not register reads and writes nothing and
runs wronggpu.ini's item.

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
@phantoslayer21
phantoslayer21 marked this pull request as ready for review November 15, 2026 02:46
@phantoslayer21
phantoslayer21 marked this pull request as draft November 15, 2026 02:50
…usive binary handles)

The loaded marker, its registration and the helper thread are gone; the game registers
nothing. The launcher's OperationGuard takes the state lock, then opens every WrongGPU binary
of the install with DELETE | GENERIC_READ | FILE_WRITE_DATA and share mode 0:
ERROR_SHARING_VIOLATION = loaded in a process (GameRunning), any other error = Unknown, a
missing file is skipped. It holds those handles for the whole operation, so a game that
starts meanwhile cannot load WrongGPU (its LoadLibrary fails). Deletes go through the held
handle (DeleteHeld: FileDispositionInfoEx POSIX delete, classic delete-on-close as the
fallback); Release hands one file back at the step that replaces it.

FILE_WRITE_DATA is needed: a loaded image keeps no open handle, so an open with DELETE |
GENERIC_READ and share mode 0 SUCCEEDS on a loaded DLL (seen in this test before the flag was
added); Windows refuses an open for writing a loaded image's data.

Tests (a real test DLL under WrongGPU's binary names): nothing loaded = Ok with every binary
held; a held guard makes LoadLibrary fail here and in another process; DeleteHeld; Release; a
binary loaded in another process / in this one = GameRunning; that process killed = Ok; a
binary the guard may not open = Unknown; the lock busy = Busy; LockDenied as before.

Refs #219

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
@phantoslayer21
phantoslayer21 marked this pull request as ready for review November 15, 2026 03:02
…d the binaries it holds)

The guard's handles (DELETE | GENERIC_READ | FILE_WRITE_DATA) now share reads. A game's
LoadLibrary still fails against them (it does not share writes), and a loaded image still
refuses the open, but the launcher's own reads during the operation (hashes, version resources,
opened sharing writes and deletes) work. Test: a held binary can be read; LoadLibrary still fails.

Refs #219

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
…tHeld)

Release is gone. PutHeld / PutHeldFrom rename the held old binary away through its own handle
(<name>.wronggpu-old, the next free name when taken), rename the complete new file into place
from a flushed temporary file, hold it at once, then delete the old file through its handle;
files the operation creates take the same rename-in-then-hold path. A load in the moment
before the hold gets the complete new file and stops the operation (sharing violation,
GameRunning). Renames go through the NT form of the full path. GameRunning's words no longer
claim it is the game: in use by the game or another program (for example antivirus).

Tests: two builds of the test DLL (219, 220); 20 replaces while another process loads the
file in a loop (complete binaries or refusals only, never another error); no .wronggpu-old or
temporary file left; a taken .wronggpu-old name; PutHeld of a new file.

Refs #219

Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com>
@phantoslayer21
phantoslayer21 merged commit 0ef4b90 into main Nov 15, 2026
9 checks passed
@phantoslayer21
phantoslayer21 deleted the shared/wg-state branch November 15, 2026 03:28
j0nsh1n added a commit to j0nsh1n/wronggpu that referenced this pull request Nov 15, 2026
…21#226)

One conflict, in run_launcher_tests.py: main (phantoslayer21#222) keeps a two-line
test_edition_download that calls launcher_edition_cases.py; the branch had
called the module from main(). Main's form is kept, and the Linux run skips
that section through it.

phantoslayer21#222 put test_re9's corrected check on main, so its entry leaves
native_linux.KNOWN_ON_MAIN: the check runs and passes natively. The
test_rr check stays skipped until main's fix for phantoslayer21#219 lands.

Verified: fresh build, ctest 22 of 22; launcher-native 366 passed, 0
failed, 5 skipped; reuse lint passes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Jonathan Shin <85975340+j0nsh1n@users.noreply.github.com>
j0nsh1n added a commit to j0nsh1n/wronggpu that referenced this pull request Nov 15, 2026
…21#226)

One conflict, in run_launcher_tests.py: main (phantoslayer21#222) keeps a two-line
test_edition_download that calls launcher_edition_cases.py; the branch had
called the module from main(). Main's form is kept, and the Linux run skips
that section through it.

phantoslayer21#222 put test_re9's corrected check on main, so its entry leaves
native_linux.KNOWN_ON_MAIN: the check runs and passes natively. The
test_rr check stays skipped until main's fix for phantoslayer21#219 lands.

Verified: fresh build, ctest 22 of 22; launcher-native 366 passed, 0
failed, 5 skipped; reuse lint passes.

Signed-off-by: Jonathan Shin <85975340+j0nsh1n@users.noreply.github.com>
phantoslayer21 added a commit that referenced this pull request Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant