Compare commits

..
Author SHA1 Message Date
poli0981andClaude Fable 5.1 6b51515dca feat(vklayer): vkQueuePresentKHR intercepted -- the layer owns the ring, records every present, and stops itself on the present path (P1 item 3, §S2 part three)
In a process both gates admitted, the layer creates the same ring the Overlay
would -- fl_shm_host.h is now the one home of the DACL, the name, the mapping
and the handshake for BOTH capture sides (the Overlay calls it too) -- at the
first vkCreateDevice, writes one record per present (api = Vulkan, output size
from vkCreateSwapchainKHR's imageExtent, no PRESENT_ARGS because the call has
none) and forwards everything. One ring per process: the first creator owns it,
the other stays inert AND forwarding -- the first fixture run measured
VK_ERROR_DEVICE_LOST when the layer had registered no next pointer, so the next
pointers now come before the ring and the ring failing only ever means
"observe nothing".

§S2 part three lands with it, on the present path (the layer owns no thread):
unhookRequested -> UNHOOKED within one present; guardTicks not advancing for the
07_IPC deadline -> UNHOOKED; pauseRequested -> no record, still forwarded.
"Stops" is passthrough forever with the reason on the mapping. Proven by a fake
loader chain (ctest fl_vklayer) and a 1.5 s test-only flavour of the DLL
(fl_vklayer_supervision: ticks every 600 ms keep it alive past the deadline,
1.8 s without one stops it).

Real loader: hook-harness --vulkan --hold-presenting N (vulkan-1 via
LoadLibraryW, hidden window, exit 77 = cannot run here) and ctest
fl_vklayer_real, which points the loader at the build tree's manifest through
VK_ADD_IMPLICIT_LAYER_PATH -- measured honoured by 1.4.357 with no registry --
and skips on CI: 241 records in 4 s. vklayer-blastradius.ps1 hand-run, green.

Launch mode: a target that mapped vulkan-1.dll is the layer's --
Reason::kTargetIsVulkanLayered (26): the full guard runs, nothing is injected,
the host attaches to the layer's ring with launch mode's budget. Vulkan WINS
over a D3D runtime beside it, because the NVIDIA Vulkan ICD maps dxgi + d3d12
itself and presents through a DXGI chain (measured: the injected Overlay
recorded 295 DXGI presents of a Vulkan swapchain). The CaptureHost's launch
hands the process the layer's environment (VkLayerLaunchEnvironment: manifest
under %LOCALAPPDATA%\FrameLedger\vklayer, enable variable, enable-list line for
the session) and stages FrameLedger.VkLayer.dll beside itself.

Docs: 17_HOOK_ENGINE §Vulkan + Presentation row, 20_OPEN_QUESTIONS §S2 ✅ /
§S24 / §S29(d), 04_CAPTURE, 12_BUILD, spike-notes §2 (two measurements),
legal/ACCURACY.md + its two copies, README, DISCLAIMER §2, 15_ROADMAP, HANDOFF,
CHANGELOG.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 19:25:45 +07:00
poli0981andClaude Fable 5.1 f61d35f7f6 feat(injector): launch mode as "inject late" -- the guard waits for a presentation runtime, then runs in full (P1 item 2, §S1 / §S13(c)) (#139)
A CREATE_SUSPENDED target has loaded nothing and EnumProcessModulesEx fails
against it (§S1, measured), so launch mode cannot be create -> guard -> inject
-> resume. Built shape: start -> the guard WAITS -> the full guard -> inject.

Guard: GuardedInjectWhenReady(pid, dll, timeoutMs) / ABI FlGuardedInjectWhenReady
polls the target every 50 ms through the module seam -- matching no blocklist;
a failing enumeration is "not yet", never a pass -- until dxgi+d3d11/d3d12,
opengl32 or vulkan-1 is mapped, then runs GuardedInjectImpl unchanged. Two new
reasons end the poll with nothing injected: LaunchTargetExited (24) and
LaunchNoPresentationRuntime (25). ctest fl_guard [launch], five cases: injects
on the first enumeration showing the runtime and not one before; exit-first and
budget-out each answer their own reason; anti-cheat mapped beside the runtime is
the full scan's refusal; the real seam against hook-harness injects in 15 ms.

Overlay: FlWriterState.dxgiPresentsBeforeHook @60 -- GetLastPresentCount at the
first hooked present on the first hooked chain, i.e. presents that ran before
the hook was in; 0xFFFFFFFF until a present is seen, set BEFORE the present
hooks go in (the first placement, after them, lost the race to an 8 ms
presenter -- caught by the fixture). Took the last reserved word; no layout
bump; the writer state now has no slack.

CaptureHost: `launch --exe <path> [--args "..."] [--seconds n]`; ProcessLauncher
(handle held from birth, FRAMELEDGER_ENABLE_VK_LAYER=1; the host never
terminates what it launched); CaptureLoop.RunLaunchedAsync sharing the gate,
attach and drain with attach mode; HookRequest.WaitForPresentationRuntimeMs
routes the same gate through IAntiCheatGuard.GuardedInjectWhenReadyAsync (the
port's fourth method, primitives only); the report prints the wait and the
before-hook count (LaunchNote). NoSecondMatcherTests 3 -> 4 as a reviewed act.

Docs: 04_CAPTURE §Launch mode (the shape, why not CREATE_SUSPENDED, what it
measures), 01_ARCHITECTURE, 19_SAFETY item 1, 20_OPEN_QUESTIONS §S1 ◐ /
§S13(c) ✅ / §S24, 17_HOOK_ENGINE, 15_ROADMAP, HANDOFF, spike-notes, CHANGELOG.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 17:42:01 +07:00
poli0981andClaude Fable 5.1 627995068d feat(overlay): the LoadLibrary detour -- lazy-install wake within milliseconds + the in-process anti-cheat stop (P1 item 1, §S6) (#138)
kernelbase.dll!LoadLibraryExW is patched from InitThread after the present hooks
(17_HOOK_ENGINE §DLL entry step 3). The body calls the original first, skips
data-file / resource mappings, reads the mapped module's own file name into a
stack buffer and compares its base name against two fixed tables:

- FL_HOOK_INVENTORY + FL_RUNTIME_CENSUS: a match bumps a saturating 15-bit wake
  count and signals the watchdog's new auto-reset event, so the lazy installers
  run within milliseconds of the module rather than on the next 1 Hz tick.
  Measured in ctest fl_guard [loader]: 94 ms against a 500 ms bound.
- the compiled floor's MODULE families (fl_ac_floor.generated.h, prefix,
  case-insensitive, allocation-free): a match CASes the family's 1-based index
  into earlyStopFamily; MayObserve or the watchdog, whichever is first, calls
  StopObserving(FL_STATUS_STOPPED_BLOCKLISTED). ctest fl_guard [S6]: a decoy
  named EasyAntiCheat_fl_fixture.dll loaded 2.5 s in stops the Overlay with the
  index the test computes from the same table, unhookRequested still 0,
  writeIndex frozen.

The detour installs nothing inline (§H2). Exact names only: the fragment and
signer tiers stay the host's 30 s scan, so the Disclaimer's window is unchanged
(19_SAFETY §During a session, the in-process half).

FlWriterState gains loaderSignals @56 and earlyStopFamily @58 from reserved[]
(no layout bump; mirror + fl-layout-dump updated). hook-harness gains
--load-after-ms N PATH. The CaptureHost reads both words (Consume/EarlyStop.cs):
"loader detour:" and "EARLY STOP" report lines, the family named from the staged
rules file, SessionEndReason.WriterStoppedBlocklisted -> exit 5.

Docs: 17_HOOK_ENGINE §DLL entry + the one system-module hook row, 19_SAFETY,
20_OPEN_QUESTIONS §S6 ✅ / §S24 / §H2, 15_ROADMAP P1, HANDOFF, CHANGELOG.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 09:46:03 +00:00
poli0981andClaude Fable 5.1 c5932cc115 P0 closing sweep — criterion 1 amended, criterion 2 met; §S19(c) and §S23-6 closed by a gate each, §S29(d) on a CI measurement, six deferrals written (#137)
* docs+tools: P0's closing sweep -- criterion 1 amended, criterion 2 met; §S19(c) and §S23-6 closed by a gate each, §S29(d) pre-committed on a CI measurement, six items deferred with rationale

The owner's "theo bảng" (2026-09-06). Criterion 1: the quality preset reads N/A on every
title by measurement (tags carry no size or preset on D3D12, NVIDIA's override fields are
the override's, XeSS is closed by licence) and an honest N/A is the correct value rule 7
asks for; upscaler, render->output, FG factor and RT verified against nine titles' menus.
Criterion 2: §S24 counts zero S-items against it, with S23-2 (a GitHub setting) outside
any PR.

- §S19(c): rules-validate gains canary 3 -- the shipped document mutated to action
  "allow" and to signerField "CN" must be rejected by the schema (proven red by loosening
  the const in a temp copy). The policy is code; the fields exist so the data cannot say
  otherwise.
- §S23-6: legal/ACCURACY.md is the one accuracy block, embedded verbatim in README.md
  and DISCLAIMER.md §4 between markers; tools/accuracy-check.ps1 (build.ps1 gate, four
  self-test cases both directions) fails on drift, missing markers or an empty source.
  The block is rewritten to 2026-09-06 truth (the old §4 still said frame generation and
  ray tracing had no hook).
- §S29(d): ci.yml prints a Vulkan runtime census; rows pre-committed -- present: the
  blast-radius script becomes a CI step; absent: deferred on that measurement.
- Deferred with rationale in the entry and phase in §S24: S6 and S2 part three (P1),
  S23-3 (P3), S4 signing, S20 feed half, S14 store-id half (P4).
- 15_ROADMAP and HANDOFF: P0 closed, P1 starts.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs: §S29(d)'s census read off the sweep run -- loader present, vulkaninfo and ICD absent; deferred on that measurement with the reopen condition written

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 09:07:04 +00:00
poli0981andClaude Fable 5.1 42e15c9dbd feat(guard): the signer half -- "name fragment AND not signed by a known vendor", under a compiled-in bound; -SkipIntegration dropped from CI (§S19(b) row G1) (#136)
Since 2026-08-05 the guard refused FrameLedger's own test host on CI: a .NET host
loads System.Security.Cryptography.ProtectedData.dll, `protect` is a heuristic
fragment, and the signer conjunct was unwired. fl-probe-signer's three legs (dev box,
CI, the owner's adapters-disabled run) all read the same: the embedded signature
verifies offline with O=Microsoft Corporation in ~2-4 ms and no verdict changes
without a network. The owner chose the bound (option 1) on 2026-09-06.

- Sources::ModuleSignerOrganisation (fl_guard_sources.cpp, never fl_ac_rules.cpp):
  WinVerifyTrust WTD_CHOICE_FILE under WTD_REVOKE_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL |
  WTD_SAFER_FLAG, then the signing certificate's subject O= -- fixed buffers, no
  allocation; kFailed for everything short of a verified, readable organisation.
- IsCompiledTrustedSigner: the five organisations compiled in; IsTrustedSigner now
  requires the rules file AND the binary, so a rules push can narrow and never widen.
- ModuleSinkFn: after the ours exemption, a fragment-matching module signed by a
  trusted organisation returns keep-looking (the load-order fail-open stays closed);
  the target is judged like its ancestors; everything else latches SuspiciousUnsigned.
- hook-harness --load PATH; fl_guard proves both directions against the real seams
  (the NuGet blocker allowed and the Overlay injected; our own unsigned Overlay under
  a `protect` name outside the guard's directory refused, by name) plus nine fake-seam
  cases (both lists, the target, kFailed, missing seam, pathless, load order, exact-hit
  precedence). The catalog half stays deferred with its rationale.
- ci.yml runs ./build.ps1 check with no switches: the nine Category=Integration cases
  are in the merge gate. The switch stays in build.ps1, loud.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 15:25:11 +07:00
poli0981andClaude Fable 5.1 1d72021a8a docs: the signer probe's two remaining legs read -- CI (rows G3/G4/G5 do not fire) and adapters-disabled (every verdict unchanged, row G1); the bound is what remains (#135)
The CI leg, off the new ci.yml step: the runner's NuGet copy of the blocker verifies
embedded/offline in 3.47 ms with O= Microsoft Corporation; mskeyprotect.dll is catalog-only;
cryptnet.dll loads under the offline flags; canary TRUST_E_NOSIGNATURE. The
adapters-disabled leg, the owner's run: every verdict unchanged, faster (2.14 ms), the
blocker's subject now CN=.NET with the same O= -- signerField "O" confirmed on a subject
class it had never met. Row G1 reads. The trustedSigners allow-widening bound is the
owner's decision and is asked for beside the reading.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 08:01:59 +00:00
poli0981andClaude Fable 5.1 bed369b21c ci: the signer probe's CI leg, printed -- §S19(b) rows G3/G4/G5 were never readable (#134)
ctest fl_signer_probe passes on a regular expression and prints nothing for a passing
test, so the CI leg §S19(b) pre-committed rows for was never in any log; and the native
tests run before dotnet restore, so a cold runner may not even have the NuGet copy the
probe searches first. ci.yml now runs the probe as its own step after the gate
(continue-on-error: a measurement, not a gate). HANDOFF's Separable item carries the
sequence: this leg, the owner's adapters-disabled leg, the owner's allow-widening bound,
then the guard PR that drops -SkipIntegration.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 07:41:06 +00:00
poli0981andClaude Fable 5.1 7dbfb5cb6f feat(capturehost): the FG N/A and the upscaler N/A carry their witnesses -- Hell Is Us at XeSS + XeSS-FG, and 7c item 4's string change (#133)
Hell Is Us at XeSS + XeSS-FG (2026-09-06): no Streamline token on that plugin at XeSS, so
nothing counted, and the report printed a bare "N/A (a hook ran ...)" while the driver's FG
word, the tags, the ffx census, the module census and the executable's strings all had
something to say. The N/A now prints the same exclusion clauses as rung 3; the upscaler N/A
says libxess.dll is loaded and XeSS cannot be hooked or declared under Intel's licence, so
the N/A is by policy, not by ignorance. Rune Factory at FSR + FSR FG printed the
pre-committed 7b line verbatim on the same run; Cronos at XeSS read none by count.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 14:27:45 +07:00
poli0981andClaude Fable 5.1 8cf3d6f3eb feat(capturehost): rung 3 by elimination, and the executable file as the census's second witness -- HANDOFF 7b / §H11, the owner's choice over "return native" (#132)
- `frame generation: Active (technology not identified)` now prints every exclusion the
  session can make: not DLSS-G when the driver's FG word reports no feature created and no
  HUD-less / UI tag was sent (or "not excluded" without the driver's answer), no FSR
  frame-generation dispatch reached a hooked module, the frame-generation runtime modules
  the census names or that none is loaded, and the SDK strings the executable carries.
  Never a vendor named as measured (XeFG cannot be hooked or declared by licence; a
  compiled-in FSR 3 has no module), and the line says a frame generator compiled into the
  executable would read the same.
- ExecutableMarkerScan reads the exe FILE on disk once after the session (chunked with
  overlap, hits capped; ffxFsr3, ffxFrameInterpolation, xefgSwapChain move the sentence;
  FidelityFX, ffxFsr2, NVSDK_NGX, xessD3D12 are printed for the reader) and the report
  prints `executable markers:`. With no module loaded and a frame-generation-capable
  string in the file, the Presented qualifier reads MAY include generated frames instead
  of cannot -- the sentence that was wrong in the dangerous direction on Rune Factory.
- Consumer only; no hook-path change. 8 new cases; one superseded expectation updated.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 06:36:12 +00:00
poli0981andClaude Fable 5.1 237765dede docs: the AMD half of 7c complete on Lies of P; the Intel licence re-checked and unchanged; identity by elimination proposed for XeFG (#131)
Lies of P at FSR 3.1 + FSR FG on #129: Fsr3 / FsrFg / 59.77 -> 119.55 (x2 FG) / 2560x1440 ->
2560x1440, presents/frame 2.00, frames/upscale-drained 1.00, unseen 0, the NVIDIA driver's
word saying nothing was created. The owner called the AMD half done.

Intel: LICENSE.txt and inc/xess/xess.h re-fetched 2026-09-06 -- Intel Simplified Software
License, unchanged; the reversal condition has not fired. Intel's README says XeSS-FG runs
on non-Intel GPUs with SM 6.4, so an XeFG session is measurable here. §H11 carries the
in-policy proposal: identity by elimination, labelled, never XeFg as a measured identity.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 06:16:19 +00:00
78 changed files with 5901 additions and 301 deletions

No files matched your search

+46 -17
View File
@@ -92,25 +92,21 @@ jobs:
# not part of `build.ps1 check`: it mutates HKCU, and a CI runner is the
# wrong place to be registering machine-wide Vulkan layers.
# -SkipIntegration, and the reason is a MEASURED property of the hard gate
# rather than CI being awkward.
#
# The drain end-to-end tests inject the Overlay into hook-harness, which
# makes the TEST HOST the target's parent — and §S16 puts a target's
# ancestors in the scan set. A .NET host can load
# System.Security.Cryptography.ProtectedData.dll, whose name contains the
# heuristic fragment `protect`, so the guard refuses our own harness with
# SuspiciousUnsigned. Measured here on 2026-08-05; it passes on a dev box
# whose test host happens not to load that assembly, which is why CI is the
# machine that found it.
#
# That is the guard behaving as specified. The defect is §S19(b) — the
# fragment matching a benign, widely-loaded Microsoft assembly — and fixing
# it is a guard change with its own PR, not something to work around here.
# Until then these run locally and CI says out loud that it skipped them.
# NO -SkipIntegration, since 2026-09-06, and the reason it was here is worth
# keeping: the drain end-to-end tests inject the Overlay into hook-harness,
# which makes the TEST HOST the target's parent — §S16 puts ancestors in the
# scan set — and a .NET host loads System.Security.Cryptography.ProtectedData.dll,
# whose name carries the heuristic fragment `protect`. From 2026-08-05 the
# guard refused our own harness here with SuspiciousUnsigned, and CI said out
# loud that it skipped nine cases. §S19(b)'s signer half now verifies that
# module's embedded signature offline and reads O=Microsoft Corporation, so
# the refusal is gone for the reason 19_SAFETY always gave ("fragment AND not
# signed by a known vendor"), and the nine cases are in the merge gate. The
# switch still exists in build.ps1 for a developer who must, and it skips
# loudly; CI is no longer a place it is passed.
- name: Quality gate
shell: pwsh
run: ./build.ps1 check -SkipIntegration
run: ./build.ps1 check
env:
CI: 'true'
@@ -135,6 +131,39 @@ jobs:
# from `git diff`, so a shallow checkout cannot silently produce a short
# list — and the script refuses an EMPTY list rather than reading it as
# "no src/ changes, therefore fine".
# THE SIGNER PROBE'S CI LEG, printed. `ctest fl_signer_probe` runs inside the
# gate and passes on a regular expression, so its ANSWERS never reach this
# log — and §S19(b)'s rows G3/G4/G5 are pre-committed for exactly this
# machine's copy of the blocker. Run here, AFTER the gate, because the gate's
# restore is what fills the NuGet cache the probe searches first. A
# measurement, not a gate: continue-on-error so a surprise (row G6) is
# printed rather than turned into a red that hides it. Reading the row off
# the table is a separate PR (the probe says so itself).
- name: Signer probe (§S19(b) CI leg — measurement, not a gate)
if: always()
continue-on-error: true
shell: pwsh
run: ./build/native/x64-release/tools/fl-probe-signer/fl-probe-signer.exe
# §S29(d)'s pre-committed measurement: can tools/vklayer-blastradius.ps1 run
# HERE? It needs a Vulkan loader and vulkaninfo.exe, which ship with a GPU
# driver's runtime, not with Windows. A census, printed, never a gate: if the
# runner has them, the next PR wires the script as a step (the runner is
# disposable, so registering an implicit layer under HKCU is acceptable
# here where it is not on a dev box); if it does not, (d) is deferred on a
# measured rationale rather than an assumed one.
- name: Vulkan runtime census (§S29(d) — measurement, not a gate)
if: always()
continue-on-error: true
shell: pwsh
run: |
foreach ($f in 'C:\Windows\System32\vulkan-1.dll', 'C:\Windows\System32\vulkaninfo.exe') {
Write-Host ("{0}: {1}" -f $f, (Test-Path $f))
}
$cmd = Get-Command vulkaninfo.exe -ErrorAction SilentlyContinue
Write-Host ("vulkaninfo.exe on PATH: {0}" -f ($(if ($cmd) { $cmd.Source } else { 'no' })))
Write-Host ("HKLM:\SOFTWARE\Khronos\Vulkan\Drivers present: {0}" -f (Test-Path 'HKLM:\SOFTWARE\Khronos\Vulkan\Drivers'))
- name: Changelog
if: github.event_name == 'pull_request'
shell: pwsh
+96
View File
@@ -19,6 +19,93 @@ GitHub release body, so a missing section will mean an empty release note.
### Added
- **P1 item 3 — the Vulkan layer intercepts `vkQueuePresentKHR` (2026-09-06; `20_OPEN_QUESTIONS` §S2 ✅).**
In a process both gates admitted, the layer creates the same ring the Overlay would (`fl_shm_host.h`,
now the one home of the DACL / name / handshake for both capture sides; one ring per process, first
creator owns it) at the first `vkCreateDevice`, writes one record per present (`api` = Vulkan, output
size from `vkCreateSwapchainKHR`'s `imageExtent`, no `PRESENT_ARGS` because the call has none), and
forwards everything — including when the ring is not its own, which the first fixture run proved
necessary. §S2 part three lands with it: `unhookRequested` and the 07_IPC tick deadline both stop the
layer on the present path (passthrough with the reason on the mapping), proven by a fake loader chain
(ctest `fl_vklayer`) and a 1.5 s test-only flavour of the DLL (`fl_vklayer_supervision`). The harness
gains `--vulkan --hold-presenting N` (real loader via `LoadLibraryW`, hidden window, exit 77 = cannot
run here) and ctest `fl_vklayer_real` drives it through the real loader with `VK_ADD_IMPLICIT_LAYER_PATH`
— measured honoured by loader 1.4.357 with no registry — skipping on CI. Launch mode classifies a
Vulkan-only target as the layer's (`TargetIsVulkanLayered` = 26: full guard, nothing injected, attach to
the layer's ring) and the CaptureHost hands the launched process the layer's environment
(`VkLayerLaunchEnvironment`: manifest, enable variable, enable-list line for the session).
- **P1 item 2 — launch mode, built as "inject late" (2026-09-06; `20_OPEN_QUESTIONS` §S1 ◐, §S13(c) ✅).**
The guard gains `FlGuardedInjectWhenReady(pid, dll, timeoutMs)`: it polls the launched target through
the module seam — matching no blocklist — until a presentation runtime is mapped, then runs every
check and injects exactly as `FlGuardedInject` does; a target that exits first or maps no runtime in
the budget answers the new `LaunchTargetExited` / `LaunchNoPresentationRuntime` with nothing injected
(ctest `fl_guard` `[launch]`, five cases incl. the real seam against `hook-harness`). The CaptureHost
gains `launch --exe <path> [--args "…"] [--seconds n]` (`ProcessLauncher`: handle held from birth,
`FRAMELEDGER_ENABLE_VK_LAYER=1`; the host never terminates what it launched), routed through the same
gate by `HookRequest.WaitForPresentationRuntimeMs`, with `IAntiCheatGuard.GuardedInjectWhenReadyAsync`
as the port's fourth method. The Overlay publishes `FlWriterState.dxgiPresentsBeforeHook` @60 — DXGI's
count of presents before the first hooked one, the early-init cost §S1 deferred on — from the last
reserved word (no layout bump; the writer state now has no slack), and the report prints it beside the
measured wait. `04_CAPTURE` §Launch mode carries the shape and why it is not `CREATE_SUSPENDED`.
- **P1 item 1 — the `LoadLibrary` detour, both jobs (2026-09-06).** The Overlay patches
`kernelbase.dll!LoadLibraryExW` after its present hooks (`17_HOOK_ENGINE` §DLL entry step 3): a module
the hook inventory or runtime census names **wakes the watchdog** through an auto-reset event, so the
lazy installers run within milliseconds of the module instead of on the next 1 Hz tick (94 ms measured
against a 500 ms bound); a module matching the compiled anti-cheat floor's MODULE families **stops the
Overlay from inside** with the new `FL_STATUS_STOPPED_BLOCKLISTED`, on the next present or watchdog
iteration — `20_OPEN_QUESTIONS` §S6 ✅, `19_SAFETY` §During a session's in-process half (exact names
only; fragment and signer stay the host's 30 s scan, so the Disclaimer's window is unchanged). The
detour installs nothing inline (§H2), calls the original first, and skips data-file / resource loads.
Two `FlWriterState` words from `reserved[]` (`loaderSignals` @56, `earlyStopFamily` @58; no layout
bump), `hook-harness --load-after-ms N PATH`, two real-Overlay ctest cases (`[loader]`, `[S6]`), and
the CaptureHost's `loader detour:` / `EARLY STOP` report lines, `SessionEndReason.WriterStoppedBlocklisted`
(exit 5) with the family named from the staged rules file.
- **P0 closed — the closing sweep (owner: "theo bảng", 2026-09-06).** Exit criterion 1 is met with
the quality preset amended to an honest `N/A` by measurement; criterion 2 is met with §S24 counting
zero S-items against it. Three items closed by a gate each: **§S19(c)** — `rules-validate` gains a
third canary proving the schema rejects `action: "allow"` and `signerField: "CN"`, so the policy is
code and the data cannot say otherwise; **§S23-6** — the accuracy blocks are one text,
`legal/ACCURACY.md`, embedded verbatim in `README.md` and `legal/DISCLAIMER.md` §4 and gated by
`tools/accuracy-check.ps1` (self-tested both directions), and rewritten to 2026-09-06 truth (the old
§4 still said frame generation and ray tracing had no hook); **§S29(d)** — `ci.yml` prints a Vulkan
runtime census, and the blast-radius script runs as a CI step the day a runner has a loader, deferred
on that measurement until then. Six items deferred with their rationale written and their phase named:
S6 and S2 part three (P1), S23-3 (P3), S4 signing, S20 feed half and S14's store-id half (P4).
`15_ROADMAP` and `HANDOFF` now say P1 starts.
- **The guard's signer half — the other conjunct of "name fragment AND not signed by a known vendor" —
and the nine integration cases in the merge gate (§S19(b) row G1; owner's bound decision 2026-09-06).**
Since 2026-08-05 the guard refused FrameLedger's own test host on CI because a .NET host loads
`System.Security.Cryptography.ProtectedData.dll` and `protect` is a heuristic fragment, and CI skipped
the drain, pause, drop and capture-host end-to-end cases. `fl-probe-signer`'s three legs (dev box, CI,
the owner's adapters-disabled run) all read the same: the embedded signature verifies offline with
`O=Microsoft Corporation`, ~2–4 ms, no verdict changing without a network. So `Sources` gained
`ModuleSignerOrganisation` — `WinVerifyTrust` under `WTD_REVOKE_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL`,
then the certificate's `O=` — and the module sink trusts a fragment-matching module only when that
organisation is on the rules file's `trustedSigners` AND on the list compiled into the binary
(`IsCompiledTrustedSigner`: the data may narrow, never widen). A trusted module keeps the scan
looking; the target is judged like its ancestors; no signature, an invalid one, an unreadable `O=`, a
null path or seam, a failing seam, one list without the other — all refuse. The catalog half stays
deferred with its rationale. `hook-harness --load` proves both directions against the real seams
(the NuGet blocker allowed; our own unsigned Overlay under a `protect` name refused, by name); nine
fake-seam cases pin the decision. `ci.yml` runs `./build.ps1 check` with no switches; the switch stays
in `build.ps1`, loud. `19_SAFETY`, §S19(b), §S29(a), `13_CI_CD`, `12_BUILD`, `HANDOFF` and the rules
file's own comment carry it.
- **Rung 3 by elimination, and the executable file as the census's second witness (HANDOFF 7b / §H11,
owner's choice 2026-09-06).** `frame generation: Active (technology not identified)` now prints every
exclusion the session can make beside it — not DLSS-G when the NVIDIA driver's FG word reports no feature
created and no HUD-less / UI tag was sent (or "not excluded" when the driver did not answer), no FSR
frame-generation dispatch reached a hooked module, the frame-generation runtime modules the census names
or that none is loaded, and the SDK strings the executable carries — never a vendor named as measured, and
it says a frame generator compiled into the executable would read the same. The capture host scans the
executable FILE on disk once after the session (`ExecutableMarkerScan`: `ffxFsr3`, `ffxFrameInterpolation`,
`xefgSwapChain` and the non-FG strings for the reader; chunked with overlap, hits capped) and prints
`executable markers:`; when a frame-generation-capable string is in the file and no module was loaded, the
Presented qualifier reads *MAY include generated frames* instead of *cannot* — the sentence that was wrong
in the dangerous direction on Rune Factory and Wukong. A marker is never identity. Intel's licence was
re-checked the same day and is unchanged; XeSS-FG runs on non-Intel GPUs, so an XeFG session measures this.
- **The super-resolution identity from the NVIDIA driver, where no hook can see it — the driver-reported
rung (owner decision 2026-09-06).** Three NGX-direct titles printed `upscaler: N/A` on every capture
while the driver's per-process NGX word (`NvAPI_NGX_GetNGXOverrideState`, R570+, MIT NVAPI) reads
@@ -42,6 +129,15 @@ GitHub release body, so a missing section will mean an empty release note.
### Changed
- **The FG `N/A` and the upscaler `N/A` carry their witnesses.** Hell Is Us at XeSS + XeSS-FG (2026-09-06):
no Streamline token on that plugin at XeSS, so nothing counted, and the report printed a bare *N/A (a hook
ran …)* while the driver's FG word, the tags, the ffx census, the module census and the executable's own
strings all had something to say. The N/A now prints the same exclusion clauses as rung 3 (*what this
session can still say: not DLSS-G (…); …; the frame-generation runtime(s) loaded: …; the executable itself
carries xefgSwapChain*), and the upscaler N/A says *libxess.dll is loaded, and XeSS cannot be hooked or
declared under Intel's licence … by policy, not by ignorance* — HANDOFF 7c item 4's string change. Rune
Factory at FSR + FSR FG printed the pre-committed 7b line verbatim on the same run.
- **A counted session whose factor was refused no longer reads "no evaluation was observed".** DL:TB at FSR
upscaling + DLSS Frame Generation (2026-09-06): 4,415 tokens, 8,174 DXGI-counted presents, `DlssG` from
the tags, factor refused because bucket 8 of 8 read 1.96 against 2.85 — and the Presented qualifier said
+37 -21
View File
@@ -4,28 +4,44 @@
> No telemetry. No accounts. All data stays on your machine.
> ⚠ **Accuracy note — 2026-08-05. This README describes the finished product; the software
> is pre-alpha and most of what follows is not built yet.** Added because every other
> user-facing document here carries such a note and this one — the first thing anyone
> reads — carried none, while `legal/DISCLAIMER.md` had already been through two rounds of
> exactly this correction.
<!-- accuracy-block:begin -->
> ⚠ **What FrameLedger actually measures today — 2026-09-06.** The software is pre-alpha: the
> measurement path exists as an injected Direct3D 11/12 component and an **unshipped** capture
> host that drives the guard loop and prints a report; there is no Agent loop, no storage, no
> charts, no library import, no UI and no installer yet.
>
> **What actually works today:** frame boundaries, frame times and output resolution, from
> a Direct3D 11/12 present hook, written into shared memory and read back by the Agent's
> ring reader. Plus, for titles that go through NVIDIA Streamline, **which upscaler is
> executing** and **whether Ray Reconstruction is running with it** — identity only, not the
> quality preset and not the render resolution. The anti-cheat guard runs all of its
> pre-injection checks and refuses.
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
> labelled *driver-reported*. Intel XeSS is **not** read (its SDK licence forbids it) and reads
> `N/A` by policy; an upscaler compiled into the game executable reads `N/A`.
> - **Quality preset:** `N/A` everywhere. No route this software may use exposes it.
> - **Render → output resolution:** measured where the vendor's own call carries the size (AMD
> dispatches, some Streamline titles); `N/A` where it does not (NVIDIA-direct titles, most
> Direct3D 12 Streamline titles).
> - **Frame generation:** the Displayed rate is counted from presents — including, on one title,
> presents DXGI counted that the hook could not — and the Native rate from the vendor's own
> per-frame calls where the title makes them. Identity: DLSS-G and FSR-FG named from the calls
> the game makes; anything else (XeSS-FG, a generator compiled into the game) is reported *by
> elimination* and never named. Where no per-frame call exists the Native rate is `N/A`.
> - **Ray tracing:** Yes/No measured from DXR dispatches and acceleration-structure builds on
> Direct3D 12; the technique and path tracing are `N/A`.
> - **Not measured at all:** video memory, shader-compilation stutter, PC latency (Reflex), HDR.
> - **Safety:** every pre-injection check runs before injection, including the signed-by-a-known-
> vendor half of the suspicious-module rule (since 2026-09-06), and the unshipped capture host
> re-runs them every 30 s and stops the capture on refusal. No shipped component drives that loop
> yet. There is no override anywhere.
>
> **What does not yet exist**, and is written above in the present tense: every bullet
> under *What makes it different* except output resolution and upscaler identity — no
> quality preset, render resolution, frame generation, ray tracing, VRAM, shader-stutter or
> Reflex hook has been written. The capture side says so in its own data rather than defaulting to "none"
> (`docs/03_METRICS.md`, CLAUDE.md rules 6 and 7). There is also no storage, no charts, no
> library import, no UI and no installer.
>
> The two rows that describe **safety behaviour** are qualified where they sit, rather than
> here, because that is where a reader checking their own risk will look.
> Where a value is not measured it reads `N/A`; the software never substitutes an estimate.
<!-- accuracy-block:end -->
> The rows below that describe **safety behaviour** are qualified where they sit, rather than
> here, because that is where a reader checking their own risk will look. What this README
> describes beyond the block above is the finished product; the block is what exists.
## What makes it different
@@ -52,7 +68,7 @@ FrameLedger is built to keep that risk small and to be honest about it:
| Safeguard | |
|---|---|
| **Off by default** | Injection is disabled for every game until you enable it individually, after a consent prompt |
| **Hard refusal** | Known anti-cheat/anti-tamper components are detected before injection and every 30 s during a session. Detected ⇒ FrameLedger refuses, or stops capturing at the next scan — so up to 30 s can pass before it reacts to anti-cheat that loads mid-session. For Direct3D/OpenGL that means hooks are removed; for Vulkan it means the layer goes passthrough, because a layer cannot leave the loader chain of a running game. **There is no override — not in settings, not in a config file, not on the command line**<br><br>⚠ **Half of this is built.** The *pre-injection* refusal is real and runs every documented check. The **in-session re-scan does not run at all**: the component inside the game removes its hooks within one frame of being told to, and within 65 s if it stops hearing from the scanner — but nothing yet drives the scanner during a session, so nothing ever tells it. `legal/DISCLAIMER.md` §2 states this in full. The Vulkan layer additionally intercepts nothing yet, so there is no Vulkan capture to stop. |
| **Hard refusal** | Known anti-cheat/anti-tamper components are detected before injection and every 30 s during a session. Detected ⇒ FrameLedger refuses, or stops capturing at the next scan — so up to 30 s can pass before it reacts to anti-cheat that loads mid-session. For Direct3D/OpenGL that means hooks are removed; for Vulkan it means the layer goes passthrough, because a layer cannot leave the loader chain of a running game. **There is no override — not in settings, not in a config file, not on the command line**<br><br>⚠ **Half of this is built.** The *pre-injection* refusal is real and runs every documented check. The **in-session re-scan does not run at all**: the component inside the game removes its hooks within one frame of being told to, and within 65 s if it stops hearing from the scanner — but nothing yet drives the scanner during a session, so nothing ever tells it. `legal/DISCLAIMER.md` §2 states this in full. For a Vulkan title the stop is the layer's own: it checks the scanner's counter on every present and goes passthrough within one present of the stop flag, or after 65 s without a scan — a title that has stopped presenting is not stopped by that deadline, and presents nothing to be observed either. |
| **No evasion, ever** | FrameLedger does not hide, rename, obfuscate, or disguise itself. It keeps its real name, real exports, and version info. It is meant to be plainly visible to any security software that looks. This is an architectural rule, not a setting |
| **Read-only** | It never reads or writes game memory, never modifies game behavior, never touches saves or input, and never changes GPU clocks, fans, or power limits |
| **Always a way out** | FrameLedger refuses rather than pushes through. When the guard finds anti-cheat, or the hook fails, or you have not enabled a game, it **stops** — and records the session anyway: start, end, duration, whatever hardware sensors your machine provides, and the reason there is nothing else. Every measured value reads `N/A`; it never estimates one.<br><br>**The way out is that it does not inject, not that it measures another way.** An earlier version of this row promised a no-injection measurement mode. It was designed around Intel PresentMon, that was dropped on 2026-08-27 after measurement, and no replacement was chosen — so **frame times require hooking**. Said in this row rather than a footnote because the row is in the SAFETY table, and a reader deciding whether to enable a game needs the real alternative, not a comfortable one |
+22 -10
View File
@@ -29,18 +29,18 @@ param(
# Excludes tests traited Category=Integration -- today, the drain end-to-end
# cases, which inject the Overlay into hook-harness.
#
# CI PASSES THIS AND A DEVELOPER MUST NOT. The reason is a MEASURED property of
# the hard gate, not flakiness: §S16 puts the injecting process's ancestors in
# the scan set, so the test host is scanned, and a .NET host can load
# System.Security.Cryptography.ProtectedData.dll -- which contains the
# heuristic fragment `protect`. The guard then refuses our own harness with
# SuspiciousUnsigned. That is the gate working exactly as specified;
# 20_OPEN_QUESTIONS §S19(b) is the defect, and it is a guard change with its
# own PR rather than something to paper over here.
# NOBODY PASSES THIS ANY MORE, and it is kept so that the day someone must, the
# skip is loud. CI passed it from 2026-08-05 to 2026-09-06 for a MEASURED reason:
# §S16 puts the injecting process's ancestors in the scan set, a .NET test host
# loads System.Security.Cryptography.ProtectedData.dll (heuristic fragment
# `protect`), and the guard refused our own harness with SuspiciousUnsigned.
# 20_OPEN_QUESTIONS §S19(b)'s signer half now verifies that module's embedded
# signature offline (O=Microsoft Corporation, on the compiled-in bound), so the
# refusal is gone for the reason the heuristic always stated, and CI runs
# `./build.ps1 check` with no switches — the same command a developer runs.
#
# It skips LOUDLY, because a suite that quietly stops running one class is how
# a gate rots. Whatever CI does, `./build.ps1 check` with no switches runs
# everything.
# a gate rots.
[switch]$SkipIntegration
)
@@ -405,6 +405,18 @@ function Invoke-ProjectGates {
# It found a defect in its own filter on its first run: a whitespace-only path
# is truthy in PowerShell, so the empty-list refusal was unreachable for that
# input.
# §S23-6: the accuracy blocks are one text in legal/ACCURACY.md; a copy that
# drifted is red. Self-test first, both directions, so the gate is seen to work.
Write-Step 'accuracy-check'
$accuracyTool = Join-Path $repo 'tools/accuracy-check.ps1'
if (Test-Path $accuracyTool) {
Invoke-Checked 'accuracy-check (self-test)' { & $accuracyTool -SelfTest }
Invoke-Checked 'accuracy-check' { & $accuracyTool }
}
else {
Skip-Gate 'accuracy-check' 'tools/accuracy-check.ps1 not implemented yet'
}
Write-Step 'changelog-check'
$changelogTool = Join-Path $repo 'tools/changelog-check.ps1'
if (Test-Path $changelogTool) {
+5
View File
@@ -66,6 +66,11 @@ watcher sees tracked exe launch
**Launch mode (preferred when FrameLedger starts the game):** `CreateProcess(CREATE_SUSPENDED)` → guard → inject → `ResumeThread`. This catches swapchain creation and early upscaler init, which attach mode can miss. Attach mode remains for games launched from Steam/GOG directly.
> **Built 2026-09-06 as start → the guard waits for a presentation runtime → the full guard → inject**
> (`FlGuardedInjectWhenReady`, P1 item 2), because a suspended target has loaded nothing for the module
> scan to read (`20_OPEN_QUESTIONS` §S1). What it costs is measured by the session itself:
> `FlWriterState.dxgiPresentsBeforeHook`. `04_CAPTURE` §Launch mode carries the shape.
Guard re-runs every 30 s for the life of the session; anti-cheat appearing late ⇒ clean unhook (`19_SAFETY` §During a session).
## Lifecycle
+16
View File
@@ -423,6 +423,22 @@ rung identified the mode — only the *identification* comes from the ladder.
**Display rule (product requirement, CLAUDE.md rule 6):** wherever FPS appears and FG is active, render `"{native} → {displayed} FPS (×{factor} FG)"`. Cards show Native large, Displayed + factor secondary. Charts default to Native with a Displayed toggle. Exports contain all three.
**Rung 3's line carries its exclusions (2026-09-06, `HANDOFF` 7b / §H11).** `Active (technology not
identified)` is printed *by elimination among what this session saw*: not DLSS-G when the NVIDIA
driver's FG word reports no feature created and no HUD-less / UI tag was sent (or "not excluded"
when the driver did not answer); no FSR frame-generation dispatch reached a hooked module; the
frame-generation runtime modules the census names, or that none is loaded; and the vendor SDK
strings the executable FILE carries. Never a vendor named as measured — XeFG cannot be hooked or
declared (licence), a compiled-in FSR 3 has no module — and the line says a frame generator compiled
into the executable would read the same.
**And the census's "cannot include generated frames" is now second-witnessed by the executable
file (2026-09-06).** A frame generator compiled into the exe loads no module (Rune Factory, Wukong),
so the capture host scans the executable on disk for the SDK strings (`ffxFsr3`,
`ffxFrameInterpolation`, `xefgSwapChain`, and the non-FG ones for the reader) and the clear-census
qualifier reads *MAY include generated frames* when a frame-generation-capable marker is in the
file. A marker is code or a symbol name in the file, never proof it ran, and never an identity.
**And when FG is not measured (2026-09-03):** render the one number as **Presented FPS** —
`144 FPS` with a qualifier chip chosen by the census above, never the word "Native", never
a factor, never `—` (which means `none`, a measured negative). The chip is muted when no
+39 -1
View File
@@ -77,6 +77,35 @@ which makes the notification more important than it was, not less.
**Launch mode (preferred).** User starts the game from FrameLedger (or FrameLedger is set as the launch wrapper): `CreateProcess(CREATE_SUSPENDED)` → guard → inject → `ResumeThread`. Catches swapchain creation and upscaler init, which attach mode can miss entirely — a game that creates its DLSS feature during startup will otherwise report `upscaler = unknown` for the whole session.
> **Built 2026-09-06 (P1 item 2) as "inject late", which is the only shape §S1 left possible, and the
> sentence above is kept as the intent it does not quite describe.** A `CREATE_SUSPENDED` target has
> loaded nothing and the module scan *fails* against it (`ERROR_PARTIAL_COPY`, §S1 measured), so the guard
> cannot run before the loader has. The built order is **start → the guard WAITS → inject**: the host
> starts the consented executable (`ProcessLauncher`: working directory beside the exe,
> `FRAMELEDGER_ENABLE_VK_LAYER=1` in its environment for the Vulkan layer, the handle held from birth so
> the pid cannot recycle), then asks the guard through its new waiting entry, `FlGuardedInjectWhenReady`,
> which polls the loader every 50 ms — through the module seam, matching **no** blocklist — until
> `dxgi.dll` with `d3d11.dll` or `d3d12.dll`, or `opengl32.dll`, or `vulkan-1.dll` is mapped, and *then*
> runs every check and injects exactly as attach mode does. The poll decides **when** the full scan runs,
> never whether it passes. A target that exits first, or maps no runtime inside the budget (60 s in the
> host), answers `LaunchTargetExited` / `LaunchNoPresentationRuntime` with nothing injected; a launcher
> that spawns the real game and quits lands on the first, and re-electing the descendant is the Agent's
> (P2, §Process watcher). **The host never terminates what it launched**: any refusal after the start
> leaves the title running unhooked, which is Tier 2.
>
> **What it measures about itself, which is the input §S1 deferred on.** The report prints the wait
> (`launch: the guard injected N ms after the process was started`) and `FlWriterState.dxgiPresentsBeforeHook`
> — DXGI's own count, read at the first hooked present on the first hooked chain, of presents completed
> before the hook was in. **0 means nothing ran unhooked on that chain**; N is the early-init cost, per
> title, from the title itself. On `hook-harness` (device at startup, presenting every 8 ms) the real-seam
> fixture injects within one poll and reports the ~1 s of presents the fixture ran before asking — a
> measurement of the fixture, not a bound on a title. What launch mode can *never* see is anything before
> its own injection, and a swapchain created before the runtime-mapped poll fired is exactly that; the
> number says how much.
>
> The CaptureHost's verb is `launch --exe <path> [--args "<game's own arguments>"] [--seconds <n>]`; the
> consent record, the gate and the payload are the ones `capture` uses, reached one process later.
**Attach mode.** Game launched from Steam/GOG/Epic normally; watcher sees it, guard runs, inject. Feature hooks install late, so early-init facts may be missed; the Overlay compensates by re-reading state on the first `EvaluateFeature` call it does observe, and the session is flagged `late_attach = true` so the UI can note that startup-time settings may be incomplete.
Steam users can also set FrameLedger as a launch option wrapper; documented in the UI rather than automated (never modify a user's Steam config for them).
@@ -176,7 +205,16 @@ Idle → Detected(pid) → Guarded → Injecting → Capturing → Finalizing
**Vulkan sessions do not pass through `Injecting`.** The layer is loaded by the
Vulkan loader when the Agent launches an opted-in game, so the path is
`Detected(pid) → Guarded → Capturing`, skipping injection entirely. This is
`Detected(pid) → Guarded → Capturing`, skipping injection entirely.
> **Built 2026-09-06 (P1 item 3), through launch mode.** The guard's waiting entry classifies the
> launched target by what it mapped: `vulkan-1.dll` with no D3D or OpenGL runtime runs the **full** guard
> and, on a pass, injects nothing — `TargetIsVulkanLayered`, which the loop reads as "attach to the
> layer's ring" with launch mode's budget (the ring appears at the title's first `vkCreateDevice`). The
> CaptureHost's `launch` gives the process the layer's environment (`VkLayerLaunchEnvironment`:
> `VK_ADD_IMPLICIT_LAYER_PATH`, the enable variable, the enable-list line for the session); a D3D title
> ignores all of it. One ring per process, the first creator owns it (`fl_shm_host.h`). Attach mode on a
> running Vulkan title stays Tier 2: only a launch can set the loader's environment. This is
stated because the state machine above, read literally, meant the 30 s guard
re-scan — which `19_SAFETY` calls the most important runtime behaviour in the
capture layer — was not specified to run for Vulkan at all. It runs for **every
+6 -4
View File
@@ -24,7 +24,7 @@ Targets:
- `FrameLedger.VkLayer` → `FrameLedger.VkLayer.dll` + `VkLayer_FRAMELEDGER_overlay.json`
- `FrameLedger.Injector` → **static lib only.** There is no `FrameLedger.Injector.exe` and none ships (`20_OPEN_QUESTIONS` §S9, decided 2026-08-02). A standalone `LoadLibraryW` injector that users can run is a path into a game process that the guard does not stand in front of — a bypass, and a bad look for a project whose position is "we refuse where we are not welcome". The Agent links the static lib; the guard owns the chokepoint inside it (§S13(b)), so there is no callable entry point that skips the gate. Manual testing uses `hook-harness`, never a real game (§Debugging).
- `FrameLedger.Overlay.Tests` → Catch2 unit tests (ring buffer, record layout, fault filter, seqlock) **and the guard's fail-closed matrix** (`14_TESTING` §Safety-guard tests) — the guard is native, so its tests are too
- `hook-harness` → the dummy **D3D11 + D3D12** app, WARP + composition swapchain so it runs headless on CI (`17_HOOK_ENGINE` §Test harness). D3D12 is device → command queue → swapchain, which is the acquisition asymmetry a D3D11-only fixture cannot exercise. Vulkan and OpenGL modes to follow as those hooks land.
- `hook-harness` → the dummy **D3D11 + D3D12** app, WARP + composition swapchain so it runs headless on CI (`17_HOOK_ENGINE` §Test harness). D3D12 is device → command queue → swapchain, which is the acquisition asymmetry a D3D11-only fixture cannot exercise. ~~Vulkan and OpenGL modes to follow as those hooks land.~~ **`--vulkan --hold-presenting N` since 2026-09-06 (P1 item 3):** a real swapchain on a hidden window through the real loader, reached by `LoadLibraryW("vulkan-1.dll")` so only the vendored headers are needed and CI (no loader) still builds it; exit 77 = cannot run here, which the ctest reads as SKIP. OpenGL to follow.
- `fl-probe-hookprofile` → build-profile probes for `/guard:cf` and `-D_HAS_EXCEPTIONS=0` (`20_OPEN_QUESTIONS` §H1/§H3)
- `fl-probe-guard` → measures the Windows APIs the guard is built on, unelevated (`spike-notes.md` §1). Not the guard, and takes no injection rights.
- `fl_stub_sl_interposer` → `sl.interposer.dll`, and `fl_stub_sl_common` → `sl.common.dll` (`src/native/tools/vendor-stubs/`). **Fixtures, never shipped**, built under `FL_BUILD_TOOLS`; nothing `12_BUILD` publishes references them. They export the **measured** vendor names from `docs/vendor-exports.json` so the Overlay's symbol resolution is observable, and the second is a **decoy** exporting the same name from a different module — without it, "we resolve module-scoped" is a property no test can falsify. Their **output filenames are the vendor's and their version blocks are ours**: `fl_add_version_resource` takes the real filename so a file called `sl.interposer.dll` in our build tree still says plainly that it is FrameLedger's, which `19_SAFETY` requires of everything we build.
@@ -183,6 +183,7 @@ document the app displays for acceptance (FR-11) is a defect, not a template.
11. **`tools/hookinventory-check.ps1`** — three passes: A resolves every vendor symbol the Overlay names against `docs/vendor-exports.json`, B sweeps for stray literals, C reads the BUILT Overlay's import table and asserts it imports no vendor module. C skips loudly under `-SkipNative`. **Missing from this list until 2026-08-28**, which is §R10 happening again
12. **`tools/package-closure-check.ps1`** — both halves: the self-test (5 cases, 4 of which must go RED) **and** a live pass over this repository. It walks the transitive `ProjectReference` closure of the two publish roots below and fails on anything outside the allowlist, naming the reference edge. `FrameLedger.CaptureHost` is an injecting entry point kept out of the package by construction, and `20_OPEN_QUESTIONS` §S27 is closed on exactly that basis
13. `tools/license-check.ps1` — asserts every vendored third-party has a licence copy in `legal/licenses/`, and that no Intel IGCL / AMD ADLX material has appeared in the tree
13b. `tools/accuracy-check.ps1 -SelfTest`, then live — the accuracy block is ONE text (`legal/ACCURACY.md`) embedded verbatim in `README.md` and `legal/DISCLAIMER.md` §4; a copy that drifted, a copy with no markers, or an empty source is red. Four self-test cases, both directions (§S23-6, 2026-09-06)
14. `tools/changelog-check.ps1 -SelfTest` — nine cases, five expected RED. The live half needs a pull request's changed-file list and is supplied by `ci.yml`
15. `tools/resx-audit` — **skipped loudly; it does not exist, and no `.resx` file does either**
16. **struct-mirror** — reads this run's `.trx` and fails when `ShmLayoutMirrorTests` did not execute, so deleting the mirror test is red as well as breaking it
@@ -196,9 +197,10 @@ document the app displays for acceptance (FR-11) is a defect, not a template.
> list of what `check` does was missing 40% of it, which is worse than having no list: a reader
> plans against it. `13_CI_CD.md` repeats the struct-mirror claim and is corrected with it.
CI runs the identical script (`13_CI_CD`), **with `-SkipIntegration`** — so a green CI is not
evidence for anything touching the managed drain, and `./build.ps1 check` with no switches is what a
developer runs before pushing.
CI runs the identical script (`13_CI_CD`) with no switches since 2026-09-06 — `-SkipIntegration` was
CI's from 2026-08-05 until §S19(b)'s signer half removed the refusal behind it — so a green CI is now
evidence for the managed drain too, and `./build.ps1 check` with no switches is what a developer runs
before pushing.
**Gates skip loudly.** A gate whose tool is not installed (no `cl.exe`) or not
yet written prints `SKIPPED`, is listed again in the summary, and the run ends
+3 -2
View File
@@ -8,8 +8,9 @@ FrameLedger uses the **`poli0981/.github` ops repo** where its templates fit, an
### `ci.yml` — push to `main` + all PRs · **repo-local**
- `runs-on: windows-latest`, .NET SDK pinned by `global.json` via `actions/setup-dotnet`, MSVC via `ilammy/msvc-dev-cmd`, NuGet cached.
- Single step of substance: **`./build.ps1 check -SkipIntegration`** — the same script a developer runs before pushing. The gate list lives in `12_BUILD` §Local quality gate, **once**, rather than being restated here where it goes stale.
- **`-SkipIntegration` is the one place local and CI deliberately differ**, and the reason is a measured property of the hard gate rather than flakiness: §S16 puts the injecting process's ancestors in the scan set, a .NET test host can load `System.Security.Cryptography.ProtectedData.dll`, and the guard's `protect` fragment then refuses our own harness (§S19(b)). So a green CI is **not** evidence for anything touching the managed drain or the capture host's end-to-end behaviour.
- Single step of substance: **`./build.ps1 check`** — the same script, with the same switches (none), a developer runs before pushing. The gate list lives in `12_BUILD` §Local quality gate, **once**, rather than being restated here where it goes stale.
- ~~**`-SkipIntegration` is the one place local and CI deliberately differ**~~ — **gone since 2026-09-06.** From 2026-08-05 CI passed it for a measured reason: §S16 puts the injecting process's ancestors in the scan set, a .NET test host loads `System.Security.Cryptography.ProtectedData.dll`, and the guard's `protect` fragment refused our own harness (§S19(b)). The signer half now verifies that module's embedded signature offline and reads `O=Microsoft Corporation` on the compiled-in bound, so the nine `Category=Integration` cases run here, and a green CI IS evidence for the managed drain and the capture host's end-to-end behaviour. The switch remains in `build.ps1`, loud, for a developer who must.
- **Signer probe step** (2026-09-06): `fl-probe-signer` runs as its own step after the gate — `continue-on-error`, a measurement and not a gate — because `ctest fl_signer_probe` passes on a regular expression and prints nothing, so §S19(b)'s CI leg was never readable from the log. Its answers are read off this step.
- Uploads coverage artifacts.
- **Changelog gate**, on pull requests only: the changed-file list comes from GitHub's own view of the PR — not `git diff`, so a shallow checkout cannot silently produce a short one — and an empty list is refused rather than read as "no `src/` changes". It is a **step of the required `check` job** and deliberately not a job of its own: `main`'s required contexts are exactly `check` and the two `analyze` jobs, so a new job would go red while the merge button stayed green, which is what already makes `Rules / validate` advisory (§S23-2).
+17 -1
View File
@@ -22,6 +22,11 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
>
> **Re-read 2026-09-04:** item 7 ✅ (the FG factor is measured, §S31 row P1), item 8's L2 half is written and measured (§M5 row R1), and exit criterion 1 reads **4 of 5** on Cyberpunk 2077 — the quality preset is the one value left, and `HANDOFF` item 7 carries the three things the next session does.
>
> **P0 CLOSED 2026-09-06 (owner).** Criterion 1 met with the quality preset amended to an
> honest `N/A` (`spike-notes` §Exit criteria carries why); criterion 2 met — §S24 counts zero
> S-items against it, with 🚫 S23-2 outside any PR. The measurement path this phase exists to
> prove runs end to end in an unshipped capture host, on nine titles. **P1 starts.**
>
> The 08-06 block below is kept and is now wrong in one specific clause — it says the writer
> *"records `measuredMask = FL_MEASURED_OUTPUT_RES | FL_MEASURED_PRESENT_ARGS` and nothing
> else"*. It records upscaler identity, upscaler params, frame-generation counts and ray
@@ -264,7 +269,7 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
*(The former items 7 "Vulkan layer" and 8 "Guard prototype" are now items 1 and 0. §R1/§R2 are folded in, not pending.)*
**Exit criteria:** a throwaway build records a real session from a real offline game reporting *correct* upscaler, quality preset, render→output resolution, FG factor and RT state — verified against the game's own settings menu.
**Exit criteria:** a throwaway build records a real session from a real offline game reporting *correct* upscaler, quality preset, render→output resolution, FG factor and RT state — verified against the game's own settings menu. *(Met 2026-09-06; the preset is an honest `N/A` by measurement — `spike-notes` §Exit criteria.)*
> **The FPS-impact criterion moves to the end of P1** (`20_OPEN_QUESTIONS` §R4,
> decided 2026-08-02). "Records a real session" with an Agent CPU/RSS budget
@@ -279,6 +284,17 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
## P1 — Native core (1.5 weeks)
`FrameLedger.Overlay` proper: hook installation for D3D11/12/9/OGL, feature hooks, ring writer, fault policy, unhook path, native logging. `FrameLedger.Injector` with launch + attach modes. Struct mirror + Catch2 tests. Vulkan layer to parity — `vkQueuePresentKHR` plus the in-layer supervision check §S2 gates on it.
> **P1 item 1 landed 2026-09-06: the `LoadLibrary` detour** (`kernelbase!LoadLibraryExW`; wake for lazily
> loaded runtimes + §S6's in-process anti-cheat stop, `FL_STATUS_STOPPED_BLOCKLISTED`), measured in
> ctest `fl_guard` `[loader]` / `[S6]`. Order for the rest, as proposed and accepted: **2** the Injector's
> launch mode (§S13(c), §S1's deferred input) — **landed 2026-09-06 as "inject late"**
> (`FlGuardedInjectWhenReady`, the CaptureHost `launch` verb, `dxgiPresentsBeforeHook` as the cost meter;
> `04_CAPTURE` §Launch mode); **3** the Vulkan layer to `vkQueuePresentKHR` with §S2's
> in-layer supervision and a harness Vulkan mode — **landed 2026-09-06** (`layer.cpp` capture side,
> `fl_shm_host.h` shared with the Overlay, `hook-harness --vulkan`, ctest `fl_vklayer*`, launch mode's
> `TargetIsVulkanLayered` branch; §S2 ✅, §S29(d)'s assertion now a ctest that skips on CI); **4** the
> unhook path, native logging, D3D9 / OpenGL.
> **The guard already shipped, in P0.** This line used to read "the guard,
> complete and fully tested — it ships before the first real injection, not
> after", which was the correct ordering stated in the wrong phase: P0 items 1
+39 -2
View File
@@ -32,6 +32,31 @@ The injected DLL. Its whole job: install hooks, write 64-byte records into a rin
1. Open/create shared memory `Local\FrameLedger.Ring.<pid>`; write the handshake header (layout version, build id, pid, api=unknown).
2. `MH_Initialize()`.
3. Resolve which graphics APIs are present (`GetModuleHandleW` on `d3d11.dll`, `d3d12.dll`, `dxgi.dll`, `opengl32.dll`) — and register a `LoadLibrary` hook so APIs loaded **later** still get hooked (many games load D3D12 lazily). **The `LoadLibrary` hook must not install hooks inline:** it runs under the loader lock, and MinHook suspends all threads to patch, which deadlocks against any thread waiting on that lock. It enqueues the request and signals the init thread, which installs outside the lock (`20_OPEN_QUESTIONS` §H2).
> **Built 2026-09-06 (P1 item 1), with two differences from the sentence above.** The detour is on
> `kernelbase.dll!LoadLibraryExW` — the one body every `LoadLibrary*` variant of `kernel32` reaches —
> and it is installed **after** the present hooks, from `InitThread`, outside any loader lock. It
> **enqueues nothing**: the module's real file name (`GetModuleFileNameW` on the handle the original
> returned, into a stack buffer — never the caller's string, which may be relative or an API set) is
> compared against two fixed tables and the detour then does one of two things, both a single store
> plus `SetEvent` on the watchdog's auto-reset wake event. **(a)** A name that is in `FL_HOOK_INVENTORY`
> or `FL_RUNTIME_CENSUS` bumps a saturating 15-bit wake count and wakes the watchdog, whose next
> iteration runs the same lazy installers it always ran — so the install happens on the watchdog
> thread, as before, but **within milliseconds of the module rather than on the next 1 Hz tick**
> (measured in ctest `fl_guard` `[loader]`: 94 ms from the module appearing to the hook family being
> published, against a 500 ms bound that discriminates the wake from the tick). **(b)** A name that
> matches a MODULE family of the compiled anti-cheat floor (`fl_ac_floor.generated.h`, the same table
> the guard carries — prefix, case-insensitive, allocation-free) records the family's 1-based index in
> `earlyStopFamily` and wakes the watchdog; the **present path** stops the Overlay on its next
> `MayObserve` and the **watchdog** stops it on its next iteration, whichever comes first, with the new
> status `FL_STATUS_STOPPED_BLOCKLISTED` (= 4) — `19_SAFETY` §During a session, the in-process half;
> `20_OPEN_QUESTIONS` §S6. The words are `FlWriterState.loaderSignals` @56 (bit 15 = installed, bits
> 0..14 = wake count) and `earlyStopFamily` @58, both carved from `reserved[]` so the layout version did
> not move. The original is always called first and its result returned untouched, and
> `LOAD_LIBRARY_AS_DATAFILE` / `_EXCLUSIVE` / `AS_IMAGE_RESOURCE` loads are skipped — no code runs from
> them and the loader does not list them. Body under `FL_HOOK_GUARD`, no allocation, no lock, no
> logging (rule 5). Exercised by `hook-harness --load-after-ms N PATH` (up to four), against the real
> Overlay in a real target, both jobs.
4. Install present hooks for what exists (below).
5. Install feature hooks (upscaler / RT / PSO) lazily — the first time their module appears.
6. Publish `status = ready` in the handshake block.
@@ -126,6 +151,12 @@ Every hook must be listed here with a purpose. Anything not on this list is not
> so a shipped hook missing from here is invisible to every gate. Flip the row **and this
> banner** in the same PR that builds a hook.
### The one system-module detour — a hook, and the asymmetry stated
| Hook | Purpose |
|---|---|
| ✅ `kernelbase.dll!LoadLibraryExW` (2026-09-06, P1 item 1) | The wake for lazily loaded runtimes and the in-process anti-cheat stop — §DLL entry step 3 above carries the mechanism. **Rule 4:** it reads one argument the API was given (`flags`) and one property of a handle the loader just returned to *its own caller* (the module file name); nothing of the game's. **It is the only hook on a system module, and it is deliberately not in `FL_HOOK_INVENTORY`:** that table is *vendor* symbols resolved by name and gated by `hookinventory-check` against `vendor-exports.json`, and `LoadLibraryExW` is neither vendor nor uncertain. It is listed here instead so the table above and this row together are the whole inventory. It **never** installs, uninstalls or patches anything itself (§H2) |
### Watchdog observations — not hooks, and listed here so nobody mistakes them for one
| Observation | Mechanism | Rule 4 | Why |
@@ -135,13 +166,13 @@ Every hook must be listed here with a purpose. Anything not on this list is not
### Presentation
| Hook | Purpose |
|---|---|
| ✅ `IDXGISwapChain::Present`, `Present1` | Frame boundary, QPC, sync interval, present flags. **`DXGI_PRESENT_TEST` calls are dropped without a record** — the occlusion probe submits nothing, and a minimised game emits a stream of them (`07_IPC` §Protocol rules). **Since 2026-09-05 the hook also reads `IDXGISwapChain::GetLastPresentCount` on the chain it just saw** (rule 4: the same COM object `FindOrAdd` already calls `GetDesc` on, no new hook) and publishes `dxgiPresentSamples` / `dxgiPresentsUnseen` — DXGI's count of presents on that chain that this hook never saw, the in-process half of `20_OPEN_QUESTIONS` §H5 Leg 1. One virtual call per hooked present, costed by `hook-harness --probe-frames`. **And per record since the same night: `dxgiUnseen` @52 under `FL_MEASURED_DXGI_PRESENTS`**, so the consumer's window counts `Displayed = hooked + unseen` per bucket (`03_METRICS` §Displayed may be DXGI-COUNTED) — measured 2.90 / 2.95 on DL:TB at Streamline 2.8.0, 0 on 2.7.3 and 2.10.3 |
| ✅ `IDXGISwapChain::Present`, `Present1` | Frame boundary, QPC, sync interval, present flags. **`DXGI_PRESENT_TEST` calls are dropped without a record** — the occlusion probe submits nothing, and a minimised game emits a stream of them (`07_IPC` §Protocol rules). **Since 2026-09-05 the hook also reads `IDXGISwapChain::GetLastPresentCount` on the chain it just saw** (rule 4: the same COM object `FindOrAdd` already calls `GetDesc` on, no new hook) and publishes `dxgiPresentSamples` / `dxgiPresentsUnseen` — DXGI's count of presents on that chain that this hook never saw, the in-process half of `20_OPEN_QUESTIONS` §H5 Leg 1. One virtual call per hooked present, costed by `hook-harness --probe-frames`. **And per record since the same night: `dxgiUnseen` @52 under `FL_MEASURED_DXGI_PRESENTS`**, so the consumer's window counts `Displayed = hooked + unseen` per bucket (`03_METRICS` §Displayed may be DXGI-COUNTED) — measured 2.90 / 2.95 on DL:TB at Streamline 2.8.0, 0 on 2.7.3 and 2.10.3. **And since 2026-09-06 (P1 item 2) the same read, at the FIRST hooked present on the first hooked chain, is published once as `FlWriterState.dxgiPresentsBeforeHook` @60** — DXGI's count of presents that ran before the hook was in, launch mode's cost meter (`20_OPEN_QUESTIONS` §S1); 0xFFFFFFFF until a present is seen, set before the present hooks go in |
| ✅ `IDXGISwapChain::ResizeBuffers` · ⏳ `ResizeTarget` | Output resolution changes mid-session. `ResizeBuffers` re-reads the swapchain description *after* the original returns; `ResizeTarget` is not hooked |
| ⏳ `IDXGISwapChain::SetFullscreenState` | Fullscreen ↔ borderless transitions |
| ⏳ `IDXGISwapChain3::SetColorSpace1` | HDR output detection. **`IDXGISwapChain3`, not 4** — 4 adds only `SetHDRMetaData` (`20_OPEN_QUESTIONS` §H9). Unbuilt, which is why `colorSpace` reads `NOT_REPORTED` and `FL_MEASURED_HDR` stays clear. **When it is built, the writer must initialise `colorSpace = FL_COLOR_SPACE_SDR` at swapchain identification** — an SDR title never calls `SetColorSpace1`, so "hook live, no call" would otherwise sit at `NOT_REPORTED` forever and HDR's definite `No` would be unreachable. DXGI documents G22/Rec.709 as the default, which makes SDR a *measured* default rather than an affirmative negative |
| ⏳ `IDXGIFactory::CreateSwapChain*` | Capture swapchain desc (format, buffer count, swap effect, flags) at creation. Unbuilt — the swapchain description is currently read on demand in the present hook via `GetDesc` |
| ⏳ `wglSwapBuffers` | OpenGL titles. Unbuilt, and deliberately not attempted before `hook-harness` has an OpenGL mode: the hook is small (a flat export, no vtable) but shipping an unexercised hook into a game process is not something this project does. Measured 2026-08-05: `opengl32!wglSwapBuffers` is a `jmp` thunk (`E9 <rel32>`) into the vendor ICD, which is already mapped before the first call |
| ⏳ Vulkan `vkQueuePresentKHR` | via layer, not hook (below). Unbuilt — P1, and §S2's in-layer supervision check lands with it. The layer today loads, gates and self-scans, and intercepts nothing |
| ✅ Vulkan `vkQueuePresentKHR` (2026-09-06, P1 item 3) | via layer, not hook (below). Frame boundary and QPC, one record per present; `vkCreateSwapchainKHR` / `vkDestroySwapchainKHR` intercepted beside it for the output size (`imageExtent`, the API's own argument — rule 4). **No `FL_MEASURED_PRESENT_ARGS`**: `vkQueuePresentKHR` carries no sync interval and no flags, which is why that bit exists. §S2's in-layer supervision check landed with it, on the present path. Measured under the real loader on the harness's `--vulkan` mode: 241 records in 4 s, status READY, `apiMask` = Vulkan (ctest `fl_vklayer_real`) |
### Upscaling / frame generation (the accuracy problem this rewrite exists to solve)
| Hook | Yields |
@@ -352,6 +383,12 @@ is not something this loader supports.
> admin. Registering under HKCU (below) is the less common choice and the better
> one: no elevation, and per-user scope.
- Intercepts `vkQueuePresentKHR`, `vkCreateSwapchainKHR`, `vkCmdTraceRaysKHR`, `vkCmdBuildAccelerationStructuresKHR`, `vkCreateGraphicsPipelines`.
> **Built 2026-09-06 (P1 item 3): the first two, plus `vkDestroySwapchainKHR`; the three feature entries are still ⏳.** How the capture side works, stated once:
> - **The ring is the same ring.** `fl_shm_host.h` (header-only, in `FrameLedger.Shm`) now holds the user-only DACL, the `Local\FrameLedger.Ring.<pid>` name, the mapping and the handshake for **both** capture sides; the Overlay calls it too. **One ring per process: whichever side creates the mapping first owns it, the other sees `ERROR_ALREADY_EXISTS` and stays inert** — and stays *forwarding*: the layer registers every device's next pointers before it tries the ring, because a hook with nothing to forward to failed the application's present (measured, `VK_ERROR_DEVICE_LOST` on the harness, the first time the Overlay got there first). That is also why the launch-mode guard **does not inject a presenter that mapped `vulkan-1.dll`** (`Reason::kTargetIsVulkanLayered`, `fl_guard.cpp`) — with or without a D3D runtime beside it, because **an NVIDIA Vulkan ICD maps `dxgi.dll` + `d3d12.dll` itself and presents the Vulkan swapchain through a DXGI flip chain** (measured on the harness's `--vulkan` mode: classified as D3D, the injected Overlay recorded 295 DXGI presents of a Vulkan swapchain and the layer forwarded into nothing). The layer is the capture side for anything that maps the Vulkan loader; a D3D title that happens to is the rarer shape and the one this rule gets wrong.
> - **It comes up at the first admitted `vkCreateDevice`**, never at load and never at `vkCreateInstance`, so a process either gate refused never has a mapping with its pid on it. Init is not a hook path; the present hook is, and it follows the Overlay's rules — SEH-guarded, allocation-free, lock-free, three faults → `SELF_DISABLED`.
> - **§S2 part three, the in-layer supervision, runs on the present path**, because the layer may not own a thread (the loader owns its mapping). `guardTicks` not advancing for `FL_GUARD_TICK_DEADLINE_MS` → `FL_STATUS_UNHOOKED`; `unhookRequested` → the same within one present; `pauseRequested` → no record, still forwarded. "Stops" means **passthrough forever with the reason on the mapping** — a layer cannot leave a running game's loader chain. A title that stops presenting is not stopped by the deadline, and has nothing to be observed either. Proven with a test-only flavour of the DLL whose deadline is 1.5 s (`fl_vklayer_shortdeadline`, never shipped; ctest `fl_vklayer_supervision`).
> - **No registry for the operator host.** Loader 1.4.357 honours `VK_ADD_IMPLICIT_LAYER_PATH` (measured 2026-09-06, `spike-notes` §2): the CaptureHost's `launch` writes a manifest under `%LOCALAPPDATA%\FrameLedger\vklayer`, points the launched process at it, sets the enable variable and adds the image name to the enable-list for the session — discoverable by that process alone, gone when it ends. The Agent's HKCU registration (`12_BUILD`) is unchanged and remains P2's.
- The layer respects the same guard, in two steps at init: it checks the enable-list, and it scans **its own process** against the anti-cheat blocklist. Either one saying no means fully passthrough. **A layer is machine-wide by nature — these checks are mandatory, not optional.**
- The self-scan uses the **same matcher and the same rules file as the injection guard** (`fl_ac_rules.h`, compiled into both targets). Not a copy: a layer with its own blocklist would be a second matcher that can disagree with the first. Every uncertainty — rules unreadable, malformed, enumeration failed, a truncated list — resolves to passthrough, which is the opposite polarity from the injection guard and the same principle: leave the host alone.
- Registered only while at least one Vulkan game has hooking enabled; unregistered on uninstall (Velopack hook) and when the last such game is disabled. **Never at install time** — `12_BUILD` §The Vulkan layer is not registered at install time.
+38
View File
@@ -50,6 +50,13 @@ Implemented in `FrameLedger.Injector` and reached from managed code through a th
> against a suspended target (§S1). Neither is "no modules found". The read
> handle rights above are confirmed sufficient for every target this call can
> legitimately reach.
>
> **Launch mode (2026-09-06, P1 item 2) does not weaken this.** `FlGuardedInjectWhenReady` polls
> the same enumeration to learn *when* the launched target has mapped a presentation runtime, and a
> failing enumeration there means "not yet" — the poll continues. That is not a pass: the poll
> matches nothing against the blocklist, and the injection happens only after check 1 has run in
> full, with the enumeration succeeding, exactly as in attach mode. A launched target that never
> becomes scannable is never injected (`LaunchNoPresentationRuntime`).
> **Which processes get scanned: the game's own subtree.** `04_CAPTURE`
> §The guard writes `Check(pid)` — singular — while `04_CAPTURE` §Process
> watcher says the capture target is a *descendant* elected from a ppid
@@ -502,6 +509,23 @@ the entire driver stack read as untrusted, and combined with the `guard` and
theoretical one. A signature that is absent, invalid, or simply could not be
checked stays untrusted and refuses — that direction is deliberate.
> **Wired 2026-09-06, the EMBEDDED half only, under a compiled-in bound** (`20_OPEN_QUESTIONS`
> §S19(b), row G1: the CI leg and the owner's adapters-disabled leg both left every verdict
> unchanged). `Sources::ModuleSignerOrganisation` verifies a fragment-matching module's embedded
> Authenticode signature with `WinVerifyTrust` under `WTD_REVOKE_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL`
> — no CRL or OCSP fetch, measured rather than assumed — and only then reads the subject `O=`. The
> guard trusts it only if the organisation is on the rules file's `trustedSigners` **and** on the list
> compiled into the binary (`IsCompiledTrustedSigner`): the rules file may narrow that list and may
> never widen it, so a rules push cannot widen the hard gate — the boundary of what the gate trusts is
> code, as it is for the launcher list. A trusted module keeps the scan looking; it never stops it, so
> an untrusted module loaded after it is still judged. It applies to the injection target as well as
> to its ancestors — a game that loads a Microsoft-signed key-protection provider is the false refusal
> this half exists to remove. **Fail-closed rows:** no embedded signature (catalog-only system
> binaries such as `mskeyprotect.dll` — the `CryptCATAdmin*` half is deferred with its own rationale),
> an invalid signature, an unreadable `O=`, a null path, a null or failing seam, an organisation on
> one list but not the other — every one is untrusted and refuses. Cost: ~2–4 ms per verified module,
> reached only on a fragment hit, inside the 30 s loop.
### During a session
Re-run **every pre-injection check** every 30 s, for **every Tier-1 session —
@@ -561,6 +585,20 @@ injected or layered**.
**Be honest about the window.** A 30 s poll means anti-cheat can be loaded for up to 30 s before we react — the unhook is immediate *once detected*, not immediate in absolute terms. Consent and disclaimer wording must say "within 30 seconds", never "immediately" (`legal/DISCLAIMER.md` §2). Whether to shrink the window, or to detect the load directly via the `LoadLibrary` hook `17_HOOK_ENGINE` §DLL entry **specifies** for lazily-loaded graphics DLLs, is `20_OPEN_QUESTIONS` §S6.
> **The in-process half exists since 2026-09-06 (P1 item 1), and the sentence above stays true because
> of what it does NOT cover.** The Overlay's `LoadLibrary` detour compares every module the loader maps
> mid-session against the **compiled floor's MODULE families — the exact prefix names, and nothing
> else** — and stops the Overlay from inside on a match (`FL_STATUS_STOPPED_BLOCKLISTED`; `17_HOOK_ENGINE`
> §DLL entry step 3), within one present or one watchdog iteration. That is the same set the Agent's
> guard matches by name. **The fragment tier and the signer tier are not in the detour**, on purpose: a
> substring scan is not allocation-free in a hook body under the loader lock, and `WinVerifyTrust` from
> inside a game process is out of the question — so a module the floor knows only by a fragment, or only
> by its signer, is still caught by **this host's 30 s scan and by nothing sooner**. The disclosure
> therefore does not change: "within 30 seconds" remains the promise; the exact-name case is now usually
> much faster, and the report says which happened (`EARLY STOP` naming the family, or the host's own
> stop). Modules loaded **before** the Overlay attached are the pre-injection scan's, as always. The
> detour supplements the poll; it replaces nothing (§S6's own ruling).
> **This sentence used to say the hook "already exists and is currently unused", which was false.** Corrected 2026-08-04: the Overlay installs no hooks at all — `dllmain.cpp` exports one function and nothing in the tree calls `MH_CreateHook` outside a probe. §S6 is therefore downstream of the whole P1 hook layer, not "the cheapest available improvement to the most important behavior in the product". A reader planning work off this paragraph was being told a mechanism was sitting there ready.
### Elevated / protected targets
+311 -19
View File
@@ -73,25 +73,25 @@ or it becomes the next stale status claim this file exists to record.
| **S28** | ✅ **resolved 2026-08-05** | The guard's entry points share process-wide statics; a concurrent call cleared the blocklist mid-match and every check fell through to `Allow`. Reproduced by CI, not argued |
| **S27** | ✅ **resolved, and restated 2026-08-06** | The chokepoint is the anti-cheat gate, not the consent gate. It was closed by *not building* a capture host; item 1 built one, and the ✅ survives on the clause that was always load-bearing — **no injecting entry point on any SHIPPED binary**. `FrameLedger.CaptureHost` is unpublished, and `tools/package-closure-check.ps1` makes that a gate rather than a fact about today's csproj. `HookRequest` is get-only behind one factory, so this entry's own rejected synthesis no longer compiles |
| S12 | 🅓 **deferred, rationale written** | Cautious mode → v1.1; it disabled nothing in v1. *(Marked ✅ until 2026-08-27 — same disposition, different glyph.)* |
| **S1** | 🅓 **deferred, rationale written** | Owner decision 2026-08-05. Deciding input — a title loading a presentation runtime lazily — is not on this machine |
| **S13(c)** | 🅓 **deferred, rationale written** | Same decision as S1; (a) and (b) were already settled |
| **S1** | ◐ **launch mode built as "inject late" 2026-09-06 (P1 item 2); the cost is now measured per title** | `FlGuardedInjectWhenReady` polls until a presentation runtime is mapped, then runs the full guard; `dxgiPresentsBeforeHook` and the reported wait are the input the 2026-08-05 deferral lacked. The ruling "inject late vs. no launch mode" is answered by construction — inject late exists — and whether it is *preferred* per title is what the numbers decide |
| **S13(c)** | ✅ **salvageable, and salvaged 2026-09-06** | The externally observable proxy the entry proposed is what was built; the missing input is produced by every launched session |
| **S19(b)** | 🅓 **deferred, rationale written — and MEASURED** | CI 2026-08-05: the fragment fires on `System.Security.Cryptography.ProtectedData.dll` loaded by a .NET **test host**, i.e. inside a real scan set in the launch-mode arrangement — refusing our own injection. The entry's "plausible and unmeasured" is superseded; the deferral rationale (a `CryptCATAdmin*` PR doing network I/O inside the hard gate, NFR-10) still stands. *(Marked 🔴 until 2026-08-27. The measurement belongs in this cell, not in the marker — a glyph that means "deferred" and a glyph that means "open defect" cannot be the same one in a table audited by counting.)* |
| **S14** | ◐ **exe half wired 2026-08-05** | Owner decision 2026-08-05: wire it, empty list, unresolvable identity refuses. The **store-id half is blocked** on the platform metadata extractors and cannot be reached through the guard ABI by design |
| **S14** | 🅓 **exe half wired 2026-08-05; store-id half deferred to P4, rationale written 2026-09-06** | The store-id half's only in-policy route is P4's platform metadata extractors feeding a guard-side resolver; a resolver with no extractor would refuse every title. No title is blocked by store id today because none is listed |
| **S23-1** | ✅ **resolved 2026-08-05** | `FlGuardBuildId` gives the Agent a build id of its own, and `ShmHandshakeValidator` performs the comparison `07_IPC` and `04_CAPTURE` both specify. Every refusal path is driven, including **both ids empty** — the shape the feature shipped in, where `"" == ""` reported `Ok` for every process on the machine |
| **S23-4** | ✅ **resolved 2026-08-05** | `19_SAFETY` §During a session said "the module scan and the driver scan"; `EvaluateImpl` runs four. Reworded to "every pre-injection check" so it cannot go stale when a check is added, with the two omissions named — `services` is the only tier measured firing on real anti-cheat, and the pre-scan is the only one touching the filesystem |
| **S2 part three** | ⏳ **open, sequenced** | In-layer supervision lands with `vkQueuePresentKHR` (P1). Building it sooner would be a predicate whose wrong answer changes nothing observable |
| **S4 signing** | ⏳ **open, residual accepted** | HTTPS authenticates the host, not the content. Recorded rather than closed — needs a rationale written or a decision |
| **S6** | ❓ **open, disposition undecided** | Owner: work, or deferral-with-rationale? See the correction block under §S6 for what #40–#44 changed and what it does not |
| **S2 part three** | ✅ **built 2026-09-06 (P1 item 3)** | In-layer supervision on the present path, landed with `vkQueuePresentKHR`; `unhookRequested` and the tick deadline both stop the layer (passthrough with the reason on the mapping), proven by a fake loader chain and a 1.5 s test-only flavour of the DLL |
| **S4 signing** | 🅓 **deferred to P4, rationale written 2026-09-06** | Signing is a property of the feed and there is no feed (§S20); every rules file today shipped inside a release whose checksum attests it. The P4 decision (compiled-in key, detached signature, fail-closed) is written in the entry |
| **S6** | ✅ **built 2026-09-06 (P1 item 1)** | The detour on `kernelbase!LoadLibraryExW` stops the Overlay from inside on an exact-floor MODULE match, within one present or one watchdog iteration, and wakes the lazy installers within milliseconds for an inventoried module; measured against the real Overlay in ctest `fl_guard` `[loader]`/`[S6]`. Exact names only — fragment and signer stay the host's 30 s scan, so the disclosure does not change |
| **S19(a)** | ✅ **resolved 2026-08-05** | `gameguard` could never fire — `guard` subsumed it. Removed; `rules-validate` now fails when any fragment contains another, so the class cannot return. Zero coverage lost: nProtect has its own named module family |
| **S19(c)** | ❓ **open, disposition undecided** | `signerField` and `action` are schema-`required` and parsed by nobody. Costing `action` honestly means first deciding `warn`/`allow` may exist, and CLAUDE.md rule 2 says they may not |
| **S19(c)** | ✅ **resolved 2026-09-06** | The fields are constants the schema pins and the guard never reads, because the policy is code by CLAUDE.md rule 2 and `19_SAFETY`; `rules-validate` now proves the schema rejects `action: "allow"` and `signerField: "CN"` (canary 3), so the data cannot say otherwise |
| **S19(d) residual** | ✅ **resolved 2026-08-05** | A second canary, **derived from the shipped document** rather than hand-written, carries `nameFragments: []` and must be rejected. The entry's stated consequence was overstated and is corrected in place: the generated floor would not have disappeared, `gen-ac-floor.ps1` hard-errors and the native build fails — what was unguarded is the *schema* half |
| **S20 feed half** | ❓ **open, disposition undecided** | **FR-7.3 is unmet**: a rules edit reaches no installed machine until a release |
| **S23-3** | ⏳ **open, sequenced** | `08_UI`'s refusal notice is wrong in the commonest case; needs to reach `08_UI` and the `Safety_*` keys before any UI exists (P3) |
| **S20 feed half** | 🅓 **deferred to P4, rationale written 2026-09-06** | **FR-7.3 stays unmet and written as unmet**: the fetch needs a shipped Agent, §S4's signing and the privacy policy's rows, all P4; until then a rules edit ships with the next release, checksum-attested |
| **S23-3** | 🅓 **deferred to P3, rationale written 2026-09-06** | `08_UI`'s refusal notice is wrong in the commonest case; the requirement reaches `08_UI` and the `Safety_*` keys in the PR that creates the first refusal UI — a string with no view would read as done |
| **S23-5** | ✅ **resolved 2026-08-05** | Closed the way §S23-4 closed the same class — by **removing** the restatement, not correcting it — and `rules-validate` now fails when any `$comment` enumerates checks again. The rule's own first version was scoped to the wrong object and could not fire; it now walks every `$comment` and fails if it finds none |
| **S23-6** | ◐ **partly closed** | `license-check` now binds `THIRD_PARTY_NOTICES` bidirectionally — the first real gate over anything in `legal/`. The **accuracy blocks remain hand-maintained prose that nothing verifies**, and `DISCLAIMER.md`'s went stale a second time on 2026-08-05 |
| **S23-6** | ✅ **closed 2026-09-06** | `license-check` binds `THIRD_PARTY_NOTICES` bidirectionally, and the accuracy blocks are now ONE text — `legal/ACCURACY.md`, embedded verbatim in `README.md` and `DISCLAIMER.md` §4, gated by `tools/accuracy-check.ps1` (self-tested both directions). Truth stays a human's job; drift between copies no longer is |
| **S23-2** | 🚫 **owner only — no PR can close it** | `Rules / validate` is **not** a required status check on `main`. **Re-verified against the live branch protection 2026-08-05**, not repeated from the entry: `required_status_checks.contexts` is exactly `["check", "analyze (csharp, none)", "analyze (cpp, manual)"]` (`strict: true`, `enforce_admins: true`, `required_linear_history: true`). The `validate` job is path-filtered and `pull_request`-only, so a red removal check does not block the merge button. **The gate that exists to make the anti-cheat blocklist un-removable is advisory.** This is a branch-protection setting |
| **S29** | 🔴 **open, new 2026-08-05 — five ✅ and two ◐, counted off the glyphs below on 2026-08-20** | (a) ◐ **CORRECTED**: the honesty assertion *is* in the merge gate, natively (`fl_guard`, 20.58 s on CI); only the **managed** drain is ungated, and §S19(b) is **not** a prerequisite of the feature hooks — the original claim was wrong and had been used to re-order the work. **Sharpened 2026-08-06:** fixing §S19(b) alone would still gate nothing, because `build.ps1`'s `-SkipIntegration` applies `--filter 'Category!=Integration'` and excludes the class *before* the guard is ever asked. Two independent mechanisms produce one absence, and `ci.yml` must drop the switch too; (b) ✅ `fl_vtable_indices` now pins the Overlay's indices through a shared header; (c) ✅ **closed 2026-08-06 by deleting `ShouldUnhookAsync`** — zero production callers, strictly weaker than `ScanOnceAsync`, and inverted in polarity; the gate's public instance surface is now pinned to `{StartAsync}`; (d) ◐ `vklayer-blastradius` case 3 is now an assertion, but the script still runs only by hand; (e) ✅ **closed 2026-08-06 host-side**, with a held process handle and a classifier that takes no elapsed-time parameter, so a frozen `writeIndex` can never end a session; (f) ✅ **closed 2026-08-20**: the normative contradiction between CLAUDE.md rule 7 and `03_METRICS` about inline RayQuery is settled the way the entry proposed — AS-build activity proves ray tracing is happening, *naming the technique* is what needs a DXIL scan — and rule 7 is amended in the PR that wrote the hooks. Its second half closes with it: `FL_MEASURED_RT` now has a producer (both command-list detours, installed off the game's own device), so all three conjuncts of the `No` branch are live and **`Yes` and `No` are both reachable for the first time**, proved by injection in both directions; (g) ✅ the present-only writer claimed `FL_MEASURED_OUTPUT_RES` unconditionally, including on records with no size |
| **S29** | 🅓 **six ✅ and one 🅓 on 2026-09-06 — nothing 🔴 remains** | (a) ✅ **closed 2026-09-06**: the managed drain is in the merge gate — §S19(b)'s signer half removed the refusal and `ci.yml` dropped `-SkipIntegration` in the same PR, both mechanisms at once, as the sharpening below said they had to be. *(History: ◐ CORRECTED — the honesty assertion *was* in the merge gate natively (`fl_guard`, 20.58 s on CI); only the **managed** drain was ungated, and §S19(b) was **not** a prerequisite of the feature hooks. Sharpened 2026-08-06: fixing §S19(b) alone would still have gated nothing, because `build.ps1`'s `-SkipIntegration` applied `--filter 'Category!=Integration'` before the guard was ever asked.)* (b) ✅ `fl_vtable_indices` now pins the Overlay's indices through a shared header; (c) ✅ **closed 2026-08-06 by deleting `ShouldUnhookAsync`** — zero production callers, strictly weaker than `ScanOnceAsync`, and inverted in polarity; the gate's public instance surface is now pinned to `{StartAsync}`; (d) 🅓 **deferred 2026-09-06 on a measurement** — `ci.yml` now prints a Vulkan runtime census, and the script runs as a CI step the day a runner has a loader; until then it stays hand-run before any layer PR, with the P1 Vulkan entry as the reminder (the pre-commitment in the entry covers both rows); (e) ✅ **closed 2026-08-06 host-side**, with a held process handle and a classifier that takes no elapsed-time parameter, so a frozen `writeIndex` can never end a session; (f) ✅ **closed 2026-08-20**: the normative contradiction between CLAUDE.md rule 7 and `03_METRICS` about inline RayQuery is settled the way the entry proposed — AS-build activity proves ray tracing is happening, *naming the technique* is what needs a DXIL scan — and rule 7 is amended in the PR that wrote the hooks. Its second half closes with it: `FL_MEASURED_RT` now has a producer (both command-list detours, installed off the game's own device), so all three conjuncts of the `No` branch are live and **`Yes` and `No` are both reachable for the first time**, proved by injection in both directions; (g) ✅ the present-only writer claimed `FL_MEASURED_OUTPUT_RES` unconditionally, including on records with no size |
| **S30** | ✅ **closed 2026-08-15** | Answered on the title that raised it: with Ray Reconstruction on, Cyberpunk 2077 evaluates `kFeatureDLSS_RR` on every application frame and `kFeatureDLSS` **not once**, so RR was doing the upscaling and the decode had no arm for it. Evidence rather than inference: `renderW/H` are published only on a frame that drained an evaluation and read 1485×835 = 0.58 × 2560×1440, so the scaling-input tag arrives ON the RR evaluation. Two further defects fell out — the pre-committed decision table had two holes, and the fix contaminated the census that found it (it derived the id from the decoded byte) |
| **S31** | ✅ **resolved 2026-09-04 — row P1, and `tokens/batch = 1.00`** | Is a drained Streamline batch an application frame? **Yes.** The `slGetNewFrameToken` count (#103, #105) reads 1.00 / 2.99 / 3.99 against Cyberpunk's own off / ×3 / ×4 and 4.00 on Hell Is Us, and on every leg with batches the two counts agree to the frame. Two independent per-frame API counts are the oracle four instruments could not be. `fg_factor` is published; `none` is reachable by counting. *(The row as it stood while open:)* ◐ **row P2, 2026-08-27 — the ORACLE is retired, the QUESTION is not** | Is a drained Streamline batch an application frame? The PresentMon 2.x `FrameType` test, with its decision table pre-committed BEFORE the run and `tools/frametype-oracle.ps1` producing the input as two dimensionless ratios. **Two obstacles measured before it could be run**: the console binary will not start a trace session unelevated on the dev box (exit 6; the account is in neither Administrators nor Performance Log Users, and the running shared service does not help), and `--track_frame_type` is a **beta** option whose own help says it needs application or driver instrumentation of the Intel-PresentMon provider — so it may be as unavailable as `fl-baseline-probe` proved to be. Two of the table's six rows retire it outright. Blocks HANDOFF item 3's producer decision |
| **H11** | ◐ **AMD ffx-api BUILT and RUN 2026-09-04 (A1–A3 accepted; the loader row added the same evening after three loader titles read silent); Intel closed at the census by licence; FSR 3.0 host route deferred to its own PR** | XeFG and FSR3-FG identity. The AMD half is measured on nine titles: the three ffx-api leaves AND the SDK 2.x loader are hooked (the loader turned out to be the game's entry on loader-shipping titles, with the leaves silent behind it), the vendored MIT headers (tag v2.3.0) decode the dispatch descriptor, and rows A1–A3 landed as pre-committed and **R6 closed on Dying Light: The Beast and KCD2 the same night** (`FSR (3.1 or 4 …)` / `FsrFg` / ×2 / 1.01 and `none` / 1.00 through the loader row). Wukong's FSR upscaling is compiled in (Rune Factory's shape; the title has no FSR frame generation), so nothing more is owed on the AMD half; the FSR 3.0 host route is the one deferred piece Intel's SDK failed the licence checklist, so XeSS/XeFG stay at the census (§Scope decisions). `ffx_fsr3_x64.dll` (FSR 3.0, Cyberpunk only here) ~~needs ten host headers from tag v1.1.4 and is deferred with that costing written~~ **built 2026-09-05** from tag `fsr3-v3.0.4` (the docs' `v1.1.4` was the wrong tag: twelve exports match 3.0.4, not 1.1.4's fifteen, and 1.1.4's descriptor appends fields after `renderSize`); one row, the host's UPSCALE; **rows B1–B4 owed** (below) |
@@ -134,6 +134,16 @@ the recount becomes the next thing that needs recounting.
> the question* rather than by a decision to stop asking it, since S30. ❓ three, ⏳ three,
> ◐ two, 🔴 one, plus 🚫 S23-2. The list above moved in the same edit as this count.
>
> **ZERO on 2026-09-06 — exit criterion 2 reads as met, with one item outside any PR.** The
> owner's closing sweep ("theo bảng"): S19(c) and S23-6 resolved by a gate each, S29 down to
> one 🅓 on a pre-committed measurement, and six items deferred with their rationale written
> in the entry and their phase named in this table — S6 and S2 part three to P1, S23-3 to P3,
> S4 signing, S20 feed half and S14's store-id half to P4. ❓ zero, ⏳ zero, ◐ zero, 🔴 zero.
> **What remains is 🚫 S23-2**, a branch-protection setting only the owner can change; it is
> not resolved and not deferred, it is outside what a PR can do, and the criterion's own
> wording does not reach it. The bullet list above is history as of 2026-09-04 and is left as
> it stood; this paragraph is the current count.
>
> **STILL TEN on 2026-08-27, for the third consecutive movement.** S31 moved from ❓ to ◐,
> so ❓ goes four to three and ◐ goes two to three. **The number has now stayed at ten across
> three different changes**, and that is worth saying out loud precisely because a reader
@@ -291,7 +301,13 @@ refuter told to default to *refuted*. The ledger drift it found is fixed in the
that records this. What follows is the residue: things that need code, recorded so
the next session finds them by reading.
**(a) ◐ The honesty contract is in the merge gate — natively. The MANAGED half is not.**
**(a) ✅ The honesty contract is in the merge gate — natively, and since 2026-09-06 the MANAGED half too.**
> **Closed 2026-09-06 by §S19(b)'s signer half and the same PR's `ci.yml` change.** The .NET
> test host still loads `System.Security.Cryptography.ProtectedData.dll`; the guard now verifies
> its embedded signature offline, reads `O=Microsoft Corporation` on the compiled-in bound, and
> keeps looking. `ShmDrainIntegrationTests`, `CaptureHostEndToEndTests` and the LHM hardware case
> run in CI under `./build.ps1 check` with no switches. The entry below is the history.
> **This entry was WRONG when it was written on 2026-08-05, and the correction
> matters because the wrong version was used to re-order the work.** It claimed the
@@ -401,6 +417,38 @@ layers) and needs `vulkaninfo` on `PATH`. So the assertion only fires when someo
runs it by hand. Nothing reminds them, and a loader upgrade is exactly when it
would matter.
> #### Disposition 2026-09-06, pre-committed on a measurement the same PR takes
>
> The "wrong place" argument inverts on a hosted runner: it is disposable, so an implicit
> layer registered under its `HKCU` harms nothing, and it IS the place a loader upgrade
> would be noticed. What decides is whether the runner has a Vulkan loader and
> `vulkaninfo.exe` at all — they ship with a GPU driver's runtime, not with Windows.
> `ci.yml` now prints a **Vulkan runtime census** (`vulkan-1.dll`, `vulkaninfo.exe`, the
> ICD registry key) as a measurement step. **Rows:** present → the next PR runs
> `vklayer-blastradius.ps1` as a CI step and (d) closes ✅; absent → (d) is 🅓 **deferred on
> that measurement**: the script stays hand-run before any layer PR (`HANDOFF` §Traps), and
> the reminder is the P1 Vulkan entry that cannot land without running it. Either row ends
> S29 as an S-item; the count below is written for the absent row and corrected if the
> census says otherwise.
>
> **2026-09-06 (P1 item 3): the assertion now lives in a ctest, and it no longer needs the registry.**
> `fl_vklayer_real` starts the harness's `--vulkan` mode with `VK_ADD_IMPLICIT_LAYER_PATH` pointed at the
> build tree's manifest and the enable variable set, and asserts the loader mapped the layer and the layer
> recorded the presents — on every dev-box build, with no HKCU write and nothing left behind. It SKIPS
> where there is no loader or no presentable device, which is CI's row; the census still decides (d)'s
> CI leg. `vklayer-blastradius.ps1` remains the hand-run check of the *unset-variable* case (it was run
> before this PR, green), and the loader-upgrade reminder is now the ctest rather than a HANDOFF trap.
>
> **Read 2026-09-06 off the sweep PR's run (`windows-latest`): `vulkan-1.dll` PRESENT in
> System32, `vulkaninfo.exe` absent (not in System32, not on PATH), no ICD registry key.** The
> absent row: **🅓 deferred on that measurement.** The loader is there but nothing to drive it
> with and nothing for it to drive — `vulkaninfo.exe` ships with a GPU driver's runtime, and
> without an ICD `vkCreateInstance` fails before the layer question is fully asked. The script
> stays hand-run before any layer PR. **Reopen condition, written now:** a Vulkan mode of
> `hook-harness` (unwritten, `12_BUILD` §Targets) could replace `vulkaninfo.exe` as the driver,
> and whether the loader's layer discovery and `enable_environment` behaviour is observable
> with no ICD is one measurement away — the P1 Vulkan entry is where it is taken.
**(e) ✅ The reader cannot tell a dead target from a quiet one — closed 2026-08-06,
host-side, with no ABI change.**
@@ -1206,7 +1254,32 @@ 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 ◐ · The guard is structurally blind in launch mode — **launch mode built as "inject late", 2026-09-06 (P1 item 2)**
> **Built, and the deferral's missing input is now something every launched session produces.**
> The guard gained `GuardedInjectWhenReady(pid, dll, timeoutMs)` (ABI `FlGuardedInjectWhenReady`): it
> polls the target every 50 ms through the module seam — a `Collected::kFailed` (the suspended /
> still-in-loader `ERROR_PARTIAL_COPY`) is "not yet", never a pass — until `dxgi.dll` with
> `d3d11.dll`/`d3d12.dll`, or `opengl32.dll`, or `vulkan-1.dll` is mapped, then runs `GuardedInjectImpl`
> in full. The poll matches nothing against the blocklist; it chooses WHEN the guard runs and nothing
> about whether it passes. Two new reasons end the poll with nothing injected: `LaunchTargetExited`
> (24) and `LaunchNoPresentationRuntime` (25). The CaptureHost's `launch` verb starts the consented
> executable itself (`ProcessLauncher`, `FRAMELEDGER_ENABLE_VK_LAYER=1`, handle held from birth) and
> routes the same gate through `HookRequest.WaitForPresentationRuntimeMs`; it never terminates what it
> launched. Measured, ctest `fl_guard` `[launch]`: the fake-driven poll injects on the first
> enumeration that shows the runtime and not one before (7 polls, ~300 ms), a target that exits first
> and a budget that runs out each answer their own reason, anti-cheat mapped beside the runtime is the
> full scan's refusal, and the real-seam case against `hook-harness` injects within one poll (15 ms).
>
> **The number nobody had:** `FlWriterState.dxgiPresentsBeforeHook` @60 — DXGI's `GetLastPresentCount`
> at the first hooked present on the first hooked chain, i.e. presents that ran before the hook was in
> (0xFFFFFFFF = the hook never saw a present). With the reported wait (`launch: the guard injected N ms
> after the process was started`) that is the early-init cost §S13(c) said needed a lazily loading title:
> it now comes from every title, on every launched session. **What the numbers decide is whether launch
> mode is *preferred* for a given title, not whether it exists.** The 2026-08-05 rationale stands as
> written below; what it deferred is now measurable rather than argued. Owed: the first real-title launch
> (the owner's next captures), which will also be the first look at a launcher-first title landing on
> `LaunchTargetExited` and needing the Agent's descendant election (P2).
> **§S1 does not gate the Vulkan path.** Added 2026-08-03, because "launch mode
> is blocked by §S1 anyway" was being used as a reason to deprioritise §S18 and
@@ -1275,7 +1348,7 @@ still lacks.
> `opengl32` or `vulkan-1` lazily rather than at startup. The owner supplies real
> fixtures on request; this one has not been found on this machine.
### S2 ◐ · The Vulkan layer has no guard — **both halves done; mid-session unhook still open**
### S2 ✅ · The Vulkan layer has no guard — **both halves done; part three built 2026-09-06 (P1 item 3)**
An implicit layer is machine-wide and loads **before** anything of ours runs, so
the injection guard cannot cover it: no module scan, no driver scan, no
@@ -1333,6 +1406,29 @@ ctest that always skips is a gate that cannot fail.
### ◐ Part three: mid-session guard inside a layered process — decided, half built
> #### ✅ Built 2026-09-06 (P1 item 3), in the PR that added the present hook — as the deferral below said it would be
>
> The layer intercepts `vkQueuePresentKHR` (+ `vkCreateSwapchainKHR` / `vkDestroySwapchainKHR`), owns the
> same ring the Overlay would (`fl_shm_host.h`, one per process) and runs the in-layer check **on the
> present path**: `unhookRequested` → `UNHOOKED` within one present; `guardTicks` not advancing for the
> 07_IPC deadline → `UNHOOKED`; `pauseRequested` → no record, still forwarded. "Stops" is passthrough forever
> with the reason on the mapping. Driven end to end by a fake loader chain (ctest `fl_vklayer`), the deadline
> proven with a 1.5 s test-only flavour of the DLL (`fl_vklayer_supervision`: ticks every 600 ms keep it
> alive past the deadline, 1.8 s without one stops it), and the real loader + the harness's `--vulkan` mode
> on the dev box (`fl_vklayer_real`, 241 records in 4 s; skips on CI, which has no loader). `17_HOOK_ENGINE`
> §Vulkan carries the shape. **The residual below is unchanged** and the Disclaimer's wording with it.
>
> #### 🅓 Deferred to P1, rationale written 2026-09-06
>
> The decision is taken (below: supervision is the Agent's job; a layer that cannot confirm
> supervision goes inert) and half of it is built. The other half is the in-layer check that
> reads `guardTicks` — and it has nothing to run on until `vkQueuePresentKHR` is intercepted,
> which is P1 (`15_ROADMAP` §P1: *"Vulkan layer to parity — `vkQueuePresentKHR` plus the
> in-layer supervision check §S2 gates on it"*). Building the predicate now would be one
> whose wrong answer changes nothing observable, the defect class this file records. Cost of
> waiting: none a user can see — the layer intercepts nothing, so there is no Vulkan capture
> to stop.
**The mechanism is decided.** The layer does NOT re-scan on its own after init.
Four options were pressure-tested (2026-08-02); the reasons the other three lost
are worth keeping, because each looks reasonable until costed:
@@ -1383,12 +1479,13 @@ process in the §S16 scan set — and the capture side would then keep observing
"the Overlay keeps writing (harmless)" on heartbeat loss described an
unsupervised hooked process as harmless.
**◐ The in-layer half is deliberately NOT built yet, and this stays open.**
**~~◐ The in-layer half is deliberately NOT built yet, and this stays open.~~ ✅ Built 2026-09-06, see the top of this part.**
The layer intercepts nothing — `vkQueuePresentKHR` is P1 — so a `ShouldObserve()`
today would be a predicate whose wrong answer *in either direction* changes
nothing observable. That is a gate on something that does not exist, which is the
defect class this file keeps recording. It lands in the PR that adds the present
hook, where a fake loader chain can drive it end to end.
hook, where a fake loader chain can drive it end to end. *(It did: `MayObserve()` in
`layer.cpp`, ctest `fl_vklayer` / `fl_vklayer_supervision`.)*
**Residual, to state rather than discover:** even once built, the mid-session
*driver* case is invisible from inside a layered process, and a layer cannot
@@ -1434,6 +1531,16 @@ override with a timer on it.
host, not the content. The rules above let a compromised feed be *rejected* but
not a genuine one *proven*. Residual risk, recorded rather than closed.
> #### 🅓 Deferred to P4, rationale written 2026-09-06
>
> Signing is a property of the feed, and there is no feed (§S20's feed half, deferred to
> P4 in the same sweep): every rules file on every machine today shipped inside a build
> whose SHA-256 is published, so the content IS attested, by the release. The decision that
> belongs to P4 — a compiled-in public key and a detached signature over the rules file,
> verified before validate-then-replace, with the same fail-closed polarity as the rest of
> the feed rules — is written here so the feed cannot ship without it. Residual until then:
> none beyond the release checksum, because nothing fetches.
### S5 ✅ · `detection-rules.json` schema — **closed**
`rules/detection-rules.schema.json` (JSON Schema 2020-12) now fixes the shape,
@@ -1501,6 +1608,10 @@ prologue) cannot produce a figure that generalises.
> entry proposes (resume, then poll until the target has mapped a presentation
> runtime *and* the scan passes *and* the blocklist is clean) remains the only
> candidate design for "inject late". It is unbuilt, not rejected.
>
> > **✅ Built 2026-09-06 (P1 item 2), exactly that proxy** — `FlGuardedInjectWhenReady`, §S1 carries
> > the mechanism and the measurements. "Salvageable" is answered yes; the cost of injecting late is
> > reported by the session itself (`dxgiPresentsBeforeHook`, and the wait).
### S15 ✅ · The four consequences of putting the guard in C++ (§S13(a)) — **closed**
@@ -2181,6 +2292,80 @@ admits it has no data for (Ricochet, VAC). Three refuters agreed.
> **Nothing under `FrameLedger.Injector` changed with the probe**, deliberately. This
> is a measurement, and reading a row off the table is a separate PR — including the
> row that says build nothing.
>
> **THE CI LEG WAS NEVER READABLE, found 2026-09-06 when it was finally looked for.**
> `ctest fl_signer_probe` passes on `BLOCKER: (FOUND|NOT PRESENT)` and ctest prints nothing
> for a passing test, so eleven days of green CI carried none of the probe's answers — the
> leg rows G3/G4/G5 are written for was "run" in the sense that a binary exited 0. And the
> native tests run BEFORE `dotnet restore` in `build.ps1`, so on a cold runner the NuGet
> copy the probe searches first may not exist yet at ctest time. `ci.yml` now runs the probe
> as its own step AFTER the gate (`continue-on-error`, a measurement and not a gate), and the
> answers are read off that step's log. **Owner-only, still unrun:** the adapters-disabled
> leg (rows G1/G2 — a network setting, not a PR), and the allow-widening bound that no row
> can lift (below). The recommendation for the bound, so the owner decides between two
> written options rather than one: **bound `trustedSigners` by a compiled-in allowlist the
> data file can only intersect** — the boundary of what the gate trusts stays code, exactly
> as `19_SAFETY` ruled for the launcher list, and it needs no branch-protection change; the
> alternative, making `Rules / validate` a required check, is §S23-2 and is the owner's
> GitHub setting, not a file in this repository.
>
> **THE CI LEG, READ 2026-09-06 off the new step (run on `ci/signer-probe-leg`, `windows-latest`,
> the probe reporting `elevated: yes` — the runner is an administrator; the dev-box leg was
> unelevated).** The blocker at the runner's NuGet cache (`system.security.cryptography.protecteddata`
> 6.0.0, `lib/net6.0`): embedded/offline **`ERROR_SUCCESS`, 3.47 ms, `O= Microsoft Corporation`**,
> no catalog; `mskeyprotect.dll` `TRUST_E_NOSIGNATURE` / catalog `ERROR_SUCCESS`; `kernel32.dll` both;
> cold 3.45 ms, warm 3.53 ms; `cryptnet.dll` newly loaded under the offline flags, as on the dev box;
> the canary `TRUST_E_NOSIGNATURE`; the probe's own verdict *"G1 is a CANDIDATE"*. **So G3 does not
> fire (the `O=` premise holds on CI's copy), G4 does not fire (CI's copy is embedded-signed), G5 does
> not fire (3.5 ms).** What is left before G1 can be read is exactly the two owner-only legs above:
> adapters disabled (G1 against G2), and the bound.
>
> **THE ADAPTERS-DISABLED LEG, the owner's run, 2026-09-06 (dev box, elevated; reported in answer
> to the request to run it with every adapter off — if it was not, this paragraph is withdrawn
> and the leg is unrun).** Every verdict UNCHANGED against `spike-notes` §1: `kernel32.dll`
> embedded `ERROR_SUCCESS` / catalog `ERROR_SUCCESS`; `mskeyprotect.dll` embedded
> `TRUST_E_NOSIGNATURE` / catalog `ERROR_SUCCESS`; the blocker embedded `ERROR_SUCCESS`, no
> catalog, **`O= Microsoft Corporation`**; canary `TRUST_E_NOSIGNATURE`; `cryptnet.dll` still
> mapped under the offline flags and still not evidence of a request. Faster than the online run
> (2.14 ms cold, 2.15 ms warm; 2.97 / 2.13 ms on the system binaries), which is what an offline
> cache-only path should look like. **One detail worth its line:** the blocker's subject now reads
> `CN=.NET` where the August copy read `CN=Microsoft Windows` — the NuGet copy was re-staged with a
> different certificate — and `O=` is the same on both, which is the `signerField: "O"` decision
> confirmed on a subject class it was never measured against. **Row G1 reads.** The embedded half
> alone, offline, clears the CI refusal; the `CryptCATAdmin*` catalog half is deferred with its own
> rationale (it reaches `mskeyprotect.dll`, which is not on the path to the merge gate, and it is
> the `CatRoot` walk §S19(b) priced). **What still stops the build is the bound**, above — the
> owner's, and asked for beside this reading.
>
> #### ✅ BUILT 2026-09-06 — the embedded half, on row G1, under the compiled-in bound (owner: option 1)
>
> **The owner chose the bound the same afternoon: a compiled-in allowlist the rules file may only
> intersect.** `IsCompiledTrustedSigner` in `fl_ac_rules.cpp` names the five organisations the shipped
> rules name, and `IsTrustedSigner` now requires BOTH lists — a rules push that adds `"Evil Corp"`
> widens nothing, which is one assertion in `fl_guard`. `Sources` gained
> `ModuleSignerOrganisation`: `WinVerifyTrust(WTD_CHOICE_FILE)` under `WTD_REVOKE_NONE |
> WTD_CACHE_ONLY_URL_RETRIEVAL | WTD_SAFER_FLAG`, and only after `ERROR_SUCCESS` the signing
> certificate's subject `O=` through `CryptQueryObject` — the probe's shape with fixed buffers, in
> `fl_guard_sources.cpp` (never `fl_ac_rules.cpp`, which the Vulkan layer compiles: wintrust and
> crypt32 stay out of every Vulkan process). `ModuleSinkFn` asks it after the ours exemption and
> BEFORE latching: a trusted module returns *keep looking*, exactly as the exemption does, so the
> load-order fail-open this entry predicted is closed by the same structure — and it applies to the
> TARGET too, because a game loading a Microsoft-signed key-protection provider is the false refusal
> the half exists to remove. **The fail-closed row, added:** no embedded signature (every catalog-only
> system binary — `mskeyprotect.dll` by design), an invalid one, an unreadable `O=`, a null path, a null
> seam, a seam that fails, an organisation on one list but not the other — all untrusted, all refuse.
> The catalog half stays deferred: it reaches only modules that are not on the path to the merge gate,
> and it is the `CatRoot` walk this entry priced.
>
> **Proved in both directions, against the real seams:** `hook-harness --load <dll>` puts a named module
> into the target before the guard looks. The NuGet copy of the CI blocker → **Allowed**, Overlay
> injected (skipped loudly on a machine with no NuGet cache; the managed integration cases are the gate
> that cannot skip it). Our own unsigned Overlay copied under a `protect`-bearing name outside the
> guard's directory → **SuspiciousUnsigned**, naming it, nothing injected. Nine fake-seam cases pin the
> decision (both lists, the target, kFailed, missing seam, pathless, load order, exact-hit precedence).
> **And `-SkipIntegration` is gone from `ci.yml` in the same PR**: the nine `Category=Integration`
> cases are in the merge gate for the first time since 2026-08-05, and CI runs the same
> `./build.ps1 check` a developer does. The switch stays in `build.ps1`, loud, for whoever must.
**(c) `signerField` and `action` are required by the schema and parsed by
nobody.** Both are `required` in `detection-rules.schema.json`, both carry
@@ -2203,6 +2388,17 @@ configurable and never was; the field that would express it has no consumer.
> `warn_and_refuse` — a predicate whose answer changes nothing observable, which
> is the defect class this file exists to record. Wiring it means first deciding
> that `warn` or `allow` may exist, and CLAUDE.md rule 2 says they may not.
>
> #### ✅ Resolved 2026-09-06 — the consumer is the validator, and the policy is code by rule
>
> Decided the way the paragraph above costs it: `warn` and `allow` do not exist (CLAUDE.md
> rule 2), and the signer field is `O=` by measurement (`19_SAFETY`), so neither field is
> for the guard to read — they exist so that the DATA cannot claim otherwise. What was
> missing was the thing that makes that true: `rules-validate` now carries a third canary
> that mutates the shipped document to `action: "allow"` and to `signerField: "CN"` and
> requires the schema to reject both. Delete either `const` and the gate goes red. The
> guard's hardcoded refusal is the specification, and `IsCompiledTrustedSigner` (§S19(b))
> made the other half of the heuristic code-bounded the same day.
**(d) ◐ The fragment list has unreconciled copies — more than three. The runtime
hole is CLOSED.** `rules/detection-rules.json`, `guard_test.cpp` (the inline
@@ -2363,6 +2559,14 @@ disproved:
with validate-then-replace; none of it exists. So **FR-7.3 is unmet**: anti-cheat
entries cannot reach a machine on their own schedule, only with a release. A
rules edit still changes nothing on any installed machine until the next build.
> **🅓 Deferred to P4, rationale written 2026-09-06.** The feed is the product's one
> permitted outbound request after the release check (CLAUDE.md rule 8), and it needs
> three things P0 does not have: a shipped Agent to run it in, the signing §S4 defers to
> the same phase, and the privacy policy's rows that describe it (`legal/PRIVACY_POLICY.md`
> already flags them as describing a request the software does not make). Until then a
> rules edit reaches a machine with the next release, whose checksum attests it — a slower
> delivery, not a weaker gate. FR-7.3 stays unmet and stays written as unmet.
- **No binary/data handshake inside the guard.** `ParseRules` still walks only the
`anticheat` subtree and never reads `schemaVersion` or `rulesVersion`. Teaching
it to refuse an unknown version would be a second machine-wide refusal lever
@@ -2782,7 +2986,7 @@ required contexts are exactly `check`, `analyze (csharp, none)` and
the gate that exists to make the anti-cheat blocklist un-removable is advisory.
Fixing it is a branch-protection change, i.e. the owner's, not a code change.
**3. `08_UI` describes a refusal notice that is wrong in the commonest case.** It
**3. 🅓 Deferred to P3, rationale written 2026-09-06 — `08_UI` describes a refusal notice that is wrong in the commonest case.** *(The requirement below must reach `08_UI` and the `Safety_*` keys in the PR that creates the first refusal UI, and not before: there is no UI to be wrong in yet, and a `.resx` string with no view is the kind of fix that reads as done. The spike log carries the measurement; this line is the reminder.)* It
promises "the specific signal named in plain language". Measured (`spike-notes`
§13): while any Easy Anti-Cheat title is running, **every** target — including a
freshly spawned, unrelated process — refuses with `BlockedService` naming
@@ -2868,6 +3072,15 @@ gate.
> four-going-on-five unimplemented promises, and now this file's bundling audit —
> remain hand-maintained prose that nothing verifies. A gate over one table is not
> a gate over `legal/`.
>
> **✅ Closed 2026-09-06, by making there be one block.** `legal/ACCURACY.md` is the single
> statement of what the software measures, dated; `README.md` and `legal/DISCLAIMER.md` §4
> embed it verbatim between markers, and `tools/accuracy-check.ps1` — a `build.ps1` gate with
> a four-case self-test, both directions — fails when any copy differs from the source, when
> a copy has no markers, or when the source is empty. What the gate does NOT do is decide
> whether the block is true; that stays with whoever changes the Overlay or the capture host,
> and the block's own comment says so. The block was rewritten to 2026-09-06 truth in the same
> PR (the previous §4 note still said frame generation and ray tracing had no hook).
### S14 ◐ · Pre-injection check 3 is **unwired**, and has no "cannot determine" state
@@ -2925,6 +3138,13 @@ nothing.
> "fix" (2) by widening the ABI.** The route is the metadata extractors plus a
> guard-side resolver, which is its own PR and its own fail-closed matrix row.
>
> **🅓 The store-id half is deferred to P4, rationale written 2026-09-06.** Its only
> in-policy route is the platform metadata extractors (Steam/GOG/Epic/itch — P4's library
> import) feeding a guard-side resolver, and a resolver with no extractor behind it would
> refuse every title (an unresolved id refuses, by the matrix). The executable half is
> wired and proven red; the data for both halves is empty by decision. Cost of waiting:
> none — no title is blocked by store id today because none is listed.
>
> Proven red: disarming the matcher makes the guard **allow** a blocked
> executable, and the test asserts `kBlockedExecutable` specifically rather than
> "it refused" — which is indistinguishable from the four refusals the guard
@@ -2967,9 +3187,32 @@ Two decisions, both the owner's:
Until both are answered the inertness is recorded in the data's own `$comment`
and beside check 3, rather than being inferable only from two empty arrays.
### S6 · The 30 s scan window is the weakest part of the most important behavior
### S6 ✅ · The 30 s scan window is the weakest part of the most important behavior — **the in-process half built 2026-09-06 (P1 item 1)**
Now disclosed honestly in the Disclaimer and README. The open question is whether
> **Built, as the deferral below said it would be: one detour, both jobs.** `kernelbase.dll!LoadLibraryExW`
> is patched from `InitThread` after the present hooks; the body calls the original first, skips
> data-file / resource mappings, reads the mapped module's own file name into a stack buffer and compares
> its base name (a) against `FL_HOOK_INVENTORY` + `FL_RUNTIME_CENSUS` — a match bumps a 15-bit wake count
> and signals the watchdog's auto-reset event, so the lazy installers run **within milliseconds** rather
> than on the next 1 Hz tick — and (b) against the compiled floor's MODULE families (prefix, case-
> insensitive, the generated table the guard itself carries; zero allocation) — a match CASes the family's
> 1-based index into `earlyStopFamily`, and the present path (`MayObserve`) or the watchdog, whichever is
> first, calls `StopObserving(FL_STATUS_STOPPED_BLOCKLISTED)`. It supplements the poll and replaces
> nothing; it installs nothing inline (§H2). **Measured**, real Overlay in a real target (ctest `fl_guard`):
> a late `sl.interposer.dll` hooked **94 ms** after it appeared (bound 500 ms, which the tick alone cannot
> meet more than half the time); a decoy copied to `EasyAntiCheat_fl_fixture.dll` and loaded 2.5 s in
> stopped the Overlay with `earlyStopFamily` equal to the index the test computed from the same generated
> table, `unhookRequested` still 0, and `writeIndex` frozen thereafter. The CaptureHost reads both words
> (`Consume/EarlyStop.cs`), ends the session as `WriterStoppedBlocklisted` (exit 5, the safety-stop code)
> and names the family from the staged rules file.
>
> **What it does not do, stated so the disclosure stays honest:** the fragment tier and the signer tier
> are not in the detour, so a module the floor knows only that way waits for the host's 30 s scan; the
> Disclaimer's "within 30 seconds" is unchanged. **Owed:** the real-game leg of §H2 — a title that loads
> D3D12 or Streamline lazily, hooked through the wake rather than the tick — which the next captures
> report via the `loader detour:` line (`woke the watchdog N time(s)`).
Now disclosed honestly in the Disclaimer and README. The open question ~~is~~ was whether
to shrink it.
> **"Already installs" was false, and it changed how this item read.** Corrected
@@ -3010,6 +3253,17 @@ acceptable in that hook under the no-allocation rule (it should be), and a
decision on whether it supplements or replaces the poll. Supplements — the poll
also catches modules loaded before we hooked.
> #### 🅓 Deferred to P1, rationale written 2026-09-06 (owner: "theo bảng")
>
> The mechanism is a `LoadLibrary` hook inside the Overlay raising the control-block flag
> the moment a blocklisted module name loads, supplementing the 30 s poll. It is specified
> (`17_HOOK_ENGINE` §DLL entry, deferred install per §H2) and it needs the P1 hook layer's
> `LoadLibrary` detour to hang on — the same detour lazily loaded graphics DLLs need — so
> building it in P0 would mean building that detour twice. The cost of waiting is the one
> the Disclaimer already discloses: up to 30 s between a mid-session load and the stop.
> Not closed: the name comparison in that hook must be against the compiled floor
> families and allocation-free, and it supplements the poll rather than replacing it.
### S7 ✅ · Guard handle rights and WOW64 — **closed**
Measured unelevated 2026-08-02 by `src/native/tools/fl-probe-guard` (ctest
@@ -3127,6 +3381,14 @@ lazily, which is the case the hook exists for. Until then, keep the rule and do
not let anyone "simplify" it back to an inline install on the grounds that the
probe never showed a deadlock.
> **The deferred path is built and exercised in a fixture (2026-09-06, P1 item 1 — §S6).** The detour
> signals an auto-reset event the watchdog waits on with its 1 s timeout; it never calls MinHook.
> ctest `fl_guard` `[loader]` loads `sl.interposer.dll` into a presenting harness 2.3 s after start and
> sees the hook family within 94 ms, wake count ≥ 1, no fault, no stop. **Still owed, unchanged:** the
> real-game leg — a title that pulls Streamline or D3D12 in lazily, hooked through the wake — which the
> `loader detour:` report line will show as a non-zero wake count with the family present from the first
> bucket.
### H5 ✅ · Proxy swapchains defeat the dummy-vtable assumption — **the DLSS / DLSS-G question closed 2026-09-06 (owner)**
> **CLOSED 2026-09-06, 12:17, on Cronos: The New Dawn demo with frame generation ON (`spike-notes` §9).**
@@ -3663,6 +3925,36 @@ load-bearing rather than stylistic.
> the sessions that measure it, and the pre-commitment is the last clause: the wording must survive the
> one static title (Rune Factory at FSR FG) reading the same way.
>
> **BUILT 2026-09-06 (owner: "build cả hai"), with the executable-file scan beside it.** `FgModePrinted`
> carries the elimination sentence on every rung-3 line; `ExecutableMarkerScan` reads the exe on disk once
> after the session and the clear-census qualifier says MAY when a frame-generation-capable SDK string is in
> the file. Expected on an XeFG session (DL:TB / Hell Is Us / Cronos / Expedition 33 with XeSS FG on):
> the trio or a Presented line from the token or DXGI count, and `frame generation: Active (technology not
> identified) — by elimination …: not DLSS-G (…), no FSR frame-generation dispatch …; the frame-generation
> runtime(s) loaded: libxess_fg.dll …`. Expected on Rune Factory at FSR FG: the same shape with *"no
> frame-generation runtime module is loaded at all; the executable itself carries ffxFsr3, …"*. Neither
> prints a vendor as measured.
>
> **LANDED 2026-09-06, 13:45–14:02 (`spike-notes` §9).** **Rune Factory at FSR + FSR FG** reads exactly the
> pre-committed line: `30.05 → 60.05 (×2 FG)` from the Streamline token, `unseen=0` (the compiled-in FSR 3
> presents through the patched body), `frame generation: Active (technology not identified) — by elimination
> …: not DLSS-G (…); no FSR frame-generation dispatch …; the frame-generation runtime(s) loaded:
> nvngx_dlssg.dll; the executable itself carries ffxFsr3, ffxFrameInterpolation — …` — 7b at its ceiling, the
> Steam overlay showing FG where the report shows the count. **Hell Is Us at XeSS + XeSS-FG** (the owner:
> the Steam overlay could not show FG there): `Presented FPS: 186.47`, **`tokens=0`** — this plugin version
> requests no Streamline token at XeSS, where it did at DLSS — so no count and no factor; `unseen=0`, so
> XeFG presents its generated frames through the patched body and the 186 IS the Displayed rate; the driver's
> words clear; the file carries `xefgSwapChain ×13`. The FG line read the bare *"N/A (a hook ran …)"* and the
> upscaler N/A named "a vendor this build does not decode" — both now carry their witnesses: the N/A prints
> the same exclusion clauses (*the frame-generation runtime(s) loaded: nvngx_dlssg.dll, libxess_fg.dll, …;
> the executable itself carries xefgSwapChain*), and the upscaler line says *libxess.dll is loaded, and XeSS
> cannot be hooked or declared under Intel's licence … N/A here by policy, not by ignorance* (7c item 4's
> string change, done). **Cronos at XeSS** (no FG option): `FPS: 110.02`, `none` by count with DXGI agreeing
> — this plugin requests the token at XeSS. **The ceiling for XeFG on a title that requests no token:**
> Displayed measured, Native unknown, vendor by elimination — there is no in-policy application-frame
> producer for XeFG (the token is the plugin's choice; the XeFG API cannot be hooked; the ffx census is
> silent by construction), and the report says so rather than inventing one.
>
> **BUILT, 2026-09-04, the AMD half — and the deferral's own rule was kept: header first, decode
> second, never from observation.** `HANDOFF` item 7c. The FidelityFX headers cleared the
+48 -5
View File
@@ -31,7 +31,22 @@ and traps**. It deliberately carries **no status**.
## Where P0 actually stands
Two exit criteria remain (`spike-notes.md` §Exit criteria). Do not re-derive them
**P0 is closed (owner, 2026-09-06).** Both criteria read as met in `spike-notes.md`
§Exit criteria — criterion 1 with the quality preset amended to an honest `N/A`,
criterion 2 with §S24 counting zero S-items against it (🚫 S23-2 is a GitHub setting
outside any PR). **What comes next is P1** (`15_ROADMAP` §P1): the Overlay proper —
hook installation for D3D11/12/9/OGL, the `LoadLibrary` detour that §S6's early stop
and lazily loaded runtimes both hang on, unhook path, native logging; the Injector's
launch mode (§S13(c), §S1's deferred input); the Vulkan layer to `vkQueuePresentKHR`
with §S2's in-layer supervision. **P1 item 1 — the `LoadLibrary` detour — landed 2026-09-06
(§S6 ✅); item 2, launch mode, landed the same day as "inject late" (§S1 ◐, §S13(c) ✅ —
`04_CAPTURE` §Launch mode); item 3, the Vulkan layer to `vkQueuePresentKHR` with §S2's in-layer
supervision, landed the same day (§S2 ✅; `17_HOOK_ENGINE` §Vulkan); next is item 4 — the unhook
path, native logging, D3D9 / OpenGL.** The ~~three~~ ~~two~~ one P1-deferred S-item (~~S6~~, ~~S2 part three~~, and
the hand-run blast-radius script behind S29(d)) are the reminders. The text below is
P0's history and stays as it stood.
Two exit criteria ~~remain~~ were the gate (`spike-notes.md` §Exit criteria). Do not re-derive them
from memory:
1. **A throwaway build records a real session** from a real offline game reporting
@@ -197,7 +212,8 @@ own PR with its own rule-4 justification.
watchdog thread runs once a second. No `LoadLibrary` hook is needed for P0 — which
keeps §S6 genuinely separable. The Overlay has **no** module-resolution machinery
today (`GetProcAddress`/`GetModuleHandle` appear nowhere), so that helper is part of
the real cost.
the real cost. *(2026-09-06: the detour exists now — P1 item 1 — and it still only
WAKES that thread; the installers did not move. `17_HOOK_ENGINE` §DLL entry step 3.)*
- `tools/hookinventory-check.ps1`: every symbol the Overlay resolves by name must
appear in `vendor-exports.json`. **No drift exists today** — a refuter resolved every
inventory symbol against all 34 measured modules — so write it as prevention and do
@@ -824,7 +840,15 @@ hole; it does not close it.
title cannot give. **The honest ceiling for a statically linked title in attach mode is
Presented FPS with the census's qualifier** — which is what ships today, with the hole named.
- **The only cheap improvement is wording**, and it is already in: the qualifier says
*statically linked FSR3-FG … outside what this can see*. If a title is found, the first PR is
*statically linked FSR3-FG … outside what this can see*. **Built 2026-09-06, two steps past that
(owner's choice over "return native", which rule 6 forbids):** the executable FILE is scanned on
disk after the session for the vendor SDK strings, and a frame-generation-capable one flips the
clear-census sentence from *cannot* to *MAY*; and the rung-3 line prints its exclusions (the
driver's FG word, the tags, the ffx census, the module census, the file's markers). The ceiling
for a title that is both compiled-in and token-less stays Presented FPS + that qualifier. **LANDED
2026-09-06 14:02: Rune Factory at FSR + FSR FG prints the pre-committed line verbatim (§H11); 7b is at its
ceiling and closed.** Hell Is Us at XeSS + XeSS-FG the same run: no token, so Displayed measured (186.47,
0 unseen) and Native unknown — the N/A now carries its witnesses, and that is the XeFG ceiling too. If a title is found, the first PR is
a `spike-notes` row and a `20_OPEN_QUESTIONS` §Scope entry with the measured shape, not code.
- ~~**Measured 2026-09-04: no such title is installed.**~~ **Found the same evening, by running
rather than by scanning: Rune Factory: Guardians of Azuma.** The scan was right that every FSR
@@ -994,6 +1018,25 @@ feature hooks — §S29(a) said it was and was wrong; see below. What it buys is
> drop the switch as well. Anyone costing this as "fix the signer half" is costing
> half of it.
**Picked up 2026-09-06 (the owner's next item after item 7).** The sequence, with what
each step needs, so nothing here is started out of order:
1. **The CI leg, made readable** (2026-09-06, this PR): the probe's ctest printed nothing,
so `ci.yml` runs `fl-probe-signer` as its own step after the gate and the answers land in
the log. Rows G3/G4/G5 are read off the next run on `main`.
2. ~~**The adapters-disabled leg — owner-only, a network setting.** Same three subjects,
`ctest fl_signer_probe` (or the exe) with every network adapter disabled, compare the
verdicts with `spike-notes` §1. Unchanged → G1; any change → G2 and the route retires.~~
**RUN 2026-09-06 by the owner: every verdict unchanged — row G1 (§S19(b)).**
3. ~~**The allow-widening bound — owner-only, a decision no PR may take (§S19(b)).**~~ **DECIDED
2026-09-06: option 1, the compiled-in allowlist `trustedSigners` may only intersect.**
4. ~~**Then the PR:** …~~ **BUILT 2026-09-06 (§S19(b) ✅ BUILT):** `ModuleSignerOrganisation` in
`fl_guard_sources.cpp`, `IsCompiledTrustedSigner` as the bound, the trusted module keeps the
scan looking, every failure refuses, the catalog half deferred with its rationale, both
directions proved against the real seams through `hook-harness --load`, and `-SkipIntegration`
dropped from `ci.yml`. **The Separable item is closed**: the nine integration cases are in the
merge gate, and CI runs the command a developer runs.
### ~~§M5 — **START HERE**~~ — MEASURED 2026-09-03, row R1, and the head moves
**Do not start here.** `LhmTelemetrySource` exists, `probe-lhm` ran unelevated and elevated,
@@ -1205,8 +1248,8 @@ diagnosis*.
needle containing `` `blockedExecutables` `` silently became something else, `.Replace`
matched nothing, the file was unchanged — and the validator correctly passed. Print
the mutated text before validating.
- **`./build.ps1 check` with no switches** after every PR. CI runs `-SkipIntegration`,
so a green CI is not evidence for anything touching the managed drain.
- **`./build.ps1 check` with no switches** after every PR. ~~CI runs `-SkipIntegration`,~~ CI runs the same since 2026-09-06,
so a green CI is evidence for the managed drain too (§S19(b) BUILT).
- **A canary that does not compile is not a canary, and this repo's analyzers make that
easy to hit.** Removing a call to prove a gate goes red can leave a constructor
parameter unread — `CS9113` under `TreatWarningsAsErrors` — so the build fails, the
+70 -6
View File
@@ -312,8 +312,20 @@ offline retires the route, and §S19(b)'s row G2 says so before the run.
yields no organisation — so a green result discriminates rather than merely running.
`fl-baseline-probe` was retired by exactly this class of test.
**Not measured here:** the CI leg (a different machine stages a different copy), and
the adapters-disabled leg. Both have pre-committed rows. An unrun leg is unrun.
~~**Not measured here:** the CI leg (a different machine stages a different copy), and
the adapters-disabled leg. Both have pre-committed rows. An unrun leg is unrun.~~
**The CI leg, 2026-09-06** (the ctest printed nothing for eleven days; `ci.yml` now runs the
probe as a step): `windows-latest`, elevated. Blocker copy from the runner's NuGet cache,
6.0.0, embedded/offline `ERROR_SUCCESS` 3.47 ms, `O= Microsoft Corporation`, no catalog;
`mskeyprotect.dll` embedded `TRUST_E_NOSIGNATURE`, catalog `ERROR_SUCCESS`; `kernel32.dll`
both; cold 3.45 / warm 3.53 ms; `cryptnet.dll` newly loaded under the offline flags; canary
`TRUST_E_NOSIGNATURE`; *"G1 is a CANDIDATE"*. Rows G3, G4, G5 do not fire.
**The adapters-disabled leg, the owner's run, 2026-09-06** (dev box, elevated): every verdict
unchanged — `kernel32.dll` both `ERROR_SUCCESS`; `mskeyprotect.dll` embedded `TRUST_E_NOSIGNATURE`,
catalog `ERROR_SUCCESS`; the blocker embedded `ERROR_SUCCESS`, `O= Microsoft Corporation`, subject
now `CN=.NET` (the August copy read `CN=Microsoft Windows`; same `O=`); cold 2.14 / warm 2.15 ms;
`cryptnet.dll` mapped; canary `TRUST_E_NOSIGNATURE`. **Row G1 reads**; the bound decision is the
owner's before anything is built.
### Still open
@@ -323,6 +335,9 @@ the adapters-disabled leg. Both have pre-committed rows. An unrun leg is unrun.
loads a presentation runtime lazily, and the only local fixtures are
`hook-harness` (creates D3D at startup) and a 2D GOG prologue. A number from
those would not generalise, which is worse than recording it as unmeasured.
*(2026-09-06: built as "inject late" — P1 item 2 — and the number now comes
from every launched session, as `dxgiPresentsBeforeHook` plus the reported
wait. `20_OPEN_QUESTIONS` §S1.)*
### ✅ Signer field for the unknown-but-suspicious heuristic — **`O=`, not `CN=`**
@@ -428,6 +443,31 @@ the same shape as defects found elsewhere in this project:
The unambiguous signal is the loader printing `Insert instance layer` /
`Inserted device layer` with our name and DLL path.
### ✅ `VK_ADD_IMPLICIT_LAYER_PATH` is honoured, and it needs no registry (2026-09-06, P1 item 3)
Measured against the same loader 1.4.357 with `vulkaninfo --summary` and `VK_LOADER_DEBUG=layer`: with
`VK_ADD_IMPLICIT_LAYER_PATH` pointed at the build tree's `FrameLedger.VkLayer` directory and
`FRAMELEDGER_ENABLE_VK_LAYER=1`, the loader prints `Insert instance layer "VK_LAYER_FRAMELEDGER_overlay"
(…\FrameLedger.VkLayer.dll)` and `Inserted device layer …` — the unambiguous signal above — with nothing
under `HKCU` or `HKLM`, and `vulkaninfo` exits 0 with the layer inert (no enable-list entry for it). The
first run's `grep … | head` cut the log before the `Insert` lines and read as "found, not inserted"; the
lines are at the instance-creation point, ~850 lines in. So the operator host launches Vulkan titles with
no registration at all, and the real-loader ctest (`fl_vklayer_real`) does the same: the harness's
`--vulkan` mode presented 241 frames in 4 s on a hidden 240-wide window and the layer recorded every one.
### ✅ On NVIDIA a Vulkan swapchain presents through DXGI — and the DXGI hook sees it (2026-09-06)
Found by the first end-to-end run of `launch` on the harness's `--vulkan` mode: the guard's poll saw
`dxgi.dll` + `d3d12.dll` (the fixture imports d3d11/dxgi; but the NVIDIA Vulkan ICD `nvoglv64` maps them
too) and injected the Overlay, whose `Present` hook then recorded **295 DXGI presents in 5 s with
`apiMask = D3D12` and DXGI's counter agreeing (248 samples, 0 unseen)** — the Vulkan swapchain's own
presents, made by the driver on an internal DXGI flip-model chain. So on this driver the injected Overlay
*can* measure a Vulkan title's presents; that is a driver property, not a portable one (AMD's and Intel's
WSI need not do it), which is why the layer stays the capture side. Two consequences landed: the
launch-mode guard now classifies **any** process that mapped `vulkan-1.dll` as the layer's, and the
harness's `--vulkan` mode maps the loader before anything else so the fixture looks like a real Vulkan
title to the first poll.
### ✅ The in-layer blocklist scan — §S2's second half
The layer scans its own process at init and goes fully passthrough on any hit,
@@ -1924,6 +1964,21 @@ one launch per capture, consent granted after launch. Exit codes and full report
Same run, Rune Factory at DLSS + FG ×4: `125.45 → 498.51 (×3.97)`, `Dlss (driver-reported)`, `DlssG` with the
driver agreeing — the 7b title on its NVIDIA path.
- **2026-09-06, 13:45–14:02, the owner's run on #132 (rung 3 by elimination + the executable scan): Cronos at
XeSS (no FG option), Hell Is Us at XeSS + XeSS-FG, Rune Factory at FSR + FSR FG.**
| Title / setting | Line | `frame generation:` | `executable markers:` |
|---|---|---|---|
| **Cronos**, XeSS, no FG | `FPS: 110.02`, `none` by count, DXGI agrees | `None` | ffxFrameInterpolation ×1, NVSDK_NGX ×112, xefgSwapChain ×13 |
| **Hell Is Us**, XeSS + **XeSS-FG** | `Presented FPS: 186.47`, **`tokens=0`**, `unseen=0` | N/A — no token on this plugin at XeSS; witnesses: not DLSS-G, no FSR dispatch, runtimes nvngx_dlssg + libxess_fg + amd FG, file carries xefgSwapChain | same set |
| **Rune Factory**, FSR + **FSR FG** (compiled in) | `30.05 → 60.05 (×2 FG)` from the token, `unseen=0` | `Active (technology not identified) — by elimination …; the executable itself carries ffxFsr3, ffxFrameInterpolation` | ffxFsr3 ×13, ffxFrameInterpolation ×9, NVSDK_NGX ×112 |
Three readings. Rune Factory is the pre-committed 7b line, verbatim. XeFG presents through the patched
body (0 unseen) so its Displayed rate is measured; its Native is not, because Hell Is Us's plugin requests
no Streamline token at XeSS (it does at DLSS, and Cronos's does at XeSS) — the count producer is the
plugin's choice, and nothing in policy replaces it. The Steam overlay could not show FG on that session
either. The upscaler N/A on both XeSS titles now names Intel's licence as the reason (7c item 4).
## 10 · Telemetry layering
- L1 baseline vendor-neutral:
@@ -2376,16 +2431,25 @@ produced no false refusal on any real install.
`15_ROADMAP` §P0. Nothing in P1 starts until all are met.
- [ ] A throwaway build records a real session from a real offline game
- [x] A throwaway build records a real session from a real offline game
reporting **correct** upscaler, quality preset, render → output
resolution, FG factor and RT state — verified against the game's own
settings menu.
settings menu. **Met 2026-09-06 with one amendment, the owner's:** the
quality preset reads `N/A` on every title, by measurement — Streamline's tags
carry no size or preset on Direct3D 12, NVIDIA's override fields are the
override's, XeSS is closed by licence — and an honest `N/A` where measurement
is impossible is the *correct* value CLAUDE.md rule 7 asks for. Upscaler,
render → output (where the vendor's call carries it), FG factor and RT state
are verified against the menus of nine titles (§9). The owner closed 7a on
this reading and closed P0 on it here.
- [x] **Moved to the end of P1** (§R4, decided 2026-08-02) — ~~measured game FPS
impact under 0.5%~~. As written it imported P2's drain, aggregate and
recorder paths; the harness-level per-present cost stayed in P0 and is
measured in §3 (8.4 ns).
- [ ] Every S-series item in `20_OPEN_QUESTIONS.md` resolved, or explicitly
deferred with a written rationale.
- [x] Every S-series item in `20_OPEN_QUESTIONS.md` resolved, or explicitly
deferred with a written rationale. **Met 2026-09-06** (§S24: zero counted
against it). 🚫 S23-2 is a branch-protection setting outside any PR and is
recorded as such, not as met.
- [x] M3 and M4 answered **before** any NVAPI or LHM code is written — both
CLEAR, §0 above.
+45
View File
@@ -0,0 +1,45 @@
<!--
THE ONE ACCURACY BLOCK. Embedded verbatim in README.md and legal/DISCLAIMER.md
between the two HTML-comment markers named `accuracy-block:begin` and
`accuracy-block:end` (spelled out in tools/accuracy-check.ps1 — not here, because a
literal marker inside this comment would end the comment early), and that gate
fails the build when any copy differs from this file
(20_OPEN_QUESTIONS §S23-6: the accuracy blocks were hand-maintained prose that
nothing verified, and DISCLAIMER's went stale four times in one direction and once
in the other). Whether the sentences below are TRUE is still a human's job — the
gate only makes there be one place to get them wrong. Re-read this file in the PR
that changes what FrameLedger.Overlay or the capture host does; date the change.
HTML comments are not part of the block.
-->
> ⚠ **What FrameLedger actually measures today — 2026-09-06.** The software is pre-alpha: the
> measurement path exists as an injected Direct3D 11/12 component and an **unshipped** capture
> host that drives the guard loop and prints a report; there is no Agent loop, no storage, no
> charts, no library import, no UI and no installer yet.
>
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
> labelled *driver-reported*. Intel XeSS is **not** read (its SDK licence forbids it) and reads
> `N/A` by policy; an upscaler compiled into the game executable reads `N/A`.
> - **Quality preset:** `N/A` everywhere. No route this software may use exposes it.
> - **Render → output resolution:** measured where the vendor's own call carries the size (AMD
> dispatches, some Streamline titles); `N/A` where it does not (NVIDIA-direct titles, most
> Direct3D 12 Streamline titles).
> - **Frame generation:** the Displayed rate is counted from presents — including, on one title,
> presents DXGI counted that the hook could not — and the Native rate from the vendor's own
> per-frame calls where the title makes them. Identity: DLSS-G and FSR-FG named from the calls
> the game makes; anything else (XeSS-FG, a generator compiled into the game) is reported *by
> elimination* and never named. Where no per-frame call exists the Native rate is `N/A`.
> - **Ray tracing:** Yes/No measured from DXR dispatches and acceleration-structure builds on
> Direct3D 12; the technique and path tracing are `N/A`.
> - **Not measured at all:** video memory, shader-compilation stutter, PC latency (Reflex), HDR.
> - **Safety:** every pre-injection check runs before injection, including the signed-by-a-known-
> vendor half of the suspicious-module rule (since 2026-09-06), and the unshipped capture host
> re-runs them every 30 s and stops the capture on refusal. No shipped component drives that loop
> yet. There is no override anywhere.
>
> Where a value is not measured it reads `N/A`; the software never substitutes an estimate.
+38 -3
View File
@@ -6,6 +6,8 @@
> ⚠ **Accuracy audit — re-checked 2026-08-14, a FOURTH time, after PR #64. SIX 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.
>
> **A FIFTH time, 2026-09-06, and the mechanism changed rather than the count.** Every drift this block records came from the same cause: the sentence about what the software measures lived in three places and was re-read in none of them. It now lives in **one** — `legal/ACCURACY.md`, embedded verbatim in §4 below and in `README.md`, and `tools/accuracy-check.ps1` fails the build when a copy differs from the source (`20_OPEN_QUESTIONS` §S23-6). The bullets below are the history of the four drifts and are kept as history; the block in §4 is the current statement, dated.
>
> **The fourth drift is the first one that ran the other way, and that is the finding.** Every previous re-count found this document claiming *more* than the software did. #64 landed the upscaler identity hook and this block went on saying "there is no upscaler hook anywhere in the software" — an under-claim, in the one file whose failure mode everybody was watching for in the opposite direction. It went unnoticed for five days for exactly that reason: a reviewer checking whether `legal/` over-promises reads a sentence like that and moves on. **Re-reading this block means checking both directions.**
>
> **The re-count was overdue and this block's own rule is what says so.** The last line of this block requires whoever changes what `FrameLedger.Overlay` does to re-read it. #48 changed exactly that — the Overlay now drops `DXGI_PRESENT_TEST` presents without recording them — and this block was not re-read. That is the second time the rule has been broken since it was written, and both breaches were invisible from inside the PR that caused them.
@@ -16,7 +18,7 @@
>
> - ~~§1's *"what it observes: … presentation, upscaling, ray tracing, pipeline creation"* and §4's *"upscaling, frame-generation and ray-tracing state are read from the parameters the game passes to those APIs"* — **only the presentation path is intercepted.** There is no upscaler hook, no frame-generation hook, no ray-tracing hook and no pipeline hook anywhere in the software.~~ **FALSE SINCE #64, corrected 2026-08-14 — the fourth drift, and this one is the block's own subject.** An **upscaler hook exists**: one detour on `sl.interposer.dll!slEvaluateFeature`, module-scoped, reading one argument. It measures **which upscaler is running** (DLSS, NIS, or `unknown` — never "none") and, for Streamline titles, **whether Ray Reconstruction is active**, which is a `Yes`/`No` the software now publishes. What still does not exist: quality preset, render resolution, frame generation, ray tracing, pipeline. The capture side states all of that in its own data on every frame rather than defaulting to "none", so nothing false is *recorded*; what over-promised was this document, in the direction of under-claiming rather than over-claiming — which is the safer direction and is still wrong. Both sentences are qualified where they sit.
> - §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 implemented**: an injected D3D title removes its hooks within one frame of the stop flag being set. The **sending half is still missing, and the missing part is narrower than this block used to say.** Both the write path (`ShmRingReader.PublishGuardResult`, which maps the shared memory and advances the field) and the read path exist in shipped code and are tested; what does not exist is a production caller that runs the loop between them. A missing loop, not a missing subsystem — and the user-facing consequence is identical: **no re-scan runs and no stop is ever sent.**
> - §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.
> - §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: for **Vulkan titles the check runs on each present rather than once a second** — the layer may not own a thread, so a Vulkan title that has stopped presenting is not stopped by the deadline (and presents nothing to be observed) — 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.
>
@@ -44,7 +46,7 @@ Install it somewhere only you can write to, and verify the published SHA-256 che
**What it observes:** arguments the game passes to graphics APIs we intercept (presentation, upscaling, ray tracing, pipeline creation) and video-memory usage reported by the graphics runtime.
> **Today that list is two items long: presentation and upscaling** — and the upscaling half is *identity only*. The software can say which upscaler is executing, and whether Ray Reconstruction is active alongside it; it cannot yet say at what quality preset or at what render resolution. No ray-tracing or pipeline hook exists yet, and video-memory usage is not read. The list describes what the software is designed to observe, and the boundary — API arguments and nothing else — holds for all of it. See the accuracy audit at the top.
> **What of that list is observed today is stated once, in §4 below** (the block `legal/ACCURACY.md` carries, dated). The list here describes what the software is designed to observe, and the boundary — API arguments and nothing else — holds for all of it.
**What it never does:** read or write the game's memory outside those API arguments; read save files, input, chat, or network traffic; modify game behavior; hide itself from any security software; or install a kernel driver of its own.
@@ -89,7 +91,40 @@ Software running inside another process can, in principle, destabilize it. Frame
Frame timing is derived from high-resolution timestamps taken at the moment the game presents each frame; upscaling, frame-generation and ray-tracing state are read from the parameters the game passes to those APIs. This is substantially more accurate than inferring settings from files on disk, but **no measurement is guaranteed to be exact**:
> **Frame timing is measured today, and so are two of the settings.** Which upscaler is executing, and whether Ray Reconstruction is running with it, are read from the arguments the game passes — for titles that go through Streamline. **The rest are not measured at all yet**: quality preset, render resolution, frame generation and ray tracing have no hook behind them. Where a value has not been measured the software marks it as unmeasured rather than reporting a zero, so it will read `N/A` and never a confident wrong answer — including for a title whose upscaler runs by a route this hook cannot see, which reports `unknown` rather than "none". See the accuracy audit at the top.
<!-- accuracy-block:begin -->
> ⚠ **What FrameLedger actually measures today — 2026-09-06.** The software is pre-alpha: the
> measurement path exists as an injected Direct3D 11/12 component and an **unshipped** capture
> host that drives the guard loop and prints a report; there is no Agent loop, no storage, no
> charts, no library import, no UI and no installer yet.
>
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
> labelled *driver-reported*. Intel XeSS is **not** read (its SDK licence forbids it) and reads
> `N/A` by policy; an upscaler compiled into the game executable reads `N/A`.
> - **Quality preset:** `N/A` everywhere. No route this software may use exposes it.
> - **Render → output resolution:** measured where the vendor's own call carries the size (AMD
> dispatches, some Streamline titles); `N/A` where it does not (NVIDIA-direct titles, most
> Direct3D 12 Streamline titles).
> - **Frame generation:** the Displayed rate is counted from presents — including, on one title,
> presents DXGI counted that the hook could not — and the Native rate from the vendor's own
> per-frame calls where the title makes them. Identity: DLSS-G and FSR-FG named from the calls
> the game makes; anything else (XeSS-FG, a generator compiled into the game) is reported *by
> elimination* and never named. Where no per-frame call exists the Native rate is `N/A`.
> - **Ray tracing:** Yes/No measured from DXR dispatches and acceleration-structure builds on
> Direct3D 12; the technique and path tracing are `N/A`.
> - **Not measured at all:** video memory, shader-compilation stutter, PC latency (Reflex), HDR.
> - **Safety:** every pre-injection check runs before injection, including the signed-by-a-known-
> vendor half of the suspicious-module rule (since 2026-09-06), and the unshipped capture host
> re-runs them every 30 s and stops the capture on refusal. No shipped component drives that loop
> yet. There is no override anywhere.
>
> Where a value is not measured it reads `N/A`; the software never substitutes an estimate.
<!-- accuracy-block:end -->
- Frame timing: typically better than 0.05% error; hardware sensors carry their own accuracy limits (±1–2 °C is normal).
- 1% Low and 0.1% Low are statistical and are hidden when the sample size is insufficient.
+6
View File
@@ -189,6 +189,12 @@
"19_SAFETY: name fragment AND not signed by a known vendor => warn-and-refuse.",
"",
"trustedSigners are matched against the certificate subject's O= field, NOT CN=.",
"",
"BOUNDED BY CODE (owner decision 2026-09-06, 20_OPEN_QUESTIONS S19(b)): the guard trusts an",
"organisation only if it is on THIS list AND on the list compiled into FrameLedger.Guard.dll",
"(IsCompiledTrustedSigner). Adding a name here that the binary does not know widens nothing;",
"widening is a reviewed code change. Removing a name here narrows, which data may do.",
"",
"Measured 2026-08-02 on Windows 11 26300, and the two fields genuinely differ:",
" kernel32.dll CN='Microsoft Windows' O='Microsoft Corporation'",
" nvapi64.dll CN='Microsoft Windows Hardware Compatibility Publisher' O='Microsoft Corporation'",
@@ -31,15 +31,27 @@ namespace FrameLedger.Application.AntiCheat;
public sealed class HookRequest
{
private HookRequest(int targetPid, string payloadPath, bool hookEnabled, DateTimeOffset? consentedAt,
string? blockedReason)
string? blockedReason, int waitForPresentationRuntimeMs)
{
TargetPid = targetPid;
PayloadPath = payloadPath;
HookEnabled = hookEnabled;
ConsentedAt = consentedAt;
BlockedReason = blockedReason;
WaitForPresentationRuntimeMs = waitForPresentationRuntimeMs;
}
/// <summary>
/// Launch mode's budget: how long the guard may wait for the target to map a presentation runtime
/// before injecting. Zero — the default, and attach mode — asks the guard to inject now.
/// </summary>
/// <remarks>
/// It cannot widen what is injected or skip a check: a positive value routes the request through
/// <see cref="IAntiCheatGuard.GuardedInjectWhenReadyAsync"/>, which runs the same full scan later
/// rather than a smaller one sooner.
/// </remarks>
public int WaitForPresentationRuntimeMs { get; }
/// <summary>The process to inject into.</summary>
public int TargetPid { get; }
@@ -75,17 +87,20 @@ public sealed class HookRequest
/// <param name="observed">The executable as it is on disk right now.</param>
/// <param name="targetPid">The process to inject into.</param>
/// <param name="payloadPath">The Overlay, resolved beside the guard (§S22).</param>
/// <param name="waitForPresentationRuntimeMs">Launch mode's budget; zero is attach mode.</param>
public static HookRequest FromConsent(
GameConsentRecord record, ExecutableFingerprint observed, int targetPid, string payloadPath)
GameConsentRecord record, ExecutableFingerprint observed, int targetPid, string payloadPath,
int waitForPresentationRuntimeMs = 0)
{
ArgumentException.ThrowIfNullOrWhiteSpace(payloadPath);
ArgumentOutOfRangeException.ThrowIfNegative(waitForPresentationRuntimeMs);
// A record nobody stored has enabled nothing and consented to nothing. Checked first so the
// fields below are never read off a default value.
if (!record.IsFromStore)
{
return new HookRequest(targetPid, payloadPath, hookEnabled: false, consentedAt: null,
blockedReason: null);
blockedReason: null, waitForPresentationRuntimeMs);
}
// A TIMESTAMP IS NOT CONSENT. games.hook_consent_at is a bare DateTime, so a record could carry
@@ -106,6 +121,7 @@ public sealed class HookRequest
consentedAt = null;
}
return new HookRequest(targetPid, payloadPath, record.HookEnabled, consentedAt, record.BlockedReason);
return new HookRequest(targetPid, payloadPath, record.HookEnabled, consentedAt, record.BlockedReason,
waitForPresentationRuntimeMs);
}
}
@@ -76,6 +76,11 @@ public sealed class HookedCaptureGate(IAntiCheatGuard guard)
return AntiCheatVerdict.Refused(AntiCheatRefusalReason.PreviouslyBlocked, "previously blocked", blocked);
}
return await _guard.GuardedInjectAsync(request.TargetPid, request.PayloadPath, ct).ConfigureAwait(false);
// Launch mode is the same gate reached through the guard's WAITING entry: the consent checks
// above are identical, and what differs is only WHEN the guard's full scan runs (P1 item 2).
return request.WaitForPresentationRuntimeMs > 0
? await _guard.GuardedInjectWhenReadyAsync(request.TargetPid, request.PayloadPath,
request.WaitForPresentationRuntimeMs, ct).ConfigureAwait(false)
: await _guard.GuardedInjectAsync(request.TargetPid, request.PayloadPath, ct).ConfigureAwait(false);
}
}
@@ -36,6 +36,23 @@ public interface IAntiCheatGuard
/// </summary>
ValueTask<AntiCheatVerdict> GuardedInjectAsync(int targetPid, string payloadPath, CancellationToken ct = default);
/// <summary>
/// Launch mode (P1 item 2). Wait — up to <paramref name="timeoutMs"/> — until the target has mapped a
/// presentation runtime, then run every check and inject exactly as <see cref="GuardedInjectAsync"/>
/// does. The wait decides WHEN the guard runs and nothing about whether it passes.
/// </summary>
/// <remarks>
/// <c>20_OPEN_QUESTIONS</c> §S1: a target held at its first instruction has loaded nothing, so the
/// module scan cannot run before the loader has. The guard therefore polls the loader's own answer
/// (through the module seam, matching no blocklist) and runs in full the moment a runtime is there. A
/// target that exits first, or never maps one, refuses with
/// <see cref="AntiCheatRefusalReason.LaunchTargetExited"/> /
/// <see cref="AntiCheatRefusalReason.LaunchNoPresentationRuntime"/>. The caller launched and holds
/// the process; the guard creates and terminates nothing.
/// </remarks>
ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath, int timeoutMs,
CancellationToken ct = default);
/// <summary>
/// Check 4 asked before anything is launched: does this game directory ship
/// anti-cheat? Answers FR-2.2's question — whether the hooking toggle may be
@@ -1,3 +1,4 @@
using System.Diagnostics;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Consent;
using FrameLedger.CaptureHost.Consume;
@@ -31,7 +32,8 @@ internal sealed class CaptureLoop(
Func<int, (ICaptureSink? Sink, ShmAttachRefusal Refusal)> attach,
CaptureOptions options,
Func<int, RuntimeModuleSet>? modules = null,
Func<int, NgxDriverState>? ngx = null)
Func<int, NgxDriverState>? ngx = null,
Func<string, string, (int Pid, ITargetLiveness Alive)?>? launcher = null)
{
/// <summary>Start one session, or say why not.</summary>
/// <remarks>
@@ -84,24 +86,90 @@ internal sealed class CaptureLoop(
}
GameConsentRecord record = await store.FindAsync(normalisedExePath, ct).ConfigureAwait(false);
if (ConsentRefusal(record, observed) is SessionEndReason refused)
{
return new CaptureResult { Reason = refused };
}
return await SessionAsync(pid.Value, alive, record, observed!.Value, payloadPath, started: null, ct)
.ConfigureAwait(false);
}
/// <summary>Launch mode (P1 item 2): start the consented executable, then the same session.</summary>
/// <remarks>
/// <para>
/// <b>The process is started FIRST and consent is still the gate's, one process later.</b> Attach mode
/// resolves a pid before consent because a <see cref="HookRequest"/> needs one; here the pid is made
/// rather than found, and the operator asked for the game to start. A refusal of any kind — no
/// record, an anti-cheat hit, no runtime inside the budget — leaves the title running, unhooked,
/// which is the product's Tier 2: this host never terminates what it launched.
/// </para>
/// <para>
/// <b>The guard is reached through its waiting entry, with the loop's budget, and never the plain
/// one</b>: <see cref="HookRequest.WaitForPresentationRuntimeMs"/> is what routes it, and the wait is
/// measured here — from the start of the process to the guard's answer — because that number is
/// the cost <c>20_OPEN_QUESTIONS</c> §S1 deferred on. <c>FlWriterState.dxgiPresentsBeforeHook</c>
/// is its other half.
/// </para>
/// </remarks>
public async Task<CaptureResult> RunLaunchedAsync(string normalisedExePath, ExecutableFingerprint? observed,
string payloadPath, string arguments, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(normalisedExePath);
if (launcher is null)
{
throw new InvalidOperationException("this loop was built without a launcher; launch mode is unavailable");
}
var started = Stopwatch.StartNew();
(int Pid, ITargetLiveness Alive)? launched = launcher(normalisedExePath, arguments ?? string.Empty);
if (launched is null)
{
return new CaptureResult { Reason = SessionEndReason.LaunchCannotStart };
}
using ITargetLiveness alive = launched.Value.Alive;
GameConsentRecord record = await store.FindAsync(normalisedExePath, ct).ConfigureAwait(false);
if (ConsentRefusal(record, observed) is SessionEndReason refused)
{
return new CaptureResult { Reason = refused };
}
return await SessionAsync(launched.Value.Pid, alive, record, observed!.Value, payloadPath, started, ct)
.ConfigureAwait(false);
}
/// <summary>The two refusals the loop makes itself, before the gate (see <see cref="RunAsync"/>'s remarks).</summary>
private static SessionEndReason? ConsentRefusal(GameConsentRecord record, ExecutableFingerprint? observed)
{
if (record.PreScanUnverified)
{
return new CaptureResult { Reason = SessionEndReason.PreScanCouldNotVerify };
return SessionEndReason.PreScanCouldNotVerify;
}
if (observed is null)
{
return new CaptureResult { Reason = SessionEndReason.ExecutableUnreadable };
}
return observed is null ? SessionEndReason.ExecutableUnreadable : null;
}
HookRequest request = HookRequest.FromConsent(record, observed.Value, pid.Value, payloadPath);
/// <summary>Gate, attach, drain — shared by both modes; <paramref name="started"/> non-null is launch mode.</summary>
private async Task<CaptureResult> SessionAsync(int pid, ITargetLiveness alive, GameConsentRecord record,
ExecutableFingerprint observed, string payloadPath, Stopwatch? started, CancellationToken ct)
{
int waitMs = started is null ? 0 : checked((int)options.LaunchWaitBudget.TotalMilliseconds);
HookRequest request = HookRequest.FromConsent(record, observed, pid, payloadPath, waitMs);
AntiCheatVerdict verdict = await gate.StartAsync(request, ct).ConfigureAwait(false);
if (!verdict.IsAllowed)
TimeSpan? launchWait = started?.Elapsed;
// THE ONE VERDICT THAT IS NEITHER: the guard passed and injected nothing because the target
// presents through Vulkan, where the implicit layer is the capture side (P1 item 3). The ring
// to attach to is the layer's, and it appears at the title's first vkCreateDevice -- which is
// why the attach budget is launch mode's, not the 5 s an already-injected Overlay gets.
bool layered = verdict.Reason == AntiCheatRefusalReason.TargetIsVulkanLayered;
if (!verdict.IsAllowed && !layered)
{
return new CaptureResult { Reason = RefusalOf(verdict.Reason), Verdict = verdict };
return new CaptureResult { Reason = RefusalOf(verdict.Reason), Verdict = verdict, LaunchWait = launchWait };
}
(ICaptureSink? sink, ShmAttachRefusal refusal) = await AttachAsync(pid.Value, ct).ConfigureAwait(false);
TimeSpan attachBudget = layered ? options.LaunchWaitBudget : options.AttachBudget;
(ICaptureSink? sink, ShmAttachRefusal refusal) = await AttachAsync(pid, attachBudget, ct).ConfigureAwait(false);
if (sink is null)
{
return new CaptureResult
@@ -109,12 +177,14 @@ internal sealed class CaptureLoop(
Reason = SessionEndReason.AttachRefused,
Verdict = verdict,
AttachRefusal = refusal,
LaunchWait = launchWait,
};
}
using (sink)
{
return await DrainAsync(pid.Value, alive, sink, verdict, ct).ConfigureAwait(false);
CaptureResult result = await DrainAsync(pid, alive, sink, verdict, ct).ConfigureAwait(false);
return result with { LaunchWait = launchWait };
}
}
@@ -123,6 +193,8 @@ internal sealed class CaptureLoop(
AntiCheatRefusalReason.HookNotEnabled => SessionEndReason.RefusedHookNotEnabled,
AntiCheatRefusalReason.ConsentMissing => SessionEndReason.RefusedConsentMissing,
AntiCheatRefusalReason.PreviouslyBlocked => SessionEndReason.RefusedPreviouslyBlocked,
AntiCheatRefusalReason.LaunchTargetExited => SessionEndReason.LaunchTargetExited,
AntiCheatRefusalReason.LaunchNoPresentationRuntime => SessionEndReason.LaunchNoPresentationRuntime,
_ => SessionEndReason.RefusedByGuard,
};
@@ -136,10 +208,11 @@ internal sealed class CaptureLoop(
/// middle one is transient. Every other refusal is terminal, and retrying one
/// would turn a clear answer into a timeout.
/// </remarks>
private async Task<(ICaptureSink? Sink, ShmAttachRefusal Refusal)> AttachAsync(int pid, CancellationToken ct)
private async Task<(ICaptureSink? Sink, ShmAttachRefusal Refusal)> AttachAsync(int pid, TimeSpan budget,
CancellationToken ct)
{
ShmAttachRefusal refusal = ShmAttachRefusal.NotEvaluated;
DateTimeOffset deadline = DateTimeOffset.UtcNow + options.AttachBudget;
DateTimeOffset deadline = DateTimeOffset.UtcNow + budget;
while (DateTimeOffset.UtcNow < deadline)
{
(ICaptureSink? sink, refusal) = attach(pid);
@@ -14,4 +14,11 @@ internal sealed record CaptureOptions
/// <summary>Zero means "until the target exits".</summary>
public TimeSpan MaxDuration { get; init; } = TimeSpan.Zero;
/// <summary>
/// Launch mode: how long the guard may wait for the launched target to map a presentation runtime
/// before it gives up with <c>LaunchNoPresentationRuntime</c>. A launcher that sits on its window
/// past this is a launcher, and the descendant election is the Agent's (P2).
/// </summary>
public TimeSpan LaunchWaitBudget { get; init; } = TimeSpan.FromSeconds(60);
}
@@ -65,4 +65,10 @@ internal sealed record CaptureResult
/// frame stream can be checked against what FrameLedger itself was doing at that moment.
/// </summary>
public IReadOnlyList<long> TouchQpc { get; init; } = [];
/// <summary>
/// Launch mode only: from the process being started to the guard's answer — the wait for a
/// presentation runtime plus the full scan and the injection. Null in attach mode.
/// </summary>
public TimeSpan? LaunchWait { get; init; }
}
@@ -0,0 +1,117 @@
using System.Text;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>
/// Streams the executable file from disk once and counts the vendor SDK strings in it.
/// </summary>
/// <remarks>
/// Chunked with an overlap of the longest marker, so a string straddling two reads is still one hit — a test
/// pins that with a tiny chunk. ASCII, case-sensitive: these are symbol prefixes and product names as the
/// SDKs spell them. Per-marker hits are capped so a file that repeats a string cannot make the scan slow to
/// describe. Every failure is an <see cref="ExecutableMarkers.Error"/>, never a throw into the loop.
/// </remarks>
internal static class ExecutableMarkerScan
{
private const int _defaultChunkBytes = 4 * 1024 * 1024;
private const int _hitCap = 1000;
/// <summary>
/// The strings, what they belong to, and whether that SDK can generate frames. Only the last column moves the
/// census's sentence; the rest are printed for the reader.
/// </summary>
private static readonly (string Name, string Vendor, bool FgCapable)[] _table =
[
("FidelityFX", "AMD FidelityFX", false),
("ffxFsr2", "AMD FSR 2 API", false),
("ffxFsr3", "AMD FSR 3 API (upscaler and frame interpolation)", true),
("ffxFrameInterpolation", "AMD FSR 3 frame interpolation", true),
("NVSDK_NGX", "NVIDIA NGX SDK (the static half; DLSS-G still needs nvngx_dlssg.dll)", false),
("xessD3D12", "Intel XeSS SDK", false),
("xefgSwapChain", "Intel XeSS-FG SDK", true),
];
public static ExecutableMarkers Scan(string exePath) => Scan(exePath, _defaultChunkBytes);
public static ExecutableMarkers Scan(string exePath, int chunkBytes)
{
ArgumentOutOfRangeException.ThrowIfLessThan(chunkBytes, 64);
int[] hits = new int[_table.Length];
byte[][] needles = [.. _table.Select(t => Encoding.ASCII.GetBytes(t.Name))];
int overlap = needles.Max(n => n.Length) - 1;
long scanned;
try
{
scanned = ScanFile(exePath, chunkBytes, needles, overlap, hits);
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException)
{
return new ExecutableMarkers([], 0, e.Message);
}
List<ExecutableMarker> markers = [];
for (int i = 0; i < _table.Length; i++)
{
markers.Add(new ExecutableMarker(_table[i].Name, _table[i].Vendor, _table[i].FgCapable, hits[i]));
}
return new ExecutableMarkers(markers, scanned, null);
}
private static long ScanFile(string exePath, int chunkBytes, byte[][] needles, int overlap, int[] hits)
{
using FileStream f = new(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
byte[] buffer = new byte[overlap + chunkBytes];
int carried = 0;
long scanned = 0;
while (true)
{
int read = f.Read(buffer, carried, chunkBytes);
if (read == 0)
{
break;
}
scanned += read;
int length = carried + read;
CountIn(buffer.AsSpan(0, length), needles, hits, carried);
// Carry the tail so a marker split across two reads is seen once, on the next pass.
carried = Math.Min(overlap, length);
Buffer.BlockCopy(buffer, length - carried, buffer, 0, carried);
}
return scanned;
}
/// <summary>
/// Count each needle in <paramref name="window"/>. A hit is counted only if it does not lie wholly inside
/// the carried prefix (<paramref name="carried"/> bytes), which the previous pass already counted.
/// </summary>
private static void CountIn(ReadOnlySpan<byte> window, byte[][] needles, int[] hits, int carried)
{
for (int n = 0; n < needles.Length; n++)
{
ReadOnlySpan<byte> needle = needles[n];
int at = 0;
while (hits[n] < _hitCap)
{
int found = window[at..].IndexOf(needle);
if (found < 0)
{
break;
}
int start = at + found;
if (start + needle.Length > carried)
{
hits[n]++;
}
at = start + 1;
}
}
}
}
@@ -0,0 +1,87 @@
using System.ComponentModel;
using System.Diagnostics;
using FrameLedger.Infrastructure.Io;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>
/// Launch mode's first step: start the consented executable and hold it from birth.
/// </summary>
/// <remarks>
/// <para>
/// <b>Not <c>CREATE_SUSPENDED</c>, and the spec's sentence is why.</b> <c>04_CAPTURE</c> §Launch mode
/// wrote <i>create suspended → guard → inject → resume</i>, and <c>20_OPEN_QUESTIONS</c> §S1 measured
/// that a suspended target has loaded nothing: <c>EnumProcessModulesEx</c> fails against it, so the guard
/// cannot run before the loader has. The built shape is <i>create → guard WAITS for a presentation
/// runtime → inject</i> (<c>FlGuardedInjectWhenReady</c>), and nothing in it needs the process held at
/// its first instruction. What the launch buys instead: the pid is ours before any code runs, the handle
/// is held from the start so it cannot recycle under us (§S29(e)), and the Vulkan layer's
/// <c>enable_environment</c> is set — which only the launching process can do (<c>17_HOOK_ENGINE</c>
/// §Vulkan). The layer still gates on its own enabled-list; the variable alone enables nothing.
/// </para>
/// <para>
/// <b>This host never terminates what it launched.</b> A refusal after the launch — no consent, an
/// anti-cheat hit, no runtime inside the budget — leaves the title running unhooked, exactly as the
/// product's Tier 2 does (duration and the reason, no measurement). The operator asked for the game to
/// start; the guard decides only whether FrameLedger goes into it.
/// </para>
/// </remarks>
internal static class ProcessLauncher
{
/// <summary>The Vulkan loader's enable variable for <c>VK_LAYER_FRAMELEDGER_overlay</c> (<c>17_HOOK_ENGINE</c> §Vulkan).</summary>
public const string VulkanLayerEnableVariable = "FRAMELEDGER_ENABLE_VK_LAYER";
/// <summary>Start <paramref name="exePath"/> with <paramref name="arguments"/>; null when it could not be started or pinned.</summary>
/// <param name="exePath">The consented executable.</param>
/// <param name="arguments">Its own command line, verbatim.</param>
/// <param name="environment">
/// Variables added to the child's environment — the Vulkan layer's, from
/// <c>VkLayerLaunchEnvironment</c>, when the layer is staged beside this host (P1 item 3).
/// </param>
public static (int Pid, ITargetLiveness Alive)? Start(string exePath, string arguments,
IReadOnlyDictionary<string, string>? environment = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(exePath);
var psi = new ProcessStartInfo(exePath, arguments ?? string.Empty)
{
UseShellExecute = false,
WorkingDirectory = Path.GetDirectoryName(exePath) ?? string.Empty,
};
psi.Environment[VulkanLayerEnableVariable] = "1";
foreach ((string name, string value) in environment ?? new Dictionary<string, string>(StringComparer.Ordinal))
{
psi.Environment[name] = value;
}
Process? process;
try
{
process = Process.Start(psi);
}
catch (Exception e) when (e is Win32Exception or InvalidOperationException or IOException)
{
return null;
}
if (process is null)
{
return null;
}
using (process)
{
// The same pin attach mode takes, taken here before anything else looks at the pid. The
// liveness OWNS the handle from here; the caller disposes it with the session (CA2000 is
// satisfied by that transfer, stated rather than suppressed).
HeldProcessHandle? held = HeldProcessHandle.TryOpen(process.Id);
if (held is null)
{
return null;
}
ITargetLiveness alive = new ProcessTargetLiveness(held, process.Id);
return (process.Id, alive);
}
}
}
@@ -56,6 +56,7 @@ internal static class SessionEndClassifier
{
FlStatus.Unhooked => weLatchedTheUnhook ? SessionEndReason.SafetyUnhook : SessionEndReason.SupervisionLost,
FlStatus.SelfDisabled => SessionEndReason.WriterSelfDisabled,
FlStatus.StoppedBlocklisted => SessionEndReason.WriterStoppedBlocklisted,
FlStatus.Init when attachSettled => SessionEndReason.WriterNeverInstalledHooks,
_ => SessionEndReason.Running,
};
@@ -32,6 +32,14 @@ internal enum SessionEndReason
/// <summary>Three hook faults; the Overlay went dormant on its own.</summary>
WriterSelfDisabled,
/// <summary>
/// The Overlay's <c>LoadLibrary</c> detour saw a module the compiled anti-cheat floor
/// names arrive mid-session and stopped the Overlay from inside, before this host's
/// 30 s scan could (<c>19_SAFETY</c> §During a session, the in-process half; §S6).
/// <c>FlWriterState.EarlyStopFamily</c> names which family.
/// </summary>
WriterStoppedBlocklisted,
/// <summary>
/// The handshake was published and <c>status</c> never left <c>INIT</c>, which
/// means MinHook failed: the ring will never move.
@@ -99,4 +107,19 @@ internal enum SessionEndReason
/// <summary>The ring could not be attached to, and the refusal was not retryable.</summary>
AttachRefused,
/// <summary>Launch mode: the executable could not be started, or the new process could not be pinned.</summary>
LaunchCannotStart,
/// <summary>
/// Launch mode: the guard was waiting for a presentation runtime and the target exited first
/// (<see cref="Domain.AntiCheat.AntiCheatRefusalReason.LaunchTargetExited"/>). Nothing was injected.
/// </summary>
LaunchTargetExited,
/// <summary>
/// Launch mode: the budget ran out with no presentation runtime mapped
/// (<see cref="Domain.AntiCheat.AntiCheatRefusalReason.LaunchNoPresentationRuntime"/>). Nothing was injected.
/// </summary>
LaunchNoPresentationRuntime,
}
+19 -3
View File
@@ -22,7 +22,7 @@ namespace FrameLedger.CaptureHost;
internal sealed record CommandLine
{
/// <summary>Every option this host accepts. A test pins it.</summary>
public static readonly string[] AcceptedOptions = ["--exe", "--seconds"];
public static readonly string[] AcceptedOptions = ["--exe", "--seconds", "--args"];
public Verb Verb { get; init; }
@@ -48,6 +48,16 @@ internal sealed record CommandLine
/// </remarks>
public int Seconds { get; init; }
/// <summary>
/// The command line handed to the executable <c>launch</c> starts, verbatim. Empty by default.
/// </summary>
/// <remarks>
/// It names nothing about injection: the payload is still the Overlay beside this binary, the target
/// is still the consented executable, and the guard still collects its own evidence. What it changes
/// is what the GAME sees, which is the operator's business and not this host's.
/// </remarks>
public string Arguments { get; init; } = string.Empty;
public string? Error { get; init; }
public static CommandLine Parse(string[] args)
@@ -58,11 +68,12 @@ internal sealed record CommandLine
if (verb == Verb.None)
{
return new CommandLine { Error = "usage: consent list | consent grant --exe <path> | consent revoke --exe <path> | capture --exe <path> [--seconds <n>] | probe-lhm [--seconds <n>]" };
return new CommandLine { Error = "usage: consent list | consent grant --exe <path> | consent revoke --exe <path> | capture --exe <path> [--seconds <n>] | launch --exe <path> [--args \"<string>\"] [--seconds <n>] | probe-lhm [--seconds <n>]" };
}
string? exe = null;
int seconds = 0;
string arguments = string.Empty;
for (int i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("--", StringComparison.Ordinal))
@@ -91,6 +102,10 @@ internal sealed record CommandLine
return new CommandLine { Error = "'--seconds' needs a positive whole number" };
}
}
else if (string.Equals(option, "--args", StringComparison.Ordinal))
{
arguments = value;
}
else
{
exe = value;
@@ -105,7 +120,7 @@ internal sealed record CommandLine
return new CommandLine { Error = "--exe <path> is required" };
}
return new CommandLine { Verb = verb, ExePath = exe, Seconds = seconds };
return new CommandLine { Verb = verb, ExePath = exe, Seconds = seconds, Arguments = arguments };
}
private static Verb VerbOf(string[] args) => args switch
@@ -114,6 +129,7 @@ internal sealed record CommandLine
["consent", "grant", ..] => Verb.ConsentGrant,
["consent", "revoke", ..] => Verb.ConsentRevoke,
["capture", ..] => Verb.Capture,
["launch", ..] => Verb.Launch,
["probe-lhm", ..] => Verb.ProbeLhm,
_ => Verb.None,
};
@@ -0,0 +1,83 @@
using System.Globalization;
using System.Text.Json;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The Overlay's <c>LoadLibrary</c> detour, as the report reads it: whether the detour is in, how often it woke
/// the watchdog for a module the inventory or census names, and — when the Overlay stopped itself — which
/// anti-cheat family the module that arrived matched (<c>fl_shm.h</c> §loaderSignals / earlyStopFamily,
/// <c>19_SAFETY</c> §During a session, the in-process half; §S6).
/// </summary>
internal static class EarlyStop
{
private const ushort _installedBit = 0x8000;
private const ushort _countMask = 0x7FFF;
/// <summary>The seed rules file staged beside this host (<c>FrameLedger.Rules.targets</c>).</summary>
public static string StagedRulesPath => Path.Combine(AppContext.BaseDirectory, "rules", "detection-rules.json");
/// <summary>
/// The family name behind a 1-based index into <c>anticheat.modules</c> of the rules file — the same order
/// <c>gen-ac-floor.ps1</c> emits the compiled floor's MODULE families in, which is what the Overlay indexes.
/// Null when the file cannot be read or the index is outside it; never a guess.
/// </summary>
public static string? FamilyName(int index, string rulesPath)
{
if (index <= 0)
{
return null;
}
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(rulesPath));
if (!doc.RootElement.TryGetProperty("anticheat", out JsonElement anticheat)
|| !anticheat.TryGetProperty("modules", out JsonElement modules)
|| modules.ValueKind != JsonValueKind.Array)
{
return null;
}
int i = 0;
foreach (JsonElement family in modules.EnumerateArray())
{
if (++i == index)
{
return family.TryGetProperty("family", out JsonElement name) ? name.GetString() : null;
}
}
return null;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
{
return null;
}
}
/// <summary>The report's two lines: the detour's state always, the stop only when it happened.</summary>
public static IEnumerable<string> Describe(FlWriterState writer, string rulesPath)
{
bool installed = (writer.LoaderSignals & _installedBit) != 0;
int wakes = writer.LoaderSignals & _countMask;
yield return installed
? $" loader detour: installed (kernelbase!LoadLibraryExW); woke the watchdog {wakes.ToString(CultureInfo.InvariantCulture)} time(s) for a module the inventory or census names"
: " loader detour: NOT installed - late vendor modules wait for the 1 Hz tick, and the in-process anti-cheat stop is absent; the host's 30 s scan is the only stop";
if (writer.EarlyStopFamily == 0)
{
yield break;
}
string? name = FamilyName(writer.EarlyStopFamily, rulesPath);
yield return " EARLY STOP: the Overlay stopped ITSELF - a module matching anti-cheat family #"
+ writer.EarlyStopFamily.ToString(CultureInfo.InvariantCulture)
+ (name is null ? " (name not resolvable from the staged rules file)" : $" ({name})")
+ " loaded mid-session (19_SAFETY §During a session, the in-process half); status="
+ ((FlStatus)writer.Status).ToString()
+ ". This is the exact-name floor only; the fragment-and-signer tier is the host's scan";
}
}
@@ -0,0 +1,13 @@
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// One vendor marker looked for in the executable FILE on disk, and how many times it occurred.
/// </summary>
/// <param name="Name">The ASCII string searched for, case-sensitive — an API symbol prefix or a product name.</param>
/// <param name="Vendor">What the string belongs to, for the report.</param>
/// <param name="FgCapable">
/// True when the SDK the marker belongs to can generate frames — the only markers that move the
/// census's "cannot include generated frames" sentence to "MAY".
/// </param>
/// <param name="Hits">Occurrences in the file, capped; 0 means absent.</param>
internal sealed record ExecutableMarker(string Name, string Vendor, bool FgCapable, int Hits);
@@ -0,0 +1,65 @@
using System.Globalization;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// What the executable FILE carries of the vendor SDKs — read from disk, the way the fingerprint reads its size
/// and mtime, never from the process (CLAUDE.md rule 4 is about game memory; this is the file the user pointed at).
/// </summary>
/// <remarks>
/// <para>
/// <b>Why it exists (<c>HANDOFF</c> 7b, 2026-09-06).</b> A title with FSR 3 compiled into its executable loads
/// no vendor module, so the runtime census is empty and the Presented qualifier said *"this number cannot
/// include in-process generated frames"* — wrong in the dangerous direction, on a shape measured twice (Rune
/// Factory, Wukong). A marker in the file says the SDK's code or its symbol names are IN the executable. It does
/// not say the code ran: the qualifier moves from *cannot* to *MAY*, never to an identity.
/// </para>
/// <para>
/// <b>A marker is not identity, and a shipped-DLL title can carry the same strings</b> (a UE plugin's exe
/// references its plugin by name). So this is consulted only where the module census has nothing to say.
/// </para>
/// </remarks>
internal sealed record ExecutableMarkers(IReadOnlyList<ExecutableMarker> Markers, long BytesScanned, string? Error)
{
/// <summary>The loop was run without a scan.</summary>
public static readonly ExecutableMarkers NotScanned = new([], 0, null);
public bool Scanned => Error is null && BytesScanned > 0;
/// <summary>Markers found at least once.</summary>
public IEnumerable<ExecutableMarker> Present => Markers.Where(m => m.Hits > 0);
/// <summary>Markers found that belong to an SDK able to generate frames.</summary>
public IEnumerable<ExecutableMarker> FgCapablePresent => Present.Where(m => m.FgCapable);
public bool AnyFgCapable => FgCapablePresent.Any();
/// <summary>The names of the frame-generation-capable markers found, for a sentence.</summary>
public string FgCapableNames => string.Join(", ", FgCapablePresent.Select(m => m.Name));
/// <summary>The report's line: what was found, or why nothing was looked at.</summary>
public string Describe()
{
const string head = " executable markers (the exe FILE on disk, vendor SDK strings; presence is not identity): ";
if (Error is not null)
{
return head + "not scanned - " + Error;
}
if (BytesScanned == 0)
{
return head + "not scanned";
}
string size = (BytesScanned / (1024.0 * 1024.0)).ToString("0.0", CultureInfo.InvariantCulture);
List<ExecutableMarker> present = [.. Present];
if (present.Count == 0)
{
return head + $"none of {Markers.Count} marker(s) in {size} MB";
}
string list = string.Join(", ", present.Select(m =>
$"{m.Name} x{m.Hits.ToString(CultureInfo.InvariantCulture)} ({m.Vendor}{(m.FgCapable ? ", can generate frames" : "")})"));
return head + $"{list} in {size} MB";
}
}
@@ -0,0 +1,29 @@
using System.Globalization;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// Launch mode's cost, as the report reads it: how long the guard waited before it injected, and how many
/// presents DXGI had already counted on the first hooked chain when the hook saw its first one — the number
/// <c>20_OPEN_QUESTIONS</c> §S1 said nobody had.
/// </summary>
internal static class LaunchNote
{
/// <summary>One line when the session was launched, and one line always.</summary>
public static IEnumerable<string> Describe(TimeSpan? launchWait, FlWriterState writer)
{
if (launchWait is TimeSpan wait)
{
yield return " launch: the guard injected "
+ ((long)wait.TotalMilliseconds).ToString(CultureInfo.InvariantCulture)
+ " ms after the process was started (it waited for a presentation runtime to map, then ran every check)";
}
yield return writer.DxgiPresentsBeforeHook == FlWriterState.DxgiPresentsBeforeHookNotRead
? " presents before the first hooked present: not read (the hook saw no present)"
: " presents before the first hooked present: "
+ writer.DxgiPresentsBeforeHook.ToString(CultureInfo.InvariantCulture)
+ " (DXGI's count on the first hooked chain; 0 means nothing ran unhooked on it -- §S1's number)";
}
}
@@ -213,6 +213,9 @@ internal sealed record MeasuredFacts
/// </remarks>
public string? UpscalerDriverReported => Upscaler is null && NgxDriver.SrCreatedAndEvaluated ? UpscalerDlssDriverReported : null;
/// <summary>What the executable FILE carries of the vendor SDKs; <see cref="ExecutableMarkers.NotScanned"/> without a scan.</summary>
public ExecutableMarkers Markers { get; init; } = ExecutableMarkers.NotScanned;
/// <summary>The string <see cref="FgMode"/> carries when the count is active, no tag named the technology, and the driver did.</summary>
public const string FgDlssGDriverReported =
"DlssG (driver-reported: the NVIDIA driver reports an NGX frame-generation feature created and evaluated in this "
@@ -223,10 +226,69 @@ internal sealed record MeasuredFacts
/// where the count is active and no tag named the technology (<c>03_METRICS</c>: identity decides the name, the
/// count decides <c>none</c> — the driver's word is a second identity source, never a count).
/// </summary>
public string? FgModePrinted =>
string.Equals(FgMode, FgActiveUnidentified, StringComparison.Ordinal) && NgxDriver.FgCreatedAndEvaluated
? FgDlssGDriverReported
: FgMode;
public string? FgModePrinted
{
get
{
if (!string.Equals(FgMode, FgActiveUnidentified, StringComparison.Ordinal))
{
return FgMode;
}
return NgxDriver.FgCreatedAndEvaluated ? FgDlssGDriverReported : FgActiveUnidentified + " — " + FgByElimination();
}
}
/// <summary>
/// The rung-3 line with every exclusion this session can make written beside it — never a vendor named as
/// measured. <c>HANDOFF</c> 7b / §H11, 2026-09-06: a frame generator this build cannot see (XeFG by licence, a
/// compiled-in FSR 3 by construction) still leaves witnesses — the driver's FG word, the tags, the ffx census,
/// the module census and the executable's own strings — and the reader gets all of them, labelled.
/// </summary>
private string FgByElimination() => "by elimination among what this session saw: " + FgWitnesses();
/// <summary>
/// The FG line when a hook ran and no evaluation was counted — the N/A, with the same witnesses beside it
/// (Hell Is Us at XeSS + XeSS-FG, 2026-09-06: no Streamline token on that plugin version, so no count, while
/// the driver, the tags, the ffx census, the module census and the file all still had something to say).
/// </summary>
public string FgNotEvaluatedPrinted =>
"N/A (a hook ran and saw no frame-generation evaluation — see the FG counts above); what this session can "
+ "still say: " + FgWitnesses();
/// <summary>
/// The clauses every FG line without a measured vendor carries: the driver's FG word and the tags against
/// DLSS-G, the ffx census against a shipped-DLL FSR-FG, the module census, and the executable's strings.
/// </summary>
private string FgWitnesses()
{
string tags = DlssgInputsTagged
? "HUD-less / UI tags WERE sent through Streamline"
: "no HUD-less / UI tag was sent through Streamline";
string dlssg = NgxDriver.Outcome == NgxProbeOutcome.Answered
? "not DLSS-G (the NVIDIA driver reports no NGX frame-generation feature created, and " + tags + ")"
: "DLSS-G not excluded (the NVIDIA driver did not answer; " + tags + ")";
string runtimes = FgRuntimesLoaded == FlRuntimeCensus.None
? "no frame-generation runtime module is loaded at all"
: "the frame-generation runtime(s) loaded: " + CensusNames.Describe(FgRuntimesLoaded);
string exe = Markers.AnyFgCapable
? "; the executable itself carries " + Markers.FgCapableNames
: "";
return dlssg + "; no FSR frame-generation dispatch reached a hooked module; " + runtimes + exe
+ " — a frame generator compiled into the executable would read the same, and nothing here is a "
+ "measured vendor identity";
}
/// <summary>
/// <c>HANDOFF</c> 7c item 4, the string change it asked for: an XeSS session reads <c>N/A</c> here by policy.
/// Null unless no hook and no driver named the upscaler and <c>libxess.dll</c> is in the census.
/// </summary>
public string? XessByLicenceNote =>
Upscaler is null && UpscalerDriverReported is null && RuntimeCensus.HasFlag(FlRuntimeCensus.LibXess)
? "libxess.dll is loaded, and XeSS cannot be hooked or declared under Intel's licence (18_GPU_VENDOR_APIS "
+ "§Intel), so an XeSS session reads N/A here by policy, not by ignorance — and the module's presence "
+ "is not identity: Cyberpunk loads it at DLSS"
: null;
/// <summary>
/// What the driver's FG word adds beside the FG line — agreement with a tagged DLSS-G, a disagreement printed
@@ -382,7 +444,7 @@ internal sealed record MeasuredFacts
/// </remarks>
public static MeasuredFacts From(IReadOnlyList<FlFrameRecord> stream, FlWriterState writer,
long qpcFrequency, long totalGaps, long totalDropped, FgWindow? fg = null, RuntimeModuleSet? modules = null,
NgxDriverState? ngx = null)
NgxDriverState? ngx = null, ExecutableMarkers? markers = null)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(qpcFrequency);
@@ -424,6 +486,7 @@ internal sealed record MeasuredFacts
Extent = UpscaleExtent.From(stream),
Upscaler = UpscalerOf(stream),
NgxDriver = ngx ?? NgxDriverState.NotRun,
Markers = markers ?? ExecutableMarkers.NotScanned,
RayTracing = RayTracingOf(stream, writer),
RayReconstruction = RayReconstructionOf(stream),
Hdr = HdrOf(stream),
@@ -199,9 +199,29 @@ internal static class SessionReport
+ "Displayed, not Native";
}
return CensusClearQualifier(facts);
}
/// <summary>The qualifier when no frame-generation module was loaded — the executable file decides its verb.</summary>
private static string CensusClearQualifier(MeasuredFacts facts)
{
// THE CENSUS IS CLEAR, and the executable file is the second witness (HANDOFF 7b). A frame
// generator compiled into the exe loads no module — Rune Factory and Wukong, measured — so
// "cannot include" was wrong there in the dangerous direction. The on-disk scan cannot say the
// code ran; it can say the sentence may not exclude it.
if (facts.Markers.AnyFgCapable)
{
return "WARNING: no known frame-generation runtime MODULE was loaded, but the executable itself carries "
+ facts.Markers.FgCapableNames + " — a frame generator compiled into the executable is outside what "
+ "the module census sees, so this number MAY include generated frames; read it as Displayed, not Native";
}
return "frame generation: not measured — no known frame-generation runtime was loaded in this process, "
+ "so this number cannot include in-process generated frames (statically linked FSR3-FG and "
+ "driver-level AFMF are outside what this can see)";
+ "driver-level AFMF are outside what this can see"
+ (facts.Markers.Scanned
? "; the executable carries none of the frame-generation SDK strings this host scans for)"
: ")");
}
/// <summary>The per-session facts, each with the reason behind its N/A.</summary>
@@ -236,11 +256,16 @@ internal static class SessionReport
sb.Append(" — ").Append(driver);
}
if (facts.XessByLicenceNote is string xess)
{
sb.Append(" — ").Append(xess);
}
sb.AppendLine();
sb.Append(" render -> output: ").AppendLine(RenderToOutput(facts.Extent));
sb.Append(" frame generation: ").Append(facts.FgModePrinted
?? (facts.FgHookRan
? "N/A (a hook ran and saw no frame-generation evaluation — see the FG counts above)"
? facts.FgNotEvaluatedPrinted
: NoHookRan("frame-generation", facts.CensusRan, facts.FgRuntimesLoaded)));
if (facts.FgDriverNote is string fgDriver)
{
@@ -100,4 +100,20 @@
</None>
</ItemGroup>
<!--
The Vulkan implicit layer beside the host (P1 item 3). `launch` writes a manifest pointing at THIS
copy and hands the launched process VK_ADD_IMPLICIT_LAYER_PATH, so the layer is discoverable only by
that process: no registry, nothing machine-wide (VkLayerLaunchEnvironment). Warn-not-fail like the
others: build.ps1 runs the native build first, and a missing DLL is reported by `launch` itself.
-->
<PropertyGroup>
<FlVkLayerDir>$(MSBuildThisFileDirectory)..\..\build\native\x64-release\FrameLedger.VkLayer\</FlVkLayerDir>
</PropertyGroup>
<ItemGroup>
<None Include="$(FlVkLayerDir)FrameLedger.VkLayer.dll" Condition="Exists('$(FlVkLayerDir)FrameLedger.VkLayer.dll')">
<Link>FrameLedger.VkLayer.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+75 -16
View File
@@ -23,6 +23,7 @@ using FrameLedger.Infrastructure.AntiCheat;
using FrameLedger.Infrastructure.Io;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Rules;
using FrameLedger.Infrastructure.Vulkan;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost;
@@ -69,6 +70,7 @@ internal static class Program
Verb.ConsentGrant => await GrantAsync(store, cmd.ExePath!).ConfigureAwait(false),
Verb.ConsentRevoke => await RevokeAsync(store, cmd.ExePath!).ConfigureAwait(false),
Verb.Capture => await CaptureAsync(store, cmd.ExePath!, cmd.Seconds).ConfigureAwait(false),
Verb.Launch => await LaunchAsync(store, cmd.ExePath!, cmd.Arguments, cmd.Seconds).ConfigureAwait(false),
Verb.ProbeLhm => LhmProbe.Run(cmd.Seconds == 0 ? LhmProbe.DefaultSeconds : cmd.Seconds),
_ => _exitUsage,
};
@@ -131,20 +133,57 @@ internal static class Program
return outcome is ConsentWriteOutcome.Written or ConsentWriteOutcome.NotFound ? _exitOk : _exitRefused;
}
// §S22: the payload must resolve into the directory the GUARD's own code was loaded from,
// compared by file id. There is no way to name a different one, which is the point.
private static string Payload => Path.Combine(AppContext.BaseDirectory, "FrameLedger.Overlay.dll");
private static async Task<int> CaptureAsync(FileGameConsentStore store, string exePath, int seconds)
{
string normalised = ExecutableIdentity.Normalise(exePath);
ExecutableFingerprint? observed = ExecutableIdentity.Read(exePath);
// §S22: the payload must resolve into the directory the GUARD's own code was loaded from,
// compared by file id. There is no way to name a different one, which is the point.
string payload = Path.Combine(AppContext.BaseDirectory, "FrameLedger.Overlay.dll");
CaptureResult result = await BuildLoop(store, seconds)
.RunAsync(normalised, observed, payload).ConfigureAwait(false);
.RunAsync(normalised, observed, Payload).ConfigureAwait(false);
return await ConcludeAsync(store, normalised, observed, result).ConfigureAwait(false);
}
/// <summary>Launch mode: the same loop, entered by starting the executable rather than finding it.</summary>
/// <remarks>
/// The Vulkan layer rides on the launch (P1 item 3): the process gets <c>VK_ADD_IMPLICIT_LAYER_PATH</c> and
/// the enable variable, and its image name goes on the layer's enable-list for the session -- no registry,
/// nothing machine-wide, removed when the session ends. A D3D title ignores all of it; a Vulkan title is
/// observed by the layer and the guard injects nothing (<c>TargetIsVulkanLayered</c>).
/// </remarks>
private static async Task<int> LaunchAsync(FileGameConsentStore store, string exePath, string arguments,
int seconds)
{
string normalised = ExecutableIdentity.Normalise(exePath);
ExecutableFingerprint? observed = ExecutableIdentity.Read(exePath);
using var vulkan = VkLayerLaunchEnvironment.Prepare(normalised,
Path.Combine(AppContext.BaseDirectory, "FrameLedger.VkLayer.dll"));
HostConsole.Line(vulkan.ManifestPath is null
? "vulkan layer: NOT staged beside this host - a Vulkan title will present unobserved"
: $"vulkan layer: {vulkan.ManifestPath} (via {VkLayerLaunchEnvironment.ImplicitLayerPathVariable}; " +
$"enable-list entry '{vulkan.ImageName}' for this session)");
CaptureResult result = await BuildLoop(store, seconds, (exe, args) => ProcessLauncher.Start(exe, args, vulkan.Variables))
.RunLaunchedAsync(normalised, observed, Payload, arguments).ConfigureAwait(false);
return await ConcludeAsync(store, normalised, observed, result).ConfigureAwait(false);
}
private static async Task<int> ConcludeAsync(FileGameConsentStore store, string normalised,
ExecutableFingerprint? observed, CaptureResult result)
{
HostConsole.Line($"session: {result.Reason}");
if (result.Verdict.Reason != Domain.AntiCheat.AntiCheatRefusalReason.Allow)
if (result.Verdict.Reason == Domain.AntiCheat.AntiCheatRefusalReason.TargetIsVulkanLayered)
{
HostConsole.Line(" capture side: the Vulkan implicit layer - the guard passed and nothing was injected " +
"(one ring per process; 17_HOOK_ENGINE §Vulkan)");
}
else if (result.Verdict.Reason != Domain.AntiCheat.AntiCheatRefusalReason.Allow)
{
HostConsole.Line($" verdict: {result.Verdict.Reason} {result.Verdict.Family} {result.Verdict.Signal}");
}
@@ -156,7 +195,9 @@ internal static class Program
if (result.Records.Count > 0)
{
Report(result);
// The exe FILE on disk, after the session so the read never overlaps the launch: the
// second witness for a frame generator compiled into the executable (HANDOFF 7b).
Report(result, ExecutableMarkerScan.Scan(normalised));
}
return result.Reason switch
@@ -164,15 +205,15 @@ internal static class Program
SessionEndReason.TargetExited => _exitOk,
SessionEndReason.Running => _exitOk,
SessionEndReason.TargetNotRunning or SessionEndReason.TargetAmbiguous
or SessionEndReason.TargetCannotBePinned => _exitTargetNotResolved,
or SessionEndReason.TargetCannotBePinned or SessionEndReason.LaunchCannotStart => _exitTargetNotResolved,
SessionEndReason.AttachRefused => _exitAttachRefused,
SessionEndReason.SafetyUnhook or SessionEndReason.SupervisionLost
or SessionEndReason.SupervisionFaulted => _exitStoppedForSafety,
or SessionEndReason.SupervisionFaulted or SessionEndReason.WriterStoppedBlocklisted => _exitStoppedForSafety,
_ => _exitRefused,
};
}
private static void Report(CaptureResult result)
private static void Report(CaptureResult result, ExecutableMarkers markers)
{
IReadOnlyList<FlFrameRecord> dominant = StreamSegmenter.DominantStream(result.Records);
IReadOnlyList<Segment> segments = StreamSegmenter.Segment(result.Records);
@@ -185,7 +226,7 @@ internal static class Program
FgWindow fg = FgWindow.From(result.Records, Stopwatch.Frequency);
MeasuredFacts facts = MeasuredFacts.From(
dominant, result.WriterState, Stopwatch.Frequency, result.TotalGaps, result.TotalDropped, fg,
result.RuntimeModules, result.NgxDriver);
result.RuntimeModules, result.NgxDriver, markers);
HostConsole.Line($" guard ticks published: {result.GuardTicksPublished}");
HostConsole.Line($" records: {result.Records.Count} ({dominant.Count} on the dominant stream), " +
@@ -206,9 +247,9 @@ internal static class Program
int withParams = dominant.Count(r => ((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.UpscalerParams));
HostConsole.Line($" hooks installed: {(FlHookFamily)result.WriterState.HooksInstalledMask}" +
$" apiMask=0x{result.WriterState.ApiMask:X} rtTier={result.WriterState.RtTier}");
PrintCensus(result);
PrintCensus(result, markers);
HostConsole.Line(WriterNote(result));
PrintWriterAndLoader(result);
HostConsole.Line($" records carrying Upscaler={withUpscaler}/{dominant.Count} " +
$"UpscalerParams={withParams}/{dominant.Count} " +
$"(a value below the total means the hook came up mid-session, not that it never did)");
@@ -239,7 +280,7 @@ internal static class Program
/// 2.7.1 from 2.8.0, and §H5 case 3 turns on exactly that. A path under the driver store rather
/// than the game directory is how a DLSS override shows up here.
/// </summary>
private static void PrintCensus(CaptureResult result)
private static void PrintCensus(CaptureResult result, ExecutableMarkers markers)
{
var census = (FlRuntimeCensus)result.WriterState.RuntimeCensus;
HostConsole.Line($" runtime census: 0x{result.WriterState.RuntimeCensus:X} ran={census.HasFlag(FlRuntimeCensus.Ran)} " +
@@ -249,6 +290,7 @@ internal static class Program
// The driver's own word on this process, out of process: the super-resolution identity the
// hooks cannot see on NGX-direct titles (03_METRICS §Upscaling, the driver-reported rung).
HostConsole.Line(result.NgxDriver.Describe());
HostConsole.Line(markers.Describe());
// Which Streamline buffer types the title tagged, on which route: the identity half of
// frame generation (fl_shm.h §slTagCensus). A DLSS-G title tags hudless and UI every
// frame; a super-resolution-only title tags neither.
@@ -303,7 +345,8 @@ internal static class Program
}
/// <summary>The loop and its four collaborators, wired the only way this host allows.</summary>
private static CaptureLoop BuildLoop(FileGameConsentStore store, int seconds)
private static CaptureLoop BuildLoop(FileGameConsentStore store, int seconds,
Func<string, string, (int Pid, ITargetLiveness Alive)?>? launcher = null)
{
var guard = new NativeAntiCheatGuard();
return new CaptureLoop(
@@ -332,7 +375,8 @@ internal static class Program
MaxDuration = seconds > 0 ? TimeSpan.FromSeconds(seconds) : TimeSpan.Zero,
},
pid => RuntimeModuleSnapshot.Take(pid, CensusNames.ModuleFileNames),
NgxDriverProbe.Run);
NgxDriverProbe.Run,
launcher ?? ((exe, args) => ProcessLauncher.Start(exe, args)));
}
/// <summary>
@@ -385,6 +429,21 @@ internal static class Program
return " cause: the record is present, enabled and matching — so the refusal came from elsewhere";
}
/// <summary>The writer's own line, then the LoadLibrary detour's (installed / woke / EARLY STOP).</summary>
private static void PrintWriterAndLoader(CaptureResult result)
{
HostConsole.Line(WriterNote(result));
foreach (string line in EarlyStop.Describe(result.WriterState, EarlyStop.StagedRulesPath))
{
HostConsole.Line(line);
}
foreach (string line in LaunchNote.Describe(result.LaunchWait, result.WriterState))
{
HostConsole.Line(line);
}
}
/// <summary>
/// The two numbers that separate "nothing happened" from "something went wrong".
/// </summary>
+7
View File
@@ -9,6 +9,13 @@ internal enum Verb
ConsentRevoke,
Capture,
/// <summary>
/// Launch mode (P1 item 2): start the consented executable, hold it, and let the guard inject the
/// moment it has mapped a presentation runtime. The same consent record, the same gate, the same
/// payload; only WHEN the full scan runs differs.
/// </summary>
Launch,
/// <summary>
/// §M5's instrument: open LibreHardwareMonitor GPU-only, print the raw sensor tree
/// and the mapped sample for a few seconds, and name the pre-committed row it landed on.
@@ -170,4 +170,31 @@ public enum AntiCheatRefusalReason
/// watchlist resurrecting the game after <c>hook_enabled</c> was forced to 0.
/// </remarks>
PreviouslyBlocked = 23,
/// <summary>
/// Launch mode (P1 item 2): the guard was waiting for the launched target to map a presentation
/// runtime and the target exited first. Nothing was injected.
/// </summary>
/// <remarks>
/// A launcher that spawned the real game and quit is the ordinary cause (the descendant election is
/// the Agent's, P2); a crash is the other. <c>20_OPEN_QUESTIONS</c> §S1 / §S13(c).
/// </remarks>
LaunchTargetExited = 24,
/// <summary>
/// Launch mode: the budget ran out and the target had mapped no presentation runtime — a 2D title,
/// or a launcher still sitting on its window. Nothing was injected.
/// </summary>
LaunchNoPresentationRuntime = 25,
/// <summary>
/// Launch mode, the Vulkan branch (P1 item 3): the target mapped <c>vulkan-1.dll</c> and no D3D or OpenGL
/// runtime, the FULL guard passed, and nothing was injected on purpose — a Vulkan title is captured by the
/// implicit layer, and one process carries one ring (<c>fl_shm_host.h</c>).
/// </summary>
/// <remarks>
/// Not an allow — the Overlay is not in the target — and not a refusal either: the host reads it as
/// "attach to the layer's ring". <c>CaptureLoop</c> is the one place that distinction is made.
/// </remarks>
TargetIsVulkanLayered = 26,
}
@@ -64,6 +64,11 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void FlGuardedInject(uint targetPid, string dllPath, out FlGuardResult result);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void FlGuardedInjectWhenReady(uint targetPid, string dllPath, uint timeoutMs,
out FlGuardResult result);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void FlStaticPreScan(string gameDirectory, out FlGuardResult result);
@@ -128,6 +133,20 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard
}, ct);
}
/// <inheritdoc />
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath, int timeoutMs,
CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(payloadPath);
ArgumentOutOfRangeException.ThrowIfNegative(timeoutMs);
return RunAsync(() =>
{
FlGuardedInjectWhenReady(checked((uint)targetPid), payloadPath, checked((uint)timeoutMs),
out FlGuardResult r);
return AntiCheatVerdict.FromNative(r.Reason, r.Family, r.Signal);
}, ct);
}
/// <inheritdoc />
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
CancellationToken ct = default)
@@ -0,0 +1,187 @@
using System.Text;
using System.Text.Json;
namespace FrameLedger.Infrastructure.Vulkan;
/// <summary>
/// What a launched process needs for the Vulkan implicit layer to observe it, and nothing else on the machine to:
/// the loader's <c>VK_ADD_IMPLICIT_LAYER_PATH</c> pointed at a directory holding our manifest, the manifest's
/// <c>enable_environment</c> variable set, and the process image name on the layer's enable-list.
/// </summary>
/// <remarks>
/// <para>
/// <b>No registry.</b> <c>12_BUILD</c> §The Vulkan layer is not registered at install time makes registration a
/// deliberate, later act of the Agent, kept only while a Vulkan game has hooking enabled. The unshipped host
/// does not need it at all: loader 1.4.357 honours <c>VK_ADD_IMPLICIT_LAYER_PATH</c> (measured 2026-09-06,
/// <c>spike-notes</c> §2), so the layer is discoverable ONLY by the process this host starts — a smaller blast
/// radius than an HKCU registration, and gone when the variable is. The Agent's registration path (P2) is
/// unchanged by this.
/// </para>
/// <para>
/// <b>The enable-list is written here because this host stands in for the Agent</b>, which
/// <c>17_HOOK_ENGINE</c> §The enable-list names as its sole writer. One line, the lowercased image name, added
/// only when absent and removed on dispose only when this object added it. An entry somebody else wrote is
/// left exactly as found.
/// </para>
/// <para>
/// <b>Without a staged layer DLL nothing is written and no variable is set</b>: a manifest pointing at a file
/// that is not there would make the loader log an error into the game for no benefit.
/// </para>
/// </remarks>
public sealed class VkLayerLaunchEnvironment : IDisposable
{
/// <summary>The manifest's <c>enable_environment</c> variable (<c>17_HOOK_ENGINE</c> §Vulkan).</summary>
public const string EnableVariable = "FRAMELEDGER_ENABLE_VK_LAYER";
/// <summary>The loader's additional implicit-layer search path, honoured without any registration.</summary>
public const string ImplicitLayerPathVariable = "VK_ADD_IMPLICIT_LAYER_PATH";
/// <summary>The layer's name, as the manifest and the loader log carry it.</summary>
public const string LayerName = "VK_LAYER_FRAMELEDGER_overlay";
private const string _manifestFileName = "VkLayer_FRAMELEDGER_overlay.json";
private static readonly JsonSerializerOptions _manifestOptions = new() { WriteIndented = true };
private readonly bool _addedEnableListEntry;
private readonly string? _writtenManifest;
private bool _disposed;
private VkLayerLaunchEnvironment(string directory, string imageName, string enableListPath, string? manifest,
bool addedEntry, IReadOnlyDictionary<string, string> variables)
{
Directory = directory;
ImageName = imageName;
EnableListPath = enableListPath;
_writtenManifest = manifest;
_addedEnableListEntry = addedEntry;
Variables = variables;
}
/// <summary>The product's per-user layer directory: <c>%LOCALAPPDATA%\FrameLedger\vklayer</c>.</summary>
public static string DefaultDirectory => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FrameLedger", "vklayer");
/// <summary>The directory the loader is pointed at, which also holds the enable-list.</summary>
public string Directory { get; }
/// <summary>The lowercased process image name written to the enable-list.</summary>
public string ImageName { get; }
/// <summary>The enable-list this object wrote to (or would have).</summary>
public string EnableListPath { get; }
/// <summary>The manifest written for this launch, or null when the layer DLL was not staged.</summary>
public string? ManifestPath => _writtenManifest;
/// <summary>Variables to add to the launched process's environment; empty when the layer is not staged.</summary>
public IReadOnlyDictionary<string, string> Variables { get; }
/// <summary>
/// Prepare the environment for launching <paramref name="exePath"/> with the layer at
/// <paramref name="layerDllPath"/>; <paramref name="directory"/> defaults to <see cref="DefaultDirectory"/>.
/// </summary>
public static VkLayerLaunchEnvironment Prepare(string exePath, string layerDllPath, string? directory = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(exePath);
ArgumentException.ThrowIfNullOrWhiteSpace(layerDllPath);
string dir = directory ?? DefaultDirectory;
#pragma warning disable CA1308 // the enable-list's format is LOWERCASED image names (17_HOOK_ENGINE §The enable-list)
string image = Path.GetFileName(exePath).ToLowerInvariant();
#pragma warning restore CA1308
string enableList = Path.Combine(dir, "enabled.txt");
if (!File.Exists(layerDllPath))
{
return new VkLayerLaunchEnvironment(dir, image, enableList, manifest: null, addedEntry: false,
new Dictionary<string, string>(StringComparer.Ordinal));
}
System.IO.Directory.CreateDirectory(dir);
bool added = AddEnableListEntry(enableList, image);
string manifest = Path.Combine(dir, _manifestFileName);
File.WriteAllText(manifest, ManifestJson(Path.GetFullPath(layerDllPath)), new UTF8Encoding(false));
var variables = new Dictionary<string, string>(StringComparer.Ordinal)
{
[EnableVariable] = "1",
[ImplicitLayerPathVariable] = dir,
};
return new VkLayerLaunchEnvironment(dir, image, enableList, manifest, added, variables);
}
/// <summary>The manifest, with the DLL's absolute path — the shape <c>VkLayer_FRAMELEDGER_overlay.json.in</c> generates.</summary>
internal static string ManifestJson(string libraryPath)
{
var doc = new
{
file_format_version = "1.2.0",
layer = new
{
name = LayerName,
type = "GLOBAL",
library_path = libraryPath,
api_version = "1.4.357",
implementation_version = "1",
description = "FrameLedger performance capture (opt-in per game; passthrough otherwise)",
enable_environment = new Dictionary<string, string>(StringComparer.Ordinal) { [EnableVariable] = "1" },
disable_environment = new Dictionary<string, string>(StringComparer.Ordinal) { ["DISABLE_FRAMELEDGER_VK_LAYER"] = "1" },
},
};
return JsonSerializer.Serialize(doc, _manifestOptions);
}
/// <summary>True when the entry was added; false when it was already there.</summary>
private static bool AddEnableListEntry(string enableList, string image)
{
List<string> lines = File.Exists(enableList) ? [.. File.ReadAllLines(enableList)] : [];
if (lines.Any(l => string.Equals(l.Trim(), image, StringComparison.OrdinalIgnoreCase)))
{
return false;
}
lines.Add(image);
File.WriteAllText(enableList, string.Join('\n', lines) + '\n', new UTF8Encoding(false));
return true;
}
/// <summary>Remove exactly what <see cref="Prepare"/> added.</summary>
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
try
{
if (_addedEnableListEntry && File.Exists(EnableListPath))
{
List<string> kept = [.. File.ReadAllLines(EnableListPath)
.Where(l => !string.Equals(l.Trim(), ImageName, StringComparison.OrdinalIgnoreCase))];
if (kept.Count == 0)
{
File.Delete(EnableListPath);
}
else
{
File.WriteAllText(EnableListPath, string.Join('\n', kept) + '\n', new UTF8Encoding(false));
}
}
if (_writtenManifest is not null && File.Exists(_writtenManifest))
{
File.Delete(_writtenManifest);
}
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
// Leaving a line or a manifest behind grants nothing: the layer still gates on the enable
// variable, which only a launch sets. Stated rather than thrown from a Dispose.
}
}
}
+28 -2
View File
@@ -76,6 +76,13 @@ public enum FlStatus : uint
/// <summary>Three hook faults; see <c>17_HOOK_ENGINE</c> §Fault policy.</summary>
SelfDisabled = 2,
Unhooked = 3,
/// <summary>
/// A module matching the anti-cheat floor compiled into the Overlay loaded mid-session and the Overlay
/// stopped itself (<c>19_SAFETY</c> §During a session, the in-process half; §S6). Which family:
/// <see cref="FlWriterState.EarlyStopFamily"/>.
/// </summary>
StoppedBlocklisted = 4,
}
/// <summary>Bits in <see cref="FlWriterState.ApiMask"/>, and the value of <see cref="FlFrameRecord.Api"/>.</summary>
@@ -564,8 +571,27 @@ public unsafe struct FlWriterState
/// <summary>Hooked presents on which the DXGI counter was read. Took <c>reserved[1]</c> on 2026-09-05.</summary>
public uint DxgiPresentSamples;
/// <summary>Must be zero; room for additive fields.</summary>
public fixed uint Reserved[2];
/// <summary>
/// The <c>LoadLibrary</c> detour's word: bit 15 = installed; bits 0..14 = how many times a module the hook
/// inventory or the runtime census names was loaded and the watchdog woken for it.
/// </summary>
public ushort LoaderSignals;
/// <summary>
/// 0 = none; else the 1-based index, among the compiled floor's MODULE families in rules order, of the
/// family whose value matched a module loaded mid-session. Paired with <see cref="FlStatus.StoppedBlocklisted"/>.
/// </summary>
public ushort EarlyStopFamily;
/// <summary>
/// DXGI's count of presents the first hooked chain had completed before this hook saw one — how many
/// presents ran unhooked, launch mode's own cost meter. <see cref="DxgiPresentsBeforeHookNotRead"/> (all
/// bits set) means the hook never saw a present.
/// </summary>
public uint DxgiPresentsBeforeHook;
/// <summary>The value <see cref="DxgiPresentsBeforeHook"/> carries until the first hooked present.</summary>
public const uint DxgiPresentsBeforeHookNotRead = 0xFFFFFFFF;
// WHY THE COUNTERS ARE PUBLISHED AT 1 Hz AND NOT ACCUMULATED HERE PER FRAME: this struct is
// region 2, which the Overlay writes on the present path, and the regions are separate cache lines
@@ -230,6 +230,17 @@ enum class ParseResult : std::uint8_t {
// with a signer check; a fragment alone never refuses (19_SAFETY: "name
// fragment AND not signed by a known vendor").
[[nodiscard]] bool HasSuspiciousFragment(const Rules& rules, const char* moduleName) noexcept;
// THE BOUND (owner decision 2026-09-06, §S19(b)). Once the signer half is wired,
// `trustedSigners` is a live allow-widening surface: a rules push that adds a
// publisher widens the hard gate, and `Rules / validate` is not a required check.
// So the data file may only INTERSECT a list compiled into this binary — the
// boundary of what the gate trusts is code, exactly as 19_SAFETY ruled for the
// launcher list. Widening it is a reviewed PR, never a data change.
[[nodiscard]] bool IsCompiledTrustedSigner(const char* signerOrganisation) noexcept;
// True only when BOTH the rules file and the compiled-in list name the
// organisation (full, case-insensitive equality on the certificate subject's O=).
[[nodiscard]] bool IsTrustedSigner(const Rules& rules, const char* signerOrganisation) noexcept;
// Local AppData, resolved from the SHELL rather than from the environment.
@@ -152,6 +152,31 @@ enum class Reason : std::uint8_t {
kConsentMissing,
kPreviouslyBlocked,
// LAUNCH MODE (P1 item 2; 20_OPEN_QUESTIONS §S1 / §S13(c)): the guard was asked
// to inject AS SOON AS the target had mapped a presentation runtime, and it
// never did. A CREATE_SUSPENDED target has loaded nothing and
// EnumProcessModulesEx fails against it with ERROR_PARTIAL_COPY (§S1, measured),
// so launch mode cannot be create -> guard -> inject -> resume. It is create ->
// resume -> POLL until dxgi+d3d11/d3d12, opengl32 or vulkan-1 is mapped -> the
// full guard -> inject. These two are the poll's own ends: the process exited
// first (a launcher that spawned the real game and quit -- the Agent's election,
// P2 -- or a crash), or the budget ran out with no runtime mapped (a 2D title, or
// a launcher still sitting on its window). Nothing was injected in either case.
kLaunchTargetExited,
kLaunchNoPresentationRuntime,
// LAUNCH MODE, the Vulkan branch (P1 item 3). The launched target mapped
// vulkan-1.dll (with or without a D3D runtime beside it -- an NVIDIA Vulkan
// ICD maps dxgi + d3d12 itself, measured), the full guard PASSED, and
// nothing was injected on purpose: a Vulkan title is captured by the implicit
// layer the loader mapped into it (17_HOOK_ENGINE §Vulkan), and one process
// carries ONE ring -- an Overlay injected beside the layer would find the
// mapping already there and stay inert, or win the race and leave the layer
// inert with nothing to hook (fl_shm_host.h). Allowed() is false because the
// DLL is NOT loaded in the target; the host reads this as "attach to the
// layer's ring", not as a refusal.
kTargetIsVulkanLayered,
// NOT A REASON. The count, so appending above it updates the exported
// FlGuardReasonCount by construction.
//
@@ -307,6 +332,34 @@ struct Sources {
// caller has to be able to distinguish them.
Collected (*ModuleIsOurOwn)(const wchar_t* modulePath, bool* isOurs) = nullptr;
// §S19(b) — WHO SIGNED this module, from its EMBEDDED Authenticode signature,
// verified OFFLINE (row G1, read 2026-09-06 after the CI leg and the owner's
// adapters-disabled leg both left every verdict unchanged).
//
// kOk writes the signing certificate's subject `O=` into `out` — the field
// 19_SAFETY §Blocklist seed names, measured on drivers, launchers and a NuGet
// assembly whose CN changed between copies while its O= did not. The guard
// then pairs it with the fragment tier: a fragment-matching module signed by
// an organisation on the TRUSTED list keeps the scan looking; anything else
// latches SuspiciousUnsigned, which is now literally what it says.
//
// kFailed is every other outcome and MEANS NOT TRUSTED: no embedded signature
// (the catalog-signed system binaries — mskeyprotect.dll — land here by
// design, the CryptCATAdmin* half being deferred with its own rationale), an
// invalid one, a certificate whose O= could not be read, a buffer too small,
// a null path. The polarity is ModuleIsOurOwn's: a seam that fails must never
// widen what is allowed.
//
// OFFLINE BY FLAG, measured rather than assumed: WTD_REVOKE_NONE and
// WTD_CACHE_ONLY_URL_RETRIEVAL, under which the probe's verdicts did not
// change with every adapter disabled. cryptnet.dll still maps; no request is
// made. NFR-10 and CLAUDE.md rule 8 are what that measurement protects.
//
// Reached only on a fragment hit, which on a measured machine is approximately
// never — ~2-4 ms per verified module, inside a 30 s loop, on a scan set that
// three real titles left empty.
Collected (*ModuleSignerOrganisation)(const wchar_t* modulePath, char* out, std::size_t cap) = nullptr;
// §S22 — is the DLL we were asked to inject one of OUR OWN binaries?
//
// The guard gated the target and nothing gated the payload. Every check
@@ -380,6 +433,18 @@ struct Sources {
// a way into a game process that never consulted a single genuine signal.
[[nodiscard]] Verdict GuardedInject(std::uint32_t targetPid, const wchar_t* dllPath) noexcept;
// LAUNCH MODE. Poll `targetPid` -- every 50 ms, up to `timeoutMs` -- until it has
// mapped a presentation runtime (dxgi.dll with d3d11.dll or d3d12.dll, or
// opengl32.dll, or vulkan-1.dll: the earliest externally observable moment at which
// a swapchain can exist), then run GuardedInject in full. The poll reads module
// names through the same seam the module scan uses and matches NOTHING against the
// blocklist: it decides WHEN the guard runs, never WHETHER it passes. A target that
// exits first, or never maps a runtime inside the budget, is refused with
// kLaunchTargetExited / kLaunchNoPresentationRuntime and nothing is injected.
// 04_CAPTURE §Launch mode; 20_OPEN_QUESTIONS §S1 / §S13(c).
[[nodiscard]] Verdict GuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath,
std::uint32_t timeoutMs) noexcept;
// Evaluate the guard WITHOUT injecting. Exists for the 30 s in-session re-scan
// (19_SAFETY §During a session), which must reach a verdict on a process it is
// already inside and has nothing to inject. Deliberately cannot be used to
@@ -402,6 +467,8 @@ struct Sources {
[[nodiscard]] Verdict EvaluateWithSources(std::uint32_t targetPid, const Sources& sources) noexcept;
[[nodiscard]] Verdict GuardedInjectWithSources(std::uint32_t targetPid, const wchar_t* dllPath,
const Sources& sources) noexcept;
[[nodiscard]] Verdict GuardedInjectWhenReadyWithSources(std::uint32_t targetPid, const wchar_t* dllPath,
std::uint32_t timeoutMs, const Sources& sources) noexcept;
#endif
// Human-readable reason, for logs and for mapping to resx keys.
@@ -55,6 +55,17 @@ FL_GUARD_ABI void FlGuardEvaluate(std::uint32_t targetPid, FlGuardResult* out);
// in evidence — the guard collects its own.
FL_GUARD_ABI void FlGuardedInject(std::uint32_t targetPid, const wchar_t* dllPath, FlGuardResult* out);
// LAUNCH MODE (P1 item 2). Wait -- polling every 50 ms, up to `timeoutMs` -- until
// `targetPid` has mapped a presentation runtime, then run every check and inject
// exactly as FlGuardedInject does. The wait decides WHEN the guard runs and
// nothing about whether it passes: the poll matches no blocklist and the full scan
// runs once the runtime is there. A target that exits first, or never maps a
// runtime inside the budget, answers LaunchTargetExited / LaunchNoPresentationRuntime
// with nothing injected. The caller launches and holds the process; this never
// creates or terminates one (04_CAPTURE §Launch mode, 20_OPEN_QUESTIONS §S1).
FL_GUARD_ABI void FlGuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
FlGuardResult* out);
// Check 4 against a directory, before anything is launched (FR-2.2). ADVISORY:
// it answers "may this game's hooking toggle be offered at all", and gates
// nothing. The same scan runs inside FlGuardEvaluate and FlGuardedInject
@@ -636,6 +636,26 @@ bool HasSuspiciousFragment(const Rules& rules, const char* moduleName) noexcept
return false;
}
// The five organisations the shipped rules name, measured on this machine's
// binaries (spike-notes §1: WHQL re-signing leaves O= intact, so both GPU vendors'
// drivers read as Microsoft; their own launchers read as themselves). Adding one is
// a code change with a review, which is the whole point of the list being here.
constexpr const char* kCompiledTrustedSigners[] = {
"Microsoft Corporation", "NVIDIA Corporation", "Valve Corp.", "Intel Corporation", "Advanced Micro Devices, Inc.",
};
bool IsCompiledTrustedSigner(const char* signerOrganisation) noexcept {
if (signerOrganisation == nullptr || signerOrganisation[0] == '\0') {
return false;
}
for (const char* s : kCompiledTrustedSigners) {
if (IEquals(signerOrganisation, s)) {
return true;
}
}
return false;
}
bool IsTrustedSigner(const Rules& rules, const char* signerOrganisation) noexcept {
// A signature that is absent, invalid, or simply could not be checked is
// NOT trusted. The caller passes nullptr for all three, and they all land
@@ -643,6 +663,11 @@ bool IsTrustedSigner(const Rules& rules, const char* signerOrganisation) noexcep
if (signerOrganisation == nullptr || signerOrganisation[0] == '\0') {
return false;
}
// The bound first: an organisation the binary does not know cannot be made
// trusted by the data file, whatever the file says.
if (!IsCompiledTrustedSigner(signerOrganisation)) {
return false;
}
for (std::size_t i = 0; i < rules.trustedSignerCount; ++i) {
// Full comparison, never a prefix or substring: a substring signer rule
// is a forgery surface, because "NVIDIA Corporation Ltd" would match
@@ -247,6 +247,33 @@ bool ModuleIsExempt(const MatchState& st, const wchar_t* modulePath) noexcept {
return st.sources->ModuleIsOurOwn(modulePath, &ours) == Collected::kOk && ours;
}
// §S19(b) — is this fragment-matching module signed by a TRUSTED organisation?
//
// The other half of 19_SAFETY's heuristic ("name fragment AND not signed by a
// known vendor"), wired 2026-09-06 on row G1. Every clause fails towards refusing:
//
// - a null seam does not suppress (Sources members default to nullptr);
// - a module whose path we could not obtain cannot be verified;
// - anything but kOk from the seam is "could not tell", which is untrusted;
// - the organisation must be on BOTH the rules list and the compiled-in bound
// (IsTrustedSigner) — full equality, never a substring.
//
// Unlike ModuleIsExempt this applies to the TARGET too: a game that loads a
// Microsoft-signed key-protection provider is exactly the false refusal the
// signer half exists to remove. Reached only after the fragment matched, so the
// ~2-4 ms verification is not on the ordinary path.
bool ModuleIsTrustedSigned(const MatchState& st, const wchar_t* modulePath) noexcept {
if (st.sources == nullptr || st.sources->ModuleSignerOrganisation == nullptr || modulePath == nullptr ||
st.rules == nullptr) {
return false;
}
char org[kMaxValueLen] = {};
if (st.sources->ModuleSignerOrganisation(modulePath, org, sizeof(org)) != Collected::kOk) {
return false;
}
return IsTrustedSigner(*st.rules, org);
}
// Check 1's sink. The ordering here is the whole of §S22(b).
bool ModuleSinkFn(void* ctx, const char* name, const wchar_t* modulePath) noexcept {
auto* st = static_cast<MatchState*>(ctx);
@@ -274,6 +301,13 @@ bool ModuleSinkFn(void* ctx, const char* name, const wchar_t* modulePath) noexce
if (ModuleIsExempt(*st, modulePath)) {
return true;
}
// TRUSTED SIGNER: the same KEEP LOOKING, for the same reason. A trusted module
// must never STOP the scan, or a genuinely suspicious module loaded after it
// is never recorded — the load-order fail-open the paragraph above describes,
// reachable through this clause exactly as through the exemption.
if (ModuleIsTrustedSigned(*st, modulePath)) {
return true;
}
st->sawSuspicious = true;
strncpy_s(st->suspicious, name, _TRUNCATE);
// Still not a stop: an EXACT blocklist hit later in the same process outranks
@@ -484,6 +518,12 @@ const char* ReasonName(Reason r) noexcept {
return "RulesMalformed";
case Reason::kRulesIncomplete:
return "RulesIncomplete";
case Reason::kLaunchTargetExited:
return "LaunchTargetExited";
case Reason::kLaunchNoPresentationRuntime:
return "LaunchNoPresentationRuntime";
case Reason::kTargetIsVulkanLayered:
return "TargetIsVulkanLayered";
case Reason::kCount:
break; // not a reason; falls through to the guard below
}
@@ -655,12 +695,120 @@ Verdict GuardedInjectImpl(std::uint32_t targetPid, const wchar_t* dllPath, const
return v;
}
// ---------------------------------------------------------------------------
// Launch mode (P1 item 2) -- WHEN the guard runs, never WHETHER it passes.
// ---------------------------------------------------------------------------
// The poll's one question: has the target mapped a presentation runtime yet? Read
// through Sources::EnumerateModules -- the module scan's own seam -- so a test can
// drive it and so the answer comes from the loader rather than from a guess about
// the title. The sink looks for five system names and MATCHES NOTHING AGAINST THE
// BLOCKLIST; the verdict is GuardedInjectImpl's, run in full once the answer is
// yes. An enumeration that fails is "not yet" here rather than a refusal, because
// ERROR_PARTIAL_COPY is exactly what a target still inside its loader returns
// (§S1), and the refusal, if one is due, is the full scan's to make.
struct RuntimeProbe {
bool dxgi = false;
bool d3d = false;
bool gl = false;
bool vk = false;
};
bool RuntimeSinkFn(void* ctx, const char* name, const wchar_t*) noexcept {
auto* p = static_cast<RuntimeProbe*>(ctx);
if (p == nullptr || name == nullptr) {
return false;
}
if (_stricmp(name, "dxgi.dll") == 0) {
p->dxgi = true;
} else if (_stricmp(name, "d3d11.dll") == 0 || _stricmp(name, "d3d12.dll") == 0) {
p->d3d = true;
} else if (_stricmp(name, "opengl32.dll") == 0) {
p->gl = true;
} else if (_stricmp(name, "vulkan-1.dll") == 0) {
p->vk = true;
}
return true;
}
// What the target presents through, as far as the loader can say. kVulkan is the
// branch the guard must NOT inject (Reason::kTargetIsVulkanLayered), and IT WINS
// over a D3D runtime mapped beside it. Measured 2026-09-06 on the harness's
// Vulkan mode under an NVIDIA driver: the Vulkan ICD itself maps dxgi.dll and
// d3d12.dll and presents the Vulkan swapchain through a DXGI chain, so "vulkan-1
// beside d3d12" is what EVERY Vulkan title looks like there -- treating it as D3D
// injected the Overlay, which owned the ring, and left the layer forwarding into
// nothing. A process does not map vulkan-1.dll unless it uses Vulkan; a D3D title
// that happens to is the rarer shape and the one this rule gets wrong.
enum class PresentationRuntime : std::uint8_t { kNone, kD3dOrOpenGl, kVulkan };
PresentationRuntime FindPresentationRuntime(const Sources& s, std::uint32_t pid) noexcept {
if (s.EnumerateModules == nullptr) {
return PresentationRuntime::kNone;
}
RuntimeProbe p;
if (s.EnumerateModules(pid, &RuntimeSinkFn, &p) == Collected::kFailed) {
return PresentationRuntime::kNone; // still in its loader, or unreadable -- the full scan refuses the latter
}
if (p.vk) {
return PresentationRuntime::kVulkan;
}
return ((p.dxgi && p.d3d) || p.gl) ? PresentationRuntime::kD3dOrOpenGl : PresentationRuntime::kNone;
}
Verdict GuardedInjectWhenReadyImpl(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
const Sources& sources) noexcept {
// SYNCHRONIZE only: this handle exists to notice an exit and for nothing else.
HANDLE proc = OpenProcess(SYNCHRONIZE, FALSE, targetPid);
if (proc == nullptr) {
return Refuse(Reason::kProcessUnreadable, nullptr, "could not open the launched target to wait on it");
}
constexpr DWORD kPollMs = 50;
const ULONGLONG start = GetTickCount64();
Verdict v; // fail-closed default, like every Verdict
for (;;) {
if (WaitForSingleObject(proc, 0) == WAIT_OBJECT_0) {
v = Refuse(Reason::kLaunchTargetExited, nullptr,
"the target exited before it mapped a presentation runtime; nothing was injected");
break;
}
const PresentationRuntime runtime = FindPresentationRuntime(sources, targetPid);
if (runtime == PresentationRuntime::kD3dOrOpenGl) {
v = GuardedInjectImpl(targetPid, dllPath, sources);
break;
}
if (runtime == PresentationRuntime::kVulkan) {
// The FULL guard still runs -- a Vulkan title with anti-cheat is refused
// by name exactly as a D3D one is -- and on a pass nothing is injected.
v = EvaluateImpl(targetPid, sources);
if (v.Allowed()) {
v = Refuse(Reason::kTargetIsVulkanLayered, nullptr,
"the guard passed; the target presents through Vulkan, where the implicit layer is the "
"capture side, so nothing was injected");
}
break;
}
if (GetTickCount64() - start >= timeoutMs) {
v = Refuse(Reason::kLaunchNoPresentationRuntime, nullptr,
"no presentation runtime was mapped within the launch budget; nothing was injected");
break;
}
Sleep(kPollMs);
}
CloseHandle(proc);
return v;
}
} // namespace
Verdict Evaluate(std::uint32_t targetPid) noexcept {
return EvaluateImpl(targetPid, SystemSources());
}
Verdict GuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs) noexcept {
return GuardedInjectWhenReadyImpl(targetPid, dllPath, timeoutMs, SystemSources());
}
Verdict GuardedInject(std::uint32_t targetPid, const wchar_t* dllPath) noexcept {
return GuardedInjectImpl(targetPid, dllPath, SystemSources());
}
@@ -673,6 +821,11 @@ Verdict EvaluateWithSources(std::uint32_t targetPid, const Sources& sources) noe
Verdict GuardedInjectWithSources(std::uint32_t targetPid, const wchar_t* dllPath, const Sources& sources) noexcept {
return GuardedInjectImpl(targetPid, dllPath, sources);
}
Verdict GuardedInjectWhenReadyWithSources(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
const Sources& sources) noexcept {
return GuardedInjectWhenReadyImpl(targetPid, dllPath, timeoutMs, sources);
}
#endif
} // namespace fl::guard
@@ -40,6 +40,14 @@ void FlGuardedInject(std::uint32_t targetPid, const wchar_t* dllPath, FlGuardRes
Fill(out, fl::guard::GuardedInject(targetPid, dllPath));
}
void FlGuardedInjectWhenReady(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
FlGuardResult* out) {
if (!Usable(out)) {
return;
}
Fill(out, fl::guard::GuardedInjectWhenReady(targetPid, dllPath, timeoutMs));
}
void FlStaticPreScan(const wchar_t* gameDirectory, FlGuardResult* out) {
if (!Usable(out)) {
return;
@@ -25,7 +25,17 @@
#include <tlhelp32.h>
#include <winsvc.h>
// clang-format off
// ORDER IS LOAD-BEARING (fl-probe-signer found it): <mscat.h> is not needed here,
// but <wintrust.h> and <softpub.h> still want <wincrypt.h>'s types first.
#include <wincrypt.h>
#include <wintrust.h>
#include <softpub.h>
// clang-format on
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "wintrust.lib")
#pragma comment(lib, "crypt32.lib")
namespace fl::guard {
namespace {
@@ -670,6 +680,99 @@ Collected FileIsOurOwnImpl(const wchar_t* dllPath, bool* isOurs) noexcept {
return Collected::kOk;
}
// §S19(b) — the EMBEDDED signer half, offline. The shape fl-probe-signer measured,
// with the probe's std::string and std::vector replaced by fixed buffers: the guard
// allocates nothing.
//
// Two calls, and the order is the contract: WinVerifyTrust decides whether the
// signature is VALID (chain, digest, policy) and only then is the certificate read
// for its O=. Reading the subject first would report an organisation off a
// signature nobody verified — a forged O= is exactly one CryptQueryObject away.
LONG VerifyEmbeddedOffline(const wchar_t* path) noexcept {
WINTRUST_FILE_INFO fi{};
fi.cbStruct = sizeof(fi);
fi.pcwszFilePath = path;
WINTRUST_DATA wd{};
wd.cbStruct = sizeof(wd);
wd.dwUIChoice = WTD_UI_NONE;
wd.fdwRevocationChecks = WTD_REVOKE_NONE;
wd.dwUnionChoice = WTD_CHOICE_FILE;
wd.pFile = &fi;
wd.dwStateAction = WTD_STATEACTION_VERIFY;
wd.dwProvFlags = WTD_SAFER_FLAG | WTD_CACHE_ONLY_URL_RETRIEVAL;
GUID action = WINTRUST_ACTION_GENERIC_VERIFY_V2;
const LONG r = WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE), &action, &wd);
wd.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE), &action, &wd);
return r;
}
// The signing certificate's subject O=, into a caller buffer. False on anything
// short of a readable, non-empty, ASCII-representable organisation.
bool ReadSignerOrganisation(const wchar_t* path, char* out, std::size_t cap) noexcept {
HCERTSTORE store = nullptr;
HCRYPTMSG msg = nullptr;
DWORD enc = 0;
DWORD ctype = 0;
DWORD fmt = 0;
if (!CryptQueryObject(CERT_QUERY_OBJECT_FILE, path, CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
CERT_QUERY_FORMAT_FLAG_BINARY, 0, &enc, &ctype, &fmt, &store, &msg, nullptr)) {
return false;
}
bool ok = false;
DWORD need = 0;
// Fixed, generous, and refused when exceeded: a signer info larger than this is
// not a shape any vendor certificate produces, and "could not read" is untrusted.
alignas(16) unsigned char buf[16384];
if (CryptMsgGetParam(msg, CMSG_SIGNER_INFO_PARAM, 0, nullptr, &need) && need > 0 && need <= sizeof(buf) &&
CryptMsgGetParam(msg, CMSG_SIGNER_INFO_PARAM, 0, buf, &need)) {
auto* si = reinterpret_cast<CMSG_SIGNER_INFO*>(buf);
CERT_INFO ci{};
ci.Issuer = si->Issuer;
ci.SerialNumber = si->SerialNumber;
PCCERT_CONTEXT cert = CertFindCertificateInStore(store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
CERT_FIND_SUBJECT_CERT, &ci, nullptr);
if (cert != nullptr) {
wchar_t org[512]{};
const DWORD n = CertGetNameStringW(cert, CERT_NAME_ATTR_TYPE, 0, const_cast<char*>(szOID_ORGANIZATION_NAME),
org, static_cast<DWORD>(sizeof(org) / sizeof(org[0])));
if (n > 1) {
// The rules compare ASCII (IEquals); a signer whose O= does not
// survive the narrowing is not one the list can name, so it fails.
const int written = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, org, -1, out,
static_cast<int>(cap), nullptr, nullptr);
ok = written > 1;
if (!ok && cap > 0) {
out[0] = '\0';
}
}
CertFreeCertificateContext(cert);
}
}
if (msg != nullptr) {
CryptMsgClose(msg);
}
if (store != nullptr) {
CertCloseStore(store, 0);
}
return ok;
}
Collected ModuleSignerOrganisationImpl(const wchar_t* modulePath, char* out, std::size_t cap) noexcept {
if (modulePath == nullptr || out == nullptr || cap == 0) {
return Collected::kFailed;
}
out[0] = '\0';
if (VerifyEmbeddedOffline(modulePath) != ERROR_SUCCESS) {
return Collected::kFailed;
}
return ReadSignerOrganisation(modulePath, out, cap) ? Collected::kOk : Collected::kFailed;
}
} // namespace
Sources SystemSources() noexcept {
@@ -685,6 +788,9 @@ Sources SystemSources() noexcept {
// Both identity seams, one implementation — see fl_guard.h §TWO SEAMS.
s.ModuleIsOurOwn = &FileIsOurOwnImpl;
s.PayloadIsOurOwn = &FileIsOurOwnImpl;
// §S19(b), the embedded half only. The catalog half is a deferral with a
// written rationale, not a gap nobody noticed.
s.ModuleSignerOrganisation = &ModuleSignerOrganisationImpl;
return s;
}
@@ -25,6 +25,13 @@ add_library(FrameLedger.Overlay SHARED src/dllmain.cpp)
# and third_party/fidelityfx/README.md: an Overlay that imports a vendor module
# fails to load in every game that ships no such module, in the loader, silently.
# hookinventory-check Pass C reads the built DLL's import AND export tables.
# fl_ac_floor: the anti-cheat MODULE families compiled into the guard, now also into
# the Overlay for the LoadLibrary detour's early stop (§S6). Types only from
# fl_ac_rules.h -- nothing of fl_ac_rules.cpp is compiled here, and the Overlay
# links neither wintrust nor the rules parser.
target_include_directories(FrameLedger.Overlay PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../FrameLedger.Injector/include")
add_dependencies(FrameLedger.Overlay fl_ac_floor_gen)
target_link_libraries(FrameLedger.Overlay PRIVATE fl_ac_floor)
target_link_libraries(FrameLedger.Overlay PRIVATE FrameLedger.Shm fl_dxgi_vtable fl_native_flags fl_hostile_env_flags minhook
fl_streamline_headers fl_fidelityfx_headers fl_fsr3_host_headers
Advapi32 d3d11 d3d12 dxgi)
+259 -135
View File
@@ -42,16 +42,23 @@
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_d3d12_vtable.h>
#include <fl_dxgi_vtable.h>
#include <fl_hook_inventory.h>
#include <fl_ring.h>
#include <fl_rt_accum.h>
#include <fl_shm.h>
#include <fl_shm_host.h>
#include <fl_sl_inputs.h>
#include <fl_sl_seen.h>
#include <MinHook.h>
#include <sddl.h>
// Its own block, below the sorted one, because it needs Family/Group/MatchKind
// from fl_ac_rules.h and clang-format sorts each block independently. Types plus
// the generated floor table only -- for the LoadLibrary detour's early stop; nothing
// of the rules parser is compiled into the Overlay.
#include <fl_ac_floor.generated.h>
// Vendored MIT headers, for TYPES ONLY -- never linked, and no vendor function's
// address is ever taken in evaluated code. See
@@ -94,134 +101,15 @@ void* g_base = nullptr;
fl::RingWriter g_writer;
HANDLE g_initThread = nullptr;
// The mapping is created with a DACL granting ONLY the current user's SID, and
// lives in the session-scoped Local\ namespace (docs/07_IPC.md §Security). No
// Global\ object: it would need admin and would be visible across sessions for
// no benefit.
//
// Returns false rather than falling back to a default DACL. A mapping the whole
// machine can write is not a degraded version of this one -- the Agent's control
// block is in it, and unhookRequested is the safety stop.
bool BuildUserOnlySecurity(SECURITY_ATTRIBUTES& sa, PSECURITY_DESCRIPTOR& sd) noexcept {
sd = nullptr;
HANDLE token = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
return false;
}
unsigned char buffer[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE]{};
DWORD got = 0;
const BOOL ok = GetTokenInformation(token, TokenUser, buffer, sizeof(buffer), &got);
CloseHandle(token);
if (!ok) {
return false;
}
LPWSTR sidText = nullptr;
const auto* user = reinterpret_cast<const TOKEN_USER*>(buffer);
if (!ConvertSidToStringSidW(user->User.Sid, &sidText)) {
return false;
}
// D:P = a protected DACL, so nothing is inherited in. One ACE, generic all,
// for us alone.
wchar_t sddl[256]{};
const int n = _snwprintf_s(sddl, _TRUNCATE, L"D:P(A;;GA;;;%ls)", sidText);
LocalFree(sidText);
if (n < 0) {
return false;
}
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &sd, nullptr)) {
return false;
}
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
return true;
}
// Local\FrameLedger.Ring.<pid>. Deliberately plain and identifiable: 19_SAFETY
// forbids obfuscated object names, because being visible to anti-cheat is the
// whole design posture.
bool MakeRingName(wchar_t* out, size_t cap, DWORD pid) noexcept {
return _snwprintf_s(out, cap, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid) >= 0;
}
// The ring host half -- the user-only DACL, the Local\FrameLedger.Ring.<pid> name,
// the mapping and the handshake -- lives in fl_shm_host.h since P1 item 3, SHARED
// with the Vulkan layer: one contract, one copy, for both capture sides.
bool CreateRing() noexcept {
SECURITY_ATTRIBUTES sa{};
PSECURITY_DESCRIPTOR sd = nullptr;
if (!BuildUserOnlySecurity(sa, sd)) {
return false;
}
wchar_t name[128]{};
if (!MakeRingName(name, 128, GetCurrentProcessId())) {
LocalFree(sd);
return false;
}
const size_t bytes = fl::FlShmSizeForCapacity(FL_SHM_DEFAULT_CAPACITY);
g_mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, static_cast<DWORD>(bytes >> 32),
static_cast<DWORD>(bytes & 0xFFFFFFFFu), name);
const DWORD err = GetLastError();
LocalFree(sd);
if (g_mapping == nullptr) {
return false;
}
// A pre-existing mapping under our own pid is not a mapping we understand:
// either a stale object or another writer. Refuse rather than share a ring
// with an unknown producer.
if (err == ERROR_ALREADY_EXISTS) {
CloseHandle(g_mapping);
g_mapping = nullptr;
return false;
}
g_base = MapViewOfFile(g_mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, bytes);
if (g_base == nullptr) {
CloseHandle(g_mapping);
g_mapping = nullptr;
return false;
}
return true;
return fl::shmhost::CreateRingMapping(g_mapping, g_base);
}
// Write-once at init, per docs/07_IPC.md §A + B. adapterLuid is deliberately
// left 0 = "not yet known": this runs two steps before any graphics module is
// resolved, and our own dummy device's adapter is not the game's (#36). It is
// published at first present, with the hook.
void PublishHandshake() noexcept {
auto* h = reinterpret_cast<FlShmHandshake*>(static_cast<unsigned char*>(g_base) + FL_SHM_HANDSHAKE_OFFSET);
h->recordSize = sizeof(FlFrameRecord);
h->capacity = FL_SHM_DEFAULT_CAPACITY;
h->pid = GetCurrentProcessId();
// FL_BUILD_ID comes from git describe at configure time (FrameLedger.Shm's
// CMakeLists). It had no producer at all until #36; without one the Agent's
// refuse-to-attach-on-mismatch compares "" with "" forever.
const char* build = FL_BUILD_ID;
size_t i = 0;
for (; i + 1 < sizeof(h->buildId) && build[i] != '\0'; ++i) {
h->buildId[i] = build[i];
}
h->buildId[i] = '\0';
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
h->qpcEpoch = static_cast<uint64_t>(qpc.QuadPart);
h->adapterLuid = 0;
// layoutVersion LAST, with a release fence in front of it. It is the field a
// reader validates first, so it must not become visible before the fields it
// vouches for. A reader that saw the version while capacity was still zero
// would compute a ring of no slots and read garbage.
std::atomic_thread_fence(std::memory_order_release);
std::atomic_ref<uint32_t> version{h->layoutVersion};
version.store(FL_SHM_LAYOUT_VERSION, std::memory_order_release);
fl::shmhost::PublishHandshake(g_base);
}
// ---------------------------------------------------------------------------
@@ -615,6 +503,12 @@ void StopObserving(uint32_t reason) noexcept {
// 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.
// The LoadLibrary detour's early stop (defined with the detour below; the present
// path reads it first): 0 = none; else 1-based index among the floor's MODULE
// families in rules order.
std::atomic<uint32_t> g_earlyStopFamily{0};
void PublishLoaderWords() noexcept;
bool MayObserve() noexcept {
if (g_observing.load(std::memory_order_acquire) == 0) {
return false;
@@ -631,6 +525,15 @@ bool MayObserve() noexcept {
return false;
}
// The IN-PROCESS stop, same path and same polarity: the LoadLibrary detour saw
// a module matching the compiled anti-cheat floor load. Published before the
// unhook so the reason is on the mapping whichever thread gets here first.
if (g_earlyStopFamily.load(std::memory_order_acquire) != 0u) {
PublishLoaderWords();
StopObserving(FL_STATUS_STOPPED_BLOCKLISTED);
return false;
}
// Pausing is not stopping: the Agent asked us to hold, and the supervision
// clock keeps running (in the watchdog), so a paused session still stops if
// the guard dies.
@@ -927,6 +830,9 @@ std::atomic<uint32_t> g_slTagCensus{0};
// watchdog-published, monotonic.
std::atomic<uint32_t> g_dxgiUnseen{0};
std::atomic<uint32_t> g_dxgiSamples{0};
// Whether FlWriterState::dxgiPresentsBeforeHook has been written: once, at the first
// hooked present, whichever chain it lands on.
std::atomic<bool> g_dxgiBeforeHookPublished{false};
// A PRESENT THIS HOOK SAW AND DECLINED TO RECORD IS NOT ONE IT NEVER SAW. While a
// session is paused (MayObserve false) the title keeps presenting and DXGI keeps
@@ -937,6 +843,180 @@ std::atomic<uint32_t> g_dxgiSamples{0};
// it: they do not move the counter (#35), so there is nothing to invalidate.
std::atomic<uint32_t> g_dxgiEpoch{0};
// ---------------------------------------------------------------------------
// THE LoadLibrary DETOUR (17_HOOK_ENGINE §DLL entry step 3; §H2; §S6). P1 item 1,
// 2026-09-06. Two jobs, one rule.
//
// The jobs: (a) a module the hook inventory or the runtime census names loaded
// AFTER init -- the watchdog is woken now instead of on its next 1 Hz tick, so
// the window in which a late vendor module's calls go unobserved shrinks from up
// to a second to milliseconds; (b) a module whose base name matches the
// anti-cheat floor compiled into this binary loaded mid-session -- the Overlay
// stops ITSELF on the next present or watchdog wake, the in-process half of
// 19_SAFETY §During a session, where the host's 30 s scan was the only half.
//
// The rule: the detour INSTALLS NOTHING AND UNHOOKS NOTHING INLINE. MinHook
// suspends every other thread to patch, and a LoadLibrary caller may hold the
// loader lock (a DllMain calling LoadLibrary is legal); suspending a thread that
// holds it, from a thread that then waits on it, is the deadlock §H2 names. So
// the detour reads a base name off the module the ORIGINAL returned, compares it
// against two fixed tables without allocating, stores two atomics, and signals an
// event. Everything that patches runs on the watchdog thread, outside the lock.
//
// kernelbase!LoadLibraryExW is the target because it is the funnel: LoadLibraryA,
// LoadLibraryW and LoadLibraryExA all reach it inside KernelBase, so one detour
// covers the four documented entry points. What it does NOT cover, stated:
// LdrLoadDll called directly (no measured title does), and delay-load thunks
// resolved before we attached (they went through it before we existed). The 1 Hz
// watchdog and the host's 30 s scan remain the backstops for both jobs.
//
// NOT an FL_HOOK_INVENTORY row: that table is (vendor module, exported symbol)
// and Pass A checks each row against measured vendor exports. This is a system
// module, and 17_HOOK_ENGINE §Hook inventory records the asymmetry beside the
// ray-tracing vtable slots, which are outside the table for the same reason.
// ---------------------------------------------------------------------------
using PFN_LoadLibraryExW = HMODULE(WINAPI*)(LPCWSTR, HANDLE, DWORD);
PFN_LoadLibraryExW g_origLoadLibraryExW = nullptr;
// Bit 15 = installed; bits 0..14 = wake-ups for inventoried modules (saturating).
constexpr uint32_t kLoaderInstalledBit = 0x8000u;
constexpr uint32_t kLoaderCountMask = 0x7FFFu;
std::atomic<uint32_t> g_loaderSignals{0};
// Auto-reset; the watchdog waits on it with its 1 s timeout, so a signal ends the
// wait early and a missing event (creation failed) degrades to the plain sleep.
HANDLE g_watchdogWake = nullptr;
const wchar_t* BaseNameOf(const wchar_t* path) noexcept {
const wchar_t* base = path;
for (const wchar_t* p = path; *p != L'\0'; ++p) {
if (*p == L'\\' || *p == L'/') {
base = p + 1;
}
}
return base;
}
wchar_t AsciiLower(wchar_t c) noexcept {
return (c >= L'A' && c <= L'Z') ? static_cast<wchar_t>(c + (L'a' - L'A')) : c;
}
// Case-insensitive ASCII compare of a wide base name against a narrow rule value:
// exact, or the value as a prefix. The rules are ASCII by schema, so a wide
// character outside ASCII simply never matches.
bool NameMatches(const wchar_t* base, const char* value, bool prefix) noexcept {
size_t i = 0;
for (; value[i] != '\0'; ++i) {
const wchar_t b = base[i];
if (b == L'\0' || AsciiLower(b) != AsciiLower(static_cast<wchar_t>(static_cast<unsigned char>(value[i])))) {
return false;
}
}
return prefix || base[i] == L'\0';
}
// The compiled floor's MODULE families, in order: the 1-based index of the first
// whose value matches, else 0. The same prefix/exact semantics the guard's
// MatchName applies to a base name, on the same generated table.
uint32_t MatchesFloorModule(const wchar_t* base) noexcept {
uint32_t index = 0;
for (const fl::guard::Family& f : fl::guard::generated::kFloorFamilies) {
if (f.group != fl::guard::Group::kModules) {
continue;
}
++index;
for (std::size_t v = 0; v < f.valueCount; ++v) {
if (NameMatches(base, f.values[v], f.match == fl::guard::MatchKind::kPrefix)) {
return index;
}
}
}
return 0;
}
// Does the inventory or the census name this module? A load of one of these is
// what the watchdog installs or counts on its next tick, so it is what wakes it.
bool ModuleIsInventoried(const wchar_t* base) noexcept {
#define FL_LOADER_NAME(mod, ...) \
if (_wcsicmp(base, mod) == 0) { \
return true; \
}
FL_HOOK_INVENTORY(FL_LOADER_NAME)
FL_RUNTIME_CENSUS(FL_LOADER_NAME)
#undef FL_LOADER_NAME
return false;
}
void WakeWatchdog() noexcept {
if (g_watchdogWake != nullptr) {
SetEvent(g_watchdogWake);
}
}
HMODULE WINAPI Hook_LoadLibraryExW(LPCWSTR name, HANDLE file, DWORD flags) noexcept {
// The original FIRST, always, and its result is returned untouched: this
// detour must be invisible to the loader's caller whatever happens below.
const HMODULE h = g_origLoadLibraryExW(name, file, flags);
FL_HOOK_GUARD({
// A data-file or resource mapping is not a module: no code runs from it
// and the loader does not list it, so neither job applies.
constexpr DWORD kNotAModule =
LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;
if (h != nullptr && (flags & kNotAModule) == 0u && g_observing.load(std::memory_order_acquire) != 0) {
// The module's real file name, not the caller's string: a relative or
// API-set name resolves to whatever the loader mapped, and that is the
// name the guard would see.
wchar_t path[MAX_PATH]{};
if (GetModuleFileNameW(h, path, MAX_PATH) != 0) {
const wchar_t* base = BaseNameOf(path);
const uint32_t family = MatchesFloorModule(base);
if (family != 0u) {
uint32_t none = 0;
g_earlyStopFamily.compare_exchange_strong(none, family, std::memory_order_acq_rel);
WakeWatchdog();
} else if (ModuleIsInventoried(base)) {
uint32_t cur = g_loaderSignals.load(std::memory_order_relaxed);
while ((cur & kLoaderCountMask) < kLoaderCountMask &&
!g_loaderSignals.compare_exchange_weak(cur, cur + 1u, std::memory_order_relaxed)) {
}
WakeWatchdog();
}
}
}
})
return h;
}
// Installed AFTER the present hooks, from InitThread, outside any loader lock.
// Failure is not fatal and is visible: bit 15 stays clear, so the report can say
// the detour is absent and the two backstops are all there is.
bool InstallLoaderHook() noexcept {
const HMODULE kb = GetModuleHandleW(L"kernelbase.dll");
if (kb == nullptr) {
return false;
}
void* target = reinterpret_cast<void*>(GetProcAddress(kb, "LoadLibraryExW"));
if (target == nullptr) {
return false;
}
if (MH_CreateHook(target, reinterpret_cast<void*>(&Hook_LoadLibraryExW),
reinterpret_cast<void**>(&g_origLoadLibraryExW)) != MH_OK ||
MH_EnableHook(target) != MH_OK) {
return false;
}
g_loaderSignals.fetch_or(kLoaderInstalledBit, std::memory_order_release);
return true;
}
void PublishLoaderWords() noexcept {
if (g_state == nullptr) {
return;
}
std::atomic_ref<uint16_t> signals{g_state->loaderSignals};
std::atomic_ref<uint16_t> family{g_state->earlyStopFamily};
signals.store(static_cast<uint16_t>(g_loaderSignals.load(std::memory_order_relaxed)), std::memory_order_relaxed);
family.store(static_cast<uint16_t>(g_earlyStopFamily.load(std::memory_order_relaxed)), std::memory_order_relaxed);
}
void NoteTagTypes(uint32_t typeBits, uint32_t routeShift) noexcept {
if (typeBits == 0u) {
return;
@@ -1845,7 +1925,13 @@ bool InstallRtHooks() noexcept {
// Overlay and was not in the Vulkan layer.
DWORD WINAPI WatchdogThread(LPVOID) noexcept {
for (;;) {
Sleep(kWatchdogIntervalMs);
// The 1 s tick, OR the LoadLibrary detour's wake -- whichever comes first.
// An event that failed to create degrades to the plain sleep.
if (g_watchdogWake != nullptr) {
WaitForSingleObject(g_watchdogWake, kWatchdogIntervalMs);
} else {
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
@@ -1860,18 +1946,32 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
return 0;
}
// The in-process stop, for a title that is NOT presenting (menu, hung,
// alt-tabbed) -- the case the present path cannot reach. Same order as the
// Agent's stop: before any install.
if (g_earlyStopFamily.load(std::memory_order_acquire) != 0u) {
PublishLoaderWords();
StopObserving(FL_STATUS_STOPPED_BLOCKLISTED);
return 0;
}
// The detour's words BEFORE the installers: a reader that sees the hook
// family appear must already be able to see the wake that caused it.
PublishLoaderWords();
// Lazy feature-hook installation. AFTER the two stops, never before: a
// tick that is going to unhook must not install anything first.
//
// THIS IS THE VEHICLE, AND IT IS WHY NO LoadLibrary HOOK IS NEEDED FOR
// P0. 17_HOOK_ENGINE §DLL entry step 5 installs feature hooks "the first
// time their module appears", and a game that loads Streamline lazily --
// most of them, since sl.interposer is pulled in at device creation --
// would be missed by a one-shot check at init. A LoadLibrary hook would
// catch it too, but it runs under the loader lock while MinHook suspends
// every thread to patch (§H2), so it must defer the work to a thread
// anyway. This thread already exists and already wakes once a second, so
// §S6 stays genuinely separable rather than becoming a prerequisite.
// THIS IS THE VEHICLE. 17_HOOK_ENGINE §DLL entry step 5 installs feature
// hooks "the first time their module appears", and a game that loads
// Streamline lazily -- most of them, since sl.interposer is pulled in at
// device creation -- would be missed by a one-shot check at init. The
// LoadLibrary detour (step 3, P1 item 1) does NOT install anything itself:
// it runs under the loader lock while MinHook suspends every thread to
// patch (§H2), so it only signals g_watchdogWake and the install still
// happens HERE, on this thread -- within milliseconds of the module rather
// than on the next tick. Through P0 the tick alone was the vehicle, which
// is why §S6 stayed separable rather than becoming a prerequisite.
//
// It RETRIES until it succeeds and latches only on SUCCESS. An
// install-attempted flag would give the module exactly one chance, at a
@@ -1889,6 +1989,7 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
PublishRuntimeCensus();
PublishSlTagCensus();
PublishDxgiPresentCounters();
PublishLoaderWords();
// Supervision loss. guardTicks counts COMPLETED guard evaluations, not
// seconds, so a stalled guard loop stops it advancing even while the
@@ -1977,6 +2078,12 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
g_dxgiUnseen.fetch_add(delta - 1u, std::memory_order_relaxed);
dxgiUnseenHere = fl::slseen::SaturateToByte(delta - 1u);
}
} else if (!slot->haveDxgiCount && g_state != nullptr &&
!g_dxgiBeforeHookPublished.exchange(true, std::memory_order_relaxed)) {
// The FIRST hooked present: DXGI's count is the presents that ran before
// this hook was in (fl_shm.h §dxgiPresentsBeforeHook). One store, once.
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
before.store(dxgiCount, std::memory_order_relaxed);
}
slot->lastDxgiCount = dxgiCount;
slot->dxgiEpoch = epoch;
@@ -2533,6 +2640,16 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
std::atomic_ref<uint32_t> status{g_state->status};
// "Not read" until the first hooked present, so a title that never presents is
// distinguishable from one whose first present the hook was in for. BEFORE the
// present hooks go in: a title presenting every 8 ms had its first hooked present
// between the install and a store placed after it, and the sentinel overwrote the
// measurement (caught by ctest fl_guard [launch] on the first run).
{
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
before.store(0xFFFFFFFFu, std::memory_order_relaxed);
}
if (MH_Initialize() != MH_OK || !InstallPresentHooks()) {
// Hooking failed, so nothing will ever be recorded. Staying at INIT says
// exactly that; READY would be a claim about a capture side that does not
@@ -2552,6 +2669,13 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
std::atomic_ref<uint32_t> hooks{g_state->hooksInstalledMask};
hooks.fetch_or(static_cast<uint32_t>(FL_HOOK_PRESENT), std::memory_order_relaxed);
// The watchdog's wake, created BEFORE the loader hook that signals it and before
// the thread that waits on it. Then the LoadLibrary detour -- non-fatal: without
// it the 1 Hz tick and the host's scan are the backstops, and bit 15 says so.
g_watchdogWake = CreateEventW(nullptr, FALSE, FALSE, nullptr);
InstallLoaderHook();
PublishLoaderWords();
status.store(FL_STATUS_READY, std::memory_order_release);
// AFTER the hooks, deliberately. The watchdog's only job is to take them out
+36 -2
View File
@@ -89,6 +89,12 @@ enum FlStatus : uint32_t {
FL_STATUS_READY = 1,
FL_STATUS_SELF_DISABLED = 2, // 3 hook faults; see 17_HOOK_ENGINE §Fault policy
FL_STATUS_UNHOOKED = 3,
// A module whose base name matches the anti-cheat floor compiled into the
// Overlay was loaded mid-session, and the Overlay stopped ITSELF -- the
// in-process half of 19_SAFETY §During a session (§S6, built 2026-09-06 as
// P1 item 1). FlWriterState::earlyStopFamily says which family. The host's
// 30 s scan remains the backstop and the only half that runs the signer tier.
FL_STATUS_STOPPED_BLOCKLISTED = 4,
};
// bits in FlWriterState::apiMask and FlFrameRecord::api
@@ -708,7 +714,33 @@ struct alignas(64) FlWriterState {
uint32_t dxgiPresentsUnseen; // @48 presents DXGI counted between two hooked presents, beyond the one seen
uint32_t dxgiPresentSamples; // @52 hooked presents on which the counter was read
uint32_t reserved[2]; // @56..63 must be zero; room for additive fields
// THE LoadLibrary DETOUR'S TWO WORDS (2026-09-06, P1 item 1; 17_HOOK_ENGINE §DLL
// entry step 3). The Overlay detours kernelbase!LoadLibraryExW -- the funnel every
// LoadLibrary* variant reaches -- and, never inline (§H2: MinHook suspends threads
// to patch, and the caller may hold the loader lock), only records what loaded and
// wakes the watchdog. Took reserved[0]; additive, no layout bump.
//
// loaderSignals: bit 15 = the detour is installed; bits 0..14 = how many times a
// module the hook inventory or the runtime census names was loaded and the
// watchdog was woken for it (saturating). A count of 0 with bit 15 set is a title
// that loaded every vendor module before we attached, which is the common case.
uint16_t loaderSignals; // @56
// earlyStopFamily: 0 = none; else the 1-based index, among the compiled floor's
// MODULE families in rules order, of the family whose value matched a module
// loaded mid-session. Set once (the first match wins) and status goes to
// FL_STATUS_STOPPED_BLOCKLISTED on the next present or watchdog wake.
uint16_t earlyStopFamily; // @58
// PRESENTS BEFORE THE FIRST HOOKED ONE (2026-09-06, P1 item 2 -- launch mode's
// own cost meter; 20_OPEN_QUESTIONS §S1 / §S13(c)). IDXGISwapChain::GetLastPresentCount
// as read at the FIRST present this hook saw, on the first chain it saw: DXGI's
// count of presents that chain had completed before we were there. 0 means the hook
// was in before the title's first present on that chain; N means N presents ran
// unhooked, which is the number §S1 said nobody had. 0xFFFFFFFF = not read (set at
// init; a title that never presents keeps it). Took the LAST reserved word --
// additive, no layout bump -- and the writer state now has NO slack: the next
// additive field is a layout bump.
uint32_t dxgiPresentsBeforeHook; // @60
// NOTE: there is deliberately no droppedRecords here. The writer has no
// reader index and cannot know whether the slot it overwrites was ever
@@ -916,7 +948,9 @@ static_assert(offsetof(FlWriterState, runtimeCensus) == 40);
static_assert(offsetof(FlWriterState, slTagCensus) == 44);
static_assert(offsetof(FlWriterState, dxgiPresentsUnseen) == 48);
static_assert(offsetof(FlWriterState, dxgiPresentSamples) == 52);
static_assert(offsetof(FlWriterState, reserved) == 56);
static_assert(offsetof(FlWriterState, loaderSignals) == 56);
static_assert(offsetof(FlWriterState, earlyStopFamily) == 58);
static_assert(offsetof(FlWriterState, dxgiPresentsBeforeHook) == 60);
static_assert(offsetof(FlControlBlock, pauseRequested) == 0);
static_assert(offsetof(FlControlBlock, unhookRequested) == 4);
@@ -0,0 +1,180 @@
// The capture side's HOST half of the shared-memory contract: create the one
// ring a process may carry, and publish the handshake a reader validates first.
//
// Header-only and shared by the two capture sides -- the injected Overlay and
// the Vulkan layer -- because 07_IPC says ONE ring per process, named
// Local\FrameLedger.Ring.<pid>, with ONE layout, ONE build id and ONE security
// descriptor, and two copies of that are two places for it to drift. It lived in
// FrameLedger.Overlay/src/dllmain.cpp until 2026-09-06 (P1 item 3), when the
// layer gained vkQueuePresentKHR and needed exactly the same thing.
//
// Not a hook path: this runs once, at init, on whichever thread creates the
// ring. It may allocate (LocalAlloc inside the SDDL conversion) and it may fail
// -- and every failure returns false, so the caller stays inert rather than
// sharing a ring it does not own.
//
// WHO OWNS THE RING WHEN BOTH SIDES ARE IN ONE PROCESS. A Vulkan title launched
// through the host has the layer mapped by the loader and could also receive the
// Overlay if the guard injected it; whichever creates the mapping FIRST owns it,
// and the other sees ERROR_ALREADY_EXISTS here and stays inert. That is the same
// rule the Overlay always had for a pre-existing mapping under its own pid --
// "either a stale object or another writer: refuse rather than share" -- and it
// is why the guard does not inject a Vulkan-only presenter at all
// (fl_guard.cpp, Reason::kTargetIsVulkanLayered).
#ifndef FRAMELEDGER_FL_SHM_HOST_H
#define FRAMELEDGER_FL_SHM_HOST_H
#include <windows.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <sddl.h>
#include "fl_shm.h"
#ifndef FL_BUILD_ID
#error "FL_BUILD_ID must be defined (FrameLedger.Shm's INTERFACE compile definition)"
#endif
namespace fl::shmhost {
// The mapping is created with a DACL granting ONLY the current user's SID, and
// lives in the session-scoped Local\ namespace (docs/07_IPC.md §Security). No
// Global\ object: it would need admin and would be visible across sessions for
// no benefit.
//
// Returns false rather than falling back to a default DACL. A mapping the whole
// machine can write is not a degraded version of this one -- the Agent's control
// block is in it, and unhookRequested is the safety stop.
inline bool BuildUserOnlySecurity(SECURITY_ATTRIBUTES& sa, PSECURITY_DESCRIPTOR& sd) noexcept {
sd = nullptr;
HANDLE token = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
return false;
}
unsigned char buffer[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE]{};
DWORD got = 0;
const BOOL ok = GetTokenInformation(token, TokenUser, buffer, sizeof(buffer), &got);
CloseHandle(token);
if (!ok) {
return false;
}
LPWSTR sidText = nullptr;
const auto* user = reinterpret_cast<const TOKEN_USER*>(buffer);
if (!ConvertSidToStringSidW(user->User.Sid, &sidText)) {
return false;
}
// D:P = a protected DACL, so nothing is inherited in. One ACE, generic all,
// for us alone.
wchar_t sddl[256]{};
const int n = _snwprintf_s(sddl, _TRUNCATE, L"D:P(A;;GA;;;%ls)", sidText);
LocalFree(sidText);
if (n < 0) {
return false;
}
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &sd, nullptr)) {
return false;
}
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
return true;
}
// Local\FrameLedger.Ring.<pid>. Deliberately plain and identifiable: 19_SAFETY
// forbids obfuscated object names, because being visible to anti-cheat is the
// whole design posture.
inline bool MakeRingName(wchar_t* out, std::size_t cap, DWORD pid) noexcept {
return _snwprintf_s(out, cap, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid) >= 0;
}
// Create and map this process's ring. On success `mapping` and `base` are set;
// on any failure both stay null and nothing is left open.
inline bool CreateRingMapping(HANDLE& mapping, void*& base) noexcept {
mapping = nullptr;
base = nullptr;
SECURITY_ATTRIBUTES sa{};
PSECURITY_DESCRIPTOR sd = nullptr;
if (!BuildUserOnlySecurity(sa, sd)) {
return false;
}
wchar_t name[128]{};
if (!MakeRingName(name, 128, GetCurrentProcessId())) {
LocalFree(sd);
return false;
}
const std::size_t bytes = fl::FlShmSizeForCapacity(FL_SHM_DEFAULT_CAPACITY);
HANDLE h = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, static_cast<DWORD>(bytes >> 32),
static_cast<DWORD>(bytes & 0xFFFFFFFFu), name);
const DWORD err = GetLastError();
LocalFree(sd);
if (h == nullptr) {
return false;
}
// A pre-existing mapping under our own pid is not a mapping we understand:
// either a stale object or another writer. Refuse rather than share a ring
// with an unknown producer (see the file header for the two-capture-sides case).
if (err == ERROR_ALREADY_EXISTS) {
CloseHandle(h);
return false;
}
void* view = MapViewOfFile(h, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, bytes);
if (view == nullptr) {
CloseHandle(h);
return false;
}
mapping = h;
base = view;
return true;
}
// Write-once at init, per docs/07_IPC.md §A + B. adapterLuid is deliberately
// left 0 = "not yet known": on the Overlay this runs two steps before any
// graphics module is resolved, and our own dummy device's adapter is not the
// game's (#36); on the layer there is no adapter LUID to publish at all.
inline void PublishHandshake(void* base) noexcept {
auto* h = reinterpret_cast<FlShmHandshake*>(static_cast<unsigned char*>(base) + FL_SHM_HANDSHAKE_OFFSET);
h->recordSize = sizeof(FlFrameRecord);
h->capacity = FL_SHM_DEFAULT_CAPACITY;
h->pid = GetCurrentProcessId();
// FL_BUILD_ID comes from git describe at configure time (FrameLedger.Shm's
// CMakeLists). It had no producer at all until #36; without one the Agent's
// refuse-to-attach-on-mismatch compares "" with "" forever.
const char* build = FL_BUILD_ID;
std::size_t i = 0;
for (; i + 1 < sizeof(h->buildId) && build[i] != '\0'; ++i) {
h->buildId[i] = build[i];
}
h->buildId[i] = '\0';
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
h->qpcEpoch = static_cast<std::uint64_t>(qpc.QuadPart);
h->adapterLuid = 0;
// layoutVersion LAST, with a release fence in front of it. It is the field a
// reader validates first, so it must not become visible before the fields it
// vouches for. A reader that saw the version while capacity was still zero
// would compute a ring of no slots and read garbage.
std::atomic_thread_fence(std::memory_order_release);
std::atomic_ref<std::uint32_t> version{h->layoutVersion};
version.store(FL_SHM_LAYOUT_VERSION, std::memory_order_release);
}
} // namespace fl::shmhost
#endif // FRAMELEDGER_FL_SHM_HOST_H
@@ -30,6 +30,24 @@ target_link_libraries(FrameLedger.VkLayer PRIVATE
add_dependencies(FrameLedger.VkLayer fl_ac_floor_gen)
set_target_properties(FrameLedger.VkLayer PROPERTIES OUTPUT_NAME "FrameLedger.VkLayer")
# TEST-ONLY flavour: the same sources with the supervision deadline shortened
# from 65 s to 1.5 s, so ctest fl_vklayer can prove §S2 part three -- the
# in-layer stop when guardTicks stops advancing -- in seconds rather than
# minutes. Never shipped: no version resource, no manifest, a different file
# name, and 12_BUILD publishes only what the App/Agent projects stage. The
# shipped DLL keeps FL_GUARD_TICK_DEADLINE_MS, the one number 07_IPC pins.
add_library(fl_vklayer_shortdeadline SHARED
src/layer.cpp
../FrameLedger.Injector/src/fl_ac_rules.cpp
FrameLedger.VkLayer.def
)
target_include_directories(fl_vklayer_shortdeadline PRIVATE ../FrameLedger.Injector/include)
target_link_libraries(fl_vklayer_shortdeadline PRIVATE
FrameLedger.Shm fl_native_flags fl_hostile_env_flags fl_vulkan_headers fl_jsmn Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_vklayer_shortdeadline fl_ac_floor_gen)
target_compile_definitions(fl_vklayer_shortdeadline PRIVATE FL_VKLAYER_TICK_DEADLINE_MS=1500u)
set_target_properties(fl_vklayer_shortdeadline PROPERTIES OUTPUT_NAME "FrameLedger.VkLayer.shortdeadline")
# Same requirement as the Overlay, and arguably sharper here: an implicit layer
# is machine-wide, so it can appear inside processes the user never associated
# with FrameLedger. It had better say who it is (docs/19_SAFETY).
+376 -4
View File
@@ -46,11 +46,14 @@
#include <vulkan/vk_layer.h>
#include <vulkan/vulkan.h>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_ring.h>
#include <fl_shm.h>
#include <fl_shm_host.h>
#include <psapi.h>
namespace fl::vklayer {
@@ -256,7 +259,356 @@ bool MustStayInert() noexcept {
}
// ---------------------------------------------------------------------------
// Loader interface. Everything forwards; nothing is observed.
// The capture side (P1 item 3): the ring, the present record, the stop.
//
// Created at the first vkCreateDevice of an ADMITTED process -- not at load, not
// at vkCreateInstance -- so a process the gates refused never has a mapping
// with its pid on it. Init is not a hook path; the present hook is, and it
// follows the Overlay's rules: SEH-guarded, allocation-free, lock-free, no
// logging, one record, forward.
// ---------------------------------------------------------------------------
bool ThisProcessIsEnabledCached();
// The supervision deadline. FL_VKLAYER_TICK_DEADLINE_MS exists so a TEST-ONLY
// flavour of this DLL (fl_vklayer_shortdeadline, never shipped) can prove the
// stop within seconds; the shipped layer uses the one number 07_IPC pins, the
// same the Overlay uses.
#ifndef FL_VKLAYER_TICK_DEADLINE_MS
#define FL_VKLAYER_TICK_DEADLINE_MS FL_GUARD_TICK_DEADLINE_MS
#endif
constexpr ULONGLONG kTickDeadlineMs = FL_VKLAYER_TICK_DEADLINE_MS;
HANDLE g_mapping = nullptr;
void* g_base = nullptr;
FlWriterState* g_state = nullptr;
FlControlBlock* g_control = nullptr;
fl::RingWriter g_writer;
std::atomic<uint32_t> g_observing{0};
std::atomic<uint32_t> g_captureState{0}; // 0 = not tried, 1 = live, 2 = failed (inert for good)
std::atomic<uint32_t> g_frameIndex{0};
std::atomic<uint32_t> g_lastTicks{0};
std::atomic<ULONGLONG> g_lastTickAt{0};
// Which device a queue belongs to is answered by the dispatch key: the loader
// gives a VkDevice and every VkQueue created from it the SAME first-pointer
// (the dispatch table), which is how every layer keys its per-device state.
inline void* DispatchKey(const void* dispatchable) noexcept {
return *reinterpret_cast<void* const*>(dispatchable);
}
struct DeviceSlot {
void* key = nullptr;
PFN_vkQueuePresentKHR present = nullptr;
PFN_vkCreateSwapchainKHR createSwapchain = nullptr;
PFN_vkDestroySwapchainKHR destroySwapchain = nullptr;
};
constexpr size_t kMaxDevices = 8;
DeviceSlot g_devices[kMaxDevices];
std::atomic<uint32_t> g_deviceCount{0};
bool HasDevice(void* key) noexcept {
const uint32_t n = g_deviceCount.load(std::memory_order_acquire);
for (uint32_t i = 0; i < n && i < kMaxDevices; ++i) {
if (g_devices[i].key == key) {
return true;
}
}
return false;
}
const DeviceSlot* FindDevice(void* key) noexcept {
const uint32_t n = g_deviceCount.load(std::memory_order_acquire);
for (uint32_t i = 0; i < n && i < kMaxDevices; ++i) {
if (g_devices[i].key == key) {
return &g_devices[i];
}
}
// A queue whose device we never registered (more than kMaxDevices, or a
// device created before the gates admitted us): forward through the first
// device's next pointer rather than through nothing.
return n != 0 ? &g_devices[0] : nullptr;
}
// Per-swapchain output size, keyed by the non-dispatchable handle; id 0 stays
// "unidentified" (fl_shm.h), exactly as the Overlay's table does.
struct SwapchainSlot {
std::atomic<uint64_t> handle{0};
uint32_t id = 0;
uint16_t w = 0;
uint16_t h = 0;
};
constexpr size_t kMaxSwapchains = 16;
SwapchainSlot g_swapchains[kMaxSwapchains];
std::atomic<uint32_t> g_nextSwapchainId{1};
const SwapchainSlot* FindSwapchain(VkSwapchainKHR sc) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
if (g_swapchains[i].handle.load(std::memory_order_acquire) == key) {
return &g_swapchains[i];
}
}
return nullptr;
}
void RememberSwapchain(VkSwapchainKHR sc, VkExtent2D extent) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
uint64_t none = 0;
if (g_swapchains[i].handle.compare_exchange_strong(none, ~0ull, std::memory_order_acq_rel)) {
g_swapchains[i].id = g_nextSwapchainId.fetch_add(1u, std::memory_order_relaxed);
g_swapchains[i].w = static_cast<uint16_t>(extent.width > 0xFFFFu ? 0u : extent.width);
g_swapchains[i].h = static_cast<uint16_t>(extent.height > 0xFFFFu ? 0u : extent.height);
g_swapchains[i].handle.store(key, std::memory_order_release); // visible LAST
return;
}
}
// Full: the present will carry id 0 = unidentified, never a wrong id.
}
void ForgetSwapchain(VkSwapchainKHR sc) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
uint64_t have = key;
if (g_swapchains[i].handle.compare_exchange_strong(have, 0ull, std::memory_order_acq_rel)) {
return;
}
}
}
// "Stops" = passthrough forever, with the reason on the mapping. There is no
// unhook: the loader owns the chain, and the Overlay's MH_DisableHook has no
// equivalent here. First reason wins, exactly as in the Overlay.
void StopObserving(uint32_t reason) noexcept {
uint32_t live = 1;
if (!g_observing.compare_exchange_strong(live, 0u, std::memory_order_acq_rel)) {
return;
}
if (g_state != nullptr) {
std::atomic_ref<uint32_t> status{g_state->status};
status.store(reason, std::memory_order_release);
}
}
LONG FlFilter(DWORD code) noexcept {
if (code == EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP) {
return EXCEPTION_CONTINUE_SEARCH;
}
return EXCEPTION_EXECUTE_HANDLER;
}
void NoteFault() noexcept {
if (g_state == nullptr) {
return;
}
std::atomic_ref<uint32_t> faults{g_state->faultCount};
if (faults.fetch_add(1, std::memory_order_acq_rel) + 1 >= 3) {
StopObserving(fl::FL_STATUS_SELF_DISABLED); // 17_HOOK_ENGINE §Fault policy: three faults, dormant
}
}
// The present-path decision. Same order and same polarity as the Overlay's
// MayObserve, minus the LoadLibrary detour it has no equivalent of -- plus the
// supervision check that the Overlay runs on its watchdog and this layer cannot
// (§S2 part three). guardTicks counts COMPLETED guard evaluations, not seconds;
// "never advanced" and "stopped advancing" are the same state, and the clock
// starts when the mapping is published.
bool MayObserve() noexcept {
if (g_observing.load(std::memory_order_acquire) == 0u) {
return false;
}
if (g_control == nullptr) {
return true;
}
std::atomic_ref<uint32_t> unhook{g_control->unhookRequested};
if (unhook.load(std::memory_order_acquire) != 0u) {
StopObserving(fl::FL_STATUS_UNHOOKED);
return false;
}
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.load(std::memory_order_relaxed)) {
g_lastTicks.store(now, std::memory_order_relaxed);
g_lastTickAt.store(t, std::memory_order_relaxed);
} else if (t - g_lastTickAt.load(std::memory_order_relaxed) >= kTickDeadlineMs) {
StopObserving(fl::FL_STATUS_UNHOOKED);
return false;
}
std::atomic_ref<uint32_t> paused{g_control->pauseRequested};
return paused.load(std::memory_order_relaxed) == 0u;
}
// Once, on the first admitted vkCreateDevice. Failure -- most likely the ring
// already existing because an Overlay got there first -- is final: the layer
// forwards and observes nothing, which is what an un-owned ring requires.
bool EnsureCapture() noexcept {
uint32_t expected = 0;
if (!g_captureState.compare_exchange_strong(expected, 3u, std::memory_order_acq_rel)) {
// 3 = in progress on another thread; treat as not yet live.
return g_captureState.load(std::memory_order_acquire) == 1u;
}
if (!fl::shmhost::CreateRingMapping(g_mapping, g_base)) {
g_captureState.store(2u, std::memory_order_release);
return false;
}
fl::shmhost::PublishHandshake(g_base);
g_state = reinterpret_cast<FlWriterState*>(static_cast<unsigned char*>(g_base) + FL_SHM_WRITER_OFFSET);
g_control = reinterpret_cast<FlControlBlock*>(static_cast<unsigned char*>(g_base) + FL_SHM_CONTROL_OFFSET);
if (!g_writer.Init(g_base, FL_SHM_DEFAULT_CAPACITY)) {
g_captureState.store(2u, std::memory_order_release);
return false;
}
g_lastTicks.store(0, std::memory_order_relaxed);
g_lastTickAt.store(GetTickCount64(), std::memory_order_relaxed);
{
std::atomic_ref<uint32_t> api{g_state->apiMask};
api.fetch_or(1u << fl::FL_API_VULKAN, std::memory_order_relaxed);
std::atomic_ref<uint32_t> hooks{g_state->hooksInstalledMask};
hooks.fetch_or(static_cast<uint32_t>(fl::FL_HOOK_PRESENT), std::memory_order_relaxed);
// No DXGI counter exists on this path; the word stays "not read".
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
before.store(0xFFFFFFFFu, std::memory_order_relaxed);
std::atomic_ref<uint32_t> status{g_state->status};
status.store(fl::FL_STATUS_READY, std::memory_order_release);
}
g_observing.store(1u, std::memory_order_release);
g_captureState.store(1u, std::memory_order_release);
return true;
}
// RULE 4: `pPresentInfo` is the argument of the API we intercept, and the only
// thing read from it is which swapchain(s) it names -- to look up an output size
// WE recorded at creation. Nothing of the game's is dereferenced beyond that.
void RecordPresent(const VkPresentInfoKHR* info) noexcept {
if (!MayObserve()) {
return;
}
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
const SwapchainSlot* slot = nullptr;
if (info != nullptr && info->swapchainCount > 0u && info->pSwapchains != nullptr) {
slot = FindSwapchain(info->pSwapchains[0]);
}
FlFrameRecord rec{};
rec.qpc = static_cast<uint64_t>(qpc.QuadPart);
rec.frameIndex = g_frameIndex.fetch_add(1u, std::memory_order_relaxed);
rec.api = static_cast<uint8_t>(fl::FL_API_VULKAN);
if (slot != nullptr) {
rec.swapchainId = slot->id;
rec.outputW = slot->w;
rec.outputH = slot->h;
}
// vkQueuePresentKHR carries no sync interval and no present flags, which is
// exactly why FL_MEASURED_PRESENT_ARGS exists rather than being assumed
// (fl_shm.h); only the output size may be claimed, and only when there is one.
rec.measuredMask = (rec.outputW != 0u && rec.outputH != 0u) ? fl::FL_MEASURED_OUTPUT_RES : 0u;
g_writer.Publish(rec);
}
// SEH around OUR code only, never around the forward (the Overlay's rule: a
// game's fault inside the next layer must not be counted as ours). A separate
// function because __try cannot share a frame with objects that need unwinding.
void RecordPresentGuarded(const VkPresentInfoKHR* info) noexcept {
__try {
RecordPresent(info);
} __except (FlFilter(GetExceptionCode())) {
NoteFault();
}
}
VKAPI_ATTR VkResult VKAPI_CALL QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) {
const DeviceSlot* d = (queue != nullptr) ? FindDevice(DispatchKey(queue)) : nullptr;
RecordPresentGuarded(pPresentInfo);
if (d == nullptr || d->present == nullptr) {
return VK_ERROR_DEVICE_LOST; // unreachable by construction: we only hand out this hook for registered
// devices
}
return d->present(queue, pPresentInfo);
}
VKAPI_ATTR VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) {
const DeviceSlot* d = (device != nullptr) ? FindDevice(DispatchKey(device)) : nullptr;
if (d == nullptr || d->createSwapchain == nullptr) {
return VK_ERROR_DEVICE_LOST;
}
const VkResult r = d->createSwapchain(device, pCreateInfo, pAllocator, pSwapchain);
if (r == VK_SUCCESS && pCreateInfo != nullptr && pSwapchain != nullptr && *pSwapchain != VK_NULL_HANDLE) {
RememberSwapchain(*pSwapchain, pCreateInfo->imageExtent); // rule 4: the API's own argument
}
return r;
}
VKAPI_ATTR void VKAPI_CALL DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
const VkAllocationCallbacks* pAllocator) {
if (swapchain != VK_NULL_HANDLE) {
ForgetSwapchain(swapchain);
}
const DeviceSlot* d = (device != nullptr) ? FindDevice(DispatchKey(device)) : nullptr;
if (d != nullptr && d->destroySwapchain != nullptr) {
d->destroySwapchain(device, swapchain, pAllocator);
}
}
// After the next layer's vkCreateDevice succeeded in an admitted process: the
// ring (once) and this device's next-pointers, resolved through the chain's own
// GetDeviceProcAddr so we call whatever sits below us and never the loader's
// trampoline for ourselves.
void RegisterDevice(VkDevice device) noexcept {
if (device == nullptr || g_nextGetDeviceProcAddr == nullptr || HasDevice(DispatchKey(device))) {
return;
}
// THE NEXT POINTERS FIRST, UNCONDITIONALLY. Once GetDeviceProcAddr has handed
// out our hooks, every present on this device passes through them, and a hook
// with nothing to forward to would fail the application's present -- measured
// 2026-09-06 as VK_ERROR_DEVICE_LOST on the harness when an injected Overlay
// owned the ring and the layer had registered nothing. The ring failing to
// come up must only ever mean "observe nothing", never "forward nothing".
const uint32_t i = g_deviceCount.load(std::memory_order_acquire);
if (i >= kMaxDevices) {
return;
}
DeviceSlot& d = g_devices[i];
d.key = DispatchKey(device);
d.present = reinterpret_cast<PFN_vkQueuePresentKHR>(g_nextGetDeviceProcAddr(device, "vkQueuePresentKHR"));
d.createSwapchain =
reinterpret_cast<PFN_vkCreateSwapchainKHR>(g_nextGetDeviceProcAddr(device, "vkCreateSwapchainKHR"));
d.destroySwapchain =
reinterpret_cast<PFN_vkDestroySwapchainKHR>(g_nextGetDeviceProcAddr(device, "vkDestroySwapchainKHR"));
g_deviceCount.store(i + 1u, std::memory_order_release); // visible LAST
// Then the capture side, whose failure (an Overlay already owning the ring,
// most likely) leaves the hooks in place as pure forwarders.
EnsureCapture();
}
bool Active() noexcept {
return ThisProcessIsEnabledCached() && !MustStayInert();
}
// The three names we answer for, in an admitted process, from either proc-addr
// entry: applications and layers above us may fetch device functions through
// vkGetInstanceProcAddr as well.
PFN_vkVoidFunction OurDeviceFunction(const char* pName) noexcept {
if (std::strcmp(pName, "vkQueuePresentKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&QueuePresentKHR);
}
if (std::strcmp(pName, "vkCreateSwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&CreateSwapchainKHR);
}
if (std::strcmp(pName, "vkDestroySwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&DestroySwapchainKHR);
}
return nullptr;
}
// ---------------------------------------------------------------------------
// Loader interface. Everything forwards; an admitted process is also observed.
// ---------------------------------------------------------------------------
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance, const char* pName);
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice device, const char* pName);
@@ -309,7 +661,13 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physicalDevice, con
}
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
return createDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
const VkResult r = createDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
// The capture side comes up HERE and only here: after the next layer built the
// device, and only in a process both gates admitted (P1 item 3).
if (r == VK_SUCCESS && pDevice != nullptr && Active()) {
RegisterDevice(*pDevice);
}
return r;
}
// Evaluated once, on first use. The enable-list decides what we INTERCEPT, not
@@ -339,8 +697,7 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance
return (g_nextGetInstanceProcAddr != nullptr) ? g_nextGetInstanceProcAddr(instance, pName) : nullptr;
}
// Exactly the entry points needed to stay in the chain and forward.
// vkQueuePresentKHR is deliberately absent — see the file header.
// The entry points needed to stay in the chain and forward, then ours.
if (std::strcmp(pName, "vkGetInstanceProcAddr") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&GetInstanceProcAddr);
}
@@ -350,6 +707,10 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance
if (std::strcmp(pName, "vkCreateDevice") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&CreateDevice);
}
// Past the gate: an admitted process gets our present / swapchain entries.
if (PFN_vkVoidFunction ours = OurDeviceFunction(pName); ours != nullptr) {
return ours;
}
if (g_nextGetInstanceProcAddr == nullptr) {
return nullptr;
}
@@ -363,6 +724,17 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice device, cons
if (std::strcmp(pName, "vkGetDeviceProcAddr") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&GetDeviceProcAddr);
}
if (Active()) {
if (PFN_vkVoidFunction ours = OurDeviceFunction(pName); ours != nullptr) {
// A device that reached us here without passing through CreateDevice
// (created before the gates were consulted, or beyond the table) is
// registered now, so the hook we hand out always has a next pointer.
if (device != nullptr) {
RegisterDevice(device);
}
return ours;
}
}
if (g_nextGetDeviceProcAddr == nullptr) {
return nullptr;
}
+35
View File
@@ -26,6 +26,7 @@ target_include_directories(fl_guard_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedge
target_link_libraries(fl_guard_test PRIVATE FrameLedger.Shm fl_native_flags fl_jsmn Catch2::Catch2WithMain
Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_guard_test fl_ac_floor_gen)
add_dependencies(fl_guard_test fl_stub_sl_common fl_stub_sl_interposer)
# /EHsc on the TEST BINARY only. Catch2 reports failures by throwing, and the
# top-level CMakeLists strips the compiler's default /EHsc so every target has
@@ -94,6 +95,12 @@ target_compile_definitions(fl_guard_test PRIVATE
FL_DXR_DISPATCH_W=${FL_DXR_DISPATCH_W}
FL_DXR_DISPATCH_H=${FL_DXR_DISPATCH_H}
FL_DXR_DISPATCH_D=${FL_DXR_DISPATCH_D}
# The Streamline stubs, for the LoadLibrary detour's late-load fixture (P1 item
# 1): sl.common is an inert decoy exporting nothing (also copied under an
# anti-cheat name for the early-stop case), sl.interposer is the module whose
# late arrival must be hooked within milliseconds rather than on the next tick.
FL_STUB_SL_COMMON=L"$<TARGET_FILE:fl_stub_sl_common>"
FL_STUB_SL_INTERPOSER=L"$<TARGET_FILE:fl_stub_sl_interposer>"
FL_OVERLAY_DLL=L"${FL_STAGED_OVERLAY}"
# The un-staged original, so a test can prove the check discriminates on
# DIRECTORY rather than on filename: same bytes, same name, wrong place.
@@ -103,6 +110,34 @@ add_dependencies(fl_guard_test hook-harness FrameLedger.Overlay fl_stage_overlay
add_test(NAME fl_guard COMMAND fl_guard_test)
# The Vulkan layer's capture side (P1 item 3), driven by a FAKE loader chain --
# no registry, no loader, no GPU -- so it is merge-gated. Three ctests, three
# processes, because one process carries one ring and each DLL flavour makes one.
# fl_ac_rules.cpp is compiled in for LocalAppDataDir / RulesFilePath, the same
# functions the layer reads through, so the files the test writes land exactly
# where the layer looks.
add_executable(fl_vklayer_test vklayer_test.cpp "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/src/fl_ac_rules.cpp")
target_include_directories(fl_vklayer_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/include")
target_link_libraries(fl_vklayer_test PRIVATE FrameLedger.Shm fl_native_flags fl_jsmn fl_vulkan_headers
Catch2::Catch2WithMain Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_vklayer_test fl_ac_floor_gen FrameLedger.VkLayer fl_vklayer_shortdeadline hook-harness)
target_compile_options(fl_vklayer_test PRIVATE /EHsc)
target_compile_definitions(fl_vklayer_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
FL_VKLAYER_DLL=L"$<TARGET_FILE:FrameLedger.VkLayer>"
FL_VKLAYER_SHORTDEADLINE_DLL=L"$<TARGET_FILE:fl_vklayer_shortdeadline>"
# The directory the loader is pointed at through VK_ADD_IMPLICIT_LAYER_PATH:
# it holds the generated manifest beside the DLL.
FL_VKLAYER_MANIFEST_DIR=L"$<TARGET_FILE_DIR:FrameLedger.VkLayer>"
FL_HARNESS_EXE=L"$<TARGET_FILE:hook-harness>"
FL_REPO_RULES=L"${CMAKE_SOURCE_DIR}/../../rules/detection-rules.json"
)
add_test(NAME fl_vklayer COMMAND fl_vklayer_test "[vklayer]")
add_test(NAME fl_vklayer_supervision COMMAND fl_vklayer_test "[vklayer-deadline]")
# The real-loader leg SKIPS (Catch2 exit 4) where there is no Vulkan loader or no
# presentable device -- CI, per the §S29(d) census -- and runs on a dev box.
add_test(NAME fl_vklayer_real COMMAND fl_vklayer_test "[vklayer-real]")
set_tests_properties(fl_vklayer_real PROPERTIES SKIP_RETURN_CODE 4)
# Check 4's fail-closed matrix, as its own ctest name so a regression in the
# static pre-scan is legible in the ctest summary rather than buried in
# fl_guard's total. Same binary, selected by tag — duplicating the evidence
+662 -5
View File
@@ -101,8 +101,15 @@ struct Fake {
// keeps its meaning and only the tests that care about identity pay for it.
std::vector<std::string> modules;
std::map<std::uint32_t, std::vector<std::string>> modulesByPid;
std::map<std::uint32_t, Collected> moduleResultByPid;
Collected moduleResult = Collected::kOk;
// Launch mode's fixture: after `moduleCallsBeforeLate` enumerations have answered
// with `modules`, every later one answers with `modulesLate` (when non-empty).
// The poll runs on the caller's thread, so a call count is what "later" means
// and no second thread has to write into this struct.
std::vector<std::string> modulesLate;
int moduleCallsBeforeLate = 0;
int moduleCalls = 0;
std::map<std::uint32_t, Collected> moduleResultByPid;
Collected moduleResult = Collected::kOk;
// Check 3's evidence. Defaults to a name no blocklist entry matches, so every
// pre-existing case keeps its meaning: check 3 runs, looks, and allows.
@@ -142,6 +149,13 @@ struct Fake {
// exempted, so it must refuse.
std::set<std::string> pathlessModules;
// §S19(b) — the signer seam: which modules verify, and as whom. A module absent
// from the map has no valid embedded signature (kFailed), which is what an
// unsigned DLL and a catalog-only system binary both look like to the embedded
// half. Empty by default, so no existing case is silently trusted.
std::map<std::string, std::string> signerByModule;
Collected signerResult = Collected::kOk;
// §S22 — the payload identity seam.
//
// DEFAULTS TO THE REAL IMPLEMENTATION, unlike every other member here, and
@@ -186,8 +200,10 @@ std::wstring FakeModulePath(const std::string& name) {
}
Collected FakeEnumModules(std::uint32_t pid, ModuleSink sink, void* ctx) {
const int call = g.moduleCalls++;
const auto it = g.modulesByPid.find(pid);
const auto& list = (it != g.modulesByPid.end()) ? it->second : g.modules;
const bool late = !g.modulesLate.empty() && call >= g.moduleCallsBeforeLate;
const auto& list = (it != g.modulesByPid.end()) ? it->second : (late ? g.modulesLate : g.modules);
for (const auto& m : list) {
const std::wstring path = FakeModulePath(m);
const bool pathless = g.pathlessModules.count(m) != 0;
@@ -297,6 +313,35 @@ Collected FakeModuleIsOurOwn(const wchar_t* modulePath, bool* isOurs) {
return Collected::kOk;
}
Collected FakeModuleSignerOrganisation(const wchar_t* modulePath, char* out, std::size_t cap) {
if (g.signerResult != Collected::kOk) {
// Writes a TRUSTED name and THEN fails — the same trap FakeModuleIsOurOwn
// sets: a caller that ignores the return code and reads the buffer would
// trust a module the seam could not verify.
if (out != nullptr && cap > 0) {
strcpy_s(out, cap, "Microsoft Corporation");
}
return g.signerResult;
}
if (out == nullptr || cap == 0) {
return Collected::kFailed;
}
out[0] = '\0';
if (modulePath == nullptr) {
// As the ours fake: answer "trusted" for a null path, deliberately wrong, so
// the guard's own null clause is load-bearing rather than redundant.
strcpy_s(out, cap, "Microsoft Corporation");
return Collected::kOk;
}
for (const auto& [name, org] : g.signerByModule) {
if (FakeModulePath(name) == modulePath) {
strcpy_s(out, cap, org.c_str());
return Collected::kOk;
}
}
return Collected::kFailed;
}
Collected FakePayloadIsOurOwn(const wchar_t* dllPath, bool* isOurs) {
switch (g.payload) {
case Fake::Payload::kOurs:
@@ -330,6 +375,7 @@ Sources FakeSources() {
s.EnumerateDirEntries = &FakeEnumDirEntries;
s.ModuleIsOurOwn = &FakeModuleIsOurOwn;
s.PayloadIsOurOwn = &FakePayloadIsOurOwn;
s.ModuleSignerOrganisation = &FakeModuleSignerOrganisation;
return s;
}
@@ -1075,15 +1121,160 @@ TEST_CASE("signer comparison is against O=, exact, and untrusted-by-default", "[
CHECK_FALSE(IsTrustedSigner(rules, ""));
}
TEST_CASE("a suspicious module name refuses while the signer path is unwired", "[guard][heuristic]") {
TEST_CASE("a suspicious module name refuses when the signer seam cannot vouch for it", "[guard][heuristic]") {
ResetFake();
g.modules = {"kernel32.dll", "someantitamper64.dll"};
g.modules = {"kernel32.dll", "someantitamper64.dll"}; // not in signerByModule: no valid signature
const Verdict v = EvaluateWithSources(1234, FakeSources());
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kSuspiciousUnsigned);
}
// ===========================================================================
// §S19(b) — the signer half, wired 2026-09-06 on row G1.
//
// 19_SAFETY's heuristic is "name fragment AND not signed by a known vendor". The
// fragment half has refused alone since the guard was written; this is the other
// conjunct. Most of the cases below are about what it must NOT do, because a
// clause that can turn a refusal into an allow is a clause that can be reached
// by the wrong module.
// ===========================================================================
TEST_CASE("§S19(b) — the compiled-in bound: the rules file may only INTERSECT it", "[guard][heuristic][S19]") {
ResetFake();
Rules rules;
REQUIRE(ParseRules(g.rulesJson.data(), g.rulesJson.size(), rules) == ParseResult::kOk);
// On both lists: trusted.
CHECK(IsCompiledTrustedSigner("Microsoft Corporation"));
CHECK(IsTrustedSigner(rules, "Microsoft Corporation"));
// On the compiled list, NOT in this rules file (the fixture names three): the
// data may narrow, so it is not trusted here.
CHECK(IsCompiledTrustedSigner("Intel Corporation"));
CHECK_FALSE(IsTrustedSigner(rules, "Intel Corporation"));
// In the rules file, NOT on the compiled list: the data may not widen. This is
// the owner's decision of 2026-09-06 in one assertion.
std::string widened = g.rulesJson;
const std::string needle = "\"Valve Corp.\"";
const std::size_t at = widened.find(needle);
REQUIRE(at != std::string::npos);
widened.replace(at, needle.size(), "\"Valve Corp.\", \"Evil Corp\"");
Rules wide;
REQUIRE(ParseRules(widened.data(), widened.size(), wide) == ParseResult::kOk);
CHECK_FALSE(IsCompiledTrustedSigner("Evil Corp"));
CHECK_FALSE(IsTrustedSigner(wide, "Evil Corp"));
CHECK(IsTrustedSigner(wide, "Valve Corp."));
// Never a substring, never a prefix, never empty.
CHECK_FALSE(IsCompiledTrustedSigner("Microsoft"));
CHECK_FALSE(IsCompiledTrustedSigner("NVIDIA Corporation Ltd"));
CHECK_FALSE(IsCompiledTrustedSigner(""));
CHECK_FALSE(IsCompiledTrustedSigner(nullptr));
}
TEST_CASE(
"§S19(b) — the fragment tier is suppressed for a module signed by a trusted organisation, and for nothing else",
"[guard][failclosed][S19]") {
ResetFake();
g.scanSet = {1234, 4000};
SECTION("a Microsoft-signed fragment module in an ANCESTOR -> Allow (the CI blocker's shape)") {
g.modulesByPid[1234] = {"kernel32.dll", "d3d11.dll"};
g.modulesByPid[4000] = {"kernel32.dll", "System.Security.Cryptography.ProtectedData.dll"};
g.signerByModule["System.Security.Cryptography.ProtectedData.dll"] = "Microsoft Corporation";
const Verdict v = EvaluateWithSources(1234, FakeSources());
INFO("reason was " << ReasonName(v.reason) << " signal=" << v.signal);
CHECK(v.Allowed());
}
SECTION("a Microsoft-signed fragment module in the TARGET -> Allow, unlike the ours exemption") {
// A game loading a signed key-protection provider is the false refusal
// this half exists to remove, so the target is NOT excluded here.
g.modulesByPid[1234] = {"kernel32.dll", "mskeyprotect.dll"};
g.signerByModule["mskeyprotect.dll"] = "Microsoft Corporation";
const Verdict v = EvaluateWithSources(1234, FakeSources());
INFO("reason was " << ReasonName(v.reason) << " signal=" << v.signal);
CHECK(v.Allowed());
}
SECTION("signed by an organisation the rules name but the binary does not -> refuse") {
std::string widened = g.rulesJson;
const std::string needle = "\"Valve Corp.\"";
widened.replace(widened.find(needle), needle.size(), "\"Valve Corp.\", \"Evil Corp\"");
g.rulesJson = widened;
g.modulesByPid[4000] = {"evilprotect.dll"};
g.signerByModule["evilprotect.dll"] = "Evil Corp";
const Verdict v = EvaluateWithSources(1234, FakeSources());
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kSuspiciousUnsigned);
}
SECTION("signed by an organisation on the compiled list but NOT in this rules file -> refuse") {
g.modulesByPid[4000] = {"intelprotect.dll"};
g.signerByModule["intelprotect.dll"] = "Intel Corporation"; // the fixture rules name three, not five
const Verdict v = EvaluateWithSources(1234, FakeSources());
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kSuspiciousUnsigned);
}
SECTION("a seam that CANNOT VERIFY does not suppress, even when it wrote a trusted name") {
g.modulesByPid[4000] = {"mskeyprotect.dll"};
g.signerByModule["mskeyprotect.dll"] = "Microsoft Corporation";
g.signerResult = Collected::kFailed;
const Verdict v = EvaluateWithSources(1234, FakeSources());
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kSuspiciousUnsigned);
}
SECTION("a MISSING seam does not suppress") {
g.modulesByPid[4000] = {"mskeyprotect.dll"};
g.signerByModule["mskeyprotect.dll"] = "Microsoft Corporation";
Sources s = FakeSources();
s.ModuleSignerOrganisation = nullptr;
const Verdict v = EvaluateWithSources(1234, s);
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kSuspiciousUnsigned);
}
SECTION("a module we could not LOCATE is not verified") {
g.modulesByPid[4000] = {"mskeyprotect.dll"};
g.signerByModule["mskeyprotect.dll"] = "Microsoft Corporation";
g.pathlessModules = {"mskeyprotect.dll"};
const Verdict v = EvaluateWithSources(1234, FakeSources());
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kSuspiciousUnsigned);
}
SECTION("LOAD ORDER: a trusted fragment module first, an unsigned one second -> refuse, naming the second") {
// The fail-open §S19(b) predicted for a latch-and-skip sink. The trusted
// module returns KEEP LOOKING, so the unsigned one after it is still seen.
g.modulesByPid[4000] = {"mskeyprotect.dll", "shadyprotect.dll"};
g.signerByModule["mskeyprotect.dll"] = "Microsoft Corporation";
const Verdict v = EvaluateWithSources(1234, FakeSources());
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kSuspiciousUnsigned);
CHECK(std::strcmp(v.signal, "shadyprotect.dll") == 0);
}
SECTION("only the FUZZY tier is suppressed — an EXACT blocklist hit stays a hit whoever signed it") {
g.modulesByPid[4000] = {"EasyAntiCheat.dll"};
g.signerByModule["EasyAntiCheat.dll"] = "Microsoft Corporation";
const Verdict v = EvaluateWithSources(1234, FakeSources());
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kBlockedModule);
}
}
// ===========================================================================
// The injection primitive, end to end.
//
@@ -1107,6 +1298,9 @@ TEST_CASE("a suspicious module name refuses while the signer path is unwired", "
// to, which is the only part of this suite that has a live Overlay to inspect.
#include <fl_ring.h>
#include <fl_shm.h>
// The compiled floor, so the early-stop case computes the family index the Overlay
// publishes from the same table rather than asserting a literal.
#include <fl_ac_floor.generated.h>
#include <vector>
namespace {
@@ -1274,6 +1468,115 @@ TEST_CASE("the injection primitive really loads our DLL into another process", "
CHECK(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
// §S19(b) against the REAL seams. The fakes above prove the decision; these two
// prove the seam: a real Authenticode verification of a real file the real
// module walk reported, in a process the real injection targets.
namespace {
// The CI blocker itself, where the test host's copy is staged from (the NuGet cache).
// fl-probe-signer looks in the same place, for the same reason.
std::wstring FindProtectedDataDll() {
wchar_t profile[MAX_PATH]{};
if (GetEnvironmentVariableW(L"USERPROFILE", profile, MAX_PATH) == 0) {
return {};
}
const std::wstring root = std::wstring(profile) + L"\\.nuget\\packages\\system.security.cryptography.protecteddata";
WIN32_FIND_DATAW fd{};
HANDLE h = FindFirstFileW((root + L"\\*").c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) {
return {};
}
std::wstring best;
do {
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 || fd.cFileName[0] == L'.') {
continue;
}
for (const wchar_t* under : {L"\\runtimes\\win\\lib\\net6.0\\", L"\\lib\\net6.0\\"}) {
const std::wstring c =
root + L"\\" + fd.cFileName + under + L"System.Security.Cryptography.ProtectedData.dll";
if (GetFileAttributesW(c.c_str()) != INVALID_FILE_ATTRIBUTES) {
best = c;
}
}
} while (FindNextFileW(h, &fd) != 0);
FindClose(h);
return best;
}
// Real module walk and real signer, fake everything else: the scan set is the
// child alone, the rules are the fixture's, and the payload check is real (kReal).
Sources RealModulesAndSigner() {
Sources s = FakeSources();
const Sources real = SystemSources();
s.EnumerateModules = real.EnumerateModules;
s.ModuleSignerOrganisation = real.ModuleSignerOrganisation;
s.ModuleIsOurOwn = real.ModuleIsOurOwn;
return s;
}
bool StartHarnessLoading(Child& child, const std::wstring& dll) {
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --load \"" + dll + L"\" --hold 30";
STARTUPINFOW si{};
si.cb = sizeof(si);
if (!CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
&child.pi)) {
return false;
}
Sleep(800);
return WaitForSingleObject(child.pi.hProcess, 0) == WAIT_TIMEOUT;
}
} // namespace
TEST_CASE("§S19(b), real seams — a target that loaded the Microsoft-signed CI blocker is ALLOWED",
"[guard][inject][S19]") {
const std::wstring dll = FindProtectedDataDll();
if (dll.empty()) {
// The NuGet cache is what stages it; a machine that never restored the test
// SDK has no copy. Loud, not green: the managed integration cases are the
// gate that cannot skip this.
SKIP("System.Security.Cryptography.ProtectedData.dll not in the NuGet cache on this machine");
}
Child child;
REQUIRE(StartHarnessLoading(child, dll));
REQUIRE(TargetHasModule(child.pi.dwProcessId, L"System.Security.Cryptography.ProtectedData.dll"));
ResetFake();
g.scanSet = {child.pi.dwProcessId};
const Verdict v = GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, RealModulesAndSigner());
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal);
REQUIRE(v.Allowed());
CHECK(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("§S19(b), real seams — a target that loaded an UNSIGNED fragment module is REFUSED, naming it",
"[guard][inject][S19]") {
// The negative: our own unsigned Overlay, copied under a fragment-bearing name to
// a directory that is not the guard's — unsigned (CLAUDE.md rule 9), `protect`
// in the name, and not ours by file id. Every clause of the heuristic, true.
wchar_t temp[MAX_PATH]{};
REQUIRE(GetTempPathW(MAX_PATH, temp) != 0);
const std::wstring copy = std::wstring(temp) + L"fl_s19_unsigned_protect_fixture.dll";
REQUIRE(CopyFileW(FL_OVERLAY_DLL, copy.c_str(), FALSE));
{
Child child;
REQUIRE(StartHarnessLoading(child, copy));
REQUIRE(TargetHasModule(child.pi.dwProcessId, L"fl_s19_unsigned_protect_fixture.dll"));
ResetFake();
g.scanSet = {child.pi.dwProcessId};
const Verdict v = GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, RealModulesAndSigner());
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal);
REQUIRE_FALSE(v.Allowed());
CHECK(v.reason == Reason::kSuspiciousUnsigned);
CHECK(_stricmp(v.signal, "fl_s19_unsigned_protect_fixture.dll") == 0);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
} // the child is gone before its module file is deleted
DeleteFileW(copy.c_str());
}
TEST_CASE("the injected Overlay publishes a handshake the Agent can validate", "[guard][inject][shm]") {
// End to end, through the real DLL: inject, then open Local\FrameLedger.Ring.<pid>
// from THIS process and check every field 04_CAPTURE says the Agent validates
@@ -1540,6 +1843,360 @@ TEST_CASE("the Agent's safety stop halts recording within a frame", "[guard][inj
CloseHandle(mapping);
}
// ===========================================================================
// P1 item 1 -- the LoadLibrary detour (17_HOOK_ENGINE §DLL entry step 3, §H2, §S6).
// Both jobs, against the real Overlay in a real target: a vendor module that
// arrives LATE is hooked within milliseconds of its arrival, and an anti-cheat-
// named module that arrives late stops the Overlay by itself.
// ===========================================================================
namespace {
struct MappedRing {
HANDLE mapping = nullptr;
void* base = nullptr;
fl::FlWriterState* st = nullptr;
fl::FlControlBlock* ctl = nullptr;
~MappedRing() {
if (base != nullptr) {
UnmapViewOfFile(base);
}
if (mapping != nullptr) {
CloseHandle(mapping);
}
}
};
bool OpenRingFor(DWORD pid, MappedRing& r) {
wchar_t name[128]{};
if (_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid) <= 0) {
return false;
}
for (int i = 0; i < 100 && r.mapping == nullptr; ++i) {
r.mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (r.mapping == nullptr) {
Sleep(50);
}
}
if (r.mapping == nullptr) {
return false;
}
r.base = MapViewOfFile(r.mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (r.base == nullptr) {
return false;
}
r.st = reinterpret_cast<fl::FlWriterState*>(static_cast<unsigned char*>(r.base) + FL_SHM_WRITER_OFFSET);
r.ctl = reinterpret_cast<fl::FlControlBlock*>(static_cast<unsigned char*>(r.base) + FL_SHM_CONTROL_OFFSET);
for (int i = 0; i < 100 && r.st->status != fl::FL_STATUS_READY; ++i) {
Sleep(50);
}
return r.st->status == fl::FL_STATUS_READY;
}
bool StartHarness(Child& child, const std::wstring& args) {
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" " + args;
STARTUPINFOW si{};
si.cb = sizeof(si);
if (!CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
&child.pi)) {
return false;
}
Sleep(800);
return WaitForSingleObject(child.pi.hProcess, 0) == WAIT_TIMEOUT;
}
} // namespace
TEST_CASE("the LoadLibrary detour hooks a vendor module that arrives LATE within milliseconds, not on the next tick",
"[guard][inject][shm][loader]") {
// The harness presents with no vendor module, then loads sl.common (an inert
// decoy) and sl.interposer 2.0 / 2.3 s in. Before: no upscaler hook. After: the
// hook family appears within 500 ms of the module -- the detour woke the
// watchdog. The 1 Hz tick alone would land anywhere in the next second, so a
// latency bound under half of that is what discriminates the wake from the tick.
Child child;
std::wstring args = L"--real --hold-presenting 14 --load-after-ms 2000 \"" + std::wstring(FL_STUB_SL_COMMON) +
L"\" --load-after-ms 2300 \"" + std::wstring(FL_STUB_SL_INTERPOSER) + L"\"";
REQUIRE(StartHarness(child, args));
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
REQUIRE(GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed());
MappedRing r;
REQUIRE(OpenRingFor(child.pi.dwProcessId, r));
CHECK((r.st->loaderSignals & 0x8000u) != 0u); // the detour installed
// Nothing vendor-shaped yet: the identity family is absent and stays absent.
Sleep(300);
++r.ctl->guardTicks;
REQUIRE((r.st->hooksInstalledMask & fl::FL_HOOK_UPSCALER_IDENTITY) == 0u);
// Wait for the interposer to appear in the target, then time the family.
ULONGLONG appeared = 0;
for (int i = 0; i < 400 && appeared == 0; ++i) {
if (TargetHasModule(child.pi.dwProcessId, L"sl.interposer.dll")) {
appeared = GetTickCount64();
break;
}
Sleep(10);
}
REQUIRE(appeared != 0);
ULONGLONG hooked = 0;
for (int i = 0; i < 300 && hooked == 0; ++i) {
if ((r.st->hooksInstalledMask & fl::FL_HOOK_UPSCALER_IDENTITY) != 0u) {
hooked = GetTickCount64();
break;
}
++r.ctl->guardTicks;
Sleep(10);
}
REQUIRE(hooked != 0);
const ULONGLONG latencyMs = hooked - appeared;
INFO("late-load hook latency " << latencyMs << " ms, loaderSignals=0x" << std::hex << r.st->loaderSignals);
CHECK(latencyMs < 500);
// The wake count is published by the watchdog, on its own iteration; give it
// the iteration rather than racing the install that the wake caused.
for (int i = 0; i < 200 && (r.st->loaderSignals & 0x7FFFu) == 0u; ++i) {
++r.ctl->guardTicks;
Sleep(10);
}
CHECK((r.st->loaderSignals & 0x7FFFu) >= 1u); // the detour saw an inventoried module and woke the watchdog
CHECK(r.st->earlyStopFamily == 0u);
CHECK(r.st->status == fl::FL_STATUS_READY);
}
TEST_CASE("the LoadLibrary detour stops the Overlay by itself when an anti-cheat-named module arrives",
"[guard][inject][shm][loader][S6]") {
// The in-process half of 19_SAFETY §During a session. A decoy DLL copied under a
// name the compiled floor's first module family matches by prefix is loaded 2.5 s
// in; the Overlay must stop within a frame, name the family, and stay stopped.
wchar_t temp[MAX_PATH]{};
REQUIRE(GetTempPathW(MAX_PATH, temp) != 0);
const std::wstring copy = std::wstring(temp) + L"EasyAntiCheat_fl_fixture.dll";
REQUIRE(CopyFileW(FL_STUB_SL_COMMON, copy.c_str(), FALSE));
// The expected index, computed from the same generated table the Overlay
// compiled in -- never a literal 1, so a reordered rules file moves both sides.
uint32_t expected = 0;
{
uint32_t index = 0;
for (const fl::guard::Family& f : fl::guard::generated::kFloorFamilies) {
if (f.group != fl::guard::Group::kModules) {
continue;
}
++index;
for (std::size_t v = 0; v < f.valueCount && expected == 0; ++v) {
if (f.match == fl::guard::MatchKind::kPrefix &&
_strnicmp("EasyAntiCheat_fl_fixture.dll", f.values[v], std::strlen(f.values[v])) == 0) {
expected = index;
}
}
if (expected != 0) {
break;
}
}
}
REQUIRE(expected != 0);
{
Child child;
std::wstring args = L"--real --hold-presenting 14 --load-after-ms 2500 \"" + copy + L"\"";
REQUIRE(StartHarness(child, args));
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
REQUIRE(GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed());
MappedRing r;
REQUIRE(OpenRingFor(child.pi.dwProcessId, r));
// It really was recording, with the supervision clock kept alive.
std::uint64_t before = 0;
for (int i = 0; i < 40 && before < 5; ++i) {
++r.ctl->guardTicks;
Sleep(100);
before = r.st->writeIndex;
}
REQUIRE(before > 5);
// THE STOP, from inside: no unhookRequested from this side, ever.
for (int i = 0; i < 100 && r.st->status != fl::FL_STATUS_STOPPED_BLOCKLISTED; ++i) {
++r.ctl->guardTicks;
Sleep(50);
}
CHECK(r.st->status == fl::FL_STATUS_STOPPED_BLOCKLISTED);
CHECK(r.st->earlyStopFamily == expected);
CHECK(r.ctl->unhookRequested == 0u);
// And it stays stopped while the harness keeps presenting and the ticks keep coming.
const std::uint64_t atStop = r.st->writeIndex;
for (int i = 0; i < 10; ++i) {
++r.ctl->guardTicks;
Sleep(100);
}
CHECK(r.st->writeIndex == atStop);
} // the child is gone before its module file is deleted
DeleteFileW(copy.c_str());
}
// ===========================================================================
// P1 item 2 -- launch mode as "inject late" (20_OPEN_QUESTIONS §S1 / §S13(c)):
// the poll decides WHEN the guard runs, never WHETHER it passes.
// ===========================================================================
TEST_CASE("launch mode injects the moment a presentation runtime is mapped, and not one poll before",
"[guard][inject][launch]") {
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"}; // a target still in its loader: no runtime yet
g.modulesLate = {"kernel32.dll", "dxgi.dll", "d3d11.dll"};
g.moduleCallsBeforeLate = 6; // the seventh poll (~300 ms) is the first that sees it
g.scanSet = {child.pi.dwProcessId};
const ULONGLONG t0 = GetTickCount64();
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
const ULONGLONG waited = GetTickCount64() - t0;
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal << " waited " << waited << " ms, polls "
<< g.moduleCalls);
REQUIRE(v.Allowed());
CHECK(g.moduleCalls >= 7); // it really waited for the runtime rather than injecting on sight
CHECK(waited >= 250);
CHECK(waited < 3000);
CHECK(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("launch mode: a target that exits before mapping a runtime is refused and nothing is injected",
"[guard][inject][launch]") {
Child child;
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --hold 1";
STARTUPINFOW si{};
si.cb = sizeof(si);
REQUIRE(CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
&child.pi));
ResetFake();
g.modules = {"kernel32.dll"}; // never a runtime
g.scanSet = {child.pi.dwProcessId};
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 20000, FakeSources());
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal);
CHECK(v.reason == Reason::kLaunchTargetExited);
CHECK_FALSE(v.Allowed());
}
TEST_CASE("launch mode: no presentation runtime inside the budget refuses, naming the budget's end",
"[guard][inject][launch]") {
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
const ULONGLONG t0 = GetTickCount64();
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 400, FakeSources());
const ULONGLONG waited = GetTickCount64() - t0;
INFO("reason " << ReasonName(v.reason) << " waited " << waited << " ms");
CHECK(v.reason == Reason::kLaunchNoPresentationRuntime);
CHECK(waited >= 400);
CHECK(waited < 2500);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("launch mode: the poll matches no blocklist, so anti-cheat mapped beside the runtime is the FULL scan's "
"refusal, and nothing is injected",
"[guard][inject][launch]") {
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"};
g.modulesLate = {"kernel32.dll", "EasyAntiCheat_EOS.dll", "dxgi.dll", "d3d12.dll"};
g.moduleCallsBeforeLate = 2;
g.scanSet = {child.pi.dwProcessId};
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
INFO("reason " << ReasonName(v.reason) << " family=" << v.family << " signal=" << v.signal);
CHECK(v.reason == Reason::kBlockedModule);
CHECK(std::string(v.signal) == "EasyAntiCheat_EOS.dll");
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("launch mode: a Vulkan-only presenter passes the FULL guard and is NOT injected -- the layer is the capture "
"side",
"[guard][inject][launch][vulkan]") {
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"};
g.modulesLate = {"kernel32.dll", "vulkan-1.dll"}; // no dxgi, no d3d, no opengl32
g.moduleCallsBeforeLate = 2;
g.scanSet = {child.pi.dwProcessId};
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal);
CHECK(v.reason == Reason::kTargetIsVulkanLayered);
CHECK_FALSE(v.Allowed());
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
// ...and the full guard really ran: anti-cheat beside vulkan-1 is refused by name.
ResetFake();
g.modules = {"kernel32.dll", "vulkan-1.dll", "BEClient_x64.dll"};
g.scanSet = {child.pi.dwProcessId};
const Verdict blocked =
GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
CHECK(blocked.reason == Reason::kBlockedModule);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
// A title that maps vulkan-1 BESIDE a D3D runtime is STILL the layer's: an NVIDIA
// Vulkan ICD maps dxgi + d3d12 itself (measured on the harness's --vulkan mode),
// so this is what every Vulkan title looks like there.
ResetFake();
g.modules = {"kernel32.dll", "vulkan-1.dll", "dxgi.dll", "d3d12.dll"};
g.scanSet = {child.pi.dwProcessId};
const Verdict both = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
CHECK(both.reason == Reason::kTargetIsVulkanLayered);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("launch mode against the real harness through the real module seam: injected once dxgi maps, and the "
"writer says how many presents ran unhooked",
"[guard][inject][shm][launch]") {
// The harness creates its device at startup and presents every 8 ms; the seam is
// the real EnumProcessModulesEx. What the writer reports afterwards is exactly the
// number 20_OPEN_QUESTIONS §S1 said nobody had: presents completed on the chain
// before the hook was in. Here that is however many the harness managed between
// its first present and our injection -- a measurement, not a target.
Child child;
REQUIRE(StartHarness(child, L"--real --hold-presenting 12"));
ResetFake();
g.scanSet = {child.pi.dwProcessId};
const ULONGLONG t0 = GetTickCount64();
const Verdict v =
GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, RealModulesAndSigner());
const ULONGLONG waited = GetTickCount64() - t0;
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal << " waited " << waited << " ms");
REQUIRE(v.Allowed());
CHECK(waited < 2000); // the runtime was already there: one poll, then the full guard
MappedRing r;
REQUIRE(OpenRingFor(child.pi.dwProcessId, r));
for (int i = 0; i < 60 && r.st->writeIndex == 0; ++i) {
++r.ctl->guardTicks;
Sleep(50);
}
REQUIRE(r.st->writeIndex > 0);
const uint32_t before = r.st->dxgiPresentsBeforeHook;
INFO("presents before the first hooked present: " << before);
CHECK(before != 0xFFFFFFFFu); // read at the first hooked present
CHECK(before < 5000); // the harness ran ~1 s at ~120/s before we were in; not a bound on a title
}
TEST_CASE("the injected Overlay records real presents into the ring", "[guard][inject][shm]") {
// The end-to-end claim the whole hook layer exists for, against a target that
// is PRESENTING WHILE WE INJECT. --hold cannot be used here: it presents 240
+559
View File
@@ -0,0 +1,559 @@
// The Vulkan layer's capture side (P1 item 3): vkQueuePresentKHR intercepted,
// the ring written, the in-layer supervision stop (§S2 part three) -- driven
// end to end by a FAKE loader chain, exactly as 20_OPEN_QUESTIONS §S2 said it
// would land: "in the PR that adds the present hook, where a fake loader chain
// can drive it end to end".
//
// Three ctests, three processes, because a process carries ONE ring and each
// flavour of the DLL creates one:
// [vklayer] the shipped DLL: records, forwarding, the unhook stop
// [vklayer-deadline] the short-deadline flavour: guardTicks stops -> the layer stops
// [vklayer-real] the REAL loader, the REAL harness (--vulkan), via
// VK_ADD_IMPLICIT_LAYER_PATH -- SKIPPED where there is no
// Vulkan loader or no presentable device (CI, §S29(d))
//
// The layer reads its enable-list and rules from the ONE product location under
// %LOCALAPPDATA% and there is deliberately no override (§S3), so this test writes
// its own image name into that enable-list and, when no rules file is installed,
// the repository seed -- and removes exactly what it added. It never touches an
// existing rules file.
#include <windows.h>
#include <vulkan/vk_layer.h>
#include <vulkan/vulkan.h>
#include <atomic>
#include <catch2/catch_test_macros.hpp>
#include <cstdio>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_shm.h>
#include <string>
namespace {
// ---------------------------------------------------------------------------
// The product's files: enable-list + rules, added and removed by this test.
// ---------------------------------------------------------------------------
struct ProductFiles {
std::wstring enableList;
std::string enableListBackup; // the previous contents, when there were any
bool hadEnableList = false;
std::wstring rules;
bool installedRules = false;
static std::wstring LocalAppData() {
wchar_t base[fl::guard::kMaxRulesPathLen]{};
REQUIRE(fl::guard::LocalAppDataDir(base, fl::guard::kMaxRulesPathLen));
return base;
}
static void EnsureDir(const std::wstring& dir) {
std::wstring cur;
for (size_t i = 0; i < dir.size(); ++i) {
cur += dir[i];
if ((dir[i] == L'\\' || i + 1 == dir.size()) && cur.size() > 3) {
CreateDirectoryW(cur.c_str(), nullptr);
}
}
}
static bool ReadAll(const std::wstring& path, std::string& out) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return false;
}
char buf[4096];
DWORD n = 0;
out.clear();
while (ReadFile(h, buf, sizeof(buf), &n, nullptr) && n > 0) {
out.append(buf, n);
}
CloseHandle(h);
return true;
}
static bool WriteAll(const std::wstring& path, const std::string& text) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return false;
}
DWORD n = 0;
const BOOL ok = WriteFile(h, text.data(), static_cast<DWORD>(text.size()), &n, nullptr);
CloseHandle(h);
return ok && n == text.size();
}
// Adds `imageName` to the enable-list (creating it if needed) and installs the
// repository seed rules when no rules file exists.
void Install(const char* imageName) {
const std::wstring base = LocalAppData();
const std::wstring dir = base + L"\\FrameLedger\\vklayer";
EnsureDir(dir);
enableList = dir + L"\\enabled.txt";
std::string existing;
hadEnableList = ReadAll(enableList, existing);
if (hadEnableList) {
enableListBackup = existing;
}
std::string text = existing;
if (!text.empty() && text.back() != '\n') {
text += '\n';
}
text += "# added by fl_vklayer_test, removed when it exits\n";
text += imageName;
text += '\n';
REQUIRE(WriteAll(enableList, text));
wchar_t rulesPath[fl::guard::kMaxRulesPathLen]{};
REQUIRE(fl::guard::RulesFilePath(rulesPath, fl::guard::kMaxRulesPathLen));
rules = rulesPath;
if (GetFileAttributesW(rulesPath) == INVALID_FILE_ATTRIBUTES) {
const std::wstring rulesDir = rules.substr(0, rules.find_last_of(L'\\'));
EnsureDir(rulesDir);
REQUIRE(CopyFileW(FL_REPO_RULES, rulesPath, TRUE));
installedRules = true;
}
}
~ProductFiles() {
if (!enableList.empty()) {
if (hadEnableList) {
WriteAll(enableList, enableListBackup);
} else {
DeleteFileW(enableList.c_str());
}
}
if (installedRules) {
DeleteFileW(rules.c_str());
}
}
};
std::string OwnImageName() {
char full[MAX_PATH]{};
REQUIRE(GetModuleFileNameA(nullptr, full, MAX_PATH) != 0);
const char* leaf = std::strrchr(full, '\\');
return leaf != nullptr ? leaf + 1 : full;
}
// ---------------------------------------------------------------------------
// The fake loader chain. Dispatchable handles are objects whose FIRST word is the
// dispatch key, which is what the loader guarantees and what the layer keys on;
// the device and its queue share one key, as they do under a real loader.
// ---------------------------------------------------------------------------
void* g_deviceKey = &g_deviceKey;
void* g_instanceKey = &g_instanceKey;
struct Dispatchable {
void* key;
};
Dispatchable g_instanceObj{g_instanceKey};
Dispatchable g_deviceObj{g_deviceKey};
Dispatchable g_queueObj{g_deviceKey};
std::atomic<int> g_forwardedPresents{0};
std::atomic<int> g_destroyed{0};
VkSwapchainKHR g_lastPresented = VK_NULL_HANDLE;
const VkSwapchainKHR kFakeSwapchain = reinterpret_cast<VkSwapchainKHR>(static_cast<uintptr_t>(0x1234));
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateInstance(const VkInstanceCreateInfo*, const VkAllocationCallbacks*,
VkInstance* pInstance) {
*pInstance = reinterpret_cast<VkInstance>(&g_instanceObj);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateDevice(VkPhysicalDevice, const VkDeviceCreateInfo*,
const VkAllocationCallbacks*, VkDevice* pDevice) {
*pDevice = reinterpret_cast<VkDevice>(&g_deviceObj);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeQueuePresent(VkQueue, const VkPresentInfoKHR* info) {
++g_forwardedPresents;
g_lastPresented = (info != nullptr && info->swapchainCount > 0) ? info->pSwapchains[0] : VK_NULL_HANDLE;
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateSwapchain(VkDevice, const VkSwapchainCreateInfoKHR*,
const VkAllocationCallbacks*, VkSwapchainKHR* out) {
*out = kFakeSwapchain;
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL FakeDestroySwapchain(VkDevice, VkSwapchainKHR, const VkAllocationCallbacks*) {
++g_destroyed;
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL FakeGetDeviceProcAddr(VkDevice, const char* name) {
if (std::strcmp(name, "vkQueuePresentKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeQueuePresent);
}
if (std::strcmp(name, "vkCreateSwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateSwapchain);
}
if (std::strcmp(name, "vkDestroySwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeDestroySwapchain);
}
return nullptr;
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL FakeGetInstanceProcAddr(VkInstance, const char* name) {
if (std::strcmp(name, "vkCreateInstance") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateInstance);
}
if (std::strcmp(name, "vkCreateDevice") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateDevice);
}
return nullptr;
}
// The layer, driven as the loader would drive it: negotiate, create an instance
// through the chain, create a device through the chain, fetch the device entries.
struct DrivenLayer {
HMODULE dll = nullptr;
PFN_vkGetInstanceProcAddr gipa = nullptr;
PFN_vkGetDeviceProcAddr gdpa = nullptr;
VkInstance instance = nullptr;
VkDevice device = nullptr;
PFN_vkQueuePresentKHR present = nullptr;
PFN_vkCreateSwapchainKHR createSwapchain = nullptr;
PFN_vkDestroySwapchainKHR destroySwapchain = nullptr;
void Drive(const wchar_t* path) {
dll = LoadLibraryW(path);
REQUIRE(dll != nullptr);
auto negotiate = reinterpret_cast<PFN_vkNegotiateLoaderLayerInterfaceVersion>(
GetProcAddress(dll, "vkNegotiateLoaderLayerInterfaceVersion"));
REQUIRE(negotiate != nullptr);
VkNegotiateLayerInterface n{};
n.sType = LAYER_NEGOTIATE_INTERFACE_STRUCT;
n.loaderLayerInterfaceVersion = 2;
REQUIRE(negotiate(&n) == VK_SUCCESS);
gipa = n.pfnGetInstanceProcAddr;
gdpa = n.pfnGetDeviceProcAddr;
REQUIRE(gipa != nullptr);
REQUIRE(gdpa != nullptr);
VkLayerInstanceLink ilink{nullptr, &FakeGetInstanceProcAddr, nullptr};
VkLayerInstanceCreateInfo ici{};
ici.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
ici.function = VK_LAYER_LINK_INFO;
ici.u.pLayerInfo = &ilink;
VkInstanceCreateInfo ci{};
ci.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
ci.pNext = &ici;
auto createInstance = reinterpret_cast<PFN_vkCreateInstance>(gipa(nullptr, "vkCreateInstance"));
REQUIRE(createInstance != nullptr);
REQUIRE(createInstance(&ci, nullptr, &instance) == VK_SUCCESS);
REQUIRE(instance == reinterpret_cast<VkInstance>(&g_instanceObj));
VkLayerDeviceLink dlink{nullptr, &FakeGetInstanceProcAddr, &FakeGetDeviceProcAddr};
VkLayerDeviceCreateInfo dci{};
dci.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
dci.function = VK_LAYER_LINK_INFO;
dci.u.pLayerInfo = &dlink;
VkDeviceCreateInfo dc{};
dc.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dc.pNext = &dci;
auto createDevice = reinterpret_cast<PFN_vkCreateDevice>(gipa(instance, "vkCreateDevice"));
REQUIRE(createDevice != nullptr);
REQUIRE(createDevice(nullptr, &dc, nullptr, &device) == VK_SUCCESS);
REQUIRE(device == reinterpret_cast<VkDevice>(&g_deviceObj));
present = reinterpret_cast<PFN_vkQueuePresentKHR>(gdpa(device, "vkQueuePresentKHR"));
createSwapchain = reinterpret_cast<PFN_vkCreateSwapchainKHR>(gdpa(device, "vkCreateSwapchainKHR"));
destroySwapchain = reinterpret_cast<PFN_vkDestroySwapchainKHR>(gdpa(device, "vkDestroySwapchainKHR"));
}
VkResult PresentOnce(VkSwapchainKHR sc) const {
uint32_t index = 0;
VkPresentInfoKHR info{};
info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
info.swapchainCount = 1;
info.pSwapchains = &sc;
info.pImageIndices = &index;
return present(reinterpret_cast<VkQueue>(&g_queueObj), &info);
}
};
struct OwnRing {
HANDLE mapping = nullptr;
void* base = nullptr;
fl::FlShmHandshake* hs = nullptr;
fl::FlWriterState* st = nullptr;
fl::FlControlBlock* ctl = nullptr;
const fl::FlFrameRecord* ring = nullptr;
bool Open() {
wchar_t name[128]{};
_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", GetCurrentProcessId());
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
return false;
}
base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (base == nullptr) {
return false;
}
auto* bytes = static_cast<unsigned char*>(base);
hs = reinterpret_cast<fl::FlShmHandshake*>(bytes + FL_SHM_HANDSHAKE_OFFSET);
st = reinterpret_cast<fl::FlWriterState*>(bytes + FL_SHM_WRITER_OFFSET);
ctl = reinterpret_cast<fl::FlControlBlock*>(bytes + FL_SHM_CONTROL_OFFSET);
ring = reinterpret_cast<const fl::FlFrameRecord*>(bytes + FL_SHM_RING_OFFSET);
return true;
}
~OwnRing() {
if (base != nullptr) {
UnmapViewOfFile(base);
}
if (mapping != nullptr) {
CloseHandle(mapping);
}
}
};
} // namespace
// ===========================================================================
TEST_CASE("the layer, driven by a fake loader chain, owns the ring and records every present it forwards",
"[vklayer]") {
ProductFiles files;
files.Install(OwnImageName().c_str()); // BEFORE the DLL loads: both gates are cached on first use
DrivenLayer layer;
layer.Drive(FL_VKLAYER_DLL);
REQUIRE(layer.present != nullptr);
CHECK(layer.present != &FakeQueuePresent); // ours, not the next layer's
REQUIRE(layer.createSwapchain != nullptr);
REQUIRE(layer.destroySwapchain != nullptr);
// The ring exists under OUR pid, with the handshake a reader validates first.
OwnRing r;
REQUIRE(r.Open());
CHECK(r.hs->layoutVersion == FL_SHM_LAYOUT_VERSION);
CHECK(r.hs->pid == GetCurrentProcessId());
CHECK(r.hs->recordSize == sizeof(fl::FlFrameRecord));
CHECK(r.st->status == fl::FL_STATUS_READY);
CHECK((r.st->apiMask & (1u << fl::FL_API_VULKAN)) != 0u);
CHECK((r.st->hooksInstalledMask & fl::FL_HOOK_PRESENT) != 0u);
CHECK(r.st->dxgiPresentsBeforeHook == 0xFFFFFFFFu); // no DXGI counter on this path: "not read"
// A swapchain created through us is remembered with its extent.
VkSwapchainCreateInfoKHR sci{};
sci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
sci.imageExtent = VkExtent2D{1280u, 720u};
VkSwapchainKHR sc = VK_NULL_HANDLE;
REQUIRE(layer.createSwapchain(layer.device, &sci, nullptr, &sc) == VK_SUCCESS);
REQUIRE(sc == kFakeSwapchain);
// Presents: one record each, forwarded each, the record naming the chain and its size.
for (int i = 0; i < 5; ++i) {
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
}
CHECK(g_forwardedPresents.load() == 5);
CHECK(g_lastPresented == kFakeSwapchain);
CHECK(r.st->writeIndex == 5u);
const fl::FlFrameRecord& rec = r.ring[0];
CHECK(rec.api == static_cast<uint8_t>(fl::FL_API_VULKAN));
CHECK(rec.outputW == 1280u);
CHECK(rec.outputH == 720u);
CHECK(rec.swapchainId != 0u);
CHECK(rec.measuredMask == fl::FL_MEASURED_OUTPUT_RES); // and NOT PRESENT_ARGS: vkQueuePresentKHR has none
CHECK(r.ring[4].frameIndex == rec.frameIndex + 4u);
CHECK(r.ring[4].qpc > rec.qpc);
// A present on a chain we never saw is still recorded, as "unidentified", and forwarded.
const auto unknown = reinterpret_cast<VkSwapchainKHR>(static_cast<uintptr_t>(0x9999));
REQUIRE(layer.PresentOnce(unknown) == VK_SUCCESS);
CHECK(r.st->writeIndex == 6u);
CHECK(r.ring[5].swapchainId == 0u);
CHECK(r.ring[5].measuredMask == 0u);
// Destroyed through us: forgotten, and the next layer told.
layer.destroySwapchain(layer.device, sc, nullptr);
CHECK(g_destroyed.load() == 1);
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.ring[6].swapchainId == 0u);
// Pause is not stop: no record, still forwarded, status untouched.
r.ctl->pauseRequested = 1;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.st->writeIndex == 7u);
CHECK(g_forwardedPresents.load() == 8);
CHECK(r.st->status == fl::FL_STATUS_READY);
r.ctl->pauseRequested = 0;
// THE SAFETY STOP: unhookRequested -> UNHOOKED within one present, writeIndex frozen,
// and every later present still forwarded -- "stops" is passthrough, never a broken app.
r.ctl->unhookRequested = 1;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_UNHOOKED);
CHECK(r.st->writeIndex == 7u);
for (int i = 0; i < 3; ++i) {
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
}
CHECK(r.st->writeIndex == 7u);
CHECK(g_forwardedPresents.load() == 12);
CHECK(r.st->faultCount == 0u);
}
// ===========================================================================
TEST_CASE("§S2 part three: when guardTicks stops advancing the layer stops itself, and while it advances it does not",
"[vklayer-deadline]") {
// The short-deadline flavour (1.5 s instead of 65 s), same sources. The clock
// starts when the ring is published; ticks that keep coming keep it alive
// past the deadline, and ticks that stop end it -- on the present path, since
// the layer owns no thread (§S2).
ProductFiles files;
files.Install(OwnImageName().c_str());
DrivenLayer layer;
layer.Drive(FL_VKLAYER_SHORTDEADLINE_DLL);
REQUIRE(layer.present != nullptr);
OwnRing r;
REQUIRE(r.Open());
REQUIRE(r.st->status == fl::FL_STATUS_READY);
// Supervised: 2.4 s of presents with a tick every 600 ms -- past the 1.5 s deadline, still READY.
for (int i = 0; i < 4; ++i) {
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
Sleep(600);
}
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_READY);
const uint64_t recorded = r.st->writeIndex;
CHECK(recorded == 5u);
// Unsupervised: no tick for 1.8 s -> the next present stops the layer.
Sleep(1800);
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_UNHOOKED);
CHECK(r.st->writeIndex == recorded);
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS); // still forwarded
CHECK(g_forwardedPresents.load() == 7);
}
// ===========================================================================
namespace {
struct Child {
PROCESS_INFORMATION pi{};
~Child() {
if (pi.hProcess != nullptr) {
TerminateProcess(pi.hProcess, 0);
WaitForSingleObject(pi.hProcess, 3000);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
}
};
struct ChildRing {
HANDLE mapping = nullptr;
void* base = nullptr;
fl::FlWriterState* st = nullptr;
fl::FlControlBlock* ctl = nullptr;
const fl::FlFrameRecord* ring = nullptr;
~ChildRing() {
if (base != nullptr) {
UnmapViewOfFile(base);
}
if (mapping != nullptr) {
CloseHandle(mapping);
}
}
bool OpenFor(DWORD pid, HANDLE process, int waitMs) {
wchar_t name[128]{};
_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid);
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(waitMs);
while (mapping == nullptr && GetTickCount64() < until) {
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
if (WaitForSingleObject(process, 0) != WAIT_TIMEOUT) {
return false; // the child is gone
}
Sleep(50);
}
}
if (mapping == nullptr) {
return false;
}
base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (base == nullptr) {
return false;
}
auto* bytes = static_cast<unsigned char*>(base);
st = reinterpret_cast<fl::FlWriterState*>(bytes + FL_SHM_WRITER_OFFSET);
ctl = reinterpret_cast<fl::FlControlBlock*>(bytes + FL_SHM_CONTROL_OFFSET);
ring = reinterpret_cast<const fl::FlFrameRecord*>(bytes + FL_SHM_RING_OFFSET);
return true;
}
};
} // namespace
TEST_CASE("the REAL loader maps the layer from VK_ADD_IMPLICIT_LAYER_PATH into the harness's Vulkan mode, and every "
"present is recorded",
"[vklayer-real]") {
// No registry: the loader honours VK_ADD_IMPLICIT_LAYER_PATH (measured 2026-09-06
// against 1.4.357, spike-notes §2), so the layer is discoverable ONLY by the
// process this test starts. Skipped honestly where there is no loader or no
// presentable device -- CI has neither (§S29(d)).
if (LoadLibraryW(L"vulkan-1.dll") == nullptr) {
SKIP("no Vulkan loader on this machine");
}
ProductFiles files;
files.Install("hook-harness.exe");
// Environment for the child: inherited from ours, so set, spawn, unset.
REQUIRE(SetEnvironmentVariableW(L"VK_ADD_IMPLICIT_LAYER_PATH", FL_VKLAYER_MANIFEST_DIR));
REQUIRE(SetEnvironmentVariableW(L"FRAMELEDGER_ENABLE_VK_LAYER", L"1"));
Child child;
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --vulkan --hold-presenting 4";
STARTUPINFOW si{};
si.cb = sizeof(si);
const BOOL started = CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr,
nullptr, &si, &child.pi);
SetEnvironmentVariableW(L"VK_ADD_IMPLICIT_LAYER_PATH", nullptr);
SetEnvironmentVariableW(L"FRAMELEDGER_ENABLE_VK_LAYER", nullptr);
REQUIRE(started);
ChildRing r;
const bool ringUp = r.OpenFor(child.pi.dwProcessId, child.pi.hProcess, 15000);
if (!ringUp) {
DWORD code = 0;
WaitForSingleObject(child.pi.hProcess, 5000);
GetExitCodeProcess(child.pi.hProcess, &code);
if (code == 77u) {
SKIP("the harness found no presentable Vulkan device on this machine (exit 77)");
}
FAIL("the layer published no ring for the harness (harness exit " << code << ")");
}
// Keep it supervised while the harness presents, then read what it wrote.
for (int i = 0; i < 50; ++i) {
++r.ctl->guardTicks;
Sleep(100);
if (WaitForSingleObject(child.pi.hProcess, 0) != WAIT_TIMEOUT) {
break;
}
}
WaitForSingleObject(child.pi.hProcess, 10000);
DWORD code = 1;
GetExitCodeProcess(child.pi.hProcess, &code);
INFO("harness exit " << code << ", records " << r.st->writeIndex << ", status " << r.st->status);
CHECK(code == 0u);
CHECK(r.st->status == fl::FL_STATUS_READY);
CHECK(r.st->writeIndex >= 20u); // ~4 s at ~120/s minus device creation; a loose floor, not a rate claim
CHECK((r.st->apiMask & (1u << fl::FL_API_VULKAN)) != 0u);
CHECK(r.ring[0].api == static_cast<uint8_t>(fl::FL_API_VULKAN));
CHECK(r.ring[0].outputW != 0u);
CHECK((r.ring[0].measuredMask & fl::FL_MEASURED_OUTPUT_RES) != 0u);
CHECK(r.st->faultCount == 0u);
}
+3 -1
View File
@@ -66,7 +66,9 @@ int main() {
Field("slTagCensus", offsetof(FlWriterState, slTagCensus), sizeof(uint32_t));
Field("dxgiPresentsUnseen", offsetof(FlWriterState, dxgiPresentsUnseen), sizeof(uint32_t));
Field("dxgiPresentSamples", offsetof(FlWriterState, dxgiPresentSamples), sizeof(uint32_t));
Field("reserved", offsetof(FlWriterState, reserved), sizeof(uint32_t) * 2, true);
Field("loaderSignals", offsetof(FlWriterState, loaderSignals), sizeof(uint16_t));
Field("earlyStopFamily", offsetof(FlWriterState, earlyStopFamily), sizeof(uint16_t));
Field("dxgiPresentsBeforeHook", offsetof(FlWriterState, dxgiPresentsBeforeHook), sizeof(uint32_t), true);
std::printf(" ] },\n");
std::printf(" \"FlControlBlock\": { \"size\": %zu, \"fields\": [\n", sizeof(FlControlBlock));
+5 -2
View File
@@ -4,14 +4,17 @@
# Deliberately NOT built with fl_hostile_env_flags. This is our own process, not
# an injected DLL: it has no reason to give up exceptions, and the COM proxy in
# proxy_swapchain.h is ordinary C++ that benefits from them.
add_executable(hook-harness main.cpp proxy_swapchain.h)
# vk_hold.cpp is the Vulkan mode (P1 item 3): the loader is reached through
# LoadLibraryW at run time, so only the vendored Khronos HEADERS are needed and
# the harness still builds and runs on a machine with no Vulkan at all.
add_executable(hook-harness main.cpp vk_hold.cpp proxy_swapchain.h)
# fl_dxgi_vtable, not a local copy of the slot numbers: this harness proves the
# indices by behaviour, and it must prove the SHIPPED ones (§S29(b)). The same
# reasoning brings in fl_hook_inventory.h from the Overlay's include directory:
# --probe-upscaler-resolve calls the OVERLAY'S resolver, not a copy of it, or it
# would prove a fact about GetProcAddress.
target_link_libraries(hook-harness PRIVATE FrameLedger.Shm fl_dxgi_vtable fl_native_flags fl_streamline_headers
fl_fidelityfx_headers fl_fsr3_host_headers)
fl_fidelityfx_headers fl_fsr3_host_headers fl_vulkan_headers)
target_include_directories(hook-harness PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include")
target_compile_definitions(hook-harness PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
+107 -7
View File
@@ -35,6 +35,22 @@
// issue DXGI_PRESENT_TEST, which submits nothing
// --plus-ui K also present K frames on a SECOND swapchain in the same
// process (fixture for stream separation)
// --load PATH LoadLibrary PATH before anything else. Fixture for the
// guard's signer half (§S19(b)): a fragment-matching
// module in the TARGET, signed or not, is what the guard
// must judge
// --load-after-ms N PATH
// LoadLibrary PATH from a worker thread N ms after startup,
// while the hold mode presents. Fixture for the Overlay's
// LoadLibrary detour (17_HOOK_ENGINE §DLL entry, §S6): a
// vendor module that appears LATE, or an anti-cheat-named
// one, is what the detour must react to. Up to 4
// --vulkan with --hold-presenting N: a REAL Vulkan swapchain on a hidden
// window instead of the D3D11 one, presented every few ms, so
// the implicit layer's vkQueuePresentKHR is exercised under the
// real loader (P1 item 3). Exit 77 = this machine cannot run it
// (no loader / no presentable device), which the test that
// spawns it reads as SKIP, never as failure. vk_hold.cpp.
// --hold-presenting-overflow N
// fill the Overlay's fixed 16-slot swapchain table, then
// present for N seconds on one that cannot get a slot. The
@@ -586,6 +602,27 @@ bool ProbeCost_PerPresent(Gfx& g) {
// a tight Present(0, DXGI_PRESENT_TEST) loop, which is what an alt-tabbed game
// runs, and the Overlay has to be measured against it deliberately rather than
// by accident.
// --load-after-ms: a module that appears while the harness presents. The worker
// sleeps, loads by absolute path, and prints; the process keeps the module for
// its life so the Overlay's scan and the guard's both see it.
struct LateLoad {
DWORD delayMs = 0;
wchar_t path[MAX_PATH * 2]{};
};
constexpr int kMaxLateLoads = 4;
LateLoad g_lateLoads[kMaxLateLoads];
int g_lateLoadCount = 0;
DWORD WINAPI LateLoadThread(LPVOID arg) {
auto* l = static_cast<LateLoad*>(arg);
Sleep(l->delayMs);
const HMODULE h = LoadLibraryW(l->path);
std::printf(" --load-after-ms %lu %ls -> %s\n", static_cast<unsigned long>(l->delayMs), l->path,
h != nullptr ? "loaded" : "FAILED");
std::fflush(stdout);
return h != nullptr ? 0u : 1u;
}
int PresentLoop(Gfx& g, int frames, bool real) {
const UINT flags = real ? 0u : DXGI_PRESENT_TEST;
for (int i = 0; i < frames; ++i) {
@@ -2747,11 +2784,31 @@ bool ProbeFrameIdentity(Gfx& g) {
} // namespace
// vk_hold.cpp -- the Vulkan mode (P1 item 3).
int HoldPresentingVulkan(int seconds, int presentIntervalMs);
int main(int argc, char** argv) {
std::printf("FrameLedger hook-harness (WARP, headless — no GPU or window required)\n");
// --vulkan skips the D3D11 device entirely: a Vulkan fixture that also mapped
// dxgi + d3d11 would be classified as a D3D target by the launch-mode guard
// (fl_guard.cpp FindPresentationRuntime) and get the Overlay instead of the
// layer -- the Overlay owning the ring and the layer observing nothing.
bool vulkanMode = false;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--vulkan") == 0) {
vulkanMode = true;
}
}
if (vulkanMode) {
// A real Vulkan title imports vulkan-1.dll, so it is mapped before its
// first instruction; this fixture imports d3d11/dxgi instead. Map the
// loader NOW so the launch-mode guard's first poll sees what it would see
// on a real title, rather than a D3D process that turns Vulkan later.
LoadLibraryW(L"vulkan-1.dll");
}
Gfx g;
if (!CreateGfx(g)) {
if (!vulkanMode && !CreateGfx(g)) {
std::printf("FAILED: could not create the graphics objects\n");
return 2;
}
@@ -2765,6 +2822,7 @@ int main(int argc, char** argv) {
bool ranSomething = false;
// --real applies to --present and --hold, wherever it appears on the line.
bool real = false;
bool vulkan = false;
int plusUi = 0;
// MILLISECONDS BETWEEN PRESENTS in the --hold-presenting modes. 8 is ~120/s and is the default for
@@ -2799,6 +2857,8 @@ int main(int argc, char** argv) {
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--real") == 0) {
real = true;
} else if (std::strcmp(argv[i], "--vulkan") == 0) {
vulkan = true;
} else if (std::strcmp(argv[i], "--plus-ui") == 0 && i + 1 < argc) {
plusUi = std::atoi(argv[++i]);
} else if (std::strcmp(argv[i], "--present-interval-ms") == 0 && i + 1 < argc) {
@@ -2830,19 +2890,52 @@ int main(int argc, char** argv) {
slTagWholeResource = true;
} else if (std::strcmp(argv[i], "--sl-tag-dlssg-inputs") == 0) {
slTagDlssgInputs = true;
} else if (std::strcmp(argv[i], "--load-after-ms") == 0 && i + 2 < argc) {
if (g_lateLoadCount < kMaxLateLoads) {
LateLoad& l = g_lateLoads[g_lateLoadCount];
l.delayMs = static_cast<DWORD>(std::atoi(argv[++i]));
const char* path = argv[++i];
MultiByteToWideChar(CP_ACP, 0, path, -1, l.path, static_cast<int>(sizeof(l.path) / sizeof(l.path[0])));
HANDLE t = CreateThread(nullptr, 0, &LateLoadThread, &l, 0, nullptr);
if (t != nullptr) {
CloseHandle(t);
}
++g_lateLoadCount;
} else {
i += 2;
}
} else if (std::strcmp(argv[i], "--load") == 0 && i + 1 < argc) {
// The fixture for the guard's signer half: put a named module into
// THIS process before the guard looks. Loaded, not injected, and it
// stays loaded for the life of the process so the scan sees it.
const char* path = argv[++i];
wchar_t wide[MAX_PATH * 2]{};
const int n =
MultiByteToWideChar(CP_ACP, 0, path, -1, wide, static_cast<int>(sizeof(wide) / sizeof(wide[0])));
HMODULE h = n > 0 ? LoadLibraryW(wide) : nullptr;
std::printf(" --load %s -> %s\n", path, h != nullptr ? "loaded" : "FAILED");
if (h == nullptr) {
return 3;
}
}
}
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--real") == 0 || std::strcmp(argv[i], "--plus-ui") == 0 ||
std::strcmp(argv[i], "--present-interval-ms") == 0 || std::strcmp(argv[i], "--presents-per-eval") == 0 ||
std::strcmp(argv[i], "--ffx-topology") == 0 || std::strcmp(argv[i], "--ffx-no-prepare") == 0 ||
std::strcmp(argv[i], "--sl-tag-for-frame") == 0 || std::strcmp(argv[i], "--sl-tag-whole-resource") == 0 ||
std::strcmp(argv[i], "--sl-tag-dlssg-inputs") == 0) {
if (std::strcmp(argv[i], "--real") == 0 || std::strcmp(argv[i], "--vulkan") == 0 ||
std::strcmp(argv[i], "--plus-ui") == 0 || std::strcmp(argv[i], "--present-interval-ms") == 0 ||
std::strcmp(argv[i], "--presents-per-eval") == 0 || std::strcmp(argv[i], "--ffx-topology") == 0 ||
std::strcmp(argv[i], "--ffx-no-prepare") == 0 || std::strcmp(argv[i], "--sl-tag-for-frame") == 0 ||
std::strcmp(argv[i], "--sl-tag-whole-resource") == 0 ||
std::strcmp(argv[i], "--sl-tag-dlssg-inputs") == 0 || std::strcmp(argv[i], "--load") == 0 ||
std::strcmp(argv[i], "--load-after-ms") == 0) {
if (std::strcmp(argv[i], "--plus-ui") == 0 || std::strcmp(argv[i], "--present-interval-ms") == 0 ||
std::strcmp(argv[i], "--presents-per-eval") == 0 || std::strcmp(argv[i], "--ffx-topology") == 0) {
std::strcmp(argv[i], "--presents-per-eval") == 0 || std::strcmp(argv[i], "--ffx-topology") == 0 ||
std::strcmp(argv[i], "--load") == 0) {
++i;
}
if (std::strcmp(argv[i], "--load-after-ms") == 0) {
i += 2;
}
continue; // consumed above
} else if (std::strcmp(argv[i], "--probe-frames") == 0) {
ok = ProbeFrameIdentity(g) && ok;
@@ -2995,6 +3088,13 @@ int main(int argc, char** argv) {
f->Release();
}
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting") == 0 && i + 1 < argc && vulkan) {
// The Vulkan mode: its own file, its own exit codes (77 = cannot run here).
const int code = HoldPresentingVulkan(std::atoi(argv[++i]), presentIntervalMs);
if (code != 0) {
return code;
}
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting") == 0 && i + 1 < argc) {
// WHAT --hold CANNOT DO, and why the injection tests needed this.
//
+328
View File
@@ -0,0 +1,328 @@
// hook-harness --vulkan --hold-presenting N: a REAL Vulkan swapchain on a hidden
// window, presented every few milliseconds for N seconds, so the layer's
// vkQueuePresentKHR can be exercised under the real loader (12_BUILD §Targets:
// "Vulkan and OpenGL modes to follow as those hooks land" -- this is the Vulkan
// one, P1 item 3).
//
// The loader is reached through LoadLibraryW("vulkan-1.dll") and
// vkGetInstanceProcAddr, never a link-time import: the repository vendors the
// Khronos HEADERS only, and CI has no loader at all. Exit codes:
// 0 presented for the whole hold
// 77 this machine cannot run the fixture (no loader, no device, no surface
// support) -- a SKIP for the test that spawns it, never a failure
// 2 the fixture is broken (an API that should have worked did not)
#define VK_USE_PLATFORM_WIN32_KHR
#include <windows.h>
#include <vulkan/vulkan.h>
#include <cstdio>
#include <cstdlib>
#include <vector>
namespace {
PFN_vkGetInstanceProcAddr g_gipa = nullptr;
template <typename T>
T Instance(VkInstance instance, const char* name) {
return reinterpret_cast<T>(g_gipa(instance, name));
}
LRESULT CALLBACK HiddenWndProc(HWND h, UINT m, WPARAM w, LPARAM l) {
return DefWindowProcW(h, m, w, l);
}
HWND CreateHiddenWindow() {
WNDCLASSW wc{};
wc.lpfnWndProc = &HiddenWndProc;
wc.hInstance = GetModuleHandleW(nullptr);
wc.lpszClassName = L"FrameLedgerHookHarnessVulkan";
RegisterClassW(&wc);
// Never shown: a surface needs an HWND, not a visible one.
return CreateWindowExW(0, wc.lpszClassName, L"FrameLedger hook-harness (Vulkan)", WS_OVERLAPPEDWINDOW, 0, 0, 256,
256, nullptr, nullptr, wc.hInstance, nullptr);
}
int Skip(const char* why) {
std::printf(" [SKIP] %s\n", why);
std::fflush(stdout);
return 77;
}
int Broken(const char* what, VkResult r) {
std::printf(" [FAIL] %s (VkResult %d)\n", what, static_cast<int>(r));
std::fflush(stdout);
return 2;
}
} // namespace
int HoldPresentingVulkan(int seconds, int presentIntervalMs) {
std::printf("\n[vulkan-hold] a real swapchain on a hidden window, presenting for %d second(s) every %d ms\n",
seconds, presentIntervalMs);
std::fflush(stdout);
const HMODULE loader = LoadLibraryW(L"vulkan-1.dll");
if (loader == nullptr) {
return Skip("no vulkan-1.dll on this machine");
}
g_gipa = reinterpret_cast<PFN_vkGetInstanceProcAddr>(GetProcAddress(loader, "vkGetInstanceProcAddr"));
if (g_gipa == nullptr) {
return Skip("vulkan-1.dll exports no vkGetInstanceProcAddr");
}
// --- instance ---------------------------------------------------------
auto createInstance = Instance<PFN_vkCreateInstance>(nullptr, "vkCreateInstance");
VkApplicationInfo app{};
app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app.pApplicationName = "FrameLedger hook-harness";
app.apiVersion = VK_API_VERSION_1_1;
const char* instanceExts[] = {"VK_KHR_surface", "VK_KHR_win32_surface"};
VkInstanceCreateInfo ici{};
ici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
ici.pApplicationInfo = &app;
ici.enabledExtensionCount = 2;
ici.ppEnabledExtensionNames = instanceExts;
VkInstance instance = nullptr;
if (createInstance == nullptr || createInstance(&ici, nullptr, &instance) != VK_SUCCESS) {
return Skip("vkCreateInstance failed (no ICD, or no surface extensions)");
}
auto enumPhys = Instance<PFN_vkEnumeratePhysicalDevices>(instance, "vkEnumeratePhysicalDevices");
auto queueProps =
Instance<PFN_vkGetPhysicalDeviceQueueFamilyProperties>(instance, "vkGetPhysicalDeviceQueueFamilyProperties");
auto surfaceSupport =
Instance<PFN_vkGetPhysicalDeviceSurfaceSupportKHR>(instance, "vkGetPhysicalDeviceSurfaceSupportKHR");
auto createSurface = Instance<PFN_vkCreateWin32SurfaceKHR>(instance, "vkCreateWin32SurfaceKHR");
auto surfaceCaps =
Instance<PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR>(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
auto surfaceFormats =
Instance<PFN_vkGetPhysicalDeviceSurfaceFormatsKHR>(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR");
auto createDevice = Instance<PFN_vkCreateDevice>(instance, "vkCreateDevice");
auto gdpa = Instance<PFN_vkGetDeviceProcAddr>(instance, "vkGetDeviceProcAddr");
if (enumPhys == nullptr || queueProps == nullptr || surfaceSupport == nullptr || createSurface == nullptr ||
surfaceCaps == nullptr || surfaceFormats == nullptr || createDevice == nullptr || gdpa == nullptr) {
return Skip("the instance lacks the surface / device entry points this fixture needs");
}
// --- surface ----------------------------------------------------------
const HWND hwnd = CreateHiddenWindow();
if (hwnd == nullptr) {
return Skip("no window could be created (no interactive window station?)");
}
VkWin32SurfaceCreateInfoKHR sci{};
sci.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
sci.hinstance = GetModuleHandleW(nullptr);
sci.hwnd = hwnd;
VkSurfaceKHR surface = VK_NULL_HANDLE;
if (createSurface(instance, &sci, nullptr, &surface) != VK_SUCCESS) {
return Skip("vkCreateWin32SurfaceKHR failed");
}
// --- a physical device with a queue that can draw AND present ---------
uint32_t physCount = 0;
enumPhys(instance, &physCount, nullptr);
std::vector<VkPhysicalDevice> phys(physCount);
enumPhys(instance, &physCount, phys.data());
VkPhysicalDevice chosen = nullptr;
uint32_t family = 0;
for (VkPhysicalDevice p : phys) {
uint32_t n = 0;
queueProps(p, &n, nullptr);
std::vector<VkQueueFamilyProperties> props(n);
queueProps(p, &n, props.data());
for (uint32_t i = 0; i < n && chosen == nullptr; ++i) {
VkBool32 present = VK_FALSE;
if ((props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0u &&
surfaceSupport(p, i, surface, &present) == VK_SUCCESS && present == VK_TRUE) {
chosen = p;
family = i;
}
}
if (chosen != nullptr) {
break;
}
}
if (chosen == nullptr) {
return Skip("no physical device with a graphics queue that can present to a Win32 surface");
}
// --- device -----------------------------------------------------------
const float priority = 1.0f;
VkDeviceQueueCreateInfo qci{};
qci.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
qci.queueFamilyIndex = family;
qci.queueCount = 1;
qci.pQueuePriorities = &priority;
const char* deviceExts[] = {"VK_KHR_swapchain"};
VkDeviceCreateInfo dci{};
dci.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dci.queueCreateInfoCount = 1;
dci.pQueueCreateInfos = &qci;
dci.enabledExtensionCount = 1;
dci.ppEnabledExtensionNames = deviceExts;
VkDevice device = nullptr;
if (VkResult r = createDevice(chosen, &dci, nullptr, &device); r != VK_SUCCESS) {
return Broken("vkCreateDevice", r);
}
#define FL_DEV(name) auto name = reinterpret_cast<PFN_##name>(gdpa(device, #name))
FL_DEV(vkGetDeviceQueue);
FL_DEV(vkCreateSwapchainKHR);
FL_DEV(vkGetSwapchainImagesKHR);
FL_DEV(vkAcquireNextImageKHR);
FL_DEV(vkQueuePresentKHR);
FL_DEV(vkQueueSubmit);
FL_DEV(vkQueueWaitIdle);
FL_DEV(vkCreateSemaphore);
FL_DEV(vkCreateCommandPool);
FL_DEV(vkAllocateCommandBuffers);
FL_DEV(vkBeginCommandBuffer);
FL_DEV(vkEndCommandBuffer);
FL_DEV(vkCmdPipelineBarrier);
FL_DEV(vkDeviceWaitIdle);
#undef FL_DEV
if (vkGetDeviceQueue == nullptr || vkCreateSwapchainKHR == nullptr || vkGetSwapchainImagesKHR == nullptr ||
vkAcquireNextImageKHR == nullptr || vkQueuePresentKHR == nullptr || vkQueueSubmit == nullptr ||
vkQueueWaitIdle == nullptr || vkCreateSemaphore == nullptr || vkCreateCommandPool == nullptr ||
vkAllocateCommandBuffers == nullptr || vkBeginCommandBuffer == nullptr || vkEndCommandBuffer == nullptr ||
vkCmdPipelineBarrier == nullptr || vkDeviceWaitIdle == nullptr) {
return Broken("a device entry point was missing", VK_ERROR_INITIALIZATION_FAILED);
}
VkQueue queue = nullptr;
vkGetDeviceQueue(device, family, 0, &queue);
// --- swapchain --------------------------------------------------------
VkSurfaceCapabilitiesKHR caps{};
surfaceCaps(chosen, surface, &caps);
uint32_t formatCount = 0;
surfaceFormats(chosen, surface, &formatCount, nullptr);
std::vector<VkSurfaceFormatKHR> formats(formatCount);
surfaceFormats(chosen, surface, &formatCount, formats.data());
if (formats.empty()) {
return Skip("the surface reports no formats");
}
VkExtent2D extent = caps.currentExtent;
if (extent.width == 0xFFFFFFFFu || extent.width == 0u || extent.height == 0u) {
extent = VkExtent2D{256u, 256u};
}
VkSwapchainCreateInfoKHR sc{};
sc.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
sc.surface = surface;
sc.minImageCount = caps.minImageCount < 2u ? 2u : caps.minImageCount;
if (caps.maxImageCount != 0u && sc.minImageCount > caps.maxImageCount) {
sc.minImageCount = caps.maxImageCount;
}
sc.imageFormat = formats[0].format;
sc.imageColorSpace = formats[0].colorSpace;
sc.imageExtent = extent;
sc.imageArrayLayers = 1;
sc.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
sc.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
sc.preTransform = caps.currentTransform;
sc.compositeAlpha = (caps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) != 0u
? VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR
: VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
sc.presentMode = VK_PRESENT_MODE_FIFO_KHR;
sc.clipped = VK_TRUE;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
if (VkResult r = vkCreateSwapchainKHR(device, &sc, nullptr, &swapchain); r != VK_SUCCESS) {
return Broken("vkCreateSwapchainKHR", r);
}
uint32_t imageCount = 0;
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr);
std::vector<VkImage> images(imageCount);
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, images.data());
// --- one command buffer per image: UNDEFINED -> PRESENT_SRC, nothing drawn -
VkCommandPoolCreateInfo pci{};
pci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pci.queueFamilyIndex = family;
VkCommandPool pool = VK_NULL_HANDLE;
if (VkResult r = vkCreateCommandPool(device, &pci, nullptr, &pool); r != VK_SUCCESS) {
return Broken("vkCreateCommandPool", r);
}
VkCommandBufferAllocateInfo cai{};
cai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cai.commandPool = pool;
cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cai.commandBufferCount = imageCount;
std::vector<VkCommandBuffer> cmds(imageCount);
if (VkResult r = vkAllocateCommandBuffers(device, &cai, cmds.data()); r != VK_SUCCESS) {
return Broken("vkAllocateCommandBuffers", r);
}
for (uint32_t i = 0; i < imageCount; ++i) {
VkCommandBufferBeginInfo bi{};
bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vkBeginCommandBuffer(cmds[i], &bi);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = images[i];
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.layerCount = 1;
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
vkCmdPipelineBarrier(cmds[i], VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0,
nullptr, 0, nullptr, 1, &barrier);
vkEndCommandBuffer(cmds[i]);
}
VkSemaphoreCreateInfo semi{};
semi.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore acquired = VK_NULL_HANDLE;
VkSemaphore ready = VK_NULL_HANDLE;
vkCreateSemaphore(device, &semi, nullptr, &acquired);
vkCreateSemaphore(device, &semi, nullptr, &ready);
// --- the hold ---------------------------------------------------------
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(seconds) * 1000ULL;
long long presented = 0;
while (GetTickCount64() < until) {
uint32_t index = 0;
VkResult r = vkAcquireNextImageKHR(device, swapchain, 1000000000ull, acquired, VK_NULL_HANDLE, &index);
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) {
return Broken("vkAcquireNextImageKHR", r);
}
const VkPipelineStageFlags wait = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkSubmitInfo si{};
si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
si.waitSemaphoreCount = 1;
si.pWaitSemaphores = &acquired;
si.pWaitDstStageMask = &wait;
si.commandBufferCount = 1;
si.pCommandBuffers = &cmds[index];
si.signalSemaphoreCount = 1;
si.pSignalSemaphores = &ready;
if (r = vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE); r != VK_SUCCESS) {
return Broken("vkQueueSubmit", r);
}
VkPresentInfoKHR pi{};
pi.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
pi.waitSemaphoreCount = 1;
pi.pWaitSemaphores = &ready;
pi.swapchainCount = 1;
pi.pSwapchains = &swapchain;
pi.pImageIndices = &index;
r = vkQueuePresentKHR(queue, &pi);
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) {
return Broken("vkQueuePresentKHR", r);
}
++presented;
vkQueueWaitIdle(queue); // simplest correct pacing: no fences to juggle in a fixture
if (presentIntervalMs > 0) {
Sleep(static_cast<DWORD>(presentIntervalMs));
}
}
vkDeviceWaitIdle(device);
// The count goes to stdout so a test can compare it against records drained
// from the ring rather than asserting "more than zero".
std::printf(" presented=%lld\n", presented);
std::fflush(stdout);
// Objects are left for process exit: this is a fixture that ends here, and a
// teardown that itself could fail would only add exit codes to a test.
return 0;
}
@@ -32,6 +32,13 @@ public sealed class HookRequestFromConsentTests
return ValueTask.FromResult(AntiCheatVerdict.Allowed());
}
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
int timeoutMs, CancellationToken ct = default)
{
InjectCalls++;
return ValueTask.FromResult(AntiCheatVerdict.Allowed());
}
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
CancellationToken ct = default) => ValueTask.FromResult(AntiCheatVerdict.Allowed());
}
@@ -160,6 +167,10 @@ public sealed class HookRequestFromConsentTests
public void ThePayloadPathIsRequired()
{
Action act = () => HookRequest.FromConsent(Consented(), OnDisk, 1, " ");
Action negativeWait = () => HookRequest.FromConsent(Consented(), OnDisk, 1, _payload, waitForPresentationRuntimeMs: -1);
negativeWait.Should().Throw<ArgumentOutOfRangeException>("a negative budget is a mistake, never attach mode");
HookRequest.FromConsent(Consented(), OnDisk, 1, _payload).WaitForPresentationRuntimeMs
.Should().Be(0, "attach mode is the default: inject now");
act.Should().Throw<ArgumentException>();
}
}
@@ -33,6 +33,10 @@ public sealed class GuardSupervisorTests
CancellationToken ct = default) =>
ValueTask.FromResult(AntiCheatVerdict.Allowed());
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
int timeoutMs, CancellationToken ct = default) =>
throw new InvalidOperationException("the supervisor must not launch or inject");
// The supervisor never asks check 4 anything: it re-evaluates a process
// it is already inside, and the pre-scan is the pre-launch question.
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
@@ -23,6 +23,18 @@ public sealed class HookedCaptureGateTests
return ValueTask.FromResult(Next);
}
public int WhenReadyCalls { get; private set; }
public int WhenReadyWaitMs { get; private set; }
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
int timeoutMs, CancellationToken ct = default)
{
WhenReadyCalls++;
WhenReadyWaitMs = timeoutMs;
return ValueTask.FromResult(Next);
}
public int PreScanCalls { get; private set; }
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
@@ -47,14 +59,16 @@ public sealed class HookedCaptureGateTests
private static HookRequest Request(
bool enabled = true,
ConsentProvenance provenance = ConsentProvenance.UnshippedHostOperator,
string? blocked = null) =>
string? blocked = null,
int waitMs = 0) =>
HookRequest.FromConsent(
GameConsentRecord.Stored(
OnDisk, enabled, DateTimeOffset.UnixEpoch, provenance, "unshipped-host-operator/1",
blocked, preScanUnverified: false, updatedAt: DateTimeOffset.UnixEpoch),
OnDisk,
targetPid: 1234,
payloadPath: @"C:\FrameLedger\FrameLedger.Overlay.dll");
payloadPath: @"C:\FrameLedger\FrameLedger.Overlay.dll",
waitMs);
[Fact]
public async Task AnEnabledConsentedGame_ReachesTheGuard()
@@ -66,6 +80,37 @@ public sealed class HookedCaptureGateTests
v.IsAllowed.Should().BeTrue();
guard.InjectCalls.Should().Be(1);
guard.WhenReadyCalls.Should().Be(0, "attach mode injects now, not after a wait");
}
[Fact]
public async Task ALaunchModeRequest_ReachesTheGuardThroughTheWaitingEntryOnly()
{
// P1 item 2. The consent checks are the same three, in the same order; the only thing a wait
// changes is WHICH guard entry runs the full scan -- and it must never be both.
RecordingGuard guard = new();
HookedCaptureGate gate = new(guard);
AntiCheatVerdict v = await gate.StartAsync(Request(waitMs: 60_000), TestContext.Current.CancellationToken);
v.IsAllowed.Should().BeTrue();
guard.WhenReadyCalls.Should().Be(1);
guard.WhenReadyWaitMs.Should().Be(60_000);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task ALaunchModeRequestWithoutConsent_ReachesNeitherEntry()
{
RecordingGuard guard = new();
HookedCaptureGate gate = new(guard);
AntiCheatVerdict v = await gate.StartAsync(Request(provenance: ConsentProvenance.NotRecorded, waitMs: 60_000),
TestContext.Current.CancellationToken);
v.Reason.Should().Be(AntiCheatRefusalReason.ConsentMissing);
guard.WhenReadyCalls.Should().Be(0);
guard.InjectCalls.Should().Be(0);
}
[Fact]
@@ -0,0 +1,249 @@
using FluentAssertions;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Consent;
using FrameLedger.CaptureHost.Capture;
using FrameLedger.CaptureHost.Consent;
using FrameLedger.Domain.AntiCheat;
using FrameLedger.Domain.Consent;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Capture;
/// <summary>
/// Launch mode's ordering (P1 item 2): the host starts what it was asked to start, consent is the gate's
/// and only the gate's, and the guard is reached through the WAITING entry with the budget, never the plain one.
/// </summary>
public sealed class CaptureLoopLaunchTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-launch-" + Guid.NewGuid().ToString("N"));
private const string _exe = @"C:\Games\Title\game.exe";
private const int _pid = 5151;
private static ExecutableFingerprint Fingerprint =>
new() { ExePath = _exe, SizeBytes = 90_000, MtimeUnixMs = 1_700_000_000_000 };
public void Dispose()
{
try
{
Directory.Delete(_dir, recursive: true);
}
catch (IOException)
{
}
}
private sealed class WaitingGuard : IAntiCheatGuard
{
public int InjectCalls { get; private set; }
public int WhenReadyCalls { get; private set; }
public int WhenReadyWaitMs { get; private set; }
public AntiCheatVerdict Verdict { get; set; } = AntiCheatVerdict.Allowed();
public ValueTask<AntiCheatVerdict> EvaluateAsync(int targetPid, CancellationToken ct = default) =>
ValueTask.FromResult(AntiCheatVerdict.Allowed());
public ValueTask<AntiCheatVerdict> GuardedInjectAsync(int targetPid, string payloadPath,
CancellationToken ct = default)
{
InjectCalls++;
return ValueTask.FromResult(Verdict);
}
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
int timeoutMs, CancellationToken ct = default)
{
WhenReadyCalls++;
WhenReadyWaitMs = timeoutMs;
return ValueTask.FromResult(Verdict);
}
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
CancellationToken ct = default) => ValueTask.FromResult(AntiCheatVerdict.Allowed());
}
private sealed class NoLiveness : ITargetLiveness
{
public bool HasExited => false;
public bool IsForeground => true;
public void Dispose()
{
}
}
private sealed class NeverResolves : ITargetResolver
{
public int? Resolve(string normalisedExePath, out SessionEndReason reason)
{
reason = SessionEndReason.TargetNotRunning;
return null;
}
}
private async Task<FileGameConsentStore> StoreAsync(bool consented)
{
var store = new FileGameConsentStore(Path.Combine(_dir, "games.json"));
if (consented)
{
await store.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
{
Fingerprint = Fingerprint,
DisclosureVersion = OperatorDisclosure.Version,
AcknowledgedAt = DateTimeOffset.UnixEpoch,
}, TestContext.Current.CancellationToken).ConfigureAwait(false);
}
return store;
}
private static CaptureLoop Loop(IGameConsentStore store, WaitingGuard guard,
Func<string, string, (int Pid, ITargetLiveness Alive)?>? launcher) =>
new(store,
new HookedCaptureGate(guard),
guard,
new NeverResolves(),
_ => new NoLiveness(),
_ => (null, ShmAttachRefusal.BuildIdMismatch),
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromMilliseconds(20),
MaxDuration = TimeSpan.FromMilliseconds(50),
LaunchWaitBudget = TimeSpan.FromSeconds(42),
},
launcher: launcher);
[Fact]
public async Task AConsentedLaunchReachesTheGuardThroughTheWaitingEntryWithTheBudget()
{
var guard = new WaitingGuard();
string? launchedWith = null;
CaptureLoop loop = Loop(await StoreAsync(consented: true), guard, (exe, args) =>
{
launchedWith = exe + " | " + args;
return (_pid, new NoLiveness());
});
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", "--real --hold 3",
TestContext.Current.CancellationToken);
launchedWith.Should().Be(_exe + " | --real --hold 3");
guard.WhenReadyCalls.Should().Be(1);
guard.WhenReadyWaitMs.Should().Be(42_000, "the loop's budget is what the guard polls against");
guard.InjectCalls.Should().Be(0, "launch mode never takes the plain entry, which would inject on sight");
r.LaunchWait.Should().NotBeNull("the report prints how long the guard waited before it injected");
r.Reason.Should().Be(SessionEndReason.AttachRefused, "this fixture has no ring; the guard's answer is what is under test");
}
[Fact]
public async Task ALaunchThatCannotStartIsItsOwnReasonAndTheGuardIsNeverAsked()
{
var guard = new WaitingGuard();
CaptureLoop loop = Loop(await StoreAsync(consented: true), guard, (_, _) => null);
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.LaunchCannotStart);
guard.WhenReadyCalls.Should().Be(0);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task WithoutConsentTheProcessIsStillStartedAndTheGateRefusesBeforeTheGuard()
{
// The operator asked for the game to start; consent decides whether FrameLedger goes INTO it, and
// that decision is the gate's alone — reached one process later than in attach mode, never skipped.
var guard = new WaitingGuard();
int launches = 0;
CaptureLoop loop = Loop(await StoreAsync(consented: false), guard, (_, _) =>
{
launches++;
return (_pid, new NoLiveness());
});
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
TestContext.Current.CancellationToken);
launches.Should().Be(1);
r.Reason.Should().Be(SessionEndReason.RefusedHookNotEnabled);
guard.WhenReadyCalls.Should().Be(0);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task TheGuardsTwoLaunchRefusalsAreTheirOwnSessionEndReasons()
{
foreach ((AntiCheatRefusalReason native, SessionEndReason expected) in new[]
{
(AntiCheatRefusalReason.LaunchTargetExited, SessionEndReason.LaunchTargetExited),
(AntiCheatRefusalReason.LaunchNoPresentationRuntime, SessionEndReason.LaunchNoPresentationRuntime),
})
{
var guard = new WaitingGuard { Verdict = AntiCheatVerdict.Refused(native, string.Empty, "poll ended") };
CaptureLoop loop = Loop(await StoreAsync(consented: true), guard, (_, _) => (_pid, new NoLiveness()));
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
TestContext.Current.CancellationToken);
r.Reason.Should().Be(expected);
r.Verdict.Reason.Should().Be(native);
}
}
[Fact]
public async Task AVulkanLayeredVerdictIsNeitherAllowNorRefusalAndTheLoopAttachesToTheLayersRing()
{
// P1 item 3: the guard passed, injected nothing, and the ring is the layer's -- so the loop goes
// on to attach exactly as it would after an injection, carrying the verdict for the report.
var guard = new WaitingGuard
{
Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.TargetIsVulkanLayered, string.Empty, "vulkan-1 only"),
};
int attachCalls = 0;
var loop = new CaptureLoop(await StoreAsync(consented: true), new HookedCaptureGate(guard), guard,
new NeverResolves(), _ => new NoLiveness(),
_ =>
{
attachCalls++;
return (null, ShmAttachRefusal.BuildIdMismatch);
},
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromMilliseconds(20),
MaxDuration = TimeSpan.FromMilliseconds(50),
LaunchWaitBudget = TimeSpan.FromSeconds(42),
},
launcher: (_, _) => (_pid, new NoLiveness()));
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
TestContext.Current.CancellationToken);
attachCalls.Should().BeGreaterThan(0, "a layered target is attached to, not refused");
r.Reason.Should().Be(SessionEndReason.AttachRefused, "this fixture has no ring");
r.Verdict.Reason.Should().Be(AntiCheatRefusalReason.TargetIsVulkanLayered);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task ALoopBuiltWithoutALauncherCannotLaunch()
{
var guard = new WaitingGuard();
CaptureLoop loop = Loop(await StoreAsync(consented: true), guard, launcher: null);
Func<Task> act = () => loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
TestContext.Current.CancellationToken);
await act.Should().ThrowAsync<InvalidOperationException>();
}
}
@@ -74,6 +74,13 @@ public sealed class CaptureLoopTests : IDisposable
return ValueTask.FromResult(Verdict);
}
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
int timeoutMs, CancellationToken ct = default)
{
InjectCalls++;
return ValueTask.FromResult(Verdict);
}
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory,
CancellationToken ct = default) => ValueTask.FromResult(AntiCheatVerdict.Allowed());
}
@@ -0,0 +1,85 @@
using System.Text;
using FluentAssertions;
using FrameLedger.CaptureHost.Capture;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Tests.Capture;
/// <summary>The on-disk scan: counts, the chunk boundary, the absent case, and a missing file as an outcome.</summary>
public sealed class ExecutableMarkerScanTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-markers-" + Guid.NewGuid().ToString("N"));
public ExecutableMarkerScanTests() => Directory.CreateDirectory(_dir);
public void Dispose()
{
try
{
Directory.Delete(_dir, recursive: true);
}
catch (IOException)
{
}
}
private string Write(string name, byte[] bytes)
{
string p = Path.Combine(_dir, name);
File.WriteAllBytes(p, bytes);
return p;
}
[Fact]
public void MarkersAreCountedAndTheFgCapableOnesAreNamed()
{
byte[] body = Encoding.ASCII.GetBytes("MZ....FidelityFX..ffxFsr3ContextCreate..ffxFsr3ContextDispatchUpscale..NVSDK_NGX_D3D12_Init..end");
string exe = Write("a.exe", body);
ExecutableMarkers m = ExecutableMarkerScan.Scan(exe);
m.Scanned.Should().BeTrue();
m.BytesScanned.Should().Be(body.Length);
m.Markers.Single(x => string.Equals(x.Name, "FidelityFX", StringComparison.Ordinal)).Hits.Should().Be(1);
m.Markers.Single(x => string.Equals(x.Name, "ffxFsr3", StringComparison.Ordinal)).Hits.Should().Be(2);
m.Markers.Single(x => string.Equals(x.Name, "NVSDK_NGX", StringComparison.Ordinal)).Hits.Should().Be(1);
m.Markers.Single(x => string.Equals(x.Name, "xefgSwapChain", StringComparison.Ordinal)).Hits.Should().Be(0);
m.AnyFgCapable.Should().BeTrue("ffxFsr3 belongs to an SDK that generates frames");
m.FgCapableNames.Should().Be("ffxFsr3");
m.Describe().Should().Contain("ffxFsr3 x2").And.Contain("can generate frames").And.Contain("NVSDK_NGX x1");
}
[Fact]
public void AMarkerStraddlingTheChunkBoundaryIsCountedExactlyOnce()
{
// 64-byte chunks; place "ffxFrameInterpolation" (21 bytes) so it starts at byte 60.
byte[] body = new byte[200];
Array.Fill(body, (byte)'.');
byte[] needle = Encoding.ASCII.GetBytes("ffxFrameInterpolation");
Buffer.BlockCopy(needle, 0, body, 60, needle.Length);
Buffer.BlockCopy(needle, 0, body, 150, needle.Length);
string exe = Write("b.exe", body);
ExecutableMarkers m = ExecutableMarkerScan.Scan(exe, chunkBytes: 64);
m.Markers.Single(x => string.Equals(x.Name, "ffxFrameInterpolation", StringComparison.Ordinal)).Hits.Should().Be(2, "one across the boundary, one inside a chunk");
m.BytesScanned.Should().Be(200);
}
[Fact]
public void AFileWithNoMarkersSaysSoAndAMissingFileIsAnOutcome()
{
string clean = Write("c.exe", Encoding.ASCII.GetBytes("MZ nothing vendor-shaped here at all"));
ExecutableMarkers none = ExecutableMarkerScan.Scan(clean);
ExecutableMarkers missing = ExecutableMarkerScan.Scan(Path.Combine(_dir, "nope.exe"));
none.Scanned.Should().BeTrue();
none.AnyFgCapable.Should().BeFalse();
none.Describe().Should().Contain("none of 7 marker(s)");
missing.Scanned.Should().BeFalse();
missing.Error.Should().NotBeNull();
missing.Describe().Should().Contain("not scanned");
ExecutableMarkers.NotScanned.Describe().Should().EndWith("not scanned");
}
}
@@ -248,6 +248,73 @@ public sealed class CaptureHostEndToEndTests : IDisposable
}
}
[Fact]
public async Task LaunchModeStartsTheHarnessItselfAndReportsWhatRanUnhooked()
{
// P1 item 2, from OUTSIDE the process: the host starts the consented harness, the guard waits
// for dxgi to map and injects, and the report carries the two numbers 20_OPEN_QUESTIONS §S1
// deferred on -- the wait, and DXGI's count of presents before the first hooked one.
var store = new FileGameConsentStore(HostConsentFile);
ExecutableFingerprint fingerprint = FrameLedger.Infrastructure.Io.ExecutableIdentity.Read(ConsentedExecutable)!.Value;
(await store.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
{
Fingerprint = fingerprint,
DisclosureVersion = OperatorDisclosure.Version,
AcknowledgedAt = DateTimeOffset.UtcNow,
}, TestContext.Current.CancellationToken)).Should().Be(ConsentWriteOutcome.Written);
using Process host = StartHost("launch", "--exe", ConsentedExecutable, "--args", "--real --hold-presenting 6",
"--seconds", "4");
string stdout = await host.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
await host.WaitForExitAsync(TestContext.Current.CancellationToken);
stdout.Should().Contain("launch: the guard injected", "the wait is printed, because it is the number §S1 lacked");
stdout.Should().Contain("presents before the first hooked present:");
stdout.Should().NotContain("not read", "the harness presents, so the first hooked present happened");
host.ExitCode.Should().Be(0, stdout);
}
[Fact]
public async Task LaunchModeOnAVulkanTargetAttachesToTheLayersRingAndInjectsNothing()
{
// P1 item 3, from OUTSIDE the process: the host launches the harness in its Vulkan mode with the
// layer's environment, the guard passes and injects nothing (TargetIsVulkanLayered), and the
// records come from the layer's ring. Skipped honestly where there is no Vulkan loader or no
// presentable device -- the harness says so with exit 77, which the session reports as
// LaunchTargetExited before any ring existed.
if (!File.Exists(Path.Combine(Environment.SystemDirectory, "vulkan-1.dll")))
{
Assert.Skip("no Vulkan loader on this machine");
}
var store = new FileGameConsentStore(HostConsentFile);
ExecutableFingerprint fingerprint = FrameLedger.Infrastructure.Io.ExecutableIdentity.Read(ConsentedExecutable)!.Value;
(await store.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
{
Fingerprint = fingerprint,
DisclosureVersion = OperatorDisclosure.Version,
AcknowledgedAt = DateTimeOffset.UtcNow,
}, TestContext.Current.CancellationToken)).Should().Be(ConsentWriteOutcome.Written);
using Process host = StartHost("launch", "--exe", ConsentedExecutable, "--args", "--vulkan --hold-presenting 8",
"--seconds", "5");
Task<string> stderrTask = host.StandardError.ReadToEndAsync(TestContext.Current.CancellationToken);
string stdout = await host.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
await host.WaitForExitAsync(TestContext.Current.CancellationToken);
stdout += "\n---- stderr ----\n" + await stderrTask + $"\n---- exit {host.ExitCode} ----\n";
if (stdout.Contains(nameof(SessionEndReason.LaunchTargetExited), StringComparison.Ordinal))
{
Assert.Skip("the harness found no presentable Vulkan device on this machine: " + stdout);
}
stdout.Should().Contain("vulkan layer: ", "the launch names the manifest it wrote and the enable-list entry");
stdout.Should().Contain("capture side: the Vulkan implicit layer", stdout);
stdout.Should().Contain("apiMask=0x8", "FL_API_VULKAN is bit 3; the ring is the layer's, not an Overlay's");
stdout.Should().NotContain("records: 0 ", stdout);
host.ExitCode.Should().Be(0, stdout);
}
[Fact]
public async Task WhenTheTargetExitsTheHostStopsAndSaysWhy()
{
@@ -24,7 +24,24 @@ public sealed class CommandLineSurfaceTests
// property that separates it from the --pid / --payload / --force / --yes this host
// refuses. It exists because CaptureLoop honoured MaxDuration and nothing could set
// it, so a bounded real-title measurement was impossible to take.
CommandLine.AcceptedOptions.Should().BeEquivalentTo(["--exe", "--seconds"]);
// THREE since P1 item 2: `--args` is the command line the launched GAME receives. It names
// nothing about injection -- payload, target and evidence are exactly what they were -- so it
// has the same property `--seconds` has: it cannot widen what is injected or skip a check.
CommandLine.AcceptedOptions.Should().BeEquivalentTo(["--exe", "--seconds", "--args"]);
}
[Fact]
public void LaunchTakesTheExecutableItsArgumentsAndABound()
{
CommandLine parsed = CommandLine.Parse(["launch", "--exe", @"C:\a\game.exe", "--args", "--real --hold 3", "--seconds", "9"]);
parsed.Error.Should().BeNull();
parsed.Verb.Should().Be(Verb.Launch);
parsed.ExePath.Should().Be(@"C:\a\game.exe");
parsed.Arguments.Should().Be("--real --hold 3", "handed to the game verbatim");
parsed.Seconds.Should().Be(9);
CommandLine.Parse(["launch"]).Error.Should().NotBeNull("--exe is required: there is nothing else to launch");
CommandLine.Parse(["launch", "--exe", "g.exe"]).Arguments.Should().BeEmpty();
}
[Fact]
@@ -108,12 +108,15 @@ public sealed class DriverReportedFrameGenerationTests
}
[Fact]
public void WithoutAnAnswerTheFgLineIsByteIdenticalToBefore()
public void WithoutAnAnswerTheFgLineIsRungThreeByEliminationWithDlssGNotExcluded()
{
// Since the elimination wording (HANDOFF 7b / §H11, 2026-09-06) the rung-3 line always
// carries its exclusions; without the driver's answer DLSS-G is stated as NOT excluded.
(_, string text) = Render(Stream(100, 4, tagged: false), NgxDriverState.NotRun);
text.Should().Contain("frame generation: " + MeasuredFacts.FgActiveUnidentified);
text.Should().NotContain("NVIDIA driver");
text.Should().Contain("frame generation: " + MeasuredFacts.FgActiveUnidentified + " — by elimination");
text.Should().Contain("DLSS-G not excluded (the NVIDIA driver did not answer");
text.Should().NotContain("driver-reported:").And.NotContain("the NVIDIA driver agrees");
}
[Fact]
@@ -0,0 +1,75 @@
using FluentAssertions;
using FrameLedger.CaptureHost.Capture;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Consume;
/// <summary>The loader detour's two words as the report reads them, and the family index against a rules file.</summary>
public sealed class EarlyStopTests : IDisposable
{
private readonly string _rules = Path.Combine(Path.GetTempPath(), "fl-rules-" + Guid.NewGuid().ToString("N") + ".json");
public EarlyStopTests() => File.WriteAllText(_rules,
"""{"anticheat":{"modules":[{"family":"Easy Anti-Cheat","match":"prefix","values":["EasyAntiCheat"]},{"family":"BattlEye","match":"prefix","values":["BEClient"]}]}}""");
public void Dispose()
{
try
{
File.Delete(_rules);
}
catch (IOException)
{
}
}
[Fact]
public void TheFamilyIndexIsOneBasedInRulesOrderAndNeverAGuess()
{
EarlyStop.FamilyName(1, _rules).Should().Be("Easy Anti-Cheat");
EarlyStop.FamilyName(2, _rules).Should().Be("BattlEye");
EarlyStop.FamilyName(3, _rules).Should().BeNull("outside the file");
EarlyStop.FamilyName(0, _rules).Should().BeNull();
EarlyStop.FamilyName(1, Path.Combine(Path.GetTempPath(), "nope.json")).Should().BeNull("unreadable is null, not a throw");
}
[Fact]
public void AnInstalledDetourWithNoStopIsOneLine()
{
var writer = new FlWriterState { LoaderSignals = 0x8003, Status = (uint)FlStatus.Ready };
List<string> lines = [.. EarlyStop.Describe(writer, _rules)];
lines.Should().ContainSingle().Which.Should().Contain("installed").And.Contain("woke the watchdog 3 time(s)");
}
[Fact]
public void AMissingDetourSaysWhatIsLost()
{
List<string> lines = [.. EarlyStop.Describe(new FlWriterState { LoaderSignals = 0 }, _rules)];
lines.Should().ContainSingle().Which.Should().Contain("NOT installed").And.Contain("host's 30 s scan is the only stop");
}
[Fact]
public void AStopNamesTheFamilyAndTheStatus()
{
var writer = new FlWriterState { LoaderSignals = 0x8000, EarlyStopFamily = 2, Status = (uint)FlStatus.StoppedBlocklisted };
List<string> lines = [.. EarlyStop.Describe(writer, _rules)];
lines.Should().HaveCount(2);
lines[1].Should().Contain("EARLY STOP").And.Contain("family #2 (BattlEye)").And.Contain("status=StoppedBlocklisted")
.And.Contain("fragment-and-signer tier is the host's scan");
}
[Fact]
public void TheClassifierMapsTheNewStatusToItsOwnReasonAndAnExitedTargetStillWins()
{
SessionEndClassifier.Classify(targetExited: false, (uint)FlStatus.StoppedBlocklisted, weLatchedTheUnhook: false, attachSettled: true)
.Should().Be(SessionEndReason.WriterStoppedBlocklisted);
SessionEndClassifier.Classify(targetExited: true, (uint)FlStatus.StoppedBlocklisted, weLatchedTheUnhook: false, attachSettled: true)
.Should().Be(SessionEndReason.TargetExited);
}
}
@@ -0,0 +1,157 @@
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Consume;
/// <summary>
/// Rung 3 by elimination, and the executable's markers as the clear census's second witness (<c>HANDOFF</c> 7b,
/// §H11): every sentence names what excluded what, and none names a vendor as measured.
/// </summary>
public sealed class EliminationAndMarkersTests
{
private const FlHookFamily _hooks =
FlHookFamily.Present | FlHookFamily.UpscalerIdentity | FlHookFamily.UpscalerParams | FlHookFamily.FgEvaluations;
private static readonly NgxDriverState _fgNotCreated = NgxDriverState.Parse(
"NGXSTATE status=ANSWERED sr=0x5 rr=0x5 fg=0x5 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664");
private static ExecutableMarkers Markers(params (string Name, bool Fg, int Hits)[] found) => new(
[.. found.Select(f => new ExecutableMarker(f.Name, "test", f.Fg, f.Hits))], BytesScanned: 1_000_000, Error: null);
/// <summary>k presents per application frame, the token on the first, no tag naming a technology.</summary>
private static List<FlFrameRecord> Stream(int appFrames, int k, bool counted = true)
{
List<FlFrameRecord> stream = [];
ulong qpc = 1_000_000;
ulong step = (ulong)(Stopwatch.Frequency / (60 * k));
for (int f = 0; f < appFrames; f++)
{
for (int p = 0; p < k; p++)
{
stream.Add(new FlFrameRecord
{
Qpc = qpc,
SwapchainId = 1,
OutputW = 2560,
OutputH = 1440,
// The hooks are live either way (the real Hell Is Us report claims Fg | FgCounts with
// tokens = 0); `counted` only decides whether a token was ever drained.
MeasuredMask = (ushort)(FlMeasured.OutputRes | FlMeasured.PresentArgs | FlMeasured.Upscaler
| FlMeasured.Fg | FlMeasured.FgCounts),
FgEvaluations = (byte)(counted && p == 0 ? 1 : 0),
FgMode = (byte)FlFgMode.Unknown,
});
qpc += step;
}
}
return stream;
}
private static (MeasuredFacts Facts, string Text) Render(List<FlFrameRecord> stream, FlRuntimeCensus census,
NgxDriverState? ngx, ExecutableMarkers? markers, uint tagCensus = 0)
{
var writer = new FlWriterState { HooksInstalledMask = (uint)_hooks, RuntimeCensus = (uint)census, SlTagCensus = tagCensus };
MeasuredFacts facts = MeasuredFacts.From(stream, writer, Stopwatch.Frequency, 0, 0,
FgWindow.From(stream, Stopwatch.Frequency), ngx: ngx, markers: markers);
return (facts, SessionReport.Render(facts));
}
[Fact]
public void AnXeFgShapeIsActiveByEliminationNamingTheRuntimeLoadedAndNeverXeFg()
{
// The expected XeFG session: counted ×2 by the token, the driver's FG word clear, no tag,
// no FSR dispatch, libxess_fg.dll the only frame-generation runtime in the census.
FlRuntimeCensus census = FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer | FlRuntimeCensus.LibXess | FlRuntimeCensus.LibXessFg;
(MeasuredFacts facts, string text) = Render(Stream(100, 2), census, _fgNotCreated, Markers());
facts.FgMode.Should().Be(MeasuredFacts.FgActiveUnidentified);
facts.FgModePrinted.Should().StartWith(MeasuredFacts.FgActiveUnidentified + " — by elimination among what this session saw: ");
text.Should().Contain("(x2 FG)");
text.Should().Contain("not DLSS-G (the NVIDIA driver reports no NGX frame-generation feature created, and no HUD-less / UI tag was sent through Streamline)");
text.Should().Contain("no FSR frame-generation dispatch reached a hooked module");
text.Should().Contain("the frame-generation runtime(s) loaded: libxess_fg.dll");
text.Should().Contain("a frame generator compiled into the executable would read the same");
text.Should().NotContain("XeFg").And.NotContain("frame generation: XeSS");
}
[Fact]
public void TheCompiledInShapeSaysNoRuntimeIsLoadedAndNamesTheExecutablesMarkers()
{
// Rune Factory at FSR FG: the UE title requests the Streamline token regardless, the census has
// no frame-generation module, and the executable carries the FSR 3 strings.
FlRuntimeCensus census = FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer;
(_, string text) = Render(Stream(100, 2), census, _fgNotCreated, Markers(("ffxFsr3", true, 7), ("FidelityFX", false, 3)));
text.Should().Contain("no frame-generation runtime module is loaded at all; the executable itself carries ffxFsr3");
text.Should().Contain("(x2 FG)");
}
[Fact]
public void WithoutTheDriversAnswerDlssGIsNotExcludedAndTheLineSaysSo()
{
FlRuntimeCensus census = FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer | FlRuntimeCensus.LibXessFg;
(_, string text) = Render(Stream(100, 2), census, null, null, tagCensus: (uint)FlSlTagType.Hudless << FlSlTagRoute.Global);
text.Should().Contain("DLSS-G not excluded (the NVIDIA driver did not answer; HUD-less / UI tags WERE sent through Streamline)");
}
[Fact]
public void HellIsUsAtXeSSFgWithNoTokenPrintsTheNaWithItsWitnessesAndTheXessByLicenceNote()
{
// 2026-09-06 13:52: XeSS + XeSS-FG on Hell Is Us — the plugin requests no Streamline token at XeSS,
// so nothing is counted; every other witness still speaks, and the upscaler N/A says why it is N/A.
FlRuntimeCensus census = FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer | FlRuntimeCensus.NvngxDlssG
| FlRuntimeCensus.LibXess | FlRuntimeCensus.LibXessFg;
(MeasuredFacts facts, string text) = Render(Stream(200, 1, counted: false), census, _fgNotCreated,
Markers(("xefgSwapChain", true, 13), ("ffxFrameInterpolation", true, 1)));
facts.FgMode.Should().BeNull();
text.Should().Contain("Presented FPS:");
text.Should().Contain("frame generation: N/A (a hook ran and saw no frame-generation evaluation — see the FG counts above); what this session can still say: not DLSS-G");
text.Should().Contain("the frame-generation runtime(s) loaded: nvngx_dlssg.dll, libxess_fg.dll");
text.Should().Contain("the executable itself carries xefgSwapChain, ffxFrameInterpolation");
text.Should().Contain("libxess.dll is loaded, and XeSS cannot be hooked or declared under Intel's licence");
text.Should().Contain("by policy, not by ignorance");
text.Should().NotContain("XeFg").And.NotContain("upscaler: Xess");
}
[Fact]
public void WithoutLibxessTheUpscalerNaCarriesNoLicenceNote()
{
(_, string text) = Render(Stream(200, 1, counted: false), FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer, _fgNotCreated, Markers());
text.Should().Contain("upscaler: N/A (an upscaler hook ran");
text.Should().NotContain("by policy, not by ignorance");
}
[Fact]
public void AClearCensusWithAnFgCapableMarkerInTheFileSaysMayNotCannot()
{
// Token-less and compiled-in: nothing counted, no module, but the file carries the FSR 3 strings.
(_, string text) = Render(Stream(200, 1, counted: false), FlRuntimeCensus.Ran, null, Markers(("ffxFrameInterpolation", true, 2)));
text.Should().Contain("Presented FPS:");
text.Should().Contain("WARNING: no known frame-generation runtime MODULE was loaded, but the executable itself carries ffxFrameInterpolation");
text.Should().Contain("MAY include generated frames");
text.Should().NotContain("cannot include in-process generated frames");
}
[Fact]
public void AClearCensusAndACleanFileKeepsCannotWithTheFileNamedAndAnUnscannedFileIsByteIdentical()
{
(_, string scanned) = Render(Stream(200, 1, counted: false), FlRuntimeCensus.Ran, null, Markers(("NVSDK_NGX", false, 4)));
(_, string unscanned) = Render(Stream(200, 1, counted: false), FlRuntimeCensus.Ran, null, null);
scanned.Should().Contain("cannot include in-process generated frames")
.And.Contain("the executable carries none of the frame-generation SDK strings this host scans for");
unscanned.Should().Contain("cannot include in-process generated frames (statically linked FSR3-FG and driver-level AFMF are outside what this can see)");
unscanned.Should().NotContain("executable carries");
}
}
@@ -0,0 +1,36 @@
using FluentAssertions;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Consume;
public sealed class LaunchNoteTests
{
[Fact]
public void AnAttachSessionPrintsOnlyTheBeforeHookCount()
{
List<string> lines = [.. LaunchNote.Describe(null, new FlWriterState { DxgiPresentsBeforeHook = 137 })];
lines.Should().ContainSingle().Which.Should().Contain("presents before the first hooked present: 137");
}
[Fact]
public void ALaunchedSessionPrintsTheWaitFirst()
{
List<string> lines = [.. LaunchNote.Describe(TimeSpan.FromMilliseconds(842), new FlWriterState { DxgiPresentsBeforeHook = 0 })];
lines.Should().HaveCount(2);
lines[0].Should().Contain("injected 842 ms after the process was started");
lines[1].Should().Contain("presents before the first hooked present: 0");
}
[Fact]
public void TheNotReadSentinelIsNamedAndNeverPrintedAsANumber()
{
var writer = new FlWriterState { DxgiPresentsBeforeHook = FlWriterState.DxgiPresentsBeforeHookNotRead };
List<string> lines = [.. LaunchNote.Describe(null, writer)];
lines.Should().ContainSingle().Which.Should().Contain("not read").And.NotContain("4294967295");
}
}
@@ -71,14 +71,18 @@ public sealed class NoSecondMatcherTests
// seam out of everything that ships.
MethodInfo[] methods = typeof(IAntiCheatGuard).GetMethods();
// Raised from 2 to 3 as a reviewed act when the static pre-scan landed.
// Raised from 2 to 3 as a reviewed act when the static pre-scan landed,
// and from 3 to 4 when launch mode's WAITING entry landed (P1 item 2):
// GuardedInjectWhenReadyAsync takes a pid, a path and a budget in
// milliseconds -- primitives, as the loop below insists -- and the budget
// decides only WHEN the guard's full scan runs, never what it sees.
//
// The alternative was a second port, which would have kept this number
// at 2 while the new surface grew somewhere this test never looks — the
// count would have gone on passing precisely because the thing it
// guards had moved. A number that has to be edited deliberately is the
// point of it.
methods.Should().HaveCount(3);
methods.Should().HaveCount(4);
// Stronger than the count, and it survives the port growing: every
// parameter must be a primitive the caller cannot smuggle evidence
@@ -0,0 +1,94 @@
using System.Text.Json;
using FluentAssertions;
using FrameLedger.Infrastructure.Vulkan;
namespace FrameLedger.Infrastructure.Tests.Vulkan;
public sealed class VkLayerLaunchEnvironmentTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-vklayer-" + Guid.NewGuid().ToString("N"));
private readonly string _dll;
public VkLayerLaunchEnvironmentTests()
{
Directory.CreateDirectory(_dir);
_dll = Path.Combine(_dir, "FrameLedger.VkLayer.dll");
File.WriteAllBytes(_dll, [0x4D, 0x5A]);
}
public void Dispose()
{
try
{
Directory.Delete(_dir, recursive: true);
}
catch (IOException)
{
}
}
private string LayerDir => Path.Combine(_dir, "vklayer");
[Fact]
public void PrepareWritesTheManifestTheEnableListEntryAndTheTwoVariables()
{
using var env = VkLayerLaunchEnvironment.Prepare(@"D:\Games\Title\Game.exe", _dll, LayerDir);
env.ImageName.Should().Be("game.exe", "the enable-list holds lowercased image names");
env.Variables.Should().Contain(VkLayerLaunchEnvironment.EnableVariable, "1");
env.Variables.Should().Contain(VkLayerLaunchEnvironment.ImplicitLayerPathVariable, LayerDir);
File.ReadAllText(env.EnableListPath).Should().Contain("game.exe");
env.ManifestPath.Should().NotBeNull();
using JsonDocument manifest = JsonDocument.Parse(File.ReadAllText(env.ManifestPath!));
JsonElement layer = manifest.RootElement.GetProperty("layer");
layer.GetProperty("name").GetString().Should().Be(VkLayerLaunchEnvironment.LayerName);
layer.GetProperty("library_path").GetString().Should().Be(Path.GetFullPath(_dll));
layer.GetProperty("enable_environment").GetProperty(VkLayerLaunchEnvironment.EnableVariable).GetString()
.Should().Be("1", "the loader compares the VALUE, so the manifest must say what the host sets");
}
[Fact]
public void DisposeRemovesExactlyWhatPrepareAddedAndNothingElse()
{
Directory.CreateDirectory(LayerDir);
string enableList = Path.Combine(LayerDir, "enabled.txt");
File.WriteAllText(enableList, "# somebody's list\nother.exe\n");
string manifest;
using (var env = VkLayerLaunchEnvironment.Prepare(@"D:\Games\Title\Game.exe", _dll, LayerDir))
{
manifest = env.ManifestPath!;
File.ReadAllLines(enableList).Should().Contain("game.exe").And.Contain("other.exe");
}
File.ReadAllLines(enableList).Should().NotContain("game.exe").And.Contain("other.exe").And.Contain("# somebody's list");
File.Exists(manifest).Should().BeFalse();
}
[Fact]
public void AnEntrySomebodyElseWroteIsNeitherDuplicatedNorRemoved()
{
Directory.CreateDirectory(LayerDir);
string enableList = Path.Combine(LayerDir, "enabled.txt");
File.WriteAllText(enableList, "GAME.EXE\n");
using (VkLayerLaunchEnvironment.Prepare(@"D:\Games\Title\Game.exe", _dll, LayerDir))
{
File.ReadAllLines(enableList).Should().ContainSingle("the existing entry matches case-insensitively");
}
File.ReadAllLines(enableList).Should().ContainSingle().Which.Should().Be("GAME.EXE");
}
[Fact]
public void WithoutAStagedLayerNothingIsWrittenAndNoVariableIsSet()
{
using var env = VkLayerLaunchEnvironment.Prepare(@"D:\Games\Title\Game.exe", Path.Combine(_dir, "missing.dll"), LayerDir);
env.Variables.Should().BeEmpty("a manifest pointing at nothing would only make the loader log an error into the game");
env.ManifestPath.Should().BeNull();
Directory.Exists(LayerDir).Should().BeFalse();
}
}
+132
View File
@@ -0,0 +1,132 @@
#Requires -Version 7.0
<#
.SYNOPSIS
The accuracy blocks in README.md and legal/DISCLAIMER.md are one text, kept in
legal/ACCURACY.md, and this gate fails when any copy has drifted from it.
.DESCRIPTION
docs/20_OPEN_QUESTIONS.md §S23-6: the accuracy blocks were hand-maintained prose
that nothing verified, and DISCLAIMER's went stale four times in one direction
and once in the other. Single-sourcing them does not make them true — that is
still a human's job, dated in the block itself — but it makes there be exactly
one place to get them wrong, and a build that notices when a copy is not that
place.
Each target file embeds the block between
<!-- accuracy-block:begin -->
<!-- accuracy-block:end -->
and the text between the markers must equal legal/ACCURACY.md with its own
`<!-- … -->` comment lines removed, after line-ending normalisation and
trimming. Missing markers fail; a second pair of markers fails; whitespace-only
drift is tolerated because CRLF/LF and a trailing newline are not what this
gate is for.
-SelfTest proves the gate discriminates, both directions, on temporary copies:
the shipped files pass, a one-character mutation inside a block fails, and a
file with its markers removed fails. A gate that has never been red is a gate
nobody has seen work.
#>
[CmdletBinding()]
param(
[string]$RepoRoot = (Split-Path $PSScriptRoot -Parent),
[switch]$SelfTest
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$beginMarker = '<!-- accuracy-block:begin -->'
$endMarker = '<!-- accuracy-block:end -->'
function Get-CanonicalBlock([string]$Text) {
# Whole HTML comments go, wherever their lines start: the source file opens with a
# multi-line comment explaining itself, and a copy may carry the markers' own.
$stripped = [regex]::Replace(($Text -replace "`r`n", "`n"), '(?s)<!--.*?-->', '')
$kept = foreach ($l in ($stripped -split "`n")) { $l.TrimEnd() }
return (($kept -join "`n").Trim())
}
# Returns $null when the file embeds exactly one block, else the reason it does not.
function Test-Embedded([string]$Path, [string]$Expected) {
if (-not (Test-Path $Path)) { return "missing file $Path" }
$text = Get-Content $Path -Raw
$begins = [regex]::Matches($text, [regex]::Escape($beginMarker)).Count
$ends = [regex]::Matches($text, [regex]::Escape($endMarker)).Count
if ($begins -ne 1 -or $ends -ne 1) {
return "$Path must embed the block exactly once (begin markers: $begins, end markers: $ends)"
}
$start = $text.IndexOf($beginMarker) + $beginMarker.Length
$stop = $text.IndexOf($endMarker)
if ($stop -lt $start) { return "$Path has its end marker before its begin marker" }
$inner = Get-CanonicalBlock $text.Substring($start, $stop - $start)
if ($inner -ne $Expected) {
return "$Path's accuracy block differs from legal/ACCURACY.md — edit the source and re-embed, never the copy"
}
return $null
}
function Invoke-Check([string]$Root) {
$source = Join-Path $Root 'legal/ACCURACY.md'
if (-not (Test-Path $source)) { return @("legal/ACCURACY.md is missing") }
$expected = Get-CanonicalBlock (Get-Content $source -Raw)
if ($expected.Length -eq 0) { return @("legal/ACCURACY.md carries no block (only comments)") }
$problems = @()
foreach ($rel in 'README.md', 'legal/DISCLAIMER.md') {
$why = Test-Embedded (Join-Path $Root $rel) $expected
if ($null -ne $why) { $problems += $why }
}
return $problems
}
if ($SelfTest) {
$tmp = Join-Path ([IO.Path]::GetTempPath()) ("fl-accuracy-" + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path (Join-Path $tmp 'legal') -Force | Out-Null
try {
foreach ($rel in 'legal/ACCURACY.md', 'README.md', 'legal/DISCLAIMER.md') {
Copy-Item (Join-Path $RepoRoot $rel) (Join-Path $tmp $rel)
}
$cases = 0
# 1. The shipped files pass.
$p = @(Invoke-Check $tmp)
if ($p.Count -ne 0) { throw "self-test: the shipped files should pass, got: $($p -join '; ')" }
$cases++
# 2. One character changed inside README's block fails, naming README.
$readme = Join-Path $tmp 'README.md'
$orig = Get-Content $readme -Raw
$s = $orig.IndexOf($beginMarker) + $beginMarker.Length + 40
$mutated = $orig.Substring(0, $s) + 'X' + $orig.Substring($s + 1)
Set-Content $readme $mutated -NoNewline
$p = @(Invoke-Check $tmp)
if ($p.Count -ne 1 -or $p[0] -notmatch 'README\.md') { throw "self-test: a mutated README block should fail naming README, got: $($p -join '; ')" }
$cases++
Set-Content $readme $orig -NoNewline
# 3. Markers removed from DISCLAIMER fails, naming it.
$disc = Join-Path $tmp 'legal/DISCLAIMER.md'
$origD = Get-Content $disc -Raw
Set-Content $disc ($origD -replace [regex]::Escape($beginMarker), '') -NoNewline
$p = @(Invoke-Check $tmp)
if ($p.Count -ne 1 -or $p[0] -notmatch 'DISCLAIMER\.md') { throw "self-test: a DISCLAIMER without markers should fail naming it, got: $($p -join '; ')" }
$cases++
Set-Content $disc $origD -NoNewline
# 4. A source with only comments fails rather than matching an empty block.
Set-Content (Join-Path $tmp 'legal/ACCURACY.md') "<!-- nothing -->`n" -NoNewline
$p = @(Invoke-Check $tmp)
if ($p.Count -ne 1 -or $p[0] -notmatch 'no block') { throw "self-test: an empty source should fail, got: $($p -join '; ')" }
$cases++
Write-Host "accuracy-check self-test OK - $cases cases, both directions"
}
finally {
Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue
}
exit 0
}
$problems = @(Invoke-Check $RepoRoot)
if ($problems.Count -ne 0) {
Write-Host 'ACCURACY CHECK FAILED:' -ForegroundColor Red
foreach ($p in $problems) { Write-Host " $p" -ForegroundColor Red }
Write-Host ' legal/ACCURACY.md is the source; README.md and legal/DISCLAIMER.md embed it between the markers.' -ForegroundColor Red
exit 1
}
Write-Host 'accuracy-check OK - README.md and legal/DISCLAIMER.md carry legal/ACCURACY.md verbatim'
exit 0
+36
View File
@@ -129,6 +129,42 @@ if ($fragmentCanaryPassed) {
exit 1
}
# --- Canary 3: `action` and `signerField` are CONSTANTS the schema pins (§S19(c)) --
#
# Neither field is read by the guard, and that is the design rather than a gap:
# CLAUDE.md rule 2 says `allow` and `warn` do not exist, and 19_SAFETY's signer
# comparison is the certificate subject's O= (measured — the CN is a WHQL
# publisher string on every driver). The policy is CODE. The fields exist so that
# the DATA cannot say otherwise, and this canary is what makes that true: mutate
# each to the value it must never take and the schema must reject the document.
# Delete either `const` and the field becomes a lie the guard would not notice.
$policyCanaryPassed = $false
try {
$mutant = $rulesRaw | ConvertFrom-Json
$mutant.anticheat.heuristic.action = 'allow'
$policyCanaryPassed = ($mutant | ConvertTo-Json -Depth 100 | Test-Json -Schema $schema -ErrorAction SilentlyContinue)
}
catch { $policyCanaryPassed = $false }
if ($policyCanaryPassed) {
Write-Host 'RULES VALIDATION FAILED: the schema accepted anticheat.heuristic.action = "allow".' -ForegroundColor Red
Write-Host ' `action` is a const (`warn_and_refuse`) because CLAUDE.md rule 2 says no other' -ForegroundColor Red
Write-Host ' action exists; if a rules push can say otherwise, the const is gone. §S19(c).' -ForegroundColor Red
exit 1
}
$signerFieldCanaryPassed = $false
try {
$mutant = $rulesRaw | ConvertFrom-Json
$mutant.anticheat.heuristic.signerField = 'CN'
$signerFieldCanaryPassed = ($mutant | ConvertTo-Json -Depth 100 | Test-Json -Schema $schema -ErrorAction SilentlyContinue)
}
catch { $signerFieldCanaryPassed = $false }
if ($signerFieldCanaryPassed) {
Write-Host 'RULES VALIDATION FAILED: the schema accepted anticheat.heuristic.signerField = "CN".' -ForegroundColor Red
Write-Host ' The guard compares O= (19_SAFETY, measured 2026-08-02: CN is a WHQL publisher' -ForegroundColor Red
Write-Host ' string on every driver); a data file must not be able to claim otherwise. §S19(c).' -ForegroundColor Red
exit 1
}
function Test-Member($Object, [string]$Name) {
return $null -ne $Object -and $Object.PSObject.Properties.Name -contains $Name
}