fix(overlay): the safety stop could not fire in a game that had stopped presenting (#46)

MayObserve() has exactly ONE caller -- RecordPresent -- which has two, the
Present and Present1 hooks. ResizeBuffers does not call it. So every runtime
safety decision in the Overlay lived behind "the game is presenting", and two
defects fell out of that. Both were merged the same day, in #43.

(a) NEITHER STOP FIRED IN A NON-PRESENTING PROCESS.

A game that has hung, been alt-tabbed, or is sitting in a menu makes no present
calls, so unhookRequested was never read and the guardTicks deadline was never
evaluated. The hooks stayed patched in for the life of the process.

fl_shm.h says over FL_GUARD_TICK_DEADLINE_MS, in capitals, that this must NOT be
driven by the present hook -- "the clock would stop when presents stop, which is
the exact scenario this exists for, a game that has hung, or been alt-tabbed,
while anti-cheat loads behind it" -- and S2 rejected a present-driven re-scan for
that reason a day earlier. A normative comment prescribing the opposite of the
code beneath it, which is the S21 MoveFileEx/ReplaceFileW shape again: a comment
that names a mechanism is a design somebody builds against.

MEASURED: unhookRequested = 1 against a live injected `hook-harness --hold`
target left status at FL_STATUS_READY (1) through 10 s of polling, where
FL_STATUS_UNHOOKED is 3.

State the exposure precisely rather than inflating it. A process that is not
presenting is also not RECORDING, so nothing false was written. What failed is
19_SAFETY During a session's clean unhook on detection, and the promise
legal/DISCLAIMER.md 2 makes to the user in its own words.

(b) pauseRequested WAS UNREACHABLE ON ANY FRAME WHERE guardTicks CHANGED.

The tick-freshness check sat between the safety stop and the pause check and
returned true as soon as the tick differed from its cached value, so the first
present after every guard evaluation was recorded regardless of pause.

MEASURED: 12 leaked records across 12 guard ticks, exactly one per tick
(writeIndex 9 -> 21 while paused). At the real 30 s re-scan cadence each leaked
record carries a qpc ~30 s after its predecessor -- a FABRICATED 30-SECOND FRAME
INTERVAL in the series 03_METRICS computes 1% and 0.1% lows from, which is the
artefact 07_IPC forbids for torn records. Latent only because nothing writes
pauseRequested yet.

THE FIX: a watchdog thread, and why a thread is acceptable HERE.

One thread, started after the hooks, sleeping 1000 ms, evaluating both stops and
EXITING once stopped. It supplements the present path rather than replacing it:
07_IPC requires the safety stop within one frame and a one-second watchdog
cannot promise that, so the present path keeps its unhookRequested check. Same
shape as S6's LoadLibrary hook supplementing the 30 s poll.

S2 rejected a worker thread for the Vulkan layer for three reasons, ALL OF WHICH
ARE PROPERTIES OF THE LAYER: the loader owns the layer's mapping so a thread
outliving it access-violates a host we do not own; the re-scan allocates ~1.15 MB
transiently; and it would call NtQuerySystemInformation and probe the SCM from
inside a game, which is the behavioural signature of anti-analysis code (rule 3).
None applies to the Overlay, which is loaded by documented LoadLibraryW and is
never FreeLibrary'd from a live process. This thread enumerates nothing, probes
nothing and allocates nothing -- two uint32 reads from our own mapping, then
sleep. That is the whole justification and it is written into 17_HOOK_ENGINE so a
future change cannot erode it quietly: a watchdog that starts scanning is a
different object under rule 3.

Moving the deadline off the present path fixes (b) BY CONSTRUCTION -- there is no
early return left to jump over the pause check.

StopObserving is now a compare-exchange: two threads can reach it, MH_DisableHook
must run exactly once, and the FIRST reason wins, so a self-disable already in
flight is not overwritten by a safety stop arriving a millisecond later. Which
reason we recorded would otherwise have depended on thread scheduling.

CANARIES, both proven RED against the pre-fix dllmain.cpp with the tests
unchanged, then GREEN after restoring it:

  RED   pause     CHECK(writeIndex == atPause) -- 21 == 9
  RED   non-pres  CHECK(status == FL_STATUS_UNHOOKED) -- 1 == 3

The pause test TICKS WHILE PAUSED on purpose: a version that paused and then
stopped ticking passes against the broken code, because the leak only happens on
frames where the tick CHANGES. It also asserts pause RESUMES, since pause is the
one control-block signal that is not one-way and a latching implementation would
satisfy every other assertion. The non-presenting test REQUIREs writeIndex == 0
first, so if --hold ever starts presenting for the whole hold this fails rather
than silently becoming a duplicate of the --hold-presenting case.

Restoring the fixed file stamped its mtime. A Copy-Item restore preserves the
BACKUP's timestamp, ninja then judges the source up to date and skips the
rebuild, and the previous canary's binary is what runs -- the failure mode that
wasted a session on 2026-08-04. Verified: source 12:12:58 against .obj 12:12:16.

FIXED WITHOUT A TEST, AND SAYING SO: NoteFault called MH_DisableHook, DISCARDED
ITS RETURN VALUE, and stored SELF_DISABLED unconditionally -- while setting no
g_observing, the flag whose own canary comment calls it "the only thing that
holds if MH_DisableHook ever fails". True of the safety stop, false of the fault
policy. It now routes through StopObserving. But the three-fault path still has
NO TEST AT ALL, and the blocker is the vehicle: a fault seam compiled into a DLL
that ships into game processes is rejected on sight, and the VirtualProtectEx
alternative cannot locate the target's view base (and protecting the whole view
makes StopObserving's own status store fault inside the __except handler, where
there is no guard). Both rejected approaches are written into
src/native/tests/CMakeLists.txt so they are not rediscovered.

Docs updated in the same PR, per CLAUDE.md: 17_HOOK_ENGINE gains The watchdog
thread; 07_IPC Supervision loss says which check runs where and why they differ;
20_OPEN_QUESTIONS S25 records both defects with their measurements; spike-notes
3 records what is still unverified; and legal/DISCLAIMER.md discloses the thread
to the user in plain language, because "what runs inside the game" is what that
document exists to state.

build.ps1 check: PASSED WITH 2 SKIPPED GATE(S) in 54s, 15/15 ctests, 124 managed
tests. clang-format 22.1.3, the pinned version -- the first run failed formatting
and the version line is printed for exactly that reason.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 authored and GitHub committed 2026-08-05 12:29:04 +07:00
1 parent c9e6aa8c77
commit 2efa1701fe
8 files changed
+493 -50

No files matched your search

+11
View File
@@ -139,6 +139,17 @@ same class of bug as record drift.
within **65 seconds** (`FL_GUARD_TICK_DEADLINE_MS`, `fl_shm.h`), the capture
side stops recording.
> **Evaluated OFF the present path, by a watchdog thread** (`17_HOOK_ENGINE`
> §The watchdog thread). For one day it was evaluated only inside the present
> hook, which made it unreachable in a hung or alt-tabbed game — the exact
> scenario it exists for, and the one `fl_shm.h` warns about in capitals over
> the constant. `20_OPEN_QUESTIONS` §S25 records the measurement.
>
> **The safety stop (`unhookRequested`) is checked in BOTH places**, and the
> asymmetry is deliberate: this rule tolerates a second of latency, while the
> safety stop is required within one frame, which only the present path can
> deliver while frames exist.
> **This sentence had no number until 2026-08-05.** One grep over `docs`, `src`
> and `tools` for "deadline" returned exactly one line — this one, the sentence
> that depends on it. A rule with no value is not implementable, and this had
+42
View File
@@ -349,6 +349,48 @@ Field notes — each of these was a defect in an earlier revision:
- **The hot path performs: one QPC read, a few field reads from cached state, one 60-byte store, two relaxed atomic stores and two compiler fences.** No syscall, no allocation, no lock, no logging. Target ≤ 1 µs per present.
- Per-frame mutable state (current upscaler, render res, dispatch counts) lives in a small struct updated by the feature hooks and *read* by the present hook; counters reset at present.
## The watchdog thread — the only thread we add to the game
One thread, started on the init thread *after* the hooks are installed, sleeping
`1000 ms` at a time. It evaluates `unhookRequested` and the `guardTicks` deadline,
calls `StopObserving` when either fires, and **exits** once stopped.
**Why it exists.** Both stops used to be evaluated only on the present path, and
`MayObserve` is reachable only from `RecordPresent`, which is reachable only from
the two present hooks. In a process that had stopped presenting — hung,
alt-tabbed, sitting in a menu — neither check ever ran and the hooks stayed
patched in for the life of the process. `fl_shm.h` says over
`FL_GUARD_TICK_DEADLINE_MS`, in capitals, that the deadline must **not** be driven
by the present hook, *"because the clock would stop when presents stop, which is
the exact scenario this exists for"*. The code did what its own normative comment
forbade. Measured: `unhookRequested` set on a `hook-harness --hold` target left
`status` at `READY` indefinitely.
**It supplements the present path, it does not replace it.** `07_IPC` requires the
safety stop within one frame, and a one-second watchdog cannot promise that, so
the present path keeps its `unhookRequested` check. Same shape as §S6's
`LoadLibrary` hook supplementing the 30 s poll.
**Why a thread here, when `20_OPEN_QUESTIONS` §S2 rejected one for the Vulkan
layer.** All three of §S2's reasons are properties of the *layer*: the Vulkan
loader owns the layer's mapping, so a thread outliving it access-violates a host
we do not own; the re-scan it would have run allocates ~1.15 MB transiently; and
it would have called `NtQuerySystemInformation` and probed the SCM from inside a
game, which is the behavioural signature of anti-analysis code (CLAUDE.md rule 3).
None applies to the Overlay, which is loaded by documented `LoadLibraryW` and is
never `FreeLibrary`'d from a live process. **This thread enumerates nothing,
probes nothing and allocates nothing** — it reads two `uint32`s from our own
mapping and sleeps. That distinction is the whole justification and must survive
any future change: a watchdog that starts scanning is a different object under
rule 3.
Failing to create it is **not** fatal — the present-path checks still work, and an
Overlay that reacts only while presenting is strictly better than none. The
failure is recorded in `faultCount` so the Agent can see it rather than infer it.
`legal/DISCLAIMER.md` §2 discloses this thread to the user in plain language,
because "what runs inside the game" is exactly what that document exists to state.
## Fault policy
Every hook body is wrapped:
+63
View File
@@ -75,6 +75,69 @@ or it becomes the next stale status claim this file exists to record.
gets either work or a written rationale, and until the owner acts on S23-2 — which
no amount of code will do.
### S25 ✅ · Both runtime stops were unreachable in a non-presenting process, and pause was unreachable on a ticking one — **closed 2026-08-05**
Found by tracing call paths while planning the next phase, in code merged the
same day (#43). Two defects, one root cause: **`MayObserve()` had exactly one
caller.** `RecordPresent` calls it, and only `Hook_Present` and `Hook_Present1`
call that. `Hook_ResizeBuffers` does not.
**(a) Neither stop fired in a process that had stopped presenting.** A game that
has hung, been alt-tabbed, or is sitting in a menu makes no present calls, so
`unhookRequested` was never read and the `guardTicks` deadline was never
evaluated. The hooks stayed patched in for the life of the process.
`fl_shm.h` states over `FL_GUARD_TICK_DEADLINE_MS`, in capitals, that this must
not be driven by the present hook — *"the clock would stop when presents stop,
which is the exact scenario this exists for — a game that has hung, or been
alt-tabbed, while anti-cheat loads behind it"* — and §S2 rejected a
present-driven re-scan for that reason a day earlier. **A normative comment
prescribing the opposite of the code beneath it**, which is the same shape as the
`MoveFileEx`/`ReplaceFileW` prescription §S21 records: a comment that names a
mechanism is a design somebody builds against.
Be precise about the exposure rather than overstating it: a process that is not
presenting is also not *recording*, so nothing false was written. What failed is
`19_SAFETY` §During a session's clean unhook on detection, and the promise
`legal/DISCLAIMER.md` §2 makes to the user in its own words.
**Measured, both directions.** `unhookRequested = 1` against a live injected
`hook-harness --hold` target (240 presents, then sleep): `status` stayed
`FL_STATUS_READY` through 10 s of polling. After the fix it reaches
`FL_STATUS_UNHOOKED`. ctest `fl_guard`, *"the safety stop fires in a target that
has STOPPED presenting"*.
**(b) `pauseRequested` was unreachable on any frame where `guardTicks` changed.**
The tick-freshness check sat between the safety stop and the pause check and
`return`ed `true` as soon as the tick differed from its cached value — so the
first present after every guard evaluation was recorded regardless of pause.
**Measured: 12 leaked records across 12 guard ticks, exactly one per tick**
(`writeIndex` 9 → 21 while paused). Each carries a `qpc` ~30 s after its
predecessor at the real re-scan cadence, which is a **fabricated 30-second frame
interval** in the series `03_METRICS` computes 1% and 0.1% lows from — the exact
artefact `07_IPC:114-119` forbids for torn records. Latent only because nothing
writes `pauseRequested` yet.
**Closed by a watchdog thread** (`17_HOOK_ENGINE` §The watchdog thread), which
takes the deadline off the present path entirely and thereby fixes (b) by
construction — there is no early return left to jump over the pause check. The
present path keeps its `unhookRequested` check, because `07_IPC` requires that
within one frame and a one-second watchdog cannot promise it. `StopObserving` is
now a compare-exchange, since two threads can reach it and `MH_DisableHook` must
run once; the **first** reason wins, so a self-disable is not overwritten by a
safety stop arriving a millisecond later.
**One thing this did NOT close, stated rather than left to look covered.** The
same trace found that `NoteFault` called `MH_DisableHook`, **discarded its return
value**, and stored `SELF_DISABLED` unconditionally — while setting no
`g_observing`, the flag whose own canary comment calls it *"the only thing that
holds if `MH_DisableHook` ever fails"*. That claim was true of the safety stop and
false of the fault policy. It is now routed through `StopObserving`, **but there
is still no fault-policy test at all**, so the fix has no regression net. The
vehicle is the blocker, not the assertions; `src/native/tests/CMakeLists.txt`
records both rejected approaches and why.
### S1 · The guard is structurally blind in launch mode
> **§S1 does not gate the Vulkan path.** Added 2026-08-03, because "launch mode
+17 -6
View File
@@ -639,12 +639,23 @@ frame generation, no ray tracing" as *measured fact* ~118 times a second — `fg
never written by anything, while its only reader is unreachable on any frame where
`guardTicks` changed.
**Still not measured on the present path**, and both are `20_OPEN_QUESTIONS` §S24 items:
the 65-second supervision deadline **in its real configuration** (a canary proves the
comparison fires, not that 65000 is the number on the shipped path — and it is evaluated
only when the game presents, which `fl_shm.h:67-70` says it must not be), and the
three-fault self-disable, which has no test at all
(`src/native/tests/CMakeLists.txt:147`).
**Two gaps found the same day by tracing call paths, and one is still open.**
- ✅ **Both runtime stops were unreachable in a non-presenting process**, and
`pauseRequested` was unreachable on any frame where `guardTicks` changed — one root
cause, `MayObserve()` having exactly one caller. Measured in both directions:
`unhookRequested` against a live `--hold` target left `status` at `READY` through 10 s
of polling, and a paused session leaked **12 records across 12 guard ticks, exactly one
per tick** (`writeIndex` 9 → 21). Closed by the watchdog thread (§S25).
- 🔴 **The three-fault self-disable still has no test at all.** `NoteFault` discarded
`MH_DisableHook`'s return and set no `g_observing`; that is fixed, without a regression
net. The blocker is the vehicle — a fault seam compiled into a DLL that ships into
games is rejected on sight, and the `VirtualProtectEx` alternative cannot locate the
target's view base. Both approaches and their failure modes are written into
`src/native/tests/CMakeLists.txt`.
- The 65-second value **in its real configuration** is also unverified: the stop is proven
to fire, but a suite that runs on every build cannot wait 65 s, so what is tested is the
mechanism, not the number.
### Still open in §3
+6 -2
View File
@@ -4,10 +4,12 @@
> ⚠ Draft for review. Not legal advice. Review before first public release — this version covers code injection and should be read carefully.
> ⚠ **Accuracy audit — re-checked 2026-08-05 after PRs #40–#44. FOUR statements below describe behaviour the software does not yet have**, and they are flagged here rather than quietly reworded because a document the user accepts must not over-promise. **Two of them changed substance in this re-check** — the capture side that receives a stop now exists, while the side that would send one still does not:
> ⚠ **Accuracy audit — re-checked 2026-08-05, twice: after PRs #40–#44, and again after the watchdog landed. FOUR statements below describe behaviour the software does not yet fully have**, and they are flagged here rather than quietly reworded because a document the user accepts must not over-promise.
>
> **Two bullets changed substance and neither could be struck.** The capture side that *receives* a stop now exists and now runs whether or not the game is presenting; the side that would *send* one still does not. That is the pattern to watch for when re-counting: half a mechanism reads as a whole one, and the half that is missing is usually the one nobody was looking at.
>
> - §2's *"and every 30 seconds afterwards … it stops at the next scan"* — the pre-injection guard is real and refuses. The **receiving half is now implemented**: an injected D3D title removes its hooks within one frame of the stop flag being set. The **sending half is still missing** — `GuardSupervisor` has no production caller and nothing in production writes the shared-memory field it would advance, so no re-scan runs and no stop is ever sent. A half-built mechanism must not read as a whole one.
> - §2's *"waits **65 seconds** before concluding that contact is lost"* — **the deadline now has a reader** (`FrameLedger.Overlay`'s present path), which the previous audit correctly said it did not. Three qualifications, none of them cosmetic: it is evaluated **only when the game presents a frame**, so a title that has hung or been alt-tabbed never reaches it — the exact case the mechanism was specified for; it covers **injected Direct3D titles only**, because the Vulkan layer intercepts nothing yet; and **no test asserts that it fires**. Until those are fixed the sentence promises more than the software delivers.
> - §2's *"waits **65 seconds** before concluding that contact is lost"* — **the deadline now has a reader, and since 2026-08-05 it runs whether or not the game is presenting.** For one day it was evaluated only on a present, so a title that had hung or been alt-tabbed never reached it — the exact case the mechanism was specified for. A watchdog inside the injected component now checks once a second regardless. Two qualifications remain: it covers **injected Direct3D titles only**, because the Vulkan layer intercepts nothing yet, and **the 65-second value itself is not covered by a test** — the stop is proven to fire, but a suite that runs on every build cannot wait 65 seconds, so what is verified is the mechanism, not the number.
> - §3's *"automatically stops injecting into a game that crashes shortly after injection twice"* — the only trace of this anywhere is a `hook_crash_count` column in a schema for which no `.sql` file exists. There is no design for it.
> - §1's *"Only FrameLedger's own component is ever loaded"* — **narrower than it sounds, and the qualification is now in §1 itself.** The check is a directory test: the payload must resolve into FrameLedger's own install directory. It does not compare a filename, a version or any content, deliberately — a name check would be defeated by any DLL that borrowed the name. A published self-contained build puts several hundred files in that directory.
>
@@ -55,6 +57,8 @@ FrameLedger is designed to reduce that risk substantially:
untouched. It records nothing further, but its library remains loaded until
the game exits.
- FrameLedger contains **no evasion techniques of any kind** — it does not hide, rename, obfuscate, or disguise itself. It is intended to be plainly identifiable to any security software that looks.
For completeness about what it *does* run inside the game: besides the intercepted calls themselves, the component starts **one background thread** that sleeps for a second at a time and checks whether it has been told to stop. It reads only FrameLedger's own shared memory. It does not scan the game, enumerate what the system has loaded, or query Windows services — deliberately, because software that does those things from inside a game process looks like the thing this tool is trying not to be mistaken for.
- A no-injection measurement mode is the default for anything the software is unsure about. It relies on Windows event tracing, which requires the FrameLedger agent to run with administrator rights; without that, measurement falls back to session duration and hardware sensors only. FrameLedger tells you which mode produced each session.
**However, these protections cannot be complete:**
+174 -41
View File
@@ -190,6 +190,10 @@ void PublishHandshake() noexcept {
// ---------------------------------------------------------------------------
FlWriterState* g_state = nullptr;
// Defined below with the safety stop. NoteFault needs it, and the fault policy
// is declared first because FL_HOOK_GUARD wraps every hook body.
void StopObserving(uint32_t reason) noexcept;
// Only OUR code is guarded, never the call to the original -- otherwise a game's
// own fault inside the trampoline would be counted as ours, and ours as the
// game's. Both directions of that confusion are bad.
@@ -210,9 +214,20 @@ void NoteFault() noexcept {
if (n >= 3) {
// Three faults total => stop writing and go dormant. MH_DisableHook is
// safe here because we are outside our own guarded body by now.
MH_DisableHook(MH_ALL_HOOKS);
std::atomic_ref<uint32_t> status{g_state->status};
status.store(FL_STATUS_SELF_DISABLED, std::memory_order_release);
//
// ROUTED THROUGH StopObserving, and that is a fix rather than a tidy-up.
// This used to call MH_DisableHook directly, DISCARD ITS RETURN VALUE and
// then store the status unconditionally -- so on a MinHook failure the
// Overlay reported SELF_DISABLED while its hooks were still patched in and
// still writing. The status field is not consulted anywhere on the write
// path, so nothing else would have stopped it either.
//
// StopObserving clears g_observing, which IS consulted on the write path,
// and whose comment (below) already called it "the only thing that holds
// if MH_DisableHook ever fails". That claim was true of the safety stop
// and false of the fault policy, which is exactly the kind of asymmetry
// between two paths doing the same job that nobody re-reads for.
StopObserving(FL_STATUS_SELF_DISABLED);
}
}
@@ -374,10 +389,46 @@ uint32_t g_frameIndex = 0;
// The safety stop, and supervision loss (07_IPC §Protocol rules, 19_SAFETY
// §During a session).
//
// Both are checked ON THE PRESENT PATH, which is the only place that runs often
// enough to react "within one frame" as 07_IPC requires. Neither costs a
// syscall: the control block is mapped memory, and GetTickCount64 reads
// KUSER_SHARED_DATA.
// TWO PLACES EVALUATE THESE, AND THE SECOND ONE IS THE POINT.
//
// The present path reacts "within one frame", which is what 07_IPC requires of
// the safety stop, and costs no syscall: the control block is mapped memory.
//
// But the present path is reachable ONLY WHILE THE GAME IS PRESENTING, and until
// 2026-08-05 it was the only place either check ran. `MayObserve` has exactly one
// caller (`RecordPresent`), which has two (the Present and Present1 hooks) -- so
// in a process that had stopped presenting, because it hung or was alt-tabbed or
// sat in a menu, unhookRequested was never read and the deadline was never
// evaluated. The hooks stayed patched in indefinitely.
//
// That is the case the mechanism exists for. fl_shm.h says so in capitals over
// FL_GUARD_TICK_DEADLINE_MS -- "NOT DRIVEN BY THE PRESENT HOOK ... the clock
// would stop when presents stop, which is the exact scenario this exists for, a
// game that has hung, or been alt-tabbed, while anti-cheat loads behind it" --
// and the code did the thing its own normative comment forbade. A process that
// has stopped presenting is also not RECORDING, so nothing false was written;
// what failed is the promise in legal/DISCLAIMER.md §2 that the part inside the
// game stops when contact is lost, and 19_SAFETY's clean unhook on detection.
//
// So the watchdog thread below supplements the present path rather than
// replacing it: within-one-frame while presenting, within-one-second otherwise.
// Same shape as §S6's LoadLibrary hook, which supplements the 30 s poll because
// the poll also catches things the hook cannot.
//
// WHY A THREAD IS ACCEPTABLE HERE AND WAS REJECTED FOR THE VULKAN LAYER.
// 20_OPEN_QUESTIONS §S2 rejected a layer-owned worker thread for three reasons,
// all of which are properties of the LAYER: the Vulkan loader owns the layer's
// mapping, so a thread outliving it access-violates a host we do not own; the
// re-scan it would have run allocates ~1.15 MB transiently; and it would have
// called NtQuerySystemInformation and probed the SCM from inside a game, which
// is the behavioural signature of anti-analysis code (CLAUDE.md rule 3). None
// applies here. The Overlay is loaded by documented LoadLibraryW and is never
// FreeLibrary'd from a live process (17_HOOK_ENGINE §Unhooking), so we own the
// lifetime; and this thread enumerates nothing, probes nothing and allocates
// nothing -- it reads two uint32s out of our own mapping and sleeps.
//
// It also EXITS once stopped. There is nothing left for it to decide, and a
// sleeping thread that can never do anything again is footprint for nothing.
//
// STOPPING IS ONE-WAY. Once we stop observing we do not resume, even if ticks
// start again -- a capture side that can un-stop itself is a capture side whose
@@ -385,9 +436,23 @@ uint32_t g_frameIndex = 0;
// important runtime behavior in the whole capture layer.
// ---------------------------------------------------------------------------
FlControlBlock* g_control = nullptr;
bool g_observing = true;
uint32_t g_lastTicks = 0;
ULONGLONG g_lastTickAt = 0;
// ATOMIC because two threads now write it: a hook body reacting to
// unhookRequested, and the watchdog. It was a plain bool while the present path
// was the only writer.
std::atomic<uint32_t> g_observing{1};
// Owned by the watchdog thread ALONE. They used to live on the present path,
// where they were read and written by whichever game thread happened to present
// -- and where the freshness check returned early, which is what made
// pauseRequested unreachable (see MayObserve).
uint32_t g_lastTicks = 0;
ULONGLONG g_lastTickAt = 0;
// One second. The safety stop's real deadline is the guard's, and this only
// bounds how late we notice; 07_IPC's "within one frame" is still met by the
// present path whenever the game is presenting at all.
constexpr DWORD kWatchdogIntervalMs = 1000;
// CANARY RESULT, recorded because it is not what I expected. Removing
// `g_observing = false` and leaving only MH_DisableHook keeps the suite GREEN:
@@ -398,10 +463,16 @@ ULONGLONG g_lastTickAt = 0;
// necessary" is NOT a property this suite verifies, and saying so is cheaper than
// letting a reader assume it does.
void StopObserving(uint32_t reason) noexcept {
if (!g_observing) {
// Compare-exchange, not a plain check-then-set: the watchdog and a game
// thread inside a hook body can both arrive here, and MH_DisableHook must run
// exactly once. The loser returns without touching status, so the FIRST
// reason wins -- a self-disable already in flight is not overwritten by a
// safety stop that arrives a millisecond later, or the record of WHY we
// stopped would depend on thread scheduling.
uint32_t expected = 1;
if (!g_observing.compare_exchange_strong(expected, 0, std::memory_order_acq_rel, std::memory_order_acquire)) {
return;
}
g_observing = false;
MH_DisableHook(MH_ALL_HOOKS);
if (g_state != nullptr) {
std::atomic_ref<uint32_t> status{g_state->status};
@@ -410,9 +481,17 @@ void StopObserving(uint32_t reason) noexcept {
}
// Returns false when we must not record this present.
//
// The supervision deadline is NOT here any more -- it is the watchdog's, which
// is the whole point of having one. What stays is the safety stop, because
// 07_IPC requires it within one frame and a one-second watchdog cannot promise
// that, and the pause check, which is inherently per-frame.
bool MayObserve() noexcept {
if (!g_observing || g_control == nullptr) {
return g_observing;
if (g_observing.load(std::memory_order_acquire) == 0) {
return false;
}
if (g_control == nullptr) {
return true;
}
// The safety stop first: the Agent's guard fired mid-session and wants the
@@ -423,33 +502,67 @@ bool MayObserve() noexcept {
return false;
}
// Supervision loss. guardTicks counts COMPLETED guard evaluations, not
// seconds, so a stalled guard loop stops it advancing even while the Agent
// process is alive -- which is exactly the case a timer-driven heartbeat
// would have missed.
//
// "Never advanced" and "stopped advancing" are the same state: the clock
// starts when the mapping is published, so a capture side no Agent ever
// adopted is inert from the beginning rather than enjoying a grace window.
std::atomic_ref<uint32_t> ticks{g_control->guardTicks};
const uint32_t now = ticks.load(std::memory_order_acquire);
const ULONGLONG t = GetTickCount64();
if (now != g_lastTicks) {
g_lastTicks = now;
g_lastTickAt = t;
return true;
}
if (t - g_lastTickAt >= FL_GUARD_TICK_DEADLINE_MS) {
StopObserving(FL_STATUS_UNHOOKED);
return false;
}
// Pausing is not stopping: the Agent asked us to hold, and the supervision
// clock keeps running, so a paused session still stops if the guard dies.
// clock keeps running (in the watchdog), so a paused session still stops if
// the guard dies.
//
// THIS LINE WAS UNREACHABLE ON ANY FRAME WHERE guardTicks HAD CHANGED. The
// freshness check used to sit between the safety stop and here and `return
// true` as soon as the tick differed from the cached value -- so the first
// present after every guard evaluation was recorded regardless of pause. One
// leaked record per evaluation does not sound like much; its qpc is ~30 s
// after its predecessor, which is a FABRICATED 30-SECOND FRAME INTERVAL in
// the series 03_METRICS computes 1% and 0.1% lows from. 07_IPC forbids
// exactly that artefact for torn records and the same reasoning applies here.
// Latent until now only because nothing writes pauseRequested yet.
std::atomic_ref<uint32_t> paused{g_control->pauseRequested};
return paused.load(std::memory_order_relaxed) == 0;
}
// The watchdog. Runs whether or not the game presents, which is the reason it
// exists; see the block comment above for why a thread is acceptable in the
// Overlay and was not in the Vulkan layer.
DWORD WINAPI WatchdogThread(LPVOID) noexcept {
for (;;) {
Sleep(kWatchdogIntervalMs);
if (g_observing.load(std::memory_order_acquire) == 0) {
return 0; // stopped by us or by a hook body; nothing left to decide
}
if (g_control == nullptr) {
continue;
}
std::atomic_ref<uint32_t> unhook{g_control->unhookRequested};
if (unhook.load(std::memory_order_acquire) != 0) {
StopObserving(FL_STATUS_UNHOOKED);
return 0;
}
// Supervision loss. guardTicks counts COMPLETED guard evaluations, not
// seconds, so a stalled guard loop stops it advancing even while the
// Agent process is alive -- which is exactly the case a timer-driven
// heartbeat would have missed.
//
// "Never advanced" and "stopped advancing" are the same state: the clock
// starts when the mapping is published, so a capture side no Agent ever
// adopted is inert from the beginning rather than enjoying a grace
// window.
std::atomic_ref<uint32_t> ticks{g_control->guardTicks};
const uint32_t now = ticks.load(std::memory_order_acquire);
const ULONGLONG t = GetTickCount64();
if (now != g_lastTicks) {
g_lastTicks = now;
g_lastTickAt = t;
continue;
}
if (t - g_lastTickAt >= FL_GUARD_TICK_DEADLINE_MS) {
StopObserving(FL_STATUS_UNHOOKED);
return 0;
}
}
}
// The hot path. One QPC read, a few cached-state reads, one 60-byte store in two
// spans, two relaxed atomic stores, two fences. No syscall, no allocation, no
// lock, no logging (NFR-1, target <= 1 us; a bare vtable detour measured 8.4 ns).
@@ -616,6 +729,22 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
}
status.store(FL_STATUS_READY, std::memory_order_release);
// AFTER the hooks, deliberately. The watchdog's only job is to take them out
// again, so starting it earlier would create a window in which it could
// "stop" a capture side that had not started -- setting g_observing to 0
// before InstallPresentHooks ran, and leaving a permanently inert Overlay
// reporting UNHOOKED with nothing ever hooked. Failure to start it is NOT
// fatal: the present-path checks still work, and an Overlay that reacts only
// while the game presents is strictly better than none. It is recorded in the
// fault counter so the Agent can see it rather than inferring it.
HANDLE watchdog = CreateThread(nullptr, 0, WatchdogThread, nullptr, 0, nullptr);
if (watchdog == nullptr) {
std::atomic_ref<uint32_t> faults{g_state->faultCount};
faults.fetch_add(1, std::memory_order_acq_rel);
} else {
CloseHandle(watchdog); // fire and forget; it exits on its own once stopped
}
return 0;
}
@@ -645,11 +774,15 @@ __declspec(dllexport) unsigned int FlGetStatus() {
return status.load(std::memory_order_acquire);
}
// The safety stop's local entry point. It does nothing yet because nothing is
// hooked; the body lands with the hooks, where 07_IPC requires it to be the
// fastest, most-tested path in the DLL. Declared now because the export list is
// part of what an anti-cheat vendor inspects, and a DLL whose exports change
// shape between builds is harder to identify, not easier.
// The safety stop's local entry point. This comment said "it does nothing yet
// because nothing is hooked; the body lands with the hooks" until 2026-08-05 --
// the body landed in #43 and the comment did not move. It removes the hooks and
// records UNHOOKED, exactly like the control-block path.
//
// It is NOT how the Agent stops a session: that is FlControlBlock::unhookRequested,
// read on the present path and by the watchdog. This export exists because the
// export list is part of what an anti-cheat vendor inspects, and a DLL whose
// exports change shape between builds is harder to identify, not easier.
__declspec(dllexport) void FlRequestUnhook() {
StopObserving(FL_STATUS_UNHOOKED);
}
+26 -1
View File
@@ -144,4 +144,29 @@ target_link_libraries(fl_ring_test PRIVATE FrameLedger.Shm fl_native_flags Catch
target_compile_options(fl_ring_test PRIVATE /EHsc)
add_test(NAME fl_ring COMMAND fl_ring_test)
# TODO(P1): the fault-policy suite, with the hook bodies.
# STILL NO FAULT-POLICY SUITE, and the reason is worth more than the TODO it
# replaces. The three-fault self-disable is NFR-3's entire mechanism and the
# clause 20_OPEN_QUESTIONS §H8 was closed on, and nothing exercises it.
#
# What blocks it is the VEHICLE, not the assertions. To count a fault we must
# make our own hook body fault, in a live injected target, deterministically:
#
# - A fault seam compiled into FrameLedger.Overlay is rejected on sight. It
# ships into game processes, and "an export that makes the DLL crash on
# demand" is a worse thing to hand an anti-cheat vendor than the bug.
# §S15's evidence-seam precedent (compiled out of everything that ships,
# verified with dumpbin) is the standard, and a fault seam cannot meet it
# because the fault has to happen on the REAL path to be counted by it.
# - VirtualProtectEx'ing the target's mapped ring to PAGE_NOACCESS was
# considered and is not safe as stated: the test cannot locate the view's
# base address in the target, and protecting the whole view makes
# StopObserving's own status store fault -- inside the __except handler,
# where there is no guard, which crashes the harness instead of testing it.
# Protecting the ring region ALONE would work, if the base address problem
# were solved.
#
# So the honest state is: FL_HOOK_GUARD's structure is reviewed and not
# exercised, and NoteFault's routing through StopObserving (2026-08-05) is a fix
# made WITHOUT a regression test. Recorded here rather than left as a bare TODO
# so the next reader knows the gap is known and why, per build.ps1's
# skip-loudly discipline. Tracked in 20_OPEN_QUESTIONS §S24.
+154
View File
@@ -1500,6 +1500,160 @@ TEST_CASE("the injected Overlay records real presents into the ring", "[guard][i
CloseHandle(mapping);
}
TEST_CASE("a PAUSED session records nothing, including across a guard tick", "[guard][inject][shm]") {
// pauseRequested had exactly one reader and it was UNREACHABLE on any frame
// where guardTicks had changed: the freshness check sat in front of it and
// returned true as soon as the tick differed from the cached value. So the
// first present after every guard evaluation was recorded regardless of
// pause.
//
// "One record per 30 s" undersells it. That record's qpc is ~30 s after its
// predecessor, which is a fabricated 30-second frame interval in the series
// 03_METRICS computes 1% and 0.1% lows from -- the exact artefact 07_IPC
// forbids for torn records.
//
// THIS TEST TICKS WHILE PAUSED ON PURPOSE. A version that paused and then
// stopped ticking would pass against the broken code, because the leak only
// happens on the frames where the tick CHANGES.
Child child;
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --real --hold-presenting 20";
STARTUPINFOW si{};
si.cb = sizeof(si);
REQUIRE(CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
&child.pi));
Sleep(800);
REQUIRE(WaitForSingleObject(child.pi.hProcess, 0) == WAIT_TIMEOUT);
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
REQUIRE(GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed());
wchar_t name[128]{};
REQUIRE(_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", child.pi.dwProcessId) > 0);
HANDLE mapping = nullptr;
for (int i = 0; i < 100 && mapping == nullptr; ++i) {
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
Sleep(50);
}
}
REQUIRE(mapping != nullptr);
void* base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
REQUIRE(base != nullptr);
auto* st = reinterpret_cast<fl::FlWriterState*>(static_cast<unsigned char*>(base) + FL_SHM_WRITER_OFFSET);
auto* ctl = reinterpret_cast<fl::FlControlBlock*>(static_cast<unsigned char*>(base) + FL_SHM_CONTROL_OFFSET);
for (int i = 0; i < 100 && st->status != fl::FL_STATUS_READY; ++i) {
Sleep(50);
}
REQUIRE(st->status == fl::FL_STATUS_READY);
// GREEN DIRECTION FIRST: it really is recording. A pause test against a
// capture side that was never writing proves nothing.
std::uint64_t running = 0;
for (int i = 0; i < 40 && running < 5; ++i) {
++ctl->guardTicks;
Sleep(100);
running = st->writeIndex;
}
REQUIRE(running > 5);
// PAUSE, and keep the guard ticking. Every tick change is a frame on which
// the old code returned early, before it ever looked at pauseRequested.
ctl->pauseRequested = 1;
Sleep(200); // let any present already in flight land
const std::uint64_t atPause = st->writeIndex;
for (int i = 0; i < 12; ++i) {
++ctl->guardTicks;
Sleep(100);
}
CHECK(st->writeIndex == atPause);
// Still supervised and still hooked -- pausing is not stopping, and a pause
// that quietly unhooked would pass the line above for the wrong reason.
CHECK(st->status == fl::FL_STATUS_READY);
// AND IT RESUMES. Pause is the one control-block signal that is NOT one-way,
// so an implementation that latched it would satisfy every assertion above.
ctl->pauseRequested = 0;
std::uint64_t after = st->writeIndex;
for (int i = 0; i < 40 && after <= atPause; ++i) {
++ctl->guardTicks;
Sleep(100);
after = st->writeIndex;
}
CHECK(after > atPause);
UnmapViewOfFile(base);
CloseHandle(mapping);
}
TEST_CASE("the safety stop fires in a target that has STOPPED presenting", "[guard][inject][shm]") {
// The case the present path structurally cannot serve, and the reason the
// watchdog exists. MayObserve has one caller (RecordPresent), which has two
// (the Present and Present1 hooks) -- so with no presents, unhookRequested
// was never read and the hooks stayed patched in for the life of the process.
//
// fl_shm.h says over FL_GUARD_TICK_DEADLINE_MS, in capitals, that this must
// not be driven by the present hook, "because the clock would stop when
// presents stop, which is the exact scenario this exists for -- a game that
// has hung, or been alt-tabbed, while anti-cheat loads behind it". It was.
//
// --hold, NOT --hold-presenting: it presents 240 frames and then sleeps, so
// by the time we inject ~800 ms later the presents are long over. That
// property is already asserted one test above via writeIndex == 0, which is
// what makes this fixture the right one rather than a hopeful one.
Child child;
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --hold 30";
STARTUPINFOW si{};
si.cb = sizeof(si);
REQUIRE(CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
&child.pi));
Sleep(800);
REQUIRE(WaitForSingleObject(child.pi.hProcess, 0) == WAIT_TIMEOUT);
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
REQUIRE(GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed());
wchar_t name[128]{};
REQUIRE(_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", child.pi.dwProcessId) > 0);
HANDLE mapping = nullptr;
for (int i = 0; i < 100 && mapping == nullptr; ++i) {
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
Sleep(50);
}
}
REQUIRE(mapping != nullptr);
void* base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
REQUIRE(base != nullptr);
auto* st = reinterpret_cast<fl::FlWriterState*>(static_cast<unsigned char*>(base) + FL_SHM_WRITER_OFFSET);
auto* ctl = reinterpret_cast<fl::FlControlBlock*>(static_cast<unsigned char*>(base) + FL_SHM_CONTROL_OFFSET);
for (int i = 0; i < 100 && st->status != fl::FL_STATUS_READY; ++i) {
Sleep(50);
}
REQUIRE(st->status == fl::FL_STATUS_READY);
// The precondition that makes this case what it says it is: hooked, alive,
// and NOT presenting. If a future harness change made --hold present for the
// whole hold, this REQUIRE fails rather than the test silently becoming a
// duplicate of the one that uses --hold-presenting.
REQUIRE(st->writeIndex == 0);
ctl->unhookRequested = 1;
for (int i = 0; i < 100 && st->status != fl::FL_STATUS_UNHOOKED; ++i) {
Sleep(100);
}
CHECK(st->status == fl::FL_STATUS_UNHOOKED);
UnmapViewOfFile(base);
CloseHandle(mapping);
}
TEST_CASE("a REFUSED guard injects nothing", "[guard][inject]") {
// The assertion the whole design exists for. The target is a real process,
// the DLL is real and loadable, and the only thing standing between them is