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
poli0981andClaude Fable 5.1 7cc4efc8e2 docs: §H5's DLSS / DLSS-G question closed on Cronos with frame generation on -- the 2.8.0 pacer bypass is Dying Light: The Beast's, not the SDK's (#130)
Cronos: The New Dawn demo (Streamline 2.8.0, UE) with FG on: 86.8 -> 172.72 (x1.99 FG),
unseen=0 over 10,063 samples, DlssG with the driver agreeing, upscaler Dlss driver-reported.
Every measured NVIDIA title now prints the rule-6 trio or a counted none; the owner closed
the item. HANDOFF 7a struck; the next item is the owner's pick from 7b / 7c.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 05:36:54 +00:00
poli0981andClaude Fable 5.1 a55be828cd feat(capturehost): the driver's FG word beside the frame-generation line, and a counted-but-refused session says so -- §H5 rows N1-N4 landed (#129)
The owner's run on #128: N3 held (Lies of P with upscaling OFF reads SR 0x5, CREATED clear),
N1 prints `Dlss (driver-reported ...)` on Lies of P, Expedition 33, Hell Is Us and the new
Cronos demo, N2 prints agreement on Onimusha and DL:TB, and a DL:TB session at FSR + DLSS-G
read SR 0x205 (created, not evaluated) and correctly claimed nothing.

One correction from the run's own readings: the FG word is NOT blind to Streamline DLSS-G.
It read CREATED | EVALUATE on every x4 session, changing between readings as the feature
came up; the morning's INITIALIZED | DLL_EXISTS was an early reading. The multiplier bits
stay clear at x4, so the word is an identity witness: printed beside `frame generation:`
as agreement or a printed disagreement, promoted to `DlssG (driver-reported ...)` only where
the count is active and no tag named the technology. The count is never the driver's.

And the FSR + DLSS-G session exposed a wrong qualifier: 4,415 tokens, 8,174 DXGI-counted
presents, a factor refused for uniformity, and the line said "no evaluation was observed".
It now says the factor was counted and refused, that DXGI counted presents this hook never
saw so the Displayed rate is above the printed number, and that the number is neither
Native nor Displayed.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 12:06:32 +07:00
poli0981andClaude Fable 5.1 f7c700acb8 feat(capturehost): the super-resolution identity from the NVIDIA driver where no hook can see it -- the driver-reported rung (#128)
Owner decision 2026-09-06 ("noi probe de bat dau"). Three NGX-direct titles printed
`upscaler: N/A` on every capture while the driver's per-process NGX word
(NvAPI_NGX_GetNGXOverrideState) reads CREATED | EVALUATE for them without an override.

- fl-probe-nvapi --ngx-state prints one machine line (NGXSTATE status=... sr=0x... ...)
  after its human output; the capture host stages the probe beside itself.
- NgxDriverProbe spawns it beside every module snapshot (out of process, no injection);
  NgxDriverState parses and merges the readings (last answered word is the state, a
  change between readings is printed, an earlier answer outranks a later silence).
- The report prints `NVIDIA driver NGX state:` in the runtime block; the `upscaler:` line
  reads `Dlss (driver-reported: ... not counted by this hook)` when no hook named one,
  prints agreement or a disagreement (printed, not resolved) beside a hook's Dlss, and
  the driver's attributed negative beside an N/A.
- Identity only, each limit measured: no quality/preset (override fields), no ratio
  (scalingRatio 0 even under an override), no FG mode/multiplier (the FG word is blind
  to Streamline DLSS-G).
- §H5 pre-commits rows N1-N4; N3 (DLSS OFF) withdraws the rung if the bit stays set.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 03:26:23 +00:00
poli0981andClaude Fable 5.1 ec181de07d docs: the NVAPI NGX-state probe measured on three running titles -- SR identity is driver-reported without an override; the FG word does not see DLSS-G (#127)
Hell Is Us (no override, DLSS-G x4 running), Expedition 33 (NVIDIA-app override ON, FG off)
and Lies of P (no override): CREATED | EVALUATE on the SR word on both no-override titles;
the FG word reads INITIALIZED | DLL_EXISTS beside a x4 DLSS-G session; frameGenerationCount
is 0 everywhere (the override target, not the multiplier); scalingRatio is 0 even under the
override. §H5 states what a driver-reported rung may and may not claim and the negative
still owed (DLSS off in the menu); HANDOFF 7a's START HERE moves to that decision.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:51:39 +00:00
poli0981andClaude Fable 5.1 d670824058 feat(capturehost): the withheld none narrowed to sessions where DXGI's counter was not read -- §H5 Leg 0 landed (#126)
The owner's morning run on #125: DL:TB at DLSS FG x4 printed the rule-6 trio from the
DXGI-counted Displayed (70.52 -> 282.08 (x4 FG), 12,387 presents DXGI-counted, DlssG),
then twice with frame generation OFF: census unchanged (sl.dlss_g.dll is a startup-time
load), presents = tokens, unseen = 0 over 3,659 / 4,519 samples, and the report withheld
`none` exactly as the gate's cost paragraph pre-committed. Expedition 33 FG off: none by
count, tag census 0.

The DXGI counter is the discriminator the gate lacked -- on the 2.8.0 shape the pacer's
presents are DXGI presents on the hooked chain -- so a counted none beside a READ counter
with zero unseen prints as none with "DXGI's own present counter agrees: 0 unseen over N
hooked present(s)"; it is withheld only when the counter was not read, with the reason
saying so; a writer state that counted unseen presents the records do not carry is refused
as a contradiction. Every other title prints the counter beside none as a second witness.
CLAUDE.md rule 6 carries the amendment; 03_METRICS, §H5, spike-notes §9, HANDOFF updated.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 09:09:55 +07:00
poli0981andClaude Fable 5.1 61dc4c4036 feat(overlay): Displayed counted by DXGI where the hook cannot count it -- §H5 row P1-DXGI landed, twice (#125)
The owner's run on #124 read 2.90 and 2.95 presents per hooked present that DXGI counted
on the same chain and the inline patches never saw (Dying Light: The Beast, Streamline
2.8.0, DLSS FG x4), against 0.00 on Streamline 2.7.3 (Hell Is Us x3.86) and 2.10.3 (the
Onimusha: Way of the Sword demo x3.67), whose generated frames come through the patched
bodies. So 2.8.0's pacer is the odd one, and the pre-committed action is built:

- FlFrameRecord.dxgiUnseen @52 (first byte of v3's reserved word, no offset moved, no
  layout bump) under FL_MEASURED_DXGI_PRESENTS; mirror, fl-layout-dump and asserts follow.
- FgWindow counts Displayed = hooked + sum(dxgiUnseen): in the rule-6 trio, presents/batch
  and the uniformity buckets, never in a frame-time distribution. The report prints
  "Displayed is DXGI-COUNTED" on its own line whenever the sum is above zero. A saturated
  byte is refused; a byte under a clear bit is an honesty violation.
- A present the hook SAW and declined (a paused session) is not unseen: every declined
  present bumps an epoch that invalidates the chain's last reading. The paused-session
  integration case caught the first record after a resume claiming the whole pause (0x55).
- The "sl.interposer + sl.common must be loaded on >= 2.8" lead is closed by the 2.10.3
  title, which injects, tags on the frame route and counts like 2.7.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 16:18:12 +00:00
poli0981andClaude Fable 5.1 ef7d657f9d feat(overlay): DXGI's own present counter against the hook's -- the in-process half of §H5 Leg 1 (#124)
On every hooked present the Overlay now reads IDXGISwapChain::GetLastPresentCount on
the chain it just saw (rule 4: the object FindOrAdd already calls GetDesc on; no new
hook) and publishes dxgiPresentSamples / dxgiPresentsUnseen on the watchdog tick
(FlWriterState @48/@52 from reserved[], no layout bump; mirror, fl-layout-dump and
the offset asserts follow). The report prints the ratio with its reading and the
withheld qualifier says which side of DXGI the generated presents fall on. §H5 carries
the rows written before the run (P1-DXGI / P3-DXGI / P5-DXGI). The harness's own
presents are the negative control (fl_guard [fg]: zero unseen); the positive cannot
be fixtured. hook-harness --probe-frames prints the call's cost (12.4 ns on WARP).

The owner's lead -- Streamline >= 2.8 needs sl.interposer.dll and sl.common.dll loaded
before injection succeeds -- was checked against the interposer source: the DXGI proxy
is identical at 2.7.32 and 2.8.0, and injection into DL:TB already succeeds. The
unknown is where the closed pacer presents, which is what this counter asks DXGI.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 14:48:49 +00:00
poli0981andClaude Fable 5.1 5656707733 feat(capturehost): a stall diagnostic placed against FrameLedger's own touches on the target (#123)
The owner saw Cyberpunk 2077 fall to 1 FPS for about a second under capture and the report
could say nothing about whose it was. The loop now records the QPC moment of every guard scan
and module snapshot (CaptureResult.TouchQpc, the records' own clock), and StallReport prints
the three longest present-to-present intervals with their session time and the nearest host
touch: inside or within 1 s -> FrameLedger is a SUSPECT, re-run on the 30 s cadence; far away ->
not ours. Counts intervals at or over 100 ms; calls itself a diagnostic, not 03_METRICS' stutter.
Four cases pin the placement. No Overlay change.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 13:29:46 +00:00
poli0981andClaude Fable 5.1 a34d9e3cd2 docs: the tag route measured -- DlssG on six of six Streamline titles; DL:TB's scaling-input tag arrives with no size (7a closed by the census) (#122)
The owner's evening run on #121: `frame generation: DlssG` on Hell Is Us (x4, twice), Expedition
33 (x1.97), Wukong (x4), Rune Factory (x3.98) and Cyberpunk; every Streamline title tags the
DLSS-G inputs through a route this build hooks (UE + Cyberpunk 2.7.1 globally, DL:TB 2.8 via
slSetTagForFrame). DL:TB's census shows a scaling-in tag on the frame route with UpscalerParams
still 0 -- no size on the tag -- closing 7a's last question at no layout cost. Cyberpunk's factor
was refused on a mixed session (bucket 1 at 3.0 vs 1.67, tokens/batch 2.97), as designed.
Recorded in spike-notes §9, §H5 and HANDOFF 7a; the one NVIDIA gap left is `upscaler: N/A` on
the NGX-direct titles (the --ngx-state probe).

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 20:07:48 +07:00
96 changed files with 8432 additions and 356 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
+190
View File
@@ -19,6 +19,188 @@ 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
`CREATED | EVALUATE` for them — measured 2026-09-06 without an NVIDIA-app override. The capture host now
spawns `fl-probe-nvapi --ngx-state <pid>` beside every module snapshot (the probe gained one machine line,
`NGXSTATE status=… sr=0x… …`, and is staged beside the host), merges the readings (`NgxDriverState`: the
last answered word is the state, a change between readings is printed), prints `NVIDIA driver NGX state:`
in the runtime block, and the `upscaler:` line reads `Dlss (driver-reported: … not counted by this hook)`
when no hook named one. Identity only, each limit measured: no quality or preset (override fields), no
ratio (`scalingRatio` is 0 even under an override), no frame-generation multiplier (`FG_MODE` /
`FG_MULTI_FRAME` stay clear at ×4). **The FG word follows DLSS-G too, corrected on the first run's own
readings:** `CREATED | EVALUATE` on every ×4 session, changing between readings as the feature came up, so
it is printed beside `frame generation:` as agreement or a printed disagreement, and promoted to
`DlssG (driver-reported …)` only where the count is active and no tag named the technology — the count is
never the driver's. Owner's run (§H5 rows N1–N4): the negative held (`CREATED` clear with upscaling off),
four NGX-direct titles now print `Dlss (driver-reported …)`, two hooked titles print agreement, and an
FSR + DLSS-G session read `SR 0x205` (created, not evaluated) and correctly claimed nothing. Beside a hook's `Dlss` the driver's word prints as agreement or as a
disagreement printed rather than resolved; beside an `N/A` with the bit clear it prints the driver's
negative. `20_OPEN_QUESTIONS` §H5 pre-commits rows N1–N4, and N3 — DLSS switched off — withdraws the rung
if the bit stays set. `03_METRICS` §Upscaling, `05_DETECTION`, `18_GPU_VENDOR_APIS` carry it.
### 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
a runtime was loaded and nothing was seen. It now says frame generation was counted and its factor
refused, that DXGI counted presents this hook never saw so the Displayed rate is above the printed
number, and that the number is neither Native nor Displayed.
- **The withheld `none` is narrowed to sessions where DXGI's counter was not read (§H5 Leg 0 landed).**
The owner's morning run on the DXGI-counted build printed the rule-6 trio on Dying Light: The Beast
(`Native 70.52 -> Displayed 282.08 (x4 FG)`, 12,387 presents DXGI-counted, `DlssG`) and then ran the
title twice with frame generation OFF: census unchanged (`sl.dlss_g.dll` is a startup-time load),
presents = tokens, `unseen=0` over thousands of samples, and the report withheld `none` exactly as the
gate's cost paragraph pre-committed. The counter is the discriminator the gate lacked — on that shape
the pacer's presents are DXGI presents on the hooked chain — so a counted `none` beside a READ counter
with zero unseen now prints as `none`, with *"DXGI's own present counter agrees: 0 unseen over N hooked
present(s)"* on the line; it is withheld only when the counter was not read, with the reason saying so.
A writer state that counted unseen presents the records do not carry is refused as a contradiction.
On every other title the counter is printed beside `none` as a second witness. CLAUDE.md rule 6 carries
the amendment; three cases changed sides and four are new.
### Added
- **Displayed FPS counted by DXGI where the hook cannot count it — the 2.8.0 pacer's presents.** The
owner's run on the DXGI counter landed `20_OPEN_QUESTIONS` §H5 row P1-DXGI twice: Dying Light: The
Beast at DLSS Frame Generation ×4 on Streamline 2.8.0 reads 2.90 and 2.95 presents per hooked present
that DXGI counted on the same chain and the inline patches never saw, while Streamline 2.7.3 (Hell Is
Us, ×3.86) and 2.10.3 (the Onimusha: Way of the Sword demo, ×3.67) read 0.00 — their generated frames
come through the patched bodies. So the record now carries `dxgiUnseen` (@52, from the reserved word,
under `FL_MEASURED_DXGI_PRESENTS`, no layout bump; mirror and `fl-layout-dump` follow), and the
consumer's window counts `Displayed = hooked + Σ dxgiUnseen` — in the rule-6 trio, in `presents/batch`
and in the uniformity buckets, never in a frame-time distribution — printing *"Displayed is
DXGI-COUNTED"* on its own line whenever the sum is above zero, because that number is a count DXGI
made rather than this hook. `none` withdraws on that title by count; a saturated byte is refused like
a saturated `fgEvaluations`; a byte under a clear bit is an honesty violation. A present the hook SAW and
declined — a paused session — is not an unseen present: every declined present bumps an epoch that
invalidates the chain's last reading, which the paused-session integration case caught (the first record
after a resume claimed the whole pause, 0x55, before the guard). On every other title
the window is byte-identical (five cases pin it; the injected `[fg]` case checks the byte is claimed
and zero on the harness). `03_METRICS` §Displayed may be DXGI-COUNTED carries the rule.
- **DXGI's own present counter against the hook's, in the writer state and the report.** On the one shape
where `none` is withheld (Streamline ≥ 2.8 with `sl.dlss_g.dll` loaded, Dying Light: The Beast), the
open question was whether the closed pacer's generated presents reach DXGI through a body the inline
patches miss or are displayed below DXGI. The Overlay now reads `IDXGISwapChain::GetLastPresentCount`
on every hooked present of the chain it just saw (rule 4: the same object `GetDesc` is already read
from) and publishes `dxgiPresentSamples` and `dxgiPresentsUnseen` (`FlWriterState @48/@52`, from
`reserved[]`, no layout bump; mirror, `fl-layout-dump` and the offset asserts updated). The report prints
`DXGI present counter: unseen=M over samples=N (r unseen per hooked present)` with the reading, and the
withheld qualifier says which side of DXGI the generated presents fall on. `20_OPEN_QUESTIONS` §H5
carries the rows written before the run: r ≈ 3 at ×4 means the generated presents ARE DXGI presents
and the next PR labels a DXGI-counted Displayed rate; r ≈ 0 means below DXGI and only the kernel and
vendor reads remain. The harness's presents are the negative control (`fl_guard` `[fg]`: zero unseen);
the positive cannot be fixtured. `hook-harness --probe-frames` now prints the call's cost.
- **A stall diagnostic in the report, placed against FrameLedger's own touches on the target.** The
owner saw Cyberpunk 2077 fall to 1 FPS for about a second under capture (2026-09-05) and the report
could say nothing about whose it was. The capture host now records the QPC moment of every guard scan
and module snapshot (`CaptureResult.TouchQpc`, the records' own clock), and `StallReport` prints the
three longest present-to-present intervals with their session time and the nearest host touch: a
touch inside or within 1 s names FrameLedger a SUSPECT and asks for a longer run on the 30 s cadence;
a far one says *not ours*. It counts intervals at or over 100 ms and calls itself a diagnostic — it is
not `03_METRICS`' stutter, which P2's calculators own. Four cases pin the placement.
- **DLSS Frame Generation is NAMED, from the tags the title already sends.** On every NVIDIA title measured
the count was right and the technology unnamed — `Active (technology not identified)` on Cyberpunk at
MFG ×3 and on the three UE titles at ×4 — because `kFeatureDLSS_G` is never evaluated through the export
@@ -38,6 +220,14 @@ GitHub release body, so a missing section will mean an empty release note.
the call resets the plugin's counter a title may read for its own FPS display, and the header marks it
not thread safe.
### Changed
- **The tag route is measured on real titles** (docs): the owner's evening run on #121 read `frame generation:
DlssG` on Hell Is Us, Expedition 33, Wukong, Rune Factory and Cyberpunk — every Streamline title tags the
DLSS-G inputs through a route this build hooks — and Dying Light: The Beast's census shows the title tags its
scaling input through `slSetTagForFrame` with no size, which closes HANDOFF 7a's last question without a
layout bump. `spike-notes` §9 carries the table; §H5 records the pre-commitment as landed.
### Fixed
- **`render -> output` prints under frame generation.** `UpscaleExtent` keyed its window on the
+2
View File
@@ -20,6 +20,8 @@ A C++ DLL (`FrameLedger.Overlay.dll`) is injected into games the user explicitly
> **Amended 2026-09-03 (owner decision).** When frame generation is *not measured* — `FL_MEASURED_FG` clear, which is every title on today's writer — the one number that may stand alone is **Presented FPS** (`presents / D`), with a mandatory qualifier from the **runtime census** (`FlWriterState.runtimeCensus`): "no frame-generation runtime was loaded, so this cannot include in-process generated frames" or "a frame-generation runtime is loaded and nothing was observed — this MAY include generated frames". The word "Native" never appears alone. **The census never produces `none`**: a statically linked FSR has no module to see, and a census-`none` there would be exactly the inflated number this rule forbids.
>
> **Amended 2026-09-05.** A counted `none` (`presents = application frames`) is **withheld** — Presented FPS with a third qualifier, "this number counts application frames; the Displayed rate is unknown" — on the one shape measured to produce a false `none`: Streamline ≥ 2.8.0 with `sl.dlss_g.dll` loaded (Dying Light: The Beast, five captures, DLSS FG ×4 per the owner). `docs/03_METRICS.md` §Frame Generation carries the key and why it is the Streamline plugin rather than `nvngx_dlssg.dll`; `20_OPEN_QUESTIONS` §H5 carries the session that keeps or withdraws it.
>
> **Amended 2026-09-06 (Leg 0 landed): narrowed, not withdrawn.** `sl.dlss_g.dll` is a startup-time load on that title (frame generation off, census unchanged, twice), and the same morning's ×4 capture measured the discriminator the gate lacked: the 2.8.0 pacer's generated presents are DXGI presents on the hooked chain (§H5 row P1-DXGI), counted through `dxgiUnseen` into `Native 70.52 → Displayed 282.08 (×4 FG)`. So a counted `none` beside a READ `IDXGISwapChain::GetLastPresentCount` with zero unseen is `none`, printed with DXGI's agreement; it is withheld only when the counter was not read.
7. **RT / PT / RR are tri-state** (`Yes` / `No` / `N/A`) with manual override. They are now *measured*, not guessed — but where measurement is genuinely impossible, the honest answer is still `N/A`. Never fabricate `Yes`.
> **Amended 2026-08-20 with the PR that wrote the hooks, per the owner ruling of 2026-08-14.** This rule named *"inline RayQuery without DXIL scan"* as one of the impossible cases, and that conflated two questions. **Whether rays are being traced is measurable** — `BuildRaytracingAccelerationStructure` is called by RayQuery titles and by `DispatchRays` titles alike, which is why both hooks exist and why the `No` branch requires the AS-build hook to have been *installed*. What needs a DXIL scan is **classifying the technique as RayQuery**, and that stays `N/A`. So the impossible cases are: naming the technique, and path-tracing classification, which has no API-level signature at all (`03_METRICS` §RT/PT/RR — a confidence score that may only ever *suggest*).
+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
+85 -1
View File
@@ -77,6 +77,41 @@ This is the metric the rewrite exists for. Resolution ladder, highest confidence
published `presents / tokens` at or below 1.05 over a uniform window (§The source, below).
Never from a hook that merely saw nothing (rung 0), and never from the census.
> ### Displayed may be DXGI-COUNTED — measured 2026-09-05 on Dying Light: The Beast
>
> `F_disp = presents observed by the hook` (§Counting, below) assumed every present reaches the
> `Present` / `Present1` bodies the Overlay inline-patches. On Streamline 2.8.0 with DLSS Frame
> Generation ×4 it does not: the hook timed 4,392 presents while `IDXGISwapChain::GetLastPresentCount`,
> read on the same chain at every hooked present, moved by 17,133 — **2.90 unseen presents per hooked
> one** (2.95 on the second capture) — against **0.00** on Streamline 2.7.3 (Hell Is Us, ×3.86) and
> 2.10.3 (the Onimusha demo, ×3.67), where the generated presents come through the patched bodies. So
> the record carries `dxgiUnseen` (@52, under `FL_MEASURED_DXGI_PRESENTS`) and the consumer's window
> counts
>
> ```
> F_disp = hooked presents + Σ dxgiUnseen (DXGI-COUNTED when the sum is > 0)
> ```
>
> **When the sum is above zero the report says so on its own line — "Displayed is DXGI-COUNTED" —
> because the number is then a count DXGI made, on the hooked chain, of presents this hook never
> timed.** It may stand in the rule-6 trio and in `presents/batch`; it may NOT stand in a frame-time
> distribution, which has no timestamps for those presents. The uniformity buckets take the same
> numerator, so a session whose pacer stopped mid-way refuses exactly as one whose tokens stopped. A
> saturated byte (255) is refused like a saturated `fgEvaluations`, and a present the hook saw and
> declined (a paused session) is not unseen — the resume's first record differences nothing.
>
> **Landed 2026-09-06 (`spike-notes` §9): `Native FPS: 70.52 -> Displayed FPS: 282.08 (x4 FG) over 16516
> present(s)` on Dying Light: The Beast, 12,387 of them DXGI-counted, `frame generation: DlssG`** — the
> rule-6 trio on the title that could not print it. **And the counter decides `none` on that shape.**
> Leg 0 the same morning (frame generation off, twice) read presents = tokens with `unseen=0` over 3,659
> and 4,519 samples, census unchanged (`sl.dlss_g.dll` is a startup-time load), so the withheld gate is
> narrowed rather than withdrawn: a counted `none` beside a READ counter with zero unseen prints as
> `none` with DXGI's agreement on the line; only a session where the counter was not read withholds.
> A writer state that counted unseen presents the records do not carry is a contradiction and is
> refused as neither. `20_OPEN_QUESTIONS` §H5 keeps the
> rows this landed on; which body the 2.8.0 pacer presents through is unlocalised and does not need
> to be for the count.
>
> **RUNG 2 IS CONDITIONAL ON THE VENDOR, measured 2026-08-20, and this list read as
> though it were not.** `--track_frame_type` is a **beta** option in PresentMon 2.5.1
> and its own help says it *"requires application and/or driver instrumentation using
@@ -259,7 +294,8 @@ F_app = Σ fgEvaluations (APPLICATION frames, counted at the
> frame generation switched off in its menu, so the consumer's rule is: **the count decides `none`,
> identity decides the name** — an active count beside the mark prints `DlssG`; a counted 1.0 beside it
> prints `none` with the inputs noted; the withheld shape (§H5) keeps its N/A with the tags reported in
> the census line. `FsrFg` keeps precedence over the count, because a drained FRAMEGENERATION dispatch
> the census line — narrowed 2026-09-06 to sessions where DXGI's counter was not read (§Displayed may be
> DXGI-COUNTED). `FsrFg` keeps precedence over the count, because a drained FRAMEGENERATION dispatch
> is a generated batch. `FlWriterState.slTagCensus` carries which types arrived on which route for the
> session (`fl_shm.h` §slTagCensus).
>
@@ -387,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
@@ -431,6 +483,38 @@ From the upscaler hooks we get, per frame:
Tier 2 has none of this: `upscaler = unknown`, ratio `N/A`.
> ### The driver-reported rung — owner decision 2026-09-06, identity only
>
> Three NGX-direct titles (Lies of P, Hell Is Us, Expedition 33) evaluate DLSS super resolution through
> a path no hook of this build sees, and printed `upscaler: N/A` on every capture. The NVIDIA driver
> keeps per-process bookkeeping of the feature — `NvAPI_NGX_GetNGXOverrideState` (R570+, MIT NVAPI,
> `18_GPU_VENDOR_APIS` L3) returns a feedback word per feature — and **measured 2026-09-06 (driver
> 616.64) its `CREATED | EVALUATE` bits are set for a process with NO NVIDIA-app override** on both
> no-override titles (`20_OPEN_QUESTIONS` §H5). So the capture host probes it out of process beside
> each module snapshot (`fl-probe-nvapi --ngx-state <pid>`, no injection, no consent), and the
> `upscaler:` line has a rung between the hooks and `N/A`:
>
> ```
> upscaler: Dlss (driver-reported: the NVIDIA driver reports an NGX super-resolution feature created
> and evaluated in this process - not counted by this hook)
> ```
>
> **What it may claim: the vendor and the feature, attributed to the driver.** What it may NOT claim,
> each one measured: a quality (`performanceMode` / `renderPreset` are populated only under an
> NVIDIA-app override and are then the OVERRIDE's values), a ratio or render size (`scalingRatio` is
> 0 even under the override), a frame-generation multiplier (`FG_MODE` / `FG_MULTI_FRAME` stay clear
> and `frameGenerationCount` is 0 at ×4 — it is the override target). **Corrected the same day, on the
> loop's own readings:** the FG word DOES follow DLSS-G once the feature exists — `CREATED | EVALUATE`
> on Hell Is Us, Onimusha and DL:TB at ×4, the word CHANGING between the session's readings; the
> morning's `INITIALIZED | DLL_EXISTS` was read before creation. So the FG word is a second witness
> for the DLSS-G IDENTITY, printed beside `frame generation:` as agreement or a printed disagreement,
> and promoted to `DlssG (driver-reported: …)` only where the count is active and no tag named the
> technology. The COUNT is never the driver's. A hook's name always outranks it, and
> beside a hook's name the driver's word is printed as agreement, or as a disagreement *printed rather
> than resolved*. Beside an `N/A` with the bit clear it prints the driver's negative, attributed, which
> says nothing about FSR or XeSS. **The negative is owed** (§H5): a title with DLSS switched off should
> read the bit clear; if it does not, the rung is withdrawn.
## RT / PT / RR — evidence-based tri-state
Tri-state `Yes | No | N/A` per session with `source` (`measured | manual | inherited`).
+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
+1 -1
View File
@@ -18,7 +18,7 @@ Derived in the Agent from the record stream; the mapping is in `03_METRICS`. Sum
| Graphics API + swapchain format, buffer count, swap effect, flags | `CreateSwapChain*` / present hooks |
| Present mode (flip / blt / independent flip) | swapchain desc + `presentFlags` + `syncInterval` |
| HDR output | `SetColorSpace1` |
| Upscaler identity + quality preset | NGX / Streamline / FFX / XeSS create+evaluate calls |
| Upscaler identity + quality preset | NGX / Streamline / FFX / XeSS create+evaluate calls — **or, when no hook saw one, the NVIDIA driver's per-process NGX word, out of process and attributed (`03_METRICS` §Upscaling, the driver-reported rung, 2026-09-06): identity only, never the preset** |
| Render resolution vs output resolution (incl. mid-session changes) | upscaler parameter reads + `ResizeBuffers` |
| Frame Generation mode + factor | NGX/SL/FFX FG feature evaluation, then cadence — **Tier 1 only**. ~~then (Tier 2 only) PresentMon `FrameType`~~ retired (§S31 row P2), and Tier 2 no longer produces frames to run cadence over either |
| Ray Tracing active | AS builds + `DispatchRays` (both, to catch inline RayQuery) |
+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) |
| ✅ `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.
+6 -1
View File
@@ -105,6 +105,7 @@ Still resolve **entry points defensively at runtime**: `nvapi64.dll` may be abse
| Memory | `NvAPI_GPU_GetMemoryInfoEx` — **not `NvAPI_GPU_GetMemoryInfo`**, which this table named until 2026-08-05. The vendored headers mark it `__nvapi_deprecated_function` ("deprecated in release 520"), so under `/W4 /WX` a call to it fails the native build |
| **Throttle reasons** | `NvAPI_GPU_GetPerfDecreaseInfo` — not available from L1 or L2 |
| Driver version | `NvAPI_SYS_GetDriverAndBranchVersion` |
| **NGX per-process state** | `NvAPI_NGX_GetNGXOverrideState` (R570+) — the driver's feedback word per DLSS feature for a PID, read OUT OF PROCESS by `fl-probe-nvapi --ngx-state` and, since 2026-09-06, by the capture host beside each module snapshot. Measured: the SR word's `CREATED \| EVALUATE` is set without an NVIDIA-app override; the FG word follows DLSS-G once created (`CREATED \| EVALUATE` at ×4, corrected the same day — the first reading was blind because it was early), the multiplier bits stay clear; `scalingRatio` is 0 even under an override. Identity only, SR and FG (`03_METRICS` §Upscaling) |
| **Reflex / PC latency** | `NvAPI_D3D_GetLatency` → per-frame sim/render/present/driver/GPU timestamps; hooking `NvAPI_D3D_SetSleepMode` / `SetLatencyMarker` in the Overlay tells us the game enabled Reflex (`17_HOOK_ENGINE`) |
Reflex latency is the single strongest reason L3 exists — it is genuinely unavailable anywhere else.
@@ -198,7 +199,11 @@ refused the same day (delegated by the owner, decided 2026-09-04).** It declares
reads no argument, but installing it inline-patches Intel's code inside the game process, and
the same licence forbids *"any modification"*; the census is the answer NGX got and Intel gets
the same one. Reversal condition: Intel publishing the headers under a licence that clears the
checklist, at which point this paragraph is re-run, not argued around.
checklist, at which point this paragraph is re-run, not argued around. **Re-run 2026-09-06 against
<https://raw.githubusercontent.com/intel/xess/main/LICENSE.txt> and `inc/xess/xess.h`: unchanged** —
the same licence, the same three needles, the same header banner. Not fired. Intel's README does
state that XeSS-FG runs on *"non-Intel GPUs with SM 6.4 support"*, so an XeFG session is measurable
on the NVIDIA dev box even though nothing in it may be hooked or declared.
### Checklist before adding any vendor SDK
+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
+497 -22
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,7 +3381,29 @@ 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.
### H5 ◐ · Proxy swapchains defeat the dummy-vtable assumption
> **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).**
> The second Streamline 2.8.0 title, UE: `Native FPS: 86.8 -> Displayed FPS: 172.72 (x1.99 FG)`,
> `unseen=0 over samples=10063`, `frame generation: DlssG — the NVIDIA driver agrees`, `upscaler: Dlss
> (driver-reported)`, RT Yes. **So the pacer that bypasses the patched `Present` bodies is Dying Light:
> The Beast's integration, not SDK 2.8.0's** — 2.8.0 on UE presents its generated frames through the body
> the inline patches cover, exactly as 2.7.x and 2.10.x do. Every measured title now prints the rule-6 trio
> or a counted `none`, on NVIDIA through one of three producers: the hooked bodies (Cyberpunk, Hell Is Us,
> Expedition 33, Wukong, Rune Factory, Onimusha, Cronos), DXGI's own counter where the hook cannot count
> (DL:TB), or a withheld `N/A` only when that counter was never read. Identity comes from the tags (DLSS-G)
> and the hooks, and from the driver's per-process word where no hook can see it (the NGX-direct titles),
> with the negative measured. **What stays unlocalised and is not needed for any number the report
> prints:** which body DL:TB's pacer reaches. The owner closed the item on this reading; the sub-items
> below are its history.
> ### CASE 3 HAS A CANDIDATE TITLE — Dying Light: The Beast, Streamline 2.8.0, DLSS Frame Generation ON, 2026-09-05
>
@@ -3241,6 +3517,83 @@ probe never showed a deadlock.
> the rule-6 pair on the hidden-presents shape could then read *application frames counted ×
> multiplier reported* — labelled as such, never as a measured Displayed.
>
> **MEASURED 2026-09-06 morning, three titles, driver 616.64 (`spike-notes` §9): the bits ARE populated
> without an override, for super resolution only.**
>
> | Title (override?) | SR feedback | RR feedback | FG feedback | ratio / mode / preset / fgCount |
> |---|---|---|---|---|
> | Hell Is Us (none), DLSS + **DLSS-G ×4 running** | `0x80605` INITIALIZED DLL_EXISTS **CREATED EVALUATE** ERR_NOT_FOUND | INITIALIZED DLL_EXISTS ERR_NOT_FOUND | `0x5` INITIALIZED DLL_EXISTS — **no CREATED / EVALUATE / FG_MODE** | 0 / 0 / 0 / 0 |
> | Expedition 33 (NVIDIA-app override ON), FG off | `0x8067F` … ENABLED DLL_LOADED DLL_SELECTED PRESET PERF_MODE **CREATED EVALUATE** ERR_NOT_FOUND | INITIALIZED DLL_EXISTS ERR_NOT_FOUND | `0x1F` INITIALIZED ENABLED DLL_EXISTS DLL_LOADED DLL_SELECTED | 0 / **2** / **11** / 0 |
> | Lies of P (none), DLSS, no FG | `0x605` INITIALIZED DLL_EXISTS **CREATED EVALUATE** | INITIALIZED ERR_FAILED ERR_NOT_FOUND | INITIALIZED ERR_FAILED ERR_NOT_FOUND | 0 / 0 / 0 / 0 |
>
> Four readings. **(1) `CREATED | EVALUATE` on the SR word is set on both no-override titles** — the
> driver keeps per-process bookkeeping of the NGX super-resolution feature whatever route the title took,
> which is exactly the identity `upscaler: N/A` lacks on the NGX-direct titles (all three print it). **(2)
> The FG word does NOT reflect DLSS-G activity:** Hell Is Us was generating at ×4 through Streamline
> (`83.21 → 332.82 (×4 FG)`, `DlssG`, the same session) and its FG word says INITIALIZED | DLL_EXISTS and
> nothing more — the word tracks the override machinery's DLL, not the plugin's evaluations. Frame
> generation stays with the tags and the count. **(3) `frameGenerationCount` is 0 on every title,
> including the one at ×4 — it is the override target the header names, never the title's multiplier**,
> so the "application frames counted × multiplier reported" pair above has no producer and is dropped.
> **(4) `scalingRatio` is 0 everywhere, override included; `performanceMode` / `renderPreset` are
> populated only under the override (E33: 2 / 11) and are then the OVERRIDE's values, not the title's** —
> so this route gives an identity and nothing about the render size or quality. `ERR_NOT_FOUND` sits
> beside CREATED | EVALUATE on two titles and is absent on the third; the header does not say what it
> refers to (a DRS profile, most likely), and it is not read as anything.
>
> **What a driver-reported rung may therefore claim — the owner's decision, not yet built:** on a
> session where every hook says `upscaler: N/A`, `Dlss (driver-reported: the NVIDIA driver reports an
> NGX super-resolution feature created and evaluated in this process — not counted by this hook)`. It
> may name the vendor and the feature; it may not state a quality, a ratio, a render size, a frame
> generation mode or a multiplier. On a hooked-identity session (Cyberpunk, DL:TB, Onimusha) the word
> is a consistency check the report prints beside the hooked name. **Owed before it is built — the
> negative:** the probe on Lies of P or Hell Is Us with DLSS switched OFF in the menu, expected
> `CREATED` clear; a rung that has only ever seen the positive would be the census's mistake again.
> Plumbing when decided: the probe already builds against `fl_nvapi`; the capture host would call it
> beside each module snapshot (out of process, no consent needed) or, if it goes in-process, through
> `Infrastructure` only (CLAUDE.md: no P/Invoke elsewhere).
>
> **BUILT 2026-09-06, on the owner's decision ("nối probe để bắt đầu").** The capture host spawns
> `fl-probe-nvapi --ngx-state <pid>` beside every module snapshot (the probe prints one machine line,
> `NGXSTATE status=… sr=0x… …`, and is staged beside the host by the project file), merges the readings
> (the last answered word is the state; a change between readings is printed, never averaged) and
> prints `NVIDIA driver NGX state:` in the runtime block. `03_METRICS` §Upscaling carries the rung and
> its limits. **Pre-committed, read off the next run:**
>
> | Row | Title / setting | Expected | Else |
> |---|---|---|---|
> | **N1** | Lies of P, Hell Is Us, Expedition 33 at DLSS | `upscaler: Dlss (driver-reported: …)` | a `CREATED \| EVALUATE` word beside `N/A` is a parser or plumbing defect — localise |
> | **N2** | Cyberpunk, DL:TB, Onimusha (hooked `Dlss`) | `upscaler: Dlss — the NVIDIA driver agrees …` | a disagreement WARNING is printed as such; it is not resolved by preferring either |
> | **N3** | **the negative, still owed:** Lies of P with DLSS switched OFF in the menu | `CREATED` clear → `upscaler: N/A (…) — the NVIDIA driver reports no NGX super-resolution feature created …` | `CREATED \| EVALUATE` still set with DLSS off → **the rung is withdrawn** (the bit is a session-lifetime latch, not a state) and the line goes back to N/A |
> | **N4** | a title at FSR / XeSS with no NGX feature | `Fsr3` / `N/A` with the driver's negative beside it | `CREATED` set on a title with no DLSS in its menu → withdraw |
>
> Lies of P has no DLSS Frame Generation (owner, 2026-09-06), which is why its FG word reads
> `ERR_FAILED ERR_NOT_FOUND`: nothing to load.
>
> **LANDED 2026-09-06, 10:39–11:36 (`spike-notes` §9): N1, N2 and N3 as pre-committed, N4 in a shape the
> row did not foresee, and one correction.** N3 first, because it decides: the standalone probe on Lies of
> P with upscaling OFF read `SR 0x5` — `CREATED` clear — and with DLSS on `0x605`; **the rung stands.** N1:
> Lies of P, Expedition 33, Hell Is Us and the new Cronos: The New Dawn demo all print
> `upscaler: Dlss (driver-reported: …)` where they printed `N/A`. N2: Onimusha and DL:TB print
> `upscaler: Dlss — the NVIDIA driver agrees`. N4 arrived as DL:TB at **FSR upscaling + DLSS Frame
> Generation**: `upscaler: FSR (3.1 or 4 …)`, `2560x1440 -> 2560x1440`, `SR 0x205` — CREATED without
> EVALUATE, so the driver's word correctly does NOT claim DLSS beside FSR (the rung needs both bits).
> **The correction:** the FG word is NOT blind to DLSS-G. It read `CREATED | EVALUATE` on Hell Is Us,
> Onimusha and DL:TB at ×4, and *"the words CHANGED between readings"* on all three — the morning's
> `INITIALIZED | DLL_EXISTS` on Hell Is Us was a first reading taken before the feature came up.
> `FG_MODE` / `FG_MULTI_FRAME` stay clear and `fgCount` is 0 at ×4, so it names the feature and never the
> multiplier: printed beside `frame generation:` as agreement, promoted to `DlssG (driver-reported)` only
> where the count is active and no tag named the technology. Also on this run: Cronos is a **second
> Streamline 2.8.0 title** (UE, FG off, `sl.dlss_g.dll` absent from its census — per-setting there — `FPS
> 105.01`, `none` with DXGI agreeing); its FG-on capture would say whether the 2.8.0 pacer bypass is the
> SDK's or Techland's. And the FSR + DLSS-G session's factor was refused (bucket 8 of 8 at 1.96 against
> 2.85 — the guard working) while the qualifier said *"no evaluation was observed"* beside 4,415 tokens; the
> qualifier now says the factor was counted and refused, and that DXGI counted 8,174 presents this hook
> never saw so the Displayed rate is above the printed one.
>
> **The last row, 12:17 — Cronos with frame generation ON: `86.8 → 172.72 (×1.99 FG)`, `unseen=0`, `DlssG`
> with the driver agreeing.** The 2.8.0 pacer bypass is Techland's, not the SDK's. Closed above.
>
> ### THE STREAMLINE DOCS, READ 2026-09-05 (v2.8.0 and main), AND WHAT THEY CHANGED
>
> The owner asked for the vendor's own guides before any rewrite. Three things in them decide this item.
@@ -3277,6 +3630,77 @@ probe never showed a deadlock.
> generation"* beside the withheld count. Lies of P at DLSS (no Streamline tokens at all) → unchanged:
> the super-resolution identity on NGX-direct titles is what the NVAPI probe above is for.
>
> **LANDED 2026-09-05 evening, on the owner's run on #121 (`spike-notes` §9):** `frame generation: DlssG` on
> Hell Is Us (×4, twice), Expedition 33 (×1.97), Wukong (×4), Rune Factory (×3.98) and Cyberpunk — every
> Streamline title tags the DLSS-G inputs through a route this build hooks (the UE plugin and Cyberpunk 2.7.1
> globally, DL:TB 2.8 through `slSetTagForFrame`), so the identity is measured six of six and *"technology
> not identified"* is gone from all of them. DL:TB's withheld line now says *"FEEDING frame generation"*
> beside the count it cannot make; its census also shows a `scaling-in` tag on the frame route with
> `UpscalerParams` still 0 — the tag carries no size on this title, which closes 7a's last question without
> the layout bump it was thought to need. Cyberpunk's factor was refused on that run (bucket 1 at 3.0 against
> 1.67 overall, `tokens/batch 2.97`): a mixed session, refused as designed rather than averaged. **What is
> left on NVIDIA is one thing: `upscaler: N/A` on the NGX-direct titles** — the probe above.
>
> **BUILT 2026-09-05, late — A1.7 promoted from "not in A1" to the in-process half of Leg 1.** The owner
> read that Streamline ≥ 2.8 "needs `sl.interposer.dll` and `sl.common.dll` loaded before an injection
> succeeds". Checked against the source, not the claim: the interposer's DXGI proxy
> (`source/core/sl.interposer/d3d12/dxgiSwapchain.cpp`) is **byte-for-byte the same file at v2.7.32 and
> v2.8.0** — plugins' before-hooks receive `m_base` and may `skip` the base call, exactly as before — and
> 2.8's `sl.common` gains `resourceTaggingForFrame.cpp` (the `slSetTagForFrame` route #121 already hooks).
> Injection into DL:TB already succeeds (every capture there has `streams=1`, a full `runtime census`, a
> tag census), so "loaded before injection" is a launcher's problem, not this hook's. What 2.8 does NOT
> show is where its closed `sl.dlss_g` pacer presents. So the Overlay now asks DXGI itself: on every hooked
> present it reads `IDXGISwapChain::GetLastPresentCount` on the chain it just saw (rule 4: the same object
> `FindOrAdd` already calls `GetDesc` on) and publishes two words on the 1 Hz watchdog —
> `dxgiPresentSamples` (hooked presents that read it) and `dxgiPresentsUnseen` (presents DXGI counted
> between two hooked ones, beyond the one seen). The report prints
> `DXGI present counter: unseen=M over samples=N (r unseen per hooked present)` and the withheld qualifier
> carries the reading. The harness's own presents are the negative control (`fl_guard` `[fg]`:
> `unseen == 0`, `samples >= drained`); the positive cannot be fixtured — nothing in this repo presents
> through a body the inline patches miss — which is why the rows below are written before the run.
> Cost: one virtual call per hooked present, measured by `hook-harness --probe-frames` (number in the PR
> body); `--probe-cost` is the empty-detour floor and does not include it.
>
> Leg 1's in-process rows, read off the new line on a DL:TB DLSS FG ×4 capture (r = unseen / samples):
>
> | Row | Reading | Meaning | Action |
> |---|---|---|---|
> | **P1-DXGI** | r ≈ 3 (×4) — `unseen ≈ 3 × samples` | the pacer presents on the SAME chain through a body the inline patches do not cover; the generated presents ARE DXGI presents | the next PR promotes `Displayed = hooked + unseen`, labelled **DXGI-counted** (a count DXGI made, not this hook), `presents/batch` from it, and `none` withdraws by count; the pacer's entry is then localised (a second `CDXGISwapChain` class, or a path that bypasses `Present`'s body) at leisure |
> | **P3-DXGI** | r ≈ 0 | DXGI counted nothing this hook did not: the generated frames are displayed below DXGI (driver pacing / flip metering) or on an object this hook never saw | the withheld wording stays; no in-process sink exists; only PresentMon (kernel) and the NVAPI corroboration remain, and if PresentMon also reads 1× the frames never were kernel presents |
> | **P5-DXGI** | 0 < r < 2.5, or r ≠ 0 with `streams > 1` | a mixed path or a second chain | stop and localise; the number is printed, never averaged into a factor |
> | **P2/P4** | r ≈ 0 with ours ≈ 4× tokens, or the count itself moved | as the kernel rows say: not generating, or the title changed | the kernel rows above decide |
>
> **LANDED 2026-09-05 night, on the owner's run on #124 (`spike-notes` §9): row P1-DXGI, twice.** DL:TB at
> DLSS FG ×4 read `unseen=12204 over samples=4136 (2.95)` at 21:56 and `unseen=12741 over samples=4392
> (2.90)` at 22:06 — DXGI counted 3.9× the presents this hook did, on the SAME chain, which is the owner's
> ~300 against ours ~75 from the afternoon, now measured in-process. The two controls read 0.00: Hell Is Us
> (Streamline **2.7.3**, `79.89 → 308.14 (×3.86)` through the patched bodies, 18,207 samples) and the
> owner's new title, the **Onimusha: Way of the Sword demo on Streamline 2.10.3** (`60.04 → 220.33
> (×3.67)`, `DlssG`, `upscaler: Dlss`, 12,914 samples, 0 unseen). So **2.8.0's pacer is the odd one** —
> 2.7.x before it and 2.10.x after it present the generated frames through `Present`'s body — and the
> "`sl.interposer.dll` + `sl.common.dll` must be loaded on ≥ 2.8" lead is closed by 2.10.3, which injects,
> tags on the frame route and counts exactly like 2.7. **The pre-committed action is built:** the record
> carries `dxgiUnseen` (@52, `FL_MEASURED_DXGI_PRESENTS`), the window counts `Displayed = hooked +
> unseen` and prints *"Displayed is DXGI-COUNTED"* on its own line, `presents/batch` takes the same
> numerator, and `none` withdraws on DL:TB by count (`03_METRICS` §Displayed may be DXGI-COUNTED). Expected
> on DL:TB's next capture: the trio at ≈ ×3.9 with the label, no withheld line, `frame generation: DlssG`.
> Which body the 2.8.0 pacer reaches stays unlocalised, as the row said.
>
> **LANDED 2026-09-06 morning, on the owner's run on #125 (`spike-notes` §9): the promotion, and Leg 0.**
> DL:TB at DLSS FG ×4 (07:31): `Native FPS: 70.52 -> Displayed FPS: 282.08 (x4 FG) over 16516 present(s)`,
> *"Displayed is DXGI-COUNTED: 12387 of those present(s)"*, `unseen=12483 over samples=4202 (2.97)`,
> `frame generation: DlssG`, uniform across every bucket, no withheld line — the trio rule 6 asks for, on
> the title that could not print it. **Leg 0, twice (07:45, 07:55): frame generation OFF**, census still
> `0x25F0F` — `sl.dlss_g.dll` is a **startup-time load**, the cost paragraph's fear measured true —
> presents = tokens, `unseen=0 over samples=3659` and `4519`, tag census `0x23600` (depth, mvec,
> scaling-in, scaling-out, other: **no hudless / UI tag with FG off**, so the DLSS-G identity is
> per-setting on this title too), and the report withheld `none` exactly as pre-committed. **The gate is
> narrowed rather than withdrawn:** DXGI's counter is the discriminator it lacked — the 2.8.0 pacer's
> presents are DXGI presents on this chain (P1-DXGI), so a counted 1.0 beside a READ counter with zero
> unseen is `none`, printed with DXGI's agreement; withheld only when the counter was not read. Control:
> Expedition 33 FG off (Streamline 2.7.30) reads `FPS: 85.86`, `none` by count, tag census `0x0` — the UE
> plugin sends no tags at all with FG off.
>
> Leg 1's rows (ours = `presents / span`; PM = PresentMon rows / span; C = the counter; ≈ = within 5 %):
>
> | Row | Reading | Meaning | Action |
@@ -3290,7 +3714,8 @@ probe never showed a deadlock.
>
> Leg 0's own row: if `sl.dlss_g.dll` is **absent** with FG off, the census bit is per-setting on
> this title and the gate is sharper than its cost paragraph feared (consider dropping the version
> conjunct); if present, the interim cost stands as written.
> conjunct); if present, the interim cost stands as written. **Landed 2026-09-06: PRESENT, twice** —
> and the cost stood for one morning, because the DXGI counter (above) narrowed the gate the same day.
>
> **Second-present-sink candidates for P1 / P5, one line each, none chosen:** MinHook inline
> patches on the `gdi32.dll` D3DKMT thunks (`D3DKMTPresent`, `D3DKMTPresentMultiPlaneOverlay3`,
@@ -3479,7 +3904,57 @@ turns a would-be STL throw into `__fastfail`, which SEH cannot intercept
(`spike-notes.md` §H3). The "no throwing STL in hook paths" rule is therefore
load-bearing rather than stylistic.
### H11 ◐ · XeFG and FSR3-FG identity — **AMD built 2026-09-04 through the ffx-api leaves; Intel closed by licence; FSR 3.0 host route deferred**
### H11 ◐ · XeFG and FSR3-FG identity — **AMD built 2026-09-04 through the ffx-api leaves, complete 2026-09-06; Intel closed by licence; FSR 3.0 host route built 2026-09-05**
> **2026-09-06: the AMD half is complete on its oracle** — Lies of P at FSR 3.1 + FSR FG on the #129 build
> prints `Fsr3` / `FsrFg` / `59.77 → 119.55 (×2 FG)` / `2560x1440 -> 2560x1440` with `presents/frame=2.00`,
> `frames/upscale-drained=1.00`, `unseen=0` and the NVIDIA driver's word saying nothing was created
> (`spike-notes` §9); the owner called it done. **Intel, re-checked the same day: the licence has not
> changed** (`18_GPU_VENDOR_APIS` §Intel), so nothing in `libxess*.dll` may be hooked or declared, and the
> signature-free thunk stays refused. **What is left in policy for an XeFG session, proposed and not yet
> built — identity BY ELIMINATION, labelled as such:** frame generation is COUNTED by the Streamline token
> (UE titles request it whatever the FG vendor — measured on Rune Factory's compiled-in FSR) or by DXGI's
> counter; DLSS-G is EXCLUDED by the NVIDIA driver's FG word (no feature created) and by the absence of the
> HUD-less / UI tags; FSR-FG through a shipped DLL is EXCLUDED by the ffx census (no FRAMEGENERATION dispatch
> at any hooked module); the frame-generation runtime the census names is `libxess_fg.dll`. The line would
> read `Active (technology not identified) — by elimination among the runtimes loaded: not DLSS-G (the
> NVIDIA driver reports no NGX frame-generation feature), no FSR dispatch reached a hooked module, and the
> frame-generation runtime present is libxess_fg.dll; a frame generator compiled into the executable would
> read the same`. Never `XeFg` as a measured identity; never a render extent. Intel's README says XeSS-FG
> runs on non-Intel GPUs with SM 6.4, so DL:TB / Hell Is Us / Cronos / Expedition 33 with XeSS FG on are
> 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
+100 -10
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
@@ -690,7 +706,15 @@ FG factor and RT state are measured against the titles' own menus. What follows
owner's list for the next session, in the order the dependencies run, each with what makes
it fail on unmodified `main` — because a criterion already true on `main` is decoration.
#### 7a. The quality preset — the last value criterion 1 lacks
#### ~~7a. The quality preset — the last value criterion 1 lacks~~ — **CLOSED 2026-09-06 (owner): DLSS / DLSS-G done on every measured title**
*Closed on the Cronos FG-on capture (`20_OPEN_QUESTIONS` §H5 head, `spike-notes` §9): the trio or a counted
`none` on every NVIDIA title through the hooked bodies, DXGI's counter where the hook cannot count (DL:TB —
that title's integration, not SDK 2.8.0's), and the driver-reported identity where no hook can see it, with
its negative measured. The quality preset itself stays `0xFF` / N/A everywhere — the override fields are
the override's, the tags carry no size on D3D12 — and the owner closed the item on that. What follows is
the history.*
*Fails on `main` because:* every real title measured reads `upscalerQuality = 0xFF`.
Cyberpunk 2077 never chains `sl::DLSSOptions`, so 0xFF there is the title's truth; **Alan Wake
@@ -758,13 +782,41 @@ Cyberpunk 2077 never chains `sl::DLSSOptions`, so 0xFF there is the title's trut
Cyberpunk at MFG and on the UE titles at ×4 on the next run, with the new `Streamline tag census:` line saying
which route carried the tags — and DL:TB's census line says whether that title feeds DLSS-G through a route
this build sees. `slDLSSGGetState` was refused (`03_METRICS` §FG: it resets the plugin's own counter).
**START HERE next:** `fl-probe-nvapi --ngx-state <pid>` against a running Lies of P, Hell Is Us, DL:TB
~~**START HERE next:** `fl-probe-nvapi --ngx-state <pid>` against a running Lies of P, Hell Is Us, DL:TB
and Cyberpunk (no capture, no injection) — the super-resolution identity on NGX-direct titles is still the
gap the tags cannot close. If the driver's per-process NGX feedback is
gap the tags cannot close.~~ **RAN 2026-09-06 on Hell Is Us, Expedition 33 and Lies of P (§H5, `spike-notes`
§9): `CREATED | EVALUATE` on the SR word without an override on both no-override titles — the identity
exists in the driver's bookkeeping; the FG word does not see DLSS-G at ×4; `frameGenerationCount` is the
override target, `scalingRatio` is 0 even under an override.** ~~**START HERE next: the owner decides the
driver-reported rung (§H5 says exactly what it may claim: `Dlss (driver-reported …)` on a session where
every hook says N/A, nothing about quality, ratio or FG), and the negative is owed first — the probe on
Lies of P with DLSS switched OFF, expected `CREATED` clear.**~~ **Decided and BUILT 2026-09-06: the capture
host probes the driver beside every module snapshot and the `upscaler:` line has the driver-reported rung
(`03_METRICS` §Upscaling). START HERE next: the owner's run — §H5 rows N1–N4, and N3 (Lies of P with DLSS
OFF) is the one that keeps or withdraws the rung — LANDED 2026-09-06 midday: N3 read `CREATED` clear with
upscaling off, N1 prints `Dlss (driver-reported …)` on four NGX-direct titles, N2 prints agreement on two,
and the FG word turned out to follow DLSS-G too (identity, never the multiplier). START HERE next: Cronos
(a second Streamline 2.8.0 title, UE) with frame generation ON — does the 2.8.0 pacer bypass the patched
bodies there too (`DXGI present counter` ≈ 3) or is it Techland's (0)? — ANSWERED 12:17: Cronos FG on reads
`86.8 → 172.72 (×1.99 FG)` with `unseen=0`; the bypass is Techland's. Item closed; the next item is the
owner's pick from 7b / 7c below.** **The tag route LANDED on the owner's evening run (`spike-notes` §9): `DlssG` on
six of six Streamline titles, and DL:TB's census shows its scaling-input tag arrives with no size, which
closes 7a's last question.** If the driver's per-process NGX feedback is
populated without an NVIDIA-app override, the identity question has a producer that is not a
hook and the owner decides whether `03_METRICS` gains a *driver-reported* rung (§H5 says what
that rung may and may not claim). If it is not populated, the answer stays `N/A` and the
session goes back to the PresentMon leg.
session goes back to the PresentMon leg. **The in-process half of that leg LANDED (2026-09-05,
night): DL:TB at DLSS FG ×4 read 2.90 and 2.95 unseen presents per hooked one on the same chain —
§H5 row P1-DXGI — while Streamline 2.7.3 (Hell Is Us) and 2.10.3 (the Onimusha demo) read 0.00, so
2.8.0's pacer is the one that bypasses the patched bodies. The record now carries `dxgiUnseen` and
the window counts `Displayed = hooked + unseen`, labelled DXGI-COUNTED (`03_METRICS`); DL:TB's next
capture is expected to print the trio at ≈ ×3.9 with that label and no withheld line — LANDED
2026-09-06: `70.52 → 282.08 (×4 FG)`, DXGI-COUNTED 12,387, `DlssG`. Leg 0 the same morning (FG off,
twice) showed the plugin is a startup-time load and the report withheld as pre-committed, so the
gate is now narrowed to sessions where the DXGI counter was not read; a read counter with zero
unseen prints `none` with DXGI's agreement.** The
"sl.common must be loaded on 2.8" lead is closed by the 2.10.3 title, which injects and counts like
2.7 (§H5).
#### 7b. Titles whose upscaler or frame generation is compiled into the executable
@@ -788,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
@@ -801,7 +861,18 @@ hole; it does not close it.
capture with the census line can. **Black Myth: Wukong is the second** — its FSR upscaling
dispatches to neither the loaded monolith nor the loader, and it offers no FSR frame generation.
#### ~~7c. AMD and Intel identity, measured rather than inferred~~ — **AMD LANDED 2026-09-04; Intel closed; the owner's three launches are owed**
#### ~~7c. AMD and Intel identity, measured rather than inferred~~ — **AMD LANDED 2026-09-04 and re-confirmed complete 2026-09-06 on Lies of P; Intel closed by licence (re-checked 2026-09-06, unchanged)**
*2026-09-06, 12:46: Lies of P at FSR 3.1 + FSR FG prints `Fsr3` / `FsrFg` / `59.77 → 119.55 (×2 FG)` /
`2560x1440 -> 2560x1440` with every count agreeing (`spike-notes` §9) — acceptance step 5 in full, beside
the DXGI counter (0 unseen) and the NVIDIA driver's word (nothing created). The owner called the AMD half
done. Intel: the licence was re-fetched the same day — Intel Simplified Software License, October 2022,
binary-only, "nor any modification", termination; the header banner still forbids copying — so the
reversal condition has not fired and the census stays the answer. What is new: Intel's own README says
XeSS-FG runs on non-Intel GPUs with SM 6.4, so an XeFG session IS capturable on this box (DL:TB, Hell Is
Us, Cronos, Expedition 33 ship `libxess_fg.dll`), and the proposal on the table is identity BY ELIMINATION,
labelled — see `20_OPEN_QUESTIONS` §H11's 2026-09-06 note.*
**Do not start here.** The three ffx-api leaves are hooked, the FidelityFX headers are vendored
at tag **`v2.3.0`** (not the `v1.1.4` step 1 below names — its own reversal condition fired:
@@ -947,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,
@@ -1158,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
+198 -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,
@@ -1796,6 +1836,149 @@ one launch per capture, consent granted after launch. Exit codes and full report
(`NvAPI_NGX_GetNGXOverrideState`, by PID) and the probe that measures it before anything is
built on it.
- **2026-09-05 evening, the owner's run on #121 (the tag route) — eight captures, six titles, every one at DLSS**
**with frame generation on**, the first with the `Streamline tag census:` line. The pre-commitment in
`20_OPEN_QUESTIONS` §H5 landed on every title that goes through Streamline:
| Title / setting | `frame generation:` | Trio | Tag census (route: types) |
|---|---|---|---|
| **Hell Is Us**, DLSS + FG ×4 (twice) | **`DlssG`** | `38.5 → 154.04 (×4)`, `81.41 → 325.58 (×4)` | global: depth, mvec, hudless, ui-color-alpha, backbuffer, other |
| **Expedition 33**, DLSS + FG ×2 | **`DlssG`** | `75.95 → 149.83 (×1.97)` | global: same set |
| **Black Myth: Wukong**, DLSS + FG ×4 | **`DlssG`** | `47.99 → 191.89 (×4)` | global: depth, mvec, hudless, ui-color-alpha, backbuffer |
| **Rune Factory**, DLSS + FG ×4 | **`DlssG`** | `128.85 → 513.02 (×3.98)` | global: same as Hell Is Us |
| **Cyberpunk 2077**, DLSS + RR + MFG | **`DlssG`**, `upscaler: Dlss`, `1707x960 -> 2560x1440 = 1.5x (67%)` | **factor refused** — bucket 1 of 8 reads 3.0 against 1.67 overall; `tokens/batch 2.97` | global: depth, mvec, hudless, scaling-in, scaling-out, other (no UI tag) |
| **Dying Light: The Beast**, DLSS FG ×4 | N/A (`none` withheld, §H5) + *"it is FEEDING frame generation"* | `Presented FPS 67.13` | **frame** (`slSetTagForFrame`): depth, mvec, hudless, scaling-in, scaling-out, ui-color-alpha, other |
Three readings. **The identity is measured on six of six Streamline titles** — the UE Streamline plugin tags
the DLSS-G inputs globally (`slSetTag`) on every UE title, Cyberpunk on 2.7.1 tags globally too, DL:TB on 2.8
tags through `slSetTagForFrame` — so `Active (technology not identified)` is gone from every one of them,
and `upscaler: N/A` on the UE titles is now the ONLY NVIDIA gap (NGX-direct super-resolution, the NVAPI
probe's job). **DL:TB's 7a question is answered by the census, at no layout cost**: the title DOES tag
`kBufferTypeScalingInputColor`, through the 2.8 export, and `UpscalerParams` is still 0 of 4030 — so the tag
carries neither an extent nor a Resource size, which is exactly the shape #116 named and could not see; the
`N/A` there is the title's truth. **Cyberpunk's refusal is the guard working**: `tokens/batch 2.97` with
`presents/batch 4.97` and bucket 1 at 3.0 is a session whose state changed after the first eighth — tokens
kept flowing while Ray Reconstruction stopped being evaluated, which is what a menu or a pause does — and the
report refused the session-level number rather than averaging two configurations (the 2026-08-16 alt-tab
lesson). The owner's settings for that run are recorded when known; the earlier 14:01 run at MFG ×3 read
`×2.98` with `tokens/batch 1.00` on the same title.
- **2026-09-05 night, the owner's run on #124 (the DXGI present counter) — DL:TB twice, Hell Is Us, and a
new title, the Onimusha: Way of the Sword demo on Streamline 2.10.3.** `20_OPEN_QUESTIONS` §H5 row
P1-DXGI landed on the first title and both controls read zero:
| Title / Streamline | Trio or Presented | `DXGI present counter:` | `frame generation:` |
|---|---|---|---|
| **Dying Light: The Beast**, 2.8.0, DLSS FG ×4 (21:56) | `Presented FPS 69.99` (withheld) | `unseen=12204 over samples=4136 (2.95)` | N/A (withheld) + *FEEDING* |
| **Dying Light: The Beast**, 2.8.0, DLSS FG ×4 (22:06) | `Presented FPS 73.19` (withheld) | `unseen=12741 over samples=4392 (2.90)` | same |
| **Hell Is Us**, 2.7.3, DLSS + FG ×4 | `79.89 → 308.14 (×3.86)` | `unseen=0 over samples=18207` | `DlssG` |
| **Onimusha: Way of the Sword demo**, **2.10.3**, DLSS + FG | `60.04 → 220.33 (×3.67)` | `unseen=0 over samples=12914` | `DlssG`, `upscaler: Dlss`, RT Yes (27.1 %) |
The 2.8.0 pacer presents on the hooked chain through a body the inline patches do not cover; 2.7.3 and
2.10.3 present through the body they do. The owner's "`sl.interposer.dll` + `sl.common.dll` must be
loaded on ≥ 2.8" lead is closed by the 2.10.3 title: it injects, tags on the frame route (`depth, mvec,
hudless, scaling-in, scaling-out, ui-color-alpha, backbuffer, other`) and counts like 2.7. Onimusha's
`render -> output: N/A` with `UpscalerParams 0/13014` is DL:TB's shape again — the frame-route tags carry
no size on D3D12, where `sl::Resource` declares none. The PR after #124 turns the 2.8.0 reading into a
DXGI-COUNTED Displayed (`03_METRICS` §Displayed may be DXGI-COUNTED).
- **2026-09-06 morning, the owner's run on #125 — DL:TB three times (frame generation on, then off twice)
and Expedition 33 with frame generation off.** The promotion landed and §H5's Leg 0 answered:
| Title / setting | Line | `DXGI present counter:` | `frame generation:` |
|---|---|---|---|
| **Dying Light: The Beast**, DLSS FG ×4 (07:31) | `Native FPS: 70.52 -> Displayed FPS: 282.08 (x4 FG) over 16516 present(s)` + *Displayed is DXGI-COUNTED: 12387* | `unseen=12483 over samples=4202 (2.97)` | **`DlssG`** |
| **Dying Light: The Beast**, DLSS, FG **off** (07:45) | `Presented FPS 75.52` (withheld) | `unseen=0 over samples=4519` | N/A (withheld) — census still `0x25F0F`, tags `0x23600` (no hudless / UI) |
| **Dying Light: The Beast**, DLSS, FG **off** (07:55) | `Presented FPS 61.14` (withheld) | `unseen=0 over samples=3659` | same |
| **Expedition 33**, FG off (Streamline 2.7.30) | `FPS: 85.86` | `unseen=0 over samples=5063` | `none` by count; tag census `0x0` |
Two readings. **The trio is printed on the title that could not print it**, from a count DXGI made
(12,387 presents this hook never timed), and it is the number the owner's own counter showed (~300 at
×4 against ~75 native). **Leg 0: `sl.dlss_g.dll` is a startup-time load** — the census cannot tell FG
off from FG on, exactly the cost the gate pre-committed — but the DXGI counter can (0 unseen with FG
off, 2.9–3.0 with it on), so the gate is narrowed to sessions where the counter was not read, and the
two FG-off captures above print `none` with DXGI's agreement on the next build. Also visible: with FG
off DL:TB sends no hudless / UI tag and the UE plugin sends no tags at all, so the DLSS-G identity is
per-setting on both.
- **2026-09-06, 09:20–09:35, the NVAPI probe against three running titles (`fl-probe-nvapi --ngx-state
<pid>`, driver 616.64), each beside a capture on the #126 build.** The question §H5 opened on 2026-09-05 —
are the driver's per-process NGX feedback bits populated without an NVIDIA-app override? — is answered
YES for super resolution and NO for frame generation:
| Title / override / capture beside it | SR | RR | FG | `scalingRatio` / `performanceMode` / `renderPreset` / `frameGenerationCount` |
|---|---|---|---|---|
| **Hell Is Us**, no override, `83.21 → 332.82 (×4 FG)` `DlssG`, `upscaler: N/A` | `0x80605` CREATED EVALUATE (+ INITIALIZED DLL_EXISTS ERR_NOT_FOUND) | INITIALIZED DLL_EXISTS ERR_NOT_FOUND | `0x5` INITIALIZED DLL_EXISTS only | 0 / 0 / 0 / 0 |
| **Expedition 33**, override ON, FG off, `FPS: 79.4` `none` (DXGI agrees), `upscaler: N/A` | `0x8067F` CREATED EVALUATE ENABLED DLL_LOADED DLL_SELECTED PRESET PERF_MODE (+ …) | INITIALIZED DLL_EXISTS ERR_NOT_FOUND | `0x1F` INITIALIZED ENABLED DLL_EXISTS DLL_LOADED DLL_SELECTED | 0 / 2 / 11 / 0 |
| **Lies of P**, no override, `Presented FPS 59.89`, `upscaler: N/A` | `0x605` CREATED EVALUATE (+ INITIALIZED DLL_EXISTS) | INITIALIZED ERR_FAILED ERR_NOT_FOUND | INITIALIZED ERR_FAILED ERR_NOT_FOUND | 0 / 0 / 0 / 0 |
The SR word carries the identity the hooks cannot see on these three titles; the FG word does not see
DLSS-G running at ×4 (it tracks the override machinery's DLL, not the plugin), `frameGenerationCount` is
the override target and not the multiplier, and `scalingRatio` is 0 even under the override. §H5 carries
what a driver-reported rung may and may not claim, and the negative still owed (DLSS off in the menu).
Also on this run: Expedition 33 with FG off now prints `none` with *DXGI's own present counter agrees:
0 unseen over 4774* (#126), and Lies of P's `Presented FPS` keeps its "MAY include generated frames"
qualifier because `amd_fidelityfx_dx12.dll` is loaded there — the census cannot say `none` and the
token count is 0 on that title, so that line is right as printed.
- **2026-09-06, 10:39–11:36, the owner's run on #128 (the driver-reported rung) — §H5 rows N1–N4 and one
correction.** The standalone probe first: Lies of P with upscaling OFF reads `SR 0x5` (CREATED clear), with
DLSS on `0x605` — N3 keeps the rung. Then the captures:
| Title / setting | `upscaler:` | `NVIDIA driver NGX state:` SR / RR / FG | FG line |
|---|---|---|---|
| **Lies of P**, DLSS (no override) | **`Dlss (driver-reported: …)`** | `0x605` / `0x90001` / `0x90001` | N/A (no FG in this title) |
| **Expedition 33**, override ON, FG off | **`Dlss (driver-reported: …)`** | `0x8067F` (mode 2, preset 11) / `0x80005` / `0x1F` | `none`, DXGI agrees |
| **Hell Is Us**, DLSS + FG ×4 | **`Dlss (driver-reported: …)`** | `0x80605` / `0x80005` / **`0x605`** (CHANGED between readings) | `81.32 → 321.73 (×3.96)`, `DlssG` |
| **Onimusha demo**, SL 2.10.3, DLSS + FG | `Dlss — the NVIDIA driver agrees` | `0x605` / `0x5` / **`0x605`** (CHANGED) | `59.99 → 235.47 (×3.93)`, `DlssG` |
| **Dying Light: The Beast**, DLSS + FG ×4 | `Dlss — the NVIDIA driver agrees` | `0x605` / `0x90001` / **`0x605`** (CHANGED) | `39.63 → 158.5 (×4)` DXGI-COUNTED, `DlssG` |
| **Cronos: The New Dawn demo** (new; UE, **SL 2.8.0**), DLSS, FG off | **`Dlss (driver-reported: …)`** | `0x80605` / `0x80005` / `0x5` | `FPS 105.01`, `none`, DXGI agrees; RT Yes |
| **Dying Light: The Beast**, **FSR upscaling + DLSS FG** | `FSR (3.1 or 4 …)`, `2560x1440 -> 2560x1440` | **`0x205`** (CREATED, not EVALUATE) / `0x90001` / `0x605` | `DlssG` from the tags; factor REFUSED (bucket 8 of 8 at 1.96 vs 2.85); DXGI 1.80 unseen / present |
Three readings. **The rung works as written and its negative held.** **The FG word is not blind** — the
morning's Hell Is Us reading was taken before the feature came up, and every ×4 session's loop readings
show `CREATED | EVALUATE` with the word changing mid-session; the multiplier bits never set, so it is an
identity witness and is now printed beside `frame generation:`. **`SR 0x205` on the FSR session is the
word telling the truth finely**: DLSS was created at some point (the title initialises it) and not
evaluated, and the rung's two-bit key keeps it from claiming DLSS beside FSR. The FSR + DLSS-G session
also exposed a wrong qualifier ("no evaluation was observed" beside 4,415 tokens and a refused factor),
fixed the same day. Cronos is a second Streamline 2.8.0 title; its FG-on capture is the one that says
whether the pacer bypass measured on DL:TB belongs to SDK 2.8.0 or to that title.
- **2026-09-06, 12:17, Cronos: The New Dawn demo with frame generation ON — the row that closed §H5's
DLSS / DLSS-G question.** Streamline 2.8.0, UE: `Native FPS: 86.8 -> Displayed FPS: 172.72 (x1.99 FG)`
over 9,948 presents, `unseen=0 over samples=10063`, tag census `frame=[depth, mvec, hudless,
ui-color-alpha, backbuffer, other]`, `frame generation: DlssG — the NVIDIA driver agrees`, `upscaler: Dlss
(driver-reported)`, RT Yes. The 2.8.0 SDK presents its generated frames through the body the inline
patches cover; the bypass measured on Dying Light: The Beast is that title's integration. With this row
every measured NVIDIA title prints the rule-6 trio or a counted `none`, and the owner closed the item.
- **2026-09-06, 12:46, Lies of P at FSR 3.1 + FSR frame generation, on the #129 build — §H11 row A1 again,
now with every witness on the page.** `upscaler: Fsr3`, `render -> output: 2560x1440 -> 2560x1440 = 1x` on
3,538 records, `frame generation: FsrFg`, `Native FPS: 59.77 -> Displayed FPS: 119.55 (x2 FG)` over 7,042
presents; the ffx census `upscale-drained=3518 fg-dispatch-drained=3518 frames=3520`, `presents/frame=2.00`,
`frames/upscale-drained=1.00`; `DXGI present counter: unseen=0 over samples=7096` (the FSR 3.1 pacer presents
through the patched body); the NVIDIA driver's word `SR 0x5` / `FG 0x90001` — nothing created, so the
driver-reported rung correctly says nothing beside an AMD identity. The census names only
`amd_fidelityfx_dx12.dll` (the 3.1 monolith Lies of P calls) — the AMD half of 7c is complete on its oracle.
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:
@@ -2248,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;
@@ -30,7 +31,9 @@ internal sealed class CaptureLoop(
Func<int, ITargetLiveness?> liveness,
Func<int, (ICaptureSink? Sink, ShmAttachRefusal Refusal)> attach,
CaptureOptions options,
Func<int, RuntimeModuleSet>? modules = null)
Func<int, RuntimeModuleSet>? modules = 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>
@@ -83,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
@@ -108,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 };
}
}
@@ -122,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,
};
@@ -135,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);
@@ -160,13 +234,15 @@ internal sealed class CaptureLoop(
var records = new List<FlFrameRecord>();
var gaps = new List<ulong>();
var focus = new FocusTally();
var loaded = new ModuleTally(modules);
var loaded = new ModuleTally(modules, ngx);
SessionEndReason end = await SuperviseAsync(pid, alive, sink, supervisor, records, gaps, focus, loaded, ct)
.ConfigureAwait(false);
return new CaptureResult
{
RuntimeModules = loaded.Set,
NgxDriver = loaded.Ngx,
TouchQpc = loaded.TouchQpc,
Reason = end,
Verdict = verdict,
AttachRefusal = ShmAttachRefusal.Ok,
@@ -296,17 +372,37 @@ internal sealed class CaptureLoop(
return mayContinue;
}
/// <summary>Accumulates module snapshots; a loop built without a source takes none.</summary>
private sealed class ModuleTally(Func<int, RuntimeModuleSet>? source)
/// <summary>
/// Accumulates module snapshots and the driver's NGX word; a loop built without a source takes none.
/// The NGX probe rides on the same touch as the snapshot: out of process, and the moment a title that
/// enabled DLSS from its menu is caught by the next scan, exactly as a late-loading module is.
/// </summary>
private sealed class ModuleTally(Func<int, RuntimeModuleSet>? source, Func<int, NgxDriverState>? ngxSource)
{
public RuntimeModuleSet Set { get; private set; } = RuntimeModuleSet.Empty;
public NgxDriverState Ngx { get; private set; } = NgxDriverState.NotRun;
/// <summary>
/// When this host touched the target — a guard scan just completed, and the module snapshot
/// is about to run — as QPC ticks (<see cref="System.Diagnostics.Stopwatch.GetTimestamp"/> is
/// QueryPerformanceCounter on Windows, the clock the records carry). Recorded whether or not a
/// snapshot source exists, because it is the stall diagnostic's alibi, not the snapshot's.
/// </summary>
public List<long> TouchQpc { get; } = [];
public void Take(int pid)
{
TouchQpc.Add(System.Diagnostics.Stopwatch.GetTimestamp());
if (source is not null)
{
Set = Set.Merge(source(pid));
}
if (ngxSource is not null)
{
Ngx = Ngx.Merge(ngxSource(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);
}
@@ -52,4 +52,23 @@ internal sealed record CaptureResult
/// had no snapshot source.
/// </summary>
public RuntimeModuleSet RuntimeModules { get; init; } = RuntimeModuleSet.Empty;
/// <summary>
/// The NVIDIA driver's per-process NGX word, probed out of process beside each module snapshot and merged.
/// <see cref="NgxDriverState.NotRun"/> when the loop had no probe.
/// </summary>
public NgxDriverState NgxDriver { get; init; } = NgxDriverState.NotRun;
/// <summary>
/// QPC timestamps of every moment this host touched the target's process — a guard scan
/// completing, followed by the module snapshot — in the records' own clock, so a stall in the
/// 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,66 @@
using System.ComponentModel;
using System.Diagnostics;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>
/// Runs <c>fl-probe-nvapi --ngx-state &lt;pid&gt;</c> beside this host and parses its machine line.
/// </summary>
/// <remarks>
/// <para>
/// <b>Out of process, on purpose.</b> The probe links <c>nvapi64.lib</c> (MIT, vendored) and asks the driver about
/// a pid; nothing is injected, nothing in the target is touched, no consent is involved. Spawning the tool this
/// repo already builds keeps the native layer reachable only through what is already there (CLAUDE.md: no
/// P/Invoke outside <c>Infrastructure</c>) — the day the shipped Agent wants this fact, it goes through
/// <c>Infrastructure</c> as a native call, not through a child process.
/// </para>
/// <para>
/// The probe is staged beside the host by the project file the way the Overlay payload is; a missing binary is
/// an outcome the report prints, never an exception the loop sees.
/// </para>
/// </remarks>
internal static class NgxDriverProbe
{
private const string _probeFileName = "fl-probe-nvapi.exe";
private static readonly TimeSpan _budget = TimeSpan.FromSeconds(5);
public static string ProbePath => Path.Combine(AppContext.BaseDirectory, _probeFileName);
public static NgxDriverState Run(int pid) => Run(pid, ProbePath);
public static NgxDriverState Run(int pid, string probePath)
{
if (!File.Exists(probePath))
{
return NgxDriverState.Of(NgxProbeOutcome.ProbeMissing, probePath);
}
try
{
using var probe = new Process();
probe.StartInfo = new ProcessStartInfo(probePath)
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
};
probe.StartInfo.ArgumentList.Add("--ngx-state");
probe.StartInfo.ArgumentList.Add(pid.ToString(System.Globalization.CultureInfo.InvariantCulture));
probe.Start();
string output = probe.StandardOutput.ReadToEnd();
if (!probe.WaitForExit((int)_budget.TotalMilliseconds))
{
probe.Kill();
return NgxDriverState.Of(NgxProbeOutcome.ProbeFailed, "the probe did not exit within " + _budget.TotalSeconds + " s");
}
return NgxDriverState.Parse(output);
}
catch (Exception e) when (e is Win32Exception or InvalidOperationException or IOException)
{
return NgxDriverState.Of(NgxProbeOutcome.ProbeFailed, e.Message);
}
}
}
@@ -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";
}
}
+105 -11
View File
@@ -61,6 +61,30 @@ internal sealed record FgWindow
/// <summary>Records whose count hit the byte's ceiling.</summary>
public required int Saturated { get; init; }
/// <summary>
/// Σ <c>dxgiUnseen</c> over the records that claim <see cref="FlMeasured.DxgiPresents"/>: presents DXGI
/// counted on the hooked chain that this hook never saw. 0 on every title measured except Dying Light:
/// The Beast on Streamline 2.8.0, where it is ≈ 3 × <see cref="Presents"/> at DLSS FG ×4 (§H5 row P1-DXGI).
/// </summary>
public required long DxgiUnseen { get; init; }
/// <summary>Records claiming <see cref="FlMeasured.DxgiPresents"/> — the byte's own denominator.</summary>
public required int DxgiClaiming { get; init; }
/// <summary>Records whose <c>dxgiUnseen</c> hit 255, the saturation sentinel; any means a refusal.</summary>
public required int DxgiSaturated { get; init; }
/// <summary>
/// The presents the window counts as DISPLAYED: the ones this hook timed plus the ones DXGI counted on the
/// same chain and this hook never saw. Equal to <see cref="Presents"/> on every title where DXGI and the hook
/// agree, and the numerator of <see cref="Factor"/>, <see cref="DisplayedFps"/> and
/// <see cref="PresentsPerBatch"/> — never of a frame-time distribution, which has no timestamps for them.
/// </summary>
public long DisplayedPresents => Presents + DxgiUnseen;
/// <summary>True when Displayed is a count DXGI made rather than this hook — the report must say so.</summary>
public bool DxgiCounted => DxgiUnseen > 0;
/// <summary>How many records carried 0, 1, 2 … evaluations. Index is the value.</summary>
public required IReadOnlyList<int> Histogram { get; init; }
@@ -86,11 +110,11 @@ internal sealed record FgWindow
/// <summary><c>presents / Σ evaluations</c>, or null.</summary>
public double? Factor =>
Refusal is null && Evaluations > 0 ? Presents / (double)Evaluations : null;
Refusal is null && Evaluations > 0 ? DisplayedPresents / (double)Evaluations : null;
/// <summary><c>F_disp</c> over this window's own intervals.</summary>
public double? DisplayedFps =>
Refusal is null && Seconds > 0 && Presents > 1 ? (Presents - 1) / Seconds : null;
Refusal is null && Seconds > 0 && DisplayedPresents > 1 ? (DisplayedPresents - 1) / Seconds : null;
/// <summary><c>F_app</c>, counted rather than derived.</summary>
public double? NativeFps => Refusal is null && Seconds > 0 ? Evaluations / Seconds : null;
@@ -129,7 +153,7 @@ internal sealed record FgWindow
/// <see cref="BatchRefusal"/>; it is never published as <c>fg_factor</c>, and
/// <see cref="Factor"/> stays keyed on counted evaluations.
/// </remarks>
public double? PresentsPerBatch => Batches > 0 ? Presents / (double)Batches : null;
public double? PresentsPerBatch => Batches > 0 ? DisplayedPresents / (double)Batches : null;
/// <summary>
/// Why <see cref="PresentsPerBatch"/> may not be read as one configuration's number, or
@@ -178,6 +202,9 @@ internal sealed record FgWindow
Unidentified = 0,
Streams = 0,
Saturated = 0,
DxgiUnseen = 0,
DxgiClaiming = 0,
DxgiSaturated = 0,
Histogram = [],
BucketFactors = [],
BatchFactors = [],
@@ -205,6 +232,7 @@ internal sealed record FgWindow
int batches = 0;
int unidentified = 0;
int saturated = 0;
(long dxgiUnseen, int dxgiClaiming, int dxgiSaturated) = TallyDxgi(all, start);
for (int i = start; i < all.Count; i++)
{
@@ -242,6 +270,9 @@ internal sealed record FgWindow
Unidentified = unidentified,
Streams = streams.Count,
Saturated = saturated,
DxgiUnseen = dxgiUnseen,
DxgiClaiming = dxgiClaiming,
DxgiSaturated = dxgiSaturated,
Histogram = histogram,
BucketFactors = BucketsOf(all, start, EvaluationWeight),
BatchFactors = BucketsOf(all, start, BatchWeight),
@@ -249,6 +280,34 @@ internal sealed record FgWindow
};
}
/// <summary>
/// Σ <c>dxgiUnseen</c>, the records claiming it, and the ones at the 255 sentinel — the DXGI half of
/// the tally, in its own pass because it is its own measurement (<c>fl_shm.h</c> §dxgiUnseen).
/// </summary>
private static (long Unseen, int Claiming, int Saturated) TallyDxgi(IReadOnlyList<FlFrameRecord> all, int start)
{
long unseen = 0;
int claiming = 0;
int saturated = 0;
for (int i = start; i < all.Count; i++)
{
FlFrameRecord r = all[i];
if (!((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.DxgiPresents))
{
continue;
}
claiming++;
unseen += r.DxgiUnseen;
if (r.DxgiUnseen == byte.MaxValue)
{
saturated++;
}
}
return (unseen, claiming, saturated);
}
/// <summary>
/// Per-bucket <c>presents ÷ weight</c> in time order, or empty when the window is too
/// short. One slicing, two weights.
@@ -276,23 +335,53 @@ internal sealed record FgWindow
int lo = start + (int)((long)n * b / _buckets);
int hi = start + (int)((long)n * (b + 1) / _buckets);
long sigma = 0;
long displayed = 0;
for (int i = lo; i < hi; i++)
{
sigma += weight(all[i]);
displayed += 1 + Unseen(all[i]);
}
factors.Add(sigma > 0 ? (hi - lo) / (double)sigma : double.PositiveInfinity);
// The SAME numerator the window publishes: a DXGI-counted present belongs to the
// bucket of the hooked present that read it, so a session where the 2.8 pacer
// stopped mid-way fails uniformity exactly as one where tokens stopped would.
factors.Add(sigma > 0 ? displayed / (double)sigma : double.PositiveInfinity);
}
return factors;
}
/// <summary><c>dxgiUnseen</c> where the record claims it, else 0 — an unclaimed byte is nobody's count.</summary>
private static long Unseen(FlFrameRecord r) =>
((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.DxgiPresents) ? r.DxgiUnseen : 0L;
/// <summary>The first reason a factor may not be published, or null.</summary>
/// <remarks>
/// Ordered so the most specific cause is named. Every one of these is a number this
/// consumer would otherwise have printed as a measurement.
/// </remarks>
private static string? RefusalFor(FgWindow w)
{
if (RefusalForRecordSet(w) is string aboutTheRecords)
{
return aboutTheRecords;
}
if (w.Evaluations == 0)
{
return "no application-frame token was counted in the window (slGetNewFrameToken, or an ffx-api "
+ "PREPARE / UPSCALE dispatch) — a data gap, "
+ "and treating it as 'no frame generation' is how fg_factor becomes 1.0";
}
return RefusalForRatio(w);
}
/// <summary>
/// Facts about the record SET that refuse a factor before anything is divided: attribution, and the
/// two saturation sentinels.
/// </summary>
private static string? RefusalForRecordSet(FgWindow w)
{
// ATTRIBUTION FIRST, AND THE ORDER IS THE FIX. These two are facts about the record
// set and hold whether or not anything was counted — but they used to sit BELOW the
@@ -319,14 +408,19 @@ internal sealed record FgWindow
+ "saturation sentinel rather than a count — dividing by it would report a floor";
}
if (w.Evaluations == 0)
if (w.DxgiSaturated > 0)
{
return "no application-frame token was counted in the window (slGetNewFrameToken, or an ffx-api "
+ "PREPARE / UPSCALE dispatch) — a data gap, "
+ "and treating it as 'no frame generation' is how fg_factor becomes 1.0";
return $"{w.DxgiSaturated} record(s) hit the dxgiUnseen ceiling of 255, which is a saturation "
+ "sentinel rather than a count — DXGI counted more presents than the byte can carry";
}
string? nonUniform = NonUniform(w.BucketFactors, w.Presents / (double)w.Evaluations, w.Presents,
return null;
}
/// <summary>The refusals that need the ratio itself: uniformity, then the unnameable band.</summary>
private static string? RefusalForRatio(FgWindow w)
{
string? nonUniform = NonUniform(w.BucketFactors, w.DisplayedPresents / (double)w.Evaluations, w.Presents,
"the frame-generation state");
if (nonUniform is not null)
{
@@ -346,7 +440,7 @@ internal sealed record FgWindow
// What is still refused is the band between: a steady 1.05–1.5 is not a configuration
// any vendor ships, and a window that mixed states would usually have failed the
// uniformity check above. Naming it would be guessing.
double factor = w.Presents / (double)w.Evaluations;
double factor = w.DisplayedPresents / (double)w.Evaluations;
return factor > NoneCeiling && factor < ActiveThreshold
? $"presents/tokens = {factor.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)} sits "
+ $"between the `none` ceiling ({NoneCeiling.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)}) "
@@ -405,7 +499,7 @@ internal sealed record FgWindow
+ "so a batch belonging to one stream can be drained by another's present";
}
return NonUniform(w.BatchFactors, w.Presents / (double)w.Batches, w.Presents,
return NonUniform(w.BatchFactors, w.DisplayedPresents / (double)w.Batches, w.Presents,
"the presents-per-batch ratio");
}
@@ -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)";
}
}
@@ -124,13 +124,27 @@ internal sealed record MeasuredFacts
/// <b>And on the interposer's version, read from the file, ≥ 2.8.0.</b> A 2.7 title that loads the
/// plugin keeps <c>none</c> — it is what Cyberpunk would be if it loaded it. A plugin loaded beside
/// an interposer whose version could not be read is withheld with its own reason: an N/A over a
/// <c>none</c> this consumer cannot discriminate. <b>Interim, and its cost is pre-committed:</b> the
/// same title with frame generation OFF reads withheld too if the plugin is a startup-time load;
/// §H5's Leg 0 measures which, and the gate is withdrawn or narrowed on that reading.
/// <c>none</c> this consumer cannot discriminate.
/// </para>
/// <para>
/// <b>Narrowed 2026-09-06, on Leg 0.</b> The plugin IS a startup-time load on Dying Light: The Beast
/// (frame generation off, census unchanged, twice), so the cost paragraph's fear was measured true —
/// and the same morning's ×4 capture measured the discriminator the gate lacked: the 2.8.0 pacer's
/// generated presents are DXGI presents on the hooked chain (§H5 row P1-DXGI, 2.90–2.97 per hooked
/// present, <c>70.52 → 282.08 (×4)</c> counted through <c>dxgiUnseen</c>). So a counted 1.0 beside a
/// READ counter is what it says: DXGI itself counted no present this hook did not. <c>none</c> is
/// withheld on this shape only when the counter was not read at all.
/// </para>
/// </remarks>
public string? NoneWithheld { get; init; }
/// <summary>
/// What DXGI's own present counter said beside a counted <c>none</c>, or null when it was not read. On the
/// Streamline 2.8.0 shape this is the discriminator the gate lacked (Leg 0, 2026-09-06); on every other
/// title it is a second witness printed beside the count.
/// </summary>
public string? NoneBesideDxgi { get; init; }
/// <summary>The Streamline interposer's file version, when a module snapshot saw it.</summary>
public Version? InterposerVersion { get; init; }
@@ -139,6 +153,22 @@ internal sealed record MeasuredFacts
/// </summary>
public uint SlTagCensus { get; init; }
/// <summary>
/// <see cref="FlWriterState.DxgiPresentsUnseen"/>: presents DXGI's own counter recorded on the hooked chain(s)
/// between two consecutive hooked presents, beyond the one the hook saw.
/// </summary>
public uint DxgiPresentsUnseen { get; init; }
/// <summary><see cref="FlWriterState.DxgiPresentSamples"/>: hooked presents on which DXGI's counter was read.</summary>
public uint DxgiPresentSamples { get; init; }
/// <summary>
/// Unseen presents per hooked present, or null before the counter was read. <c>0</c> means DXGI counted nothing this
/// hook did not; <c>≈ N−1</c> beside a withheld count is a frame-generation pacer presenting on the hooked chain
/// through a body the inline patches do not cover — i.e. the generated presents ARE DXGI presents.
/// </summary>
public double? DxgiUnseenPerHookedPresent => DxgiPresentSamples > 0 ? DxgiPresentsUnseen / (double)DxgiPresentSamples : null;
/// <summary>
/// The title tagged a HUD-less or UI buffer through Streamline on some route — the inputs only DLSS Frame
/// Generation consumes (DLSS-G programming guide §5.0). Identity, never a count: the title is FEEDING frame
@@ -160,6 +190,177 @@ internal sealed record MeasuredFacts
/// </remarks>
public bool UpscalerHookRan { get; init; }
/// <summary>The driver's per-process NGX word, merged over the session; <see cref="NgxDriverState.NotRun"/> without a probe.</summary>
public NgxDriverState NgxDriver { get; init; } = NgxDriverState.NotRun;
/// <summary>The string the <c>upscaler:</c> line carries when the identity is the driver's word and not a hook's.</summary>
public const string UpscalerDlssDriverReported =
"Dlss (driver-reported: the NVIDIA driver reports an NGX super-resolution feature created and evaluated in "
+ "this process - not counted by this hook; 03_METRICS §Upscaling, the driver-reported rung)";
/// <summary>
/// <c>03_METRICS</c> §Upscaling, the driver-reported rung (owner decision 2026-09-06): when NO hook named an
/// upscaler and the driver says an NGX super-resolution feature was created and evaluated in this process,
/// the identity is DLSS, attributed to the driver. Null whenever a hook answered, or the driver did not.
/// </summary>
/// <remarks>
/// Identity and nothing else. Measured 2026-09-06 on Hell Is Us, Expedition 33 and Lies of P: the bits are
/// set without an NVIDIA-app override; <c>scalingRatio</c> is 0 even with one; <c>performanceMode</c> and
/// <c>renderPreset</c> are the override's values; the FG word is blind to Streamline DLSS-G. So this may name
/// the vendor and the feature and may not state a quality, a ratio, a render size or a frame-generation mode.
/// The negative is owed: a title with DLSS switched off should read the bit clear, and until it is measured
/// this rung has only ever seen the positive — §H5 pre-commits its withdrawal if the bit stays set.
/// </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 "
+ "process - the identity only; the count above is the record)";
/// <summary>
/// The FG line as printed: the resolved mode, promoted to <see cref="FgDlssGDriverReported"/> only on the one shape
/// 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
{
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
/// rather than resolved, or the bare fact beside a count that read <c>none</c> — or null when it says nothing.
/// </summary>
/// <remarks>
/// Corrected 2026-09-06 midday: the morning's reading called this word blind to Streamline DLSS-G; the captures
/// beside the loop read <c>CREATED | EVALUATE</c> on every ×4 session (Hell Is Us, Onimusha, DL:TB), the word
/// changing between readings as the feature came up. Identity only — the multiplier bits stay clear at ×4.
/// </remarks>
public string? FgDriverNote
{
get
{
if (NgxDriver.Outcome != NgxProbeOutcome.Answered)
{
return null;
}
bool created = NgxDriver.FgCreatedAndEvaluated;
bool dlssg = FgMode is not null && FgMode.StartsWith(nameof(FlFgMode.DlssG), StringComparison.Ordinal);
if (dlssg)
{
return created
? "the NVIDIA driver agrees: an NGX frame-generation feature was created and evaluated in this process"
: "WARNING: the NVIDIA driver reports NO NGX frame-generation feature created in this process while the "
+ "tags named DLSS-G - a disagreement, printed rather than resolved";
}
return created
? "the NVIDIA driver reports an NGX frame-generation feature created and evaluated in this process "
+ "(driver-reported identity; the count above is the record and is not changed by it)"
: null;
}
}
/// <summary>
/// What the driver's word adds beside a hook's identity — agreement, a disagreement printed rather than
/// resolved, or the driver's negative beside an N/A — or null when the driver did not answer.
/// </summary>
public string? UpscalerDriverNote
{
get
{
if (NgxDriver.Outcome != NgxProbeOutcome.Answered)
{
return null;
}
bool created = NgxDriver.SrCreatedAndEvaluated;
if (Upscaler is null)
{
return created
? null
: "the NVIDIA driver reports no NGX super-resolution feature created in this process (driver-reported; "
+ "it says nothing about FSR or XeSS)";
}
if (string.Equals(Upscaler, nameof(FlUpscaler.Dlss), StringComparison.Ordinal))
{
return created
? "the NVIDIA driver agrees: an NGX super-resolution feature was created and evaluated in this process"
: "WARNING: the NVIDIA driver reports NO NGX super-resolution feature created in this process while the "
+ "hook named DLSS - a disagreement, printed rather than resolved";
}
return created
? "the NVIDIA driver also reports an NGX super-resolution feature created and evaluated in this process"
: null;
}
}
/// <summary>Whether a hook capable of naming the frame-generation mode was live.</summary>
public bool FgHookRan { get; init; }
@@ -242,7 +443,8 @@ internal sealed record MeasuredFacts
/// overstates the factor. <see cref="FgWindow"/> owns that decision and its refusals.
/// </remarks>
public static MeasuredFacts From(IReadOnlyList<FlFrameRecord> stream, FlWriterState writer,
long qpcFrequency, long totalGaps, long totalDropped, FgWindow? fg = null, RuntimeModuleSet? modules = null)
long qpcFrequency, long totalGaps, long totalDropped, FgWindow? fg = null, RuntimeModuleSet? modules = null,
NgxDriverState? ngx = null, ExecutableMarkers? markers = null)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(qpcFrequency);
@@ -260,7 +462,7 @@ internal sealed record MeasuredFacts
int violations = stream.Count(r => !IsHonest(r, entitled));
var census = (FlRuntimeCensus)writer.RuntimeCensus;
string? withheld = fg?.IsNone == true ? WithholdNone(census, modules) : null;
string? withheld = fg?.IsNone == true ? WithholdNone(census, modules, writer) : null;
return new MeasuredFacts
{
@@ -270,8 +472,11 @@ internal sealed record MeasuredFacts
Fg = fg,
FgMode = ResolveFgMode(FgModeOf(stream), fg, withheld),
NoneWithheld = withheld,
NoneBesideDxgi = fg?.IsNone == true && withheld is null ? DxgiBesideNone(writer) : null,
InterposerVersion = modules?.VersionOf(_slInterposerFileName),
SlTagCensus = writer.SlTagCensus,
DxgiPresentsUnseen = writer.DxgiPresentsUnseen,
DxgiPresentSamples = writer.DxgiPresentSamples,
UpscalerHookRan = RecordWindow.ClaimedSuffixStart(
stream, static r => ((FlMeasured)r.MeasuredMask).HasFlag(FlMeasured.Upscaler)) < stream.Count,
FgHookRan = RecordWindow.ClaimedSuffixStart(
@@ -280,6 +485,8 @@ 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),
@@ -325,7 +532,7 @@ internal sealed record MeasuredFacts
var allowed = FlMeasured.None;
if (hooks.HasFlag(FlHookFamily.Present))
{
allowed |= FlMeasured.OutputRes | FlMeasured.PresentArgs;
allowed |= FlMeasured.OutputRes | FlMeasured.PresentArgs | FlMeasured.DxgiPresents;
}
if (hooks.HasFlag(FlHookFamily.UpscalerIdentity))
@@ -396,6 +603,13 @@ internal sealed record MeasuredFacts
return false;
}
// dxgiUnseen has no in-band sentinel either — 0 is DXGI agreeing with the hook — so a
// value under a clear bit is the same defect as an unclaimed count.
if (!mask.HasFlag(FlMeasured.DxgiPresents) && r.DxgiUnseen != 0)
{
return false;
}
// fgEvaluations has no in-band sentinel — 0 is a real count — so only the mask bit
// can say whether anyone counted. Added here to keep this in step with the native
// twin in guard_test.cpp, which HANDOFF item 3 will make load-bearing.
@@ -462,26 +676,57 @@ internal sealed record MeasuredFacts
/// The one shape on which a counted 1.0 may not be published as <c>none</c> — see
/// <see cref="NoneWithheld"/> for the measurement and the choice of key.
/// </summary>
private static string? WithholdNone(FlRuntimeCensus census, RuntimeModuleSet? modules)
private static string? WithholdNone(FlRuntimeCensus census, RuntimeModuleSet? modules, FlWriterState writer)
{
if (!census.HasFlag(FlRuntimeCensus.Ran) || !census.HasFlag(FlRuntimeCensus.SlDlssG))
{
return null;
}
// THE DISCRIMINATOR, since Leg 0 (2026-09-06): DXGI's own counter on the hooked chain. The
// 2.8.0 pacer's generated presents ARE DXGI presents there (§H5 row P1-DXGI), so a counter that
// was read and saw nothing unseen is DXGI saying what the count says. A counter that was read
// and DID see presents while the count still sits at 1.0 is a contradiction between two words
// of the same writer — the records should have carried them — and is refused as such.
if (writer.DxgiPresentSamples > 0)
{
return writer.DxgiPresentsUnseen == 0
? null
: $"DXGI's present counter read {writer.DxgiPresentsUnseen} present(s) this hook never saw over "
+ $"{writer.DxgiPresentSamples} hooked present(s) while the records carry none of them — the writer "
+ "state and the records disagree, and neither may be read as `none`";
}
const string notRead = "DXGI's present counter was not read this session, and on Streamline 2.8.0 the DLSS-G "
+ "pacer's generated presents are DXGI presents this hook never sees (20_OPEN_QUESTIONS "
+ "§H5 row P1-DXGI), so a 1.0 cannot be told from generation";
Version? v = modules?.VersionOf(_slInterposerFileName);
if (v is null)
{
return "sl.dlss_g.dll (Streamline's DLSS Frame Generation plugin) is loaded and sl.interposer.dll's file "
+ "version could not be read, so the discriminator 20_OPEN_QUESTIONS §H5 names is missing";
return "sl.dlss_g.dll (Streamline's DLSS Frame Generation plugin) is loaded, sl.interposer.dll's file "
+ "version could not be read, and " + notRead;
}
return v >= StreamlineNoneWithheldFrom
? $"sl.dlss_g.dll (Streamline's DLSS Frame Generation plugin) is loaded on sl.interposer.dll {v}, the shape "
+ "Dying Light: The Beast measured five times with the title's frame generation ON while presents = tokens"
? $"sl.dlss_g.dll (Streamline's DLSS Frame Generation plugin) is loaded on sl.interposer.dll {v}; " + notRead
: null;
}
/// <summary>DXGI's counter as a second witness beside a counted <c>none</c>; null when it was not read.</summary>
private static string? DxgiBesideNone(FlWriterState writer)
{
if (writer.DxgiPresentSamples == 0)
{
return null;
}
string samples = writer.DxgiPresentSamples.ToString(System.Globalization.CultureInfo.InvariantCulture);
return writer.DxgiPresentsUnseen == 0
? $"DXGI's own present counter agrees: 0 unseen over {samples} hooked present(s)"
: $"DXGI's own present counter read {writer.DxgiPresentsUnseen.ToString(System.Globalization.CultureInfo.InvariantCulture)} "
+ $"unseen over {samples} hooked present(s), inside the `none` ceiling";
}
/// <summary>Which frame-generation technology ran, or null. NEVER the string "none".</summary>
/// <remarks>
/// <c>03_METRICS</c>'s ladder ends "otherwise <c>fg_mode = none</c>", and rung 0 — added
@@ -0,0 +1,165 @@
using System.Globalization;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The NVIDIA driver's own per-process NGX bookkeeping — <c>NvAPI_NGX_GetNGXOverrideState</c>, read out of
/// process by <c>fl-probe-nvapi --ngx-state</c> beside each module snapshot — merged over a session.
/// </summary>
/// <remarks>
/// <para>
/// <b>A driver-reported fact, and the report says so wherever it uses one.</b> It is neither a hooked argument
/// (CLAUDE.md rule 4) nor a static hint (<c>05_DETECTION</c>): the driver says a feature was created and
/// evaluated in this process, and this host repeats that with the attribution. What it may stand in for is
/// the super-resolution IDENTITY on a session where no hook saw an evaluation (<c>03_METRICS</c> §Upscaling,
/// the driver-reported rung, owner decision 2026-09-06). What it may not stand in for: a quality, a ratio, a
/// render size, a frame-generation mode or a multiplier — measured 2026-09-06 to be override fields or blind.
/// </para>
/// <para>
/// The last ANSWERED reading is the state; <see cref="Readings"/> counts probe runs, <see cref="Answered"/> the
/// ones the driver answered, and <see cref="Changed"/> whether two answered readings disagreed on a mask — a
/// title switching DLSS on mid-session would show as a change, and the report prints it rather than averaging.
/// </para>
/// </remarks>
internal sealed record NgxDriverState(
NgxProbeOutcome Outcome,
ulong Sr,
ulong Rr,
ulong Fg,
double ScalingRatio,
uint PerformanceMode,
uint RenderPreset,
uint FgCount,
uint FgPreset,
uint FgMode,
uint Driver,
int Readings,
int Answered,
bool Changed,
string? Detail)
{
/// <summary>The loop was built without a probe.</summary>
public static readonly NgxDriverState NotRun = new(NgxProbeOutcome.NotRun, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false, null);
/// <summary>The one reading this host acts on: the driver says an NGX super-resolution feature ran here.</summary>
public bool SrCreatedAndEvaluated =>
Outcome == NgxProbeOutcome.Answered && (Sr & NgxOverrideFlags.CreatedAndEvaluated) == NgxOverrideFlags.CreatedAndEvaluated;
/// <summary>The driver says an NGX frame-generation feature ran here — an IDENTITY witness, never a count.</summary>
public bool FgCreatedAndEvaluated =>
Outcome == NgxProbeOutcome.Answered && (Fg & NgxOverrideFlags.CreatedAndEvaluated) == NgxOverrideFlags.CreatedAndEvaluated;
/// <summary>One outcome with no masks — a probe that did not answer, and why.</summary>
public static NgxDriverState Of(NgxProbeOutcome outcome, string? detail) =>
NotRun with { Outcome = outcome, Readings = 1, Detail = detail };
/// <summary>
/// The machine line the probe prints (<c>NGXSTATE status=… sr=0x… …</c>), or a <see cref="NgxProbeOutcome.ProbeFailed"/>
/// when nothing in <paramref name="output"/> is one. Every other line of the probe's output is for a human.
/// </summary>
public static NgxDriverState Parse(string output)
{
ArgumentNullException.ThrowIfNull(output);
foreach (string raw in output.Split('\n'))
{
string line = raw.Trim();
if (!line.StartsWith("NGXSTATE ", StringComparison.Ordinal))
{
continue;
}
Dictionary<string, string> kv = new(StringComparer.Ordinal);
foreach (string token in line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Skip(1))
{
int eq = token.IndexOf('=', StringComparison.Ordinal);
if (eq > 0)
{
kv[token[..eq]] = token[(eq + 1)..];
}
}
return FromFields(kv, line);
}
return Of(NgxProbeOutcome.ProbeFailed, "the probe printed no NGXSTATE line");
}
private static NgxDriverState FromFields(Dictionary<string, string> kv, string line)
{
string status = kv.GetValueOrDefault("status", "");
if (string.Equals(status, "ANSWERED", StringComparison.Ordinal))
{
try
{
return new NgxDriverState(NgxProbeOutcome.Answered, Hex(kv["sr"]), Hex(kv["rr"]), Hex(kv["fg"]),
double.Parse(kv["ratio"], CultureInfo.InvariantCulture), U(kv["mode"]), U(kv["preset"]),
U(kv["fgcount"]), U(kv["fgpreset"]), U(kv["fgmode"]), U(kv["driver"]), 1, 1, false, null);
}
catch (Exception e) when (e is KeyNotFoundException or FormatException or OverflowException)
{
return Of(NgxProbeOutcome.ProbeFailed, "an NGXSTATE line this host could not read: " + line);
}
}
return status switch
{
"UNANSWERED" => Of(NgxProbeOutcome.Unanswered, "NvAPI " + kv.GetValueOrDefault("nvapi", "?")),
"DEGRADED" => Of(NgxProbeOutcome.Degraded, "NvAPI_Initialize " + kv.GetValueOrDefault("nvapi", "?")),
_ => Of(NgxProbeOutcome.ProbeFailed, "an NGXSTATE status this host does not know: " + status),
};
}
private static ulong Hex(string v) =>
ulong.Parse(v.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? v[2..] : v, NumberStyles.HexNumber,
CultureInfo.InvariantCulture);
private static uint U(string v) => uint.Parse(v, CultureInfo.InvariantCulture);
/// <summary>Fold a later reading in: an answered one becomes the state, any one counts.</summary>
public NgxDriverState Merge(NgxDriverState later)
{
ArgumentNullException.ThrowIfNull(later);
if (Outcome == NgxProbeOutcome.NotRun)
{
return later;
}
int readings = Readings + later.Readings;
int answered = Answered + later.Answered;
if (later.Outcome != NgxProbeOutcome.Answered)
{
// An earlier answer outranks a later silence: the driver's words do not expire, and a
// probe that failed once mid-session says nothing about what it had already read.
return Outcome == NgxProbeOutcome.Answered
? this with { Readings = readings }
: later with { Readings = readings, Answered = answered };
}
bool changed = Changed || (Outcome == NgxProbeOutcome.Answered && (Sr != later.Sr || Rr != later.Rr || Fg != later.Fg));
return later with { Readings = readings, Answered = answered, Changed = changed };
}
/// <summary>The report's line: the three words decoded, the override fields named as such, the caveats measured.</summary>
public string Describe()
{
string head = " NVIDIA driver NGX state (NvAPI_NGX_GetNGXOverrideState, out of process): ";
return Outcome switch
{
NgxProbeOutcome.NotRun => head + "not probed",
NgxProbeOutcome.ProbeMissing => head + "probe not found - " + Detail,
NgxProbeOutcome.ProbeFailed => head + "probe failed - " + Detail,
NgxProbeOutcome.Degraded => head + "no usable NVIDIA driver on this machine (" + Detail + ")",
NgxProbeOutcome.Unanswered => head + $"the driver did not answer for this process over {Readings} probe(s) ({Detail}) - "
+ "not an NVIDIA-rendered process, a driver older than R570, or the API refusing the caller",
_ => head + $"answered {Answered} of {Readings} probe(s){(Changed ? ", and the words CHANGED between readings" : "")}"
+ $"; driver {Driver / 100}.{Driver % 100:00}\n"
+ $" SR 0x{Sr:X} [{NgxOverrideFlags.Describe(Sr)}] RR 0x{Rr:X} [{NgxOverrideFlags.Describe(Rr)}] "
+ $"FG 0x{Fg:X} [{NgxOverrideFlags.Describe(Fg)}]\n"
+ $" override fields: scalingRatio={ScalingRatio.ToString("0.0000", CultureInfo.InvariantCulture)} "
+ $"performanceMode={PerformanceMode} renderPreset={RenderPreset} fgCount={FgCount} fgPreset={FgPreset} fgMode={FgMode} "
+ "- the OVERRIDE's values when an NVIDIA-app override is set, zero otherwise (measured 2026-09-06); "
+ "the SR and FG words name a feature the driver saw created and evaluated - identity, never a count or a multiplier "
+ "(FG_MODE / FG_MULTI_FRAME stay clear and fgCount is 0 at x4)",
};
}
}
@@ -0,0 +1,79 @@
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The bits of <c>NV_NGX_DLSS_OVERRIDE_BITFIELD</c> (vendored <c>nvapi.h</c>, R570+), as the driver reports them per
/// process through <c>NvAPI_NGX_GetNGXOverrideState</c>. Constants rather than a <c>[Flags]</c> enum because the
/// masks are 64-bit words the probe prints raw, and a word is what the parser keeps.
/// </summary>
/// <remarks>
/// <b>Measured 2026-09-06 (driver 616.64, <c>20_OPEN_QUESTIONS</c> §H5):</b> <see cref="Created"/> and
/// <see cref="Evaluate"/> on the super-resolution word are set for a process with NO NVIDIA-app override
/// (Hell Is Us, Lies of P), and CLEAR on Lies of P with upscaling switched off — the negative that keeps the rung.
/// <b>The frame-generation word follows DLSS-G too, once the feature exists</b> — the morning's
/// <see cref="Initialized"/> | <see cref="DllExists"/> on Hell Is Us was read before creation; the captures beside
/// the loop read <see cref="Created"/> | <see cref="Evaluate"/> on Hell Is Us, Onimusha and Dying Light: The Beast at
/// ×4, with the word CHANGING between the session's readings. <see cref="FgMode"/> and <see cref="FgMultiFrame"/>
/// stay clear at ×4 and <c>frameGenerationCount</c> is 0, so the word names the feature and never the multiplier.
/// </remarks>
internal static class NgxOverrideFlags
{
public const ulong Initialized = 1UL << 0;
public const ulong Enabled = 1UL << 1;
public const ulong DllExists = 1UL << 2;
public const ulong DllLoaded = 1UL << 3;
public const ulong DllSelected = 1UL << 4;
public const ulong Preset = 1UL << 5;
public const ulong PerfMode = 1UL << 6;
public const ulong ScalingRatio = 1UL << 7;
public const ulong OptimalSettings = 1UL << 8;
public const ulong Created = 1UL << 9;
public const ulong Evaluate = 1UL << 10;
public const ulong FgMode = 1UL << 13;
public const ulong SrDlaaMode = 1UL << 14;
public const ulong FgMultiFrame = 1UL << 15;
public const ulong ErrFailed = 1UL << 16;
public const ulong ErrDenied = 1UL << 17;
public const ulong ErrDrs = 1UL << 18;
public const ulong ErrNotFound = 1UL << 19;
public const ulong ErrDllLoad = 1UL << 20;
/// <summary>The two bits that together say "this feature ran in this process": created, and evaluated.</summary>
public const ulong CreatedAndEvaluated = Created | Evaluate;
private static readonly (ulong Bit, string Name)[] _names =
[
(Initialized, "INITIALIZED"), (Enabled, "ENABLED"), (DllExists, "DLL_EXISTS"), (DllLoaded, "DLL_LOADED"),
(DllSelected, "DLL_SELECTED"), (Preset, "PRESET"), (PerfMode, "PERF_MODE"), (ScalingRatio, "SCALING_RATIO"),
(OptimalSettings, "OPTIMAL_SETTINGS"), (Created, "CREATED"), (Evaluate, "EVALUATE"), (FgMode, "FG_MODE"),
(SrDlaaMode, "SR_DLAA_MODE"), (FgMultiFrame, "FG_MULTI_FRAME"), (ErrFailed, "ERR_FAILED"),
(ErrDenied, "ERR_DENIED"), (ErrDrs, "ERR_DRS"), (ErrNotFound, "ERR_NOT_FOUND"), (ErrDllLoad, "ERR_DLL_LOAD"),
];
/// <summary>The probe's own spelling of a word's bits, unknown bits printed as hex so nothing is dropped.</summary>
public static string Describe(ulong mask)
{
if (mask == 0)
{
return "-";
}
List<string> parts = [];
ulong seen = 0;
foreach ((ulong bit, string name) in _names)
{
if ((mask & bit) != 0)
{
parts.Add(name);
seen |= bit;
}
}
ulong unknown = mask & ~seen;
if (unknown != 0)
{
parts.Add("0x" + unknown.ToString("X", System.Globalization.CultureInfo.InvariantCulture));
}
return string.Join(' ', parts);
}
}
@@ -0,0 +1,23 @@
namespace FrameLedger.CaptureHost.Consume;
/// <summary>What one run of <c>fl-probe-nvapi --ngx-state</c> came back with.</summary>
internal enum NgxProbeOutcome
{
/// <summary>The loop was built without a probe, or the probe never ran.</summary>
NotRun,
/// <summary>The driver answered for this pid; the masks are the driver's.</summary>
Answered,
/// <summary>NvAPI answered but not for this pid: not NVIDIA-rendered, an old driver, or the API refusing the caller.</summary>
Unanswered,
/// <summary>No usable NVIDIA driver on this machine.</summary>
Degraded,
/// <summary>The probe binary was not beside this host.</summary>
ProbeMissing,
/// <summary>The probe could not be started, timed out, or printed nothing this host understands.</summary>
ProbeFailed,
}
@@ -46,7 +46,17 @@ internal static class SessionReport
sb.Append(" Native FPS: ").Append(Num(w.NativeFps))
.Append(" -> Displayed FPS: ").Append(Num(w.DisplayedFps))
.Append(" (x").Append(Num(w.Factor)).Append(" FG)")
.Append(" over ").Append(Count(w.Presents)).AppendLine(" present(s)");
.Append(" over ").Append(Count(w.DisplayedPresents)).AppendLine(" present(s)");
if (w.DxgiCounted)
{
// A COUNT DXGI MADE, NOT THIS HOOK, and the line says so before anyone reads the
// trio: those presents have no timestamps here, so they may stand in a rate and
// a factor and never in a frame-time distribution (03_METRICS §Counting).
sb.Append(" Displayed is DXGI-COUNTED: ").Append(Count(w.DxgiUnseen))
.Append(" of those present(s) were counted by IDXGISwapChain::GetLastPresentCount on the hooked ")
.Append("chain and never reached this hook (").Append(Count(w.Presents))
.AppendLine(" hooked) — a count DXGI made, not this hook; 20_OPEN_QUESTIONS §H5 row P1-DXGI");
}
}
else if (facts.Fg?.IsNone == true && facts.NoneWithheld is null)
{
@@ -58,13 +68,7 @@ internal static class SessionReport
// 1.00 five times while the title was generating (§H5 case 3), so that shape falls
// through to the Presented line and its qualifier says why. MeasuredFacts owns the
// decision; this branch only honours it.
FgWindow w = facts.Fg;
sb.Append(" FPS: ").Append(Num(w.NativeFps))
.Append(" over ").Append(Count(w.Presents)).AppendLine(" present(s)");
sb.Append(" frame generation: none — ").Append(Count(w.Evaluations))
.Append(" application frame(s) counted (slGetNewFrameToken, or an ffx-api PREPARE / UPSCALE dispatch) against ")
.Append(Count(w.Presents))
.AppendLine(" present(s); every present carried an application frame");
AppendNone(sb, facts.Fg, facts);
}
else
{
@@ -78,6 +82,18 @@ internal static class SessionReport
return sb.ToString().TrimEnd();
}
/// <summary>The bare number and the counted negative, with DXGI's counter beside it when it was read.</summary>
private static void AppendNone(StringBuilder sb, FgWindow w, MeasuredFacts facts)
{
sb.Append(" FPS: ").Append(Num(w.NativeFps))
.Append(" over ").Append(Count(w.Presents)).AppendLine(" present(s)");
sb.Append(" frame generation: none — ").Append(Count(w.Evaluations))
.Append(" application frame(s) counted (slGetNewFrameToken, or an ffx-api PREPARE / UPSCALE dispatch) against ")
.Append(Count(w.Presents))
.Append(" present(s); every present carried an application frame")
.AppendLine(facts.NoneBesideDxgi is string dxgi ? "; " + dxgi : "");
}
/// <summary>
/// PRESENTED FPS, the name for the one number that stands alone (03_METRICS §Core definitions,
/// 2026-09-03). Numerically it is Displayed FPS; the name changes because "Displayed" is half of
@@ -154,6 +170,22 @@ internal static class SessionReport
: "");
}
// A COUNTED SESSION WHOSE FACTOR WAS REFUSED is not "no evaluation was observed". Measured
// 2026-09-06 on DL:TB at FSR + DLSS-G: 4,415 tokens, 8,174 DXGI-counted presents, the tags naming
// DLSS-G, and the factor refused because the last bucket read 1.96 against 2.85 — and this line
// said a runtime was loaded and nothing was seen. The number is every hooked present over a
// session that held more than one configuration, and it is neither Native nor Displayed.
if (facts.Fg is { Refusal: not null, Evaluations: > 0 } counted)
{
return "WARNING: frame generation was counted (" + Count(counted.Evaluations) + " application-frame token(s)"
+ (counted.DxgiCounted
? ", and DXGI counted " + Count(counted.DxgiUnseen) + " present(s) this hook never saw, so the "
+ "Displayed rate is ABOVE this number"
: "")
+ ") and its factor is REFUSED — see `no FG factor` below — so this number is every hooked present "
+ "over a session that did not hold one configuration; read it as neither Native nor Displayed";
}
if (!facts.CensusRan)
{
return "frame generation: NOT measured, and the runtime census did not run — this number is presents, "
@@ -167,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>
@@ -189,18 +241,38 @@ internal static class SessionReport
// can tell that apart from a title driving DLSS through a path we do not hook — Black Myth:
// Wukong loads sl.interposer.dll, runs DLSS-G, and calls it never — so the line names all
// three rather than picking the one that flatters the hook.
sb.Append(" upscaler: ").AppendLine(facts.Upscaler
// A hook's name first; else the driver's word, attributed (03_METRICS §Upscaling, the
// driver-reported rung); else the two N/As. The driver's note rides beside whichever printed.
sb.Append(" upscaler: ").Append(facts.Upscaler
?? facts.UpscalerDriverReported
?? (facts.UpscalerHookRan
? "N/A (an upscaler hook ran — Streamline's slEvaluateFeature and/or an ffx-api leaf's ffxDispatch — "
+ "and no evaluation this build decodes arrived: "
+ "upscaling is off in this title's settings, or it runs through a path this build does not "
+ "hook — measured on 3 of 5 Streamline titles — or a vendor this build does not decode)"
: NoHookRan("upscaler", facts.CensusRan, facts.UpscalerRuntimesLoaded)));
if (facts.UpscalerDriverNote is string driver)
{
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: ").AppendLine(facts.FgMode
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)
{
sb.Append(" — ").Append(fgDriver);
}
sb.AppendLine();
sb.Append(" ray tracing: ").AppendLine(facts.RayTracing.ToString());
sb.Append(" ray reconstruction: ").AppendLine(facts.RayReconstruction.ToString());
sb.Append(" path tracing: ").AppendLine(facts.PathTracing.ToString());
@@ -246,6 +318,7 @@ internal static class SessionReport
// record 0 while this one starts after the lazy-install prefix — and the resulting rate
// moved across 78.6-83 on window choice alone, ten times the residual that draft quoted.
sb.Append(" FG counts: presents=").Append(Count(w.Presents))
.Append(" dxgi-unseen=").Append(Count(w.DxgiUnseen))
.Append(" batches=").Append(Count(w.Batches))
.Append(" tokens=").Append(Count(w.Evaluations))
.Append(" streams=").Append(Count(w.Streams))
@@ -0,0 +1,146 @@
using System.Globalization;
using System.Text;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Consume;
/// <summary>
/// The longest present-to-present intervals in a stream, each placed against the moments this host
/// touched the target — so "the game dropped to 1 FPS for a second" can be read as ours or not ours.
/// </summary>
/// <remarks>
/// <para>
/// <b>Why this exists.</b> The owner saw Cyberpunk 2077 fall to 1 FPS for about a second under capture
/// (2026-09-05) and the report had nothing to say about it: no frame-time statistic is computed by this
/// throwaway (P2's calculators own them), and nothing correlated a gap with what FrameLedger was doing.
/// FrameLedger touches the target at known moments — the guard's 30 s re-scan enumerates its modules,
/// and the module snapshot reads the same list beside it — and the records carry QPC, the same clock
/// <see cref="System.Diagnostics.Stopwatch.GetTimestamp"/> reads. So a stall can be placed: within a
/// touch window it is a suspect; far from every touch it is the title's own (a shader compile, a
/// level stream, a menu).
/// </para>
/// <para>
/// <b>Not a stutter metric.</b> <c>03_METRICS</c> defines stutter against a rolling median with edge
/// rules and a sufficiency floor, and this prints none of that. It prints the few longest raw
/// intervals and where they sit, which is a diagnostic, and it says so.
/// </para>
/// </remarks>
internal sealed record StallReport
{
/// <summary>One long interval: where it starts in the session, how long it is, and the nearest touch.</summary>
internal sealed record Stall(double AtSeconds, double Milliseconds, double? NearestTouchSeconds)
{
/// <summary>A touch inside the interval or within <see cref="TouchWindowSeconds"/> of it is a suspect.</summary>
public bool NearATouch => NearestTouchSeconds is double d && Math.Abs(d) <= TouchWindowSeconds;
}
/// <summary>How far a host touch may be from a stall and still be named beside it.</summary>
public const double TouchWindowSeconds = 1.0;
/// <summary>Intervals at or above this are counted as stalls — ten presents' worth at 100 FPS.</summary>
public const double StallThresholdMs = 100.0;
public required IReadOnlyList<Stall> Longest { get; init; }
public required int OverThreshold { get; init; }
public required int Intervals { get; init; }
public required int Touches { get; init; }
public static StallReport From(IReadOnlyList<FlFrameRecord> stream, long qpcFrequency, IReadOnlyList<long> touchQpc,
int keep = 3)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(touchQpc);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(qpcFrequency);
var stalls = new List<Stall>();
int over = 0;
int intervals = 0;
if (stream.Count > 1)
{
long origin = (long)stream[0].Qpc;
var candidates = new List<(long StartQpc, long DeltaQpc)>();
for (int i = 1; i < stream.Count; i++)
{
long delta = (long)stream[i].Qpc - (long)stream[i - 1].Qpc;
if (delta <= 0)
{
continue; // a torn or reordered record; the drain reports gaps separately
}
intervals++;
if (delta * 1000.0 / qpcFrequency >= StallThresholdMs)
{
over++;
}
candidates.Add(((long)stream[i - 1].Qpc, delta));
}
foreach ((long startQpc, long deltaQpc) in candidates.OrderByDescending(c => c.DeltaQpc).Take(keep))
{
double at = (startQpc - origin) / (double)qpcFrequency;
double ms = deltaQpc * 1000.0 / qpcFrequency;
double? nearest = null;
foreach (long t in touchQpc)
{
// Distance from the touch to the interval [start, start + delta]: 0 when inside.
double d = t < startQpc ? (t - startQpc) / (double)qpcFrequency
: t > startQpc + deltaQpc ? (t - (startQpc + deltaQpc)) / (double)qpcFrequency
: 0.0;
if (nearest is null || Math.Abs(d) < Math.Abs(nearest.Value))
{
nearest = d;
}
}
stalls.Add(new Stall(at, ms, nearest));
}
}
return new StallReport { Longest = stalls, OverThreshold = over, Intervals = intervals, Touches = touchQpc.Count };
}
/// <summary>The report lines. A diagnostic, and it names itself as one.</summary>
public string Describe()
{
if (Intervals == 0)
{
return " stalls: no interval to read (fewer than two presents)";
}
var sb = new StringBuilder();
sb.Append(" stalls (diagnostic, not 03_METRICS' stutter): ").Append(Num(OverThreshold))
.Append(" interval(s) of ").Append(Num(Intervals)).Append(" at or over ")
.Append(Ms(StallThresholdMs)).Append("; host touches (guard scan + module snapshot): ").Append(Num(Touches));
foreach (Stall s in Longest)
{
sb.AppendLine();
sb.Append(" longest: ").Append(Ms(s.Milliseconds)).Append(" at t=").Append(Sec(s.AtSeconds)).Append(" — ");
if (s.NearestTouchSeconds is not double d)
{
sb.Append("no host touch recorded");
}
else if (s.NearATouch)
{
sb.Append("A HOST TOUCH ").Append(d == 0 ? "INSIDE the interval" : (Math.Abs(d).ToString("0.00", CultureInfo.InvariantCulture) + " s "
+ (d < 0 ? "before" : "after") + " it"))
.Append(" — FrameLedger is a SUSPECT for this one; re-run with a longer --seconds and see whether it recurs on the 30 s cadence");
}
else
{
sb.Append("nearest host touch ").Append(Math.Abs(d).ToString("0.0", CultureInfo.InvariantCulture)).Append(" s away — not ours");
}
}
return sb.ToString();
}
private static string Num(long v) => v.ToString(CultureInfo.InvariantCulture);
private static string Ms(double v) => v.ToString("0.#", CultureInfo.InvariantCulture) + " ms";
private static string Sec(double v) => v.ToString("0.00", CultureInfo.InvariantCulture) + " s";
}
@@ -83,4 +83,37 @@
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Overlay.targets" />
<!--
fl-probe-nvapi.exe beside the host, the way the Overlay is: NgxDriverProbe spawns it
by absolute path from AppContext.BaseDirectory and reports ProbeMissing rather than
searching. Warn-not-fail for the same reason the Overlay targets do: build.ps1 runs
the native build first. UNSHIPPED with this host; the Agent would call NVAPI through
Infrastructure, not a child process.
-->
<PropertyGroup>
<FlNativeProbeDir>$(MSBuildThisFileDirectory)..\..\build\native\x64-release\tools\fl-probe-nvapi\</FlNativeProbeDir>
</PropertyGroup>
<ItemGroup>
<None Include="$(FlNativeProbeDir)fl-probe-nvapi.exe" Condition="Exists('$(FlNativeProbeDir)fl-probe-nvapi.exe')">
<Link>fl-probe-nvapi.exe</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</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>
+104 -16
View File
@@ -10,6 +10,7 @@
// flag on a shipped one.
using System.Diagnostics;
using System.Globalization;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Consent;
using FrameLedger.Application.Rules;
@@ -22,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;
@@ -68,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,
};
@@ -130,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}");
}
@@ -155,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
@@ -163,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);
@@ -184,12 +226,15 @@ 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.RuntimeModules, result.NgxDriver, markers);
HostConsole.Line($" guard ticks published: {result.GuardTicksPublished}");
HostConsole.Line($" records: {result.Records.Count} ({dominant.Count} on the dominant stream), " +
$"{segments.Count} segment(s), gaps {result.TotalGaps}, dropped {result.TotalDropped}");
HostConsole.Line(FocusNote(result));
// The longest raw intervals, placed against the moments this host touched the target: the
// owner saw a one-second drop to 1 FPS under capture and nothing here could say whose it was.
HostConsole.Line(StallReport.From(dominant, Stopwatch.Frequency, result.TouchQpc).Describe());
// WHICH HOOKS THE WRITER ACTUALLY INSTALLED, and it is not cosmetic.
//
@@ -202,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)");
@@ -235,18 +280,43 @@ 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)} " +
$"fg=[{CensusNames.Describe(census & FlRuntimeCensusFamilies.Fg)}] " +
$"upscaler=[{CensusNames.Describe(census & FlRuntimeCensusFamilies.Upscaler)}]");
PrintRuntimeModules(result.RuntimeModules);
// 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.
HostConsole.Line($" Streamline tag census: 0x{result.WriterState.SlTagCensus:X} " +
SlTagCensusNames.DescribeRoutes(result.WriterState.SlTagCensus));
// DXGI's own present counter against this hook's, on the hooked chain(s): the in-process
// answer to whether a pacer's generated presents are DXGI presents this hook misses (§H5).
HostConsole.Line(DxgiCounterNote(result.WriterState));
}
/// <summary>DXGI's counter against ours, and what a ratio means; never a count of anything by itself.</summary>
private static string DxgiCounterNote(FlWriterState writer)
{
if (writer.DxgiPresentSamples == 0)
{
return " DXGI present counter: not read (no hooked present sampled it)";
}
double per = writer.DxgiPresentsUnseen / (double)writer.DxgiPresentSamples;
string reading = writer.DxgiPresentsUnseen == 0
? "DXGI counted nothing this hook did not: frame generation was off, or whatever generates frames on this title presents below DXGI or on another object"
: per >= 0.5
? "DXGI counted presents this hook never saw on the SAME chain - a pacer presenting through a body the inline patches do not cover; the generated presents ARE DXGI presents here and Displayed above is DXGI-counted from them"
: "a few presents reached DXGI outside this hook - too few for a pacer, read the number rather than the ratio";
return $" DXGI present counter: unseen={writer.DxgiPresentsUnseen} over samples={writer.DxgiPresentSamples} " +
$"({per.ToString("0.00", CultureInfo.InvariantCulture)} unseen per hooked present) - {reading}";
}
/// <summary>One line per census-named module the target had loaded, version and path beside it.</summary>
@@ -275,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(
@@ -303,7 +374,9 @@ internal static class Program
// already honoured MaxDuration -- nothing could set it.
MaxDuration = seconds > 0 ? TimeSpan.FromSeconds(seconds) : TimeSpan.Zero,
},
pid => RuntimeModuleSnapshot.Take(pid, CensusNames.ModuleFileNames));
pid => RuntimeModuleSnapshot.Take(pid, CensusNames.ModuleFileNames),
NgxDriverProbe.Run,
launcher ?? ((exe, args) => ProcessLauncher.Start(exe, args)));
}
/// <summary>
@@ -356,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.
}
}
}
+58 -5
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>
@@ -453,7 +460,14 @@ public enum FlMeasured : ushort
/// </summary>
FgCounts = 1 << 10,
// Bits 11-15 reserved. Writers leave them zero; readers IGNORE them rather than validating them as
/// <summary>
/// <c>dxgiUnseen</c> (2026-09-05, <c>20_OPEN_QUESTIONS</c> §H5 row P1-DXGI): the present hook read
/// <c>IDXGISwapChain::GetLastPresentCount</c> at this present and at the previous hooked present on the
/// same chain, so the byte is a measurement, a zero included. Clear on a chain's first hooked present.
/// </summary>
DxgiPresents = 1 << 11,
// Bits 12-15 reserved. Writers leave them zero; readers IGNORE them rather than validating them as
// zero. That does NOT make a future field bump-free — recordSize and layoutVersion are compared
// first, so an old reader refuses a new writer outright.
}
@@ -547,8 +561,37 @@ public unsafe struct FlWriterState
/// </summary>
public uint SlTagCensus;
/// <summary>Must be zero; room for additive fields.</summary>
public fixed uint Reserved[4];
/// <summary>
/// Presents DXGI's own counter (<c>IDXGISwapChain::GetLastPresentCount</c>) recorded between two consecutive
/// hooked presents on the same chain, beyond the one the hook saw — presents that reached DXGI through a body
/// the inline patches do not cover. Watchdog-published. Took <c>reserved[0]</c> on 2026-09-05.
/// </summary>
public uint DxgiPresentsUnseen;
/// <summary>Hooked presents on which the DXGI counter was read. Took <c>reserved[1]</c> on 2026-09-05.</summary>
public uint DxgiPresentSamples;
/// <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
@@ -588,7 +631,7 @@ public unsafe struct FlControlBlock
/// <summary>Region 4 — the ring. Exactly 64 bytes, no implicit padding.</summary>
[StructLayout(LayoutKind.Sequential, Size = 64)]
public struct FlFrameRecord
public unsafe struct FlFrameRecord
{
/// <summary>Present entry timestamp.</summary>
public ulong Qpc;
@@ -678,8 +721,18 @@ public struct FlFrameRecord
/// <summary>0 = unavailable.</summary>
public uint ReflexLatencyUs;
/// <summary>
/// Presents DXGI's own counter recorded on this record's chain since the previous hooked present, beyond
/// that one — the per-present form of <see cref="FlWriterState.DxgiPresentsUnseen"/>, under
/// <see cref="FlMeasured.DxgiPresents"/>. Measured 2.90 / 2.95 per hooked present on Dying Light: The
/// Beast (Streamline 2.8.0, DLSS FG ×4) and 0 on Streamline 2.7.3 and 2.10.3 titles, so on that shape
/// the generated presents ARE DXGI presents and the consumer counts <c>Displayed = hooked + this</c>,
/// labelled DXGI-COUNTED. Saturates at 255, which the consumer refuses as a sentinel.
/// </summary>
public byte DxgiUnseen;
/// <summary>Must be zero. Slack, so the next addition does not start from none.</summary>
public uint Reserved;
public fixed byte Reserved[3];
/// <summary>
/// Seqlock counter. Monotonic per slot and NEVER reset, so a full lap of the ring always changes it —
@@ -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)
+332 -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);
}
// ---------------------------------------------------------------------------
@@ -291,12 +179,18 @@ void NoteFault() noexcept {
// ---------------------------------------------------------------------------
constexpr size_t kMaxSwapChains = 16;
// The last GetLastPresentCount value read at a hooked present on this chain, and whether
// one has been read at all (fl_shm.h §dxgiPresentsUnseen). Per chain, because the
// counter is per chain.
struct SwapChainSlot {
void* ptr = nullptr;
uint32_t id = 0;
uint16_t outW = 0;
uint16_t outH = 0;
uint8_t api = FL_API_UNKNOWN;
bool haveDxgiCount = false;
uint32_t lastDxgiCount = 0;
uint32_t dxgiEpoch = 0; // g_dxgiEpoch when lastDxgiCount was read; a mismatch means presents went by unrecorded
};
// Ask the device whether it can ray-trace, once, and publish it as FlRtTier.
@@ -609,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;
@@ -625,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.
@@ -917,6 +826,197 @@ static_assert(offsetof(fsr3host::FfxFsr3DispatchUpscaleDescription, renderSize)
std::atomic<uint32_t> g_slTagTypes{0};
std::atomic<uint32_t> g_slTagCensus{0};
// DXGI's own present counter against ours (fl_shm.h §dxgiPresentsUnseen): hook-local,
// 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
// counting, so the first record after the resume would otherwise claim the whole
// pause as unseen presents -- measured 0x55 on the paused-session integration case.
// Every declined present bumps this epoch; a slot whose last read is from an older
// epoch differences nothing and starts again. DXGI_PRESENT_TEST presents do not bump
// 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;
@@ -1442,6 +1542,18 @@ void PublishRuntimeCensus() noexcept {
// The tag census, on the same tick and by the same rule: OR-only, from the
// process-local word the three tag routes accumulate into, so region 2 takes one
// write a second rather than one per tag list (fl_shm.h §slTagCensus).
// DXGI's counter against ours, published on the same tick. Monotonic, so a plain store
// of the hook-local value is the whole publish.
void PublishDxgiPresentCounters() noexcept {
if (g_state == nullptr) {
return;
}
std::atomic_ref<uint32_t> unseen{g_state->dxgiPresentsUnseen};
std::atomic_ref<uint32_t> samples{g_state->dxgiPresentSamples};
unseen.store(g_dxgiUnseen.load(std::memory_order_relaxed), std::memory_order_relaxed);
samples.store(g_dxgiSamples.load(std::memory_order_relaxed), std::memory_order_relaxed);
}
void PublishSlTagCensus() noexcept {
if (g_state == nullptr) {
return;
@@ -1813,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
@@ -1828,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
@@ -1856,6 +1988,8 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
// appeared this second is both hooked and counted in the same pass.
PublishRuntimeCensus();
PublishSlTagCensus();
PublishDxgiPresentCounters();
PublishLoaderWords();
// Supervision loss. guardTicks counts COMPLETED guard evaluations, not
// seconds, so a stalled guard loop stops it advancing even while the
@@ -1886,6 +2020,9 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
// lock, no logging (NFR-1, target <= 1 us; a bare vtable detour measured 8.4 ns).
void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
if (!MayObserve()) {
if ((flags & DXGI_PRESENT_TEST) == 0u) {
g_dxgiEpoch.fetch_add(1u, std::memory_order_relaxed); // see the declaration
}
return;
}
@@ -1920,6 +2057,41 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
SwapChainSlot* slot = FindOrAdd(sc);
PublishAdapterOnce(sc);
// DXGI'S OWN COUNT OF THIS CHAIN'S PRESENTS, read here on the object the title passed
// (the same class of read as GetDesc above), BEFORE this present is forwarded: the
// value is therefore the number of presents completed before this one, and the
// delta from the previous hooked present on the same chain is 1 + whatever DXGI
// counted that this hook never saw -- a pacer presenting through a body the inline
// patches do not cover. A delta of exactly 1 every time says DXGI saw nothing more
// than we did. DXGI_PRESENT_TEST presents are already filtered above and do not
// move this counter (measured, #35), so they cannot read as unseen presents.
bool dxgiDelta = false;
uint8_t dxgiUnseenHere = 0;
if (slot != nullptr) {
UINT dxgiCount = 0;
const uint32_t epoch = g_dxgiEpoch.load(std::memory_order_relaxed);
if (SUCCEEDED(sc->GetLastPresentCount(&dxgiCount))) {
if (slot->haveDxgiCount && slot->dxgiEpoch == epoch) {
const uint32_t delta = dxgiCount - slot->lastDxgiCount;
dxgiDelta = true;
if (delta > 1u) {
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;
slot->haveDxgiCount = true;
g_dxgiSamples.fetch_add(1u, std::memory_order_relaxed);
}
}
FlFrameRecord rec{};
rec.qpc = static_cast<uint64_t>(qpc.QuadPart);
rec.frameIndex = g_frameIndex++;
@@ -1961,6 +2133,14 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
const uint16_t haveOutputRes = (rec.outputW != 0 && rec.outputH != 0) ? FL_MEASURED_OUTPUT_RES : 0u;
rec.measuredMask = static_cast<uint16_t>(haveOutputRes | FL_MEASURED_PRESENT_ARGS);
// The per-present form of the DXGI counter read above (fl_shm.h §dxgiUnseen). The
// bit says a delta EXISTED -- a zero under it is DXGI agreeing with this hook, not
// silence -- which is why the first present of a chain claims nothing.
if (dxgiDelta) {
rec.dxgiUnseen = dxgiUnseenHere;
rec.measuredMask = static_cast<uint16_t>(rec.measuredMask | FL_MEASURED_DXGI_PRESENTS);
}
// --- Upscaler identity, and the three states it must keep apart ----------
//
// The counter is CONSUMED here, once per present, so the record describes
@@ -2460,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
@@ -2479,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
+79 -7
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
@@ -568,13 +574,20 @@ enum FlMeasured : uint16_t {
// must be able to say so.
FL_MEASURED_FG_COUNTS = 1u << 10,
// bits 11-15 reserved. Writers leave them zero; readers must IGNORE them
// dxgiUnseen @52 (2026-09-05, 20_OPEN_QUESTIONS §H5 row P1-DXGI): the present hook
// read IDXGISwapChain::GetLastPresentCount at this present AND at the previous
// hooked present on the same chain, so the byte is a measurement -- a zero
// included. Clear on the first hooked present of every chain, where there is no
// previous value to difference against, and whenever the read failed.
FL_MEASURED_DXGI_PRESENTS = 1u << 11,
// bits 12-15 reserved. Writers leave them zero; readers must IGNORE them
// rather than validate them as zero.
//
// BE PRECISE ABOUT WHAT THAT BUYS, because the tempting claim is false: it
// does NOT mean a future field can be added without a layout bump. Any new
// field also needs a byte, and every byte of this record is allocated except
// `reserved` @52 -- and FlShmHandshake::recordSize plus the layout version are
// `reserved` @53..55 -- and FlShmHandshake::recordSize plus the layout version are
// compared before a reader looks at anything, so an old reader refuses a new
// writer outright and never gets as far as an unknown bit. What the reserve
// actually buys is that existing offsets do not move, which keeps the diff,
@@ -687,7 +700,47 @@ struct alignas(64) FlWriterState {
// no layout bump, refused-before-read by the build-id handshake.
uint32_t slTagCensus; // @44
uint32_t reserved[4]; // @48..63 must be zero; room for additive fields
// DXGI'S OWN PRESENT COUNTER AGAINST THIS HOOK'S, on the hooked swapchain(s)
// (2026-09-05, 20_OPEN_QUESTIONS §H5 case 3). On every present the hook sees it
// reads IDXGISwapChain::GetLastPresentCount on the object the title passed -- the
// same class of read as GetDesc in FindOrAdd -- and compares it with the value at
// the previous hooked present on the same chain. Exactly one present (the previous
// hooked one) is expected in between; every present beyond that is one DXGI
// counted and this hook did not. A frame-generation pacer that presents on this
// chain through a body the inline patches do not cover shows up here; one that
// presents below DXGI, or on another object, does not. Hook-local counters,
// watchdog-published (the region-2 cache-line rule above). Took reserved[0..1],
// additive, no layout bump.
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
// 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
@@ -818,7 +871,22 @@ struct alignas(64) FlFrameRecord {
// and layoutVersion are compared before a reader looks at anything, so an old
// reader refuses a new writer and never reaches an unknown field. What it buys
// is that existing offsets do not move, which keeps the next diff small.
uint32_t reserved; // @52
// @52 -- DXGI'S OWN COUNT OF THIS CHAIN'S PRESENTS SINCE THE PREVIOUS HOOKED ONE,
// beyond that one (2026-09-05, 20_OPEN_QUESTIONS §H5 row P1-DXGI). The per-present
// form of FlWriterState.dxgiPresentsUnseen: the delta of GetLastPresentCount between
// two consecutive hooked presents on the same chain, minus the one present the hook
// saw. Measured 2.90 and 2.95 per hooked present on Dying Light: The Beast
// (Streamline 2.8.0, DLSS Frame Generation x4) and 0 on every other title (Streamline
// 2.7.3 and 2.10.3 present their generated frames through the patched bodies) -- so
// on that shape the generated presents ARE DXGI presents, reaching a body the inline
// patches do not cover, and the consumer counts Displayed = hooked + this, labelled
// DXGI-COUNTED. Per record rather than per session so the consumer's uniformity
// buckets see it. SATURATES AT 255: a NUMERATOR, so a wrap would read low rather than
// high, but 255 is still a sentinel the consumer refuses rather than a count. Took the
// first byte of v3's reserved word; additive, no offset moved, no layout bump.
uint8_t dxgiUnseen; // @52
uint8_t reserved[3]; // @53..55 MUST BE ZERO
// Seqlock counter. Monotonic per slot and NEVER reset, so a full lap of
// the ring always changes it — otherwise a reader stalled exactly one lap
@@ -878,7 +946,11 @@ static_assert(offsetof(FlWriterState, rtStateObjectsCreated) == 32);
static_assert(offsetof(FlWriterState, rasterPsoCreated) == 36);
static_assert(offsetof(FlWriterState, runtimeCensus) == 40);
static_assert(offsetof(FlWriterState, slTagCensus) == 44);
static_assert(offsetof(FlWriterState, reserved) == 48);
static_assert(offsetof(FlWriterState, dxgiPresentsUnseen) == 48);
static_assert(offsetof(FlWriterState, dxgiPresentSamples) == 52);
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);
@@ -908,7 +980,8 @@ static_assert(offsetof(FlFrameRecord, upscalerSharpness) == 42);
static_assert(offsetof(FlFrameRecord, fgEvaluations) == 43);
static_assert(offsetof(FlFrameRecord, vramUsedMb) == 44);
static_assert(offsetof(FlFrameRecord, reflexLatencyUs) == 48);
static_assert(offsetof(FlFrameRecord, reserved) == 52);
static_assert(offsetof(FlFrameRecord, dxgiUnseen) == 52);
static_assert(offsetof(FlFrameRecord, reserved) == 53);
static_assert(offsetof(FlFrameRecord, seq) == 56);
static_assert(offsetof(FlFrameRecord, swapchainId) == 60);
@@ -924,7 +997,6 @@ static_assert(offsetof(FlFrameRecord, swapchainId) == 60, "07_IPC pins the paylo
static_assert(offsetof(FlFrameRecord, qpc) % 8 == 0);
static_assert(offsetof(FlFrameRecord, measuredMask) % 2 == 0);
static_assert(offsetof(FlFrameRecord, vramUsedMb) % 4 == 0);
static_assert(offsetof(FlFrameRecord, reserved) % 4 == 0);
static_assert(offsetof(FlFrameRecord, seq) % 4 == 0);
// The regions must not overlap, and the ring must stay 64-aligned.
@@ -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
+699 -7
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 {
@@ -1179,7 +1373,8 @@ bool StartHarness(Child& child) {
uint16_t EntitledBy(uint32_t hooks) noexcept {
uint16_t allowed = 0;
if ((hooks & fl::FL_HOOK_PRESENT) != 0u) {
allowed |= static_cast<uint16_t>(fl::FL_MEASURED_OUTPUT_RES | fl::FL_MEASURED_PRESENT_ARGS);
allowed |= static_cast<uint16_t>(fl::FL_MEASURED_OUTPUT_RES | fl::FL_MEASURED_PRESENT_ARGS |
fl::FL_MEASURED_DXGI_PRESENTS);
}
if ((hooks & fl::FL_HOOK_UPSCALER_IDENTITY) != 0u) {
allowed |= static_cast<uint16_t>(fl::FL_MEASURED_UPSCALER | fl::FL_MEASURED_FG);
@@ -1225,6 +1420,11 @@ bool IsHonest(const fl::FlFrameRecord& r, uint16_t entitled) noexcept {
if ((r.measuredMask & fl::FL_MEASURED_FG_COUNTS) == 0u && r.fgEvaluations != 0u) {
return false;
}
// dxgiUnseen has no in-band sentinel either -- 0 is DXGI agreeing with the hook -- so
// a value under a clear bit is the same defect as an unclaimed count.
if ((r.measuredMask & fl::FL_MEASURED_DXGI_PRESENTS) == 0u && r.dxgiUnseen != 0u) {
return false;
}
// featureFlags carries Ray Reconstruction's fact and OBSERVED bits, produced by the
// same Streamline detour as the upscaler identity. A writer not entitled to claim
// an upscaler is not entitled to say anything about RR either.
@@ -1268,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
@@ -1534,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
@@ -3175,8 +3838,12 @@ namespace {
// What one --hold-presenting-fg run yields, drained after the identity hook is live.
struct FgObservation {
std::uint32_t census = 0;
std::uint32_t dxgiUnseen = 0;
std::uint32_t dxgiSamples = 0;
std::size_t drained = 0;
std::uint64_t sigma = 0; // sum of fgEvaluations over the window
std::uint64_t sigma = 0; // sum of fgEvaluations over the window
std::uint64_t dxgiRecUnseen = 0; // sum of dxgiUnseen over records claiming it
std::size_t dxgiRecClaiming = 0; // records carrying FL_MEASURED_DXGI_PRESENTS
std::uint32_t hooks = 0;
std::uint32_t faults = 0;
bool everyRecordClaimsCounts = true;
@@ -3256,6 +3923,10 @@ bool ObserveFg(int presentsPerEval, FgObservation& out) {
out.drained = all.size();
for (const auto& r : all) {
out.sigma += r.fgEvaluations;
if ((r.measuredMask & fl::FL_MEASURED_DXGI_PRESENTS) != 0u) {
++out.dxgiRecClaiming;
out.dxgiRecUnseen += r.dxgiUnseen;
}
if ((r.measuredMask & fl::FL_MEASURED_FG_COUNTS) == 0u) {
out.everyRecordClaimsCounts = false;
}
@@ -3278,6 +3949,13 @@ bool ObserveFg(int presentsPerEval, FgObservation& out) {
}
}
out.hooks = st->hooksInstalledMask;
// DXGI's counter against ours: published by the watchdog on its 1 Hz tick, so poll for
// the samples to reach the window rather than reading the words once (HANDOFF §Traps).
for (int i = 0; i < 80 && st->dxgiPresentSamples < out.drained; ++i) {
Sleep(50);
}
out.dxgiUnseen = st->dxgiPresentsUnseen;
out.dxgiSamples = st->dxgiPresentSamples;
out.census = st->runtimeCensus;
out.faults = st->faultCount;
@@ -3354,6 +4032,20 @@ TEST_CASE("application-frame tokens are COUNTED, and the count tracks the fixtur
// is in this process. The second check is the one that matters: it is what
// keeps a title with Streamline loaded and no evaluation observed from being
// printed as "no frame-generation runtime was loaded".
// DXGI'S COUNTER AGAINST OURS, the negative control: this fixture presents only through
// the body the inline patch covers, so DXGI must count exactly the presents the hook
// saw -- zero unseen -- and the counter must have been read on every hooked present.
// A real title where DXGI counts MORE is the §H5 question this word exists to answer.
CAPTURE(obs.dxgiUnseen);
CAPTURE(obs.dxgiSamples);
CHECK(obs.dxgiUnseen == 0u);
CHECK(obs.dxgiSamples >= static_cast<std::uint32_t>(obs.drained));
// And per record, in the form the consumer's buckets read: every drained record
// claims the bit (the chain's first present, which cannot, is in the discarded
// backlog) and carries a zero byte.
CAPTURE(obs.dxgiRecClaiming);
CHECK(obs.dxgiRecUnseen == 0u);
CHECK(obs.dxgiRecClaiming == obs.drained);
CHECK((obs.census & fl::FL_CENSUS_RAN) != 0u);
CHECK((obs.census & fl::FL_CENSUS_SL_INTERPOSER) != 0u);
CHECK((obs.census & fl::FL_CENSUS_FG_FAMILIES) == 0u);
+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);
}
+7 -2
View File
@@ -64,7 +64,11 @@ int main() {
Field("rasterPsoCreated", offsetof(FlWriterState, rasterPsoCreated), sizeof(uint32_t));
Field("runtimeCensus", offsetof(FlWriterState, runtimeCensus), sizeof(uint32_t));
Field("slTagCensus", offsetof(FlWriterState, slTagCensus), sizeof(uint32_t));
Field("reserved", offsetof(FlWriterState, reserved), sizeof(uint32_t) * 4, true);
Field("dxgiPresentsUnseen", offsetof(FlWriterState, dxgiPresentsUnseen), sizeof(uint32_t));
Field("dxgiPresentSamples", offsetof(FlWriterState, dxgiPresentSamples), sizeof(uint32_t));
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));
@@ -99,7 +103,8 @@ int main() {
Field("fgEvaluations", offsetof(FlFrameRecord, fgEvaluations), sizeof(uint8_t));
Field("vramUsedMb", offsetof(FlFrameRecord, vramUsedMb), sizeof(uint32_t));
Field("reflexLatencyUs", offsetof(FlFrameRecord, reflexLatencyUs), sizeof(uint32_t));
Field("reserved", offsetof(FlFrameRecord, reserved), sizeof(uint32_t));
Field("dxgiUnseen", offsetof(FlFrameRecord, dxgiUnseen), sizeof(uint8_t));
Field("reserved", offsetof(FlFrameRecord, reserved), sizeof(uint8_t) * 3);
Field("seq", offsetof(FlFrameRecord, seq), sizeof(uint32_t));
Field("swapchainId", offsetof(FlFrameRecord, swapchainId), sizeof(uint32_t), true);
std::printf(" ] }\n");
+12
View File
@@ -124,6 +124,7 @@ int NgxState(unsigned long pid) {
NvAPI_GetErrorMessage(init, desc);
std::printf(" NvAPI_Initialize -> %d (%s)\n BRANCH: DEGRADED — no usable NVIDIA driver on this machine.\n",
static_cast<int>(init), desc);
std::printf("NGXSTATE status=DEGRADED nvapi=%d\n", static_cast<int>(init));
return 2;
}
NvU32 driverVersion = 0;
@@ -143,6 +144,7 @@ int NgxState(unsigned long pid) {
std::printf(" BRANCH: UNANSWERED — the driver did not answer for pid %lu (not an NVIDIA-rendered process, a "
"driver older than R570, or the API refusing this caller).\n",
pid);
std::printf("NGXSTATE status=UNANSWERED nvapi=%d\n", static_cast<int>(status));
NvAPI_Unload();
return 3;
}
@@ -160,6 +162,16 @@ int NgxState(unsigned long pid) {
std::printf(" frameGenerationPreset %u\n", params.frameGenerationPreset);
std::printf(" frameGenerationMode %u\n", params.frameGenerationMode);
std::printf(" reserved %u %u\n", params.reserved[0], params.reserved[1]);
// THE MACHINE LINE. FrameLedger.CaptureHost spawns this probe beside each module snapshot
// (NgxDriverProbe) and reads exactly this line; everything above is for a human. One line,
// key=value, hex masks, so a parser cannot mistake a decoded name for a field.
std::printf(
"NGXSTATE status=ANSWERED sr=0x%016llX rr=0x%016llX fg=0x%016llX ratio=%.4f mode=%u preset=%u fgcount=%u "
"fgpreset=%u fgmode=%u driver=%u\n",
static_cast<unsigned long long>(params.feedbackMaskSR), static_cast<unsigned long long>(params.feedbackMaskRR),
static_cast<unsigned long long>(params.feedbackMaskFG), static_cast<double>(params.scalingRatio),
params.performanceMode, params.renderPreset, params.frameGenerationCount, params.frameGenerationPreset,
params.frameGenerationMode, driverVersion);
NvAPI_Unload();
return 0;
}
+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)
+131 -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) {
@@ -2715,6 +2752,30 @@ bool ProbeFrameIdentity(Gfx& g) {
Check(realIsAFrame, "a real present submits exactly one frame");
std::printf(" %d real present(s) moved the counter by %u\n", kReal, afterReal - afterTest);
// The cost of asking. The Overlay reads this counter on every hooked present
// (dllmain RecordPresent, the DXGI-counted diagnostic 20_OPEN_QUESTIONS §H5
// A1.7), so the price of one call is part of the present hook's overhead
// statement. A measurement, not a check: a threshold here fails on a shared
// runner for reasons unrelated to the code (see --probe-cost).
{
constexpr int kCalls = 20000;
LARGE_INTEGER f{};
LARGE_INTEGER t0{};
LARGE_INTEGER t1{};
QueryPerformanceFrequency(&f);
UINT sink = 0;
QueryPerformanceCounter(&t0);
for (int i = 0; i < kCalls; ++i) {
g.swapChain1->GetLastPresentCount(&sink);
}
QueryPerformanceCounter(&t1);
const double ns =
static_cast<double>(t1.QuadPart - t0.QuadPart) * 1e9 / static_cast<double>(f.QuadPart) / kCalls;
std::printf(" GetLastPresentCount costs %.1f ns/call (%d calls, WARP; the Overlay pays this once per hooked "
"present)\n",
ns, kCalls);
}
// The two together are the contract. Separately, each passes against a
// wrong writer: a writer that ignores everything satisfies the first, and
// one that counts everything satisfies the second.
@@ -2723,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;
}
@@ -2741,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
@@ -2775,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) {
@@ -2806,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;
@@ -2971,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());
}
@@ -277,6 +284,56 @@ public sealed class CaptureLoopTests : IDisposable
CaptureResult r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.RuntimeModules.Should().BeSameAs(RuntimeModuleSet.Empty);
r.NgxDriver.Should().BeSameAs(NgxDriverState.NotRun, "no probe was given to the loop");
}
[Fact]
public async Task TheDriverProbeRidesOnTheSameTouchAsTheModuleSnapshotAndIsMergedOntoTheResult()
{
// The probe is out of process and answers per pid; it rides the scan's cadence exactly as the
// module snapshot does, and a later answer that differs is reported as a CHANGE, not averaged.
var guard = new CountingGuard();
using var sink = new FakeSink();
int probes = 0;
var loop = new CaptureLoop(
await StoreWithAsync(), new HookedCaptureGate(guard), guard, new FixedResolver(_pid, SessionEndReason.Running),
_ => new FakeLiveness(),
_ => (sink, ShmAttachRefusal.Ok),
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromMilliseconds(50),
MaxDuration = TimeSpan.FromMilliseconds(120),
},
modules: null,
ngx: pid =>
{
pid.Should().Be(_pid);
probes++;
sink.Events.Add("ngx");
// The first reading has DLSS not yet created; every later one has it created and evaluated.
ulong sr = probes == 1 ? NgxOverrideFlags.Initialized | NgxOverrideFlags.DllExists
: NgxOverrideFlags.Initialized | NgxOverrideFlags.DllExists | NgxOverrideFlags.CreatedAndEvaluated;
return NgxDriverState.Parse($"NGXSTATE status=ANSWERED sr=0x{sr:X16} rr=0x1 fg=0x5 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664");
});
CaptureResult r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
probes.Should().Be(sink.Published.Count + 1, "one per scan, plus the one before the last drain");
r.NgxDriver.Outcome.Should().Be(NgxProbeOutcome.Answered);
r.NgxDriver.Readings.Should().Be(probes);
r.NgxDriver.Answered.Should().Be(probes);
r.NgxDriver.SrCreatedAndEvaluated.Should().BeTrue("the last answered reading is the state");
r.NgxDriver.Changed.Should().BeTrue("the first reading differed from the later ones");
r.NgxDriver.Driver.Should().Be(61664u);
for (int i = 0; i < sink.Events.Count; i++)
{
if (string.Equals(sink.Events[i], "publish", StringComparison.Ordinal))
{
sink.Events[i + 1].Should().Be("ngx", "the probe follows the publish directly, on the snapshot's touch");
}
}
}
[Fact]
@@ -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");
}
}
@@ -0,0 +1,36 @@
using FluentAssertions;
using FrameLedger.CaptureHost.Capture;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Tests.Capture;
/// <summary>
/// The out-of-process probe as the loop calls it: every way it can fail is an outcome on the result, never a throw.
/// </summary>
public sealed class NgxDriverProbeTests
{
[Fact]
public void AMissingProbeIsAnOutcomeThatNamesThePath()
{
NgxDriverState s = NgxDriverProbe.Run(Environment.ProcessId, @"C:\nowhere\fl-probe-nvapi.exe");
s.Outcome.Should().Be(NgxProbeOutcome.ProbeMissing);
s.Detail.Should().Contain("fl-probe-nvapi.exe");
s.SrCreatedAndEvaluated.Should().BeFalse();
}
[Fact]
public void RunAgainstThisTestProcessNeverThrowsAndNeverClaimsAFeature()
{
// The real binary is staged beside the host by the project file when the native build ran
// first (CI does; a fresh clone may not). Whichever it is, this process renders nothing
// through NGX, so the only honest outcomes are the ones that say so.
NgxDriverState s = NgxDriverProbe.Run(Environment.ProcessId);
s.Outcome.Should().BeOneOf(NgxProbeOutcome.Unanswered, NgxProbeOutcome.Degraded, NgxProbeOutcome.ProbeMissing,
NgxProbeOutcome.ProbeFailed);
s.SrCreatedAndEvaluated.Should().BeFalse();
s.Readings.Should().Be(1);
s.Describe().Should().StartWith(" NVIDIA driver NGX state");
}
}
@@ -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]
@@ -0,0 +1,138 @@
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Consume;
/// <summary>
/// The driver's FG word beside the <c>frame generation:</c> line (corrected 2026-09-06: it follows DLSS-G once the
/// feature exists), and the qualifier a counted-but-refused session prints.
/// </summary>
public sealed class DriverReportedFrameGenerationTests
{
private const FlHookFamily _hooks =
FlHookFamily.Present | FlHookFamily.UpscalerIdentity | FlHookFamily.UpscalerParams | FlHookFamily.FgEvaluations;
private static readonly NgxDriverState _fgCreated = NgxDriverState.Parse(
"NGXSTATE status=ANSWERED sr=0x605 rr=0x5 fg=0x605 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664");
private static readonly NgxDriverState _fgNotCreated = NgxDriverState.Parse(
"NGXSTATE status=ANSWERED sr=0x605 rr=0x5 fg=0x5 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664");
/// <summary>k hooked presents per application frame; the token on the first; DLSS-G marked on it when tagged.</summary>
private static List<FlFrameRecord> Stream(int appFrames, int k, bool tagged, byte unseenFrom = 0, int unseenAfter = int.MaxValue)
{
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++)
{
bool first = p == 0;
stream.Add(new FlFrameRecord
{
Qpc = qpc,
SwapchainId = 1,
OutputW = 2560,
OutputH = 1440,
MeasuredMask = (ushort)(FlMeasured.OutputRes | FlMeasured.PresentArgs | FlMeasured.Upscaler
| FlMeasured.Fg | FlMeasured.FgCounts | FlMeasured.DxgiPresents),
Upscaler = (byte)(first ? FlUpscaler.Dlss : FlUpscaler.Unknown),
FgEvaluations = (byte)(first ? 1 : 0),
FgMode = (byte)(first && tagged ? FlFgMode.DlssG : FlFgMode.Unknown),
DxgiUnseen = f >= unseenAfter ? unseenFrom : (byte)0,
});
qpc += step;
}
}
return stream;
}
private static (MeasuredFacts Facts, string Text) Render(List<FlFrameRecord> stream, NgxDriverState ngx)
{
var writer = new FlWriterState
{
HooksInstalledMask = (uint)_hooks,
RuntimeCensus = (uint)(FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer | FlRuntimeCensus.NvngxDlssG),
DxgiPresentSamples = (uint)stream.Count,
};
MeasuredFacts facts = MeasuredFacts.From(stream, writer, Stopwatch.Frequency, 0, 0,
FgWindow.From(stream, Stopwatch.Frequency), ngx: ngx);
return (facts, SessionReport.Render(facts));
}
[Fact]
public void ATaggedDlssGBesideTheDriversCreatedWordPrintsAgreement()
{
(MeasuredFacts facts, string text) = Render(Stream(100, 4, tagged: true), _fgCreated);
facts.FgMode.Should().Be("DlssG");
facts.FgModePrinted.Should().Be("DlssG");
text.Should().Contain("frame generation: DlssG — the NVIDIA driver agrees: an NGX frame-generation feature");
text.Should().Contain("(x4 FG)");
}
[Fact]
public void AnActiveCountWithNoTagAndTheDriversCreatedWordIsDlssGDriverReported()
{
(MeasuredFacts facts, string text) = Render(Stream(100, 4, tagged: false), _fgCreated);
facts.FgMode.Should().Be(MeasuredFacts.FgActiveUnidentified, "no tag named the technology");
facts.FgModePrinted.Should().Be(MeasuredFacts.FgDlssGDriverReported, "the driver did, as identity only");
text.Should().Contain("frame generation: DlssG (driver-reported:");
text.Should().Contain("(x4 FG)", "the count is the record and is not changed by the driver");
text.Should().NotContain("technology not identified");
}
[Fact]
public void ATaggedDlssGBesideTheDriversNegativeIsADisagreementPrintedNotResolved()
{
(_, string text) = Render(Stream(100, 4, tagged: true), _fgNotCreated);
text.Should().Contain("frame generation: DlssG — WARNING: the NVIDIA driver reports NO NGX frame-generation feature");
text.Should().Contain("printed rather than resolved");
}
[Fact]
public void ACountedNoneBesideTheDriversCreatedWordPrintsTheFactAndKeepsTheCount()
{
(MeasuredFacts facts, string text) = Render(Stream(200, 1, tagged: false), _fgCreated);
facts.FgMode.Should().Be(MeasuredFacts.FgNone);
facts.FgModePrinted.Should().Be(MeasuredFacts.FgNone, "the count decides none; the driver's word is identity only");
text.Should().Contain("frame generation: None — the NVIDIA driver reports an NGX frame-generation feature created and evaluated");
text.Should().Contain("the count above is the record and is not changed by it");
}
[Fact]
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 + " — 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]
public void ACountedSessionWhoseFactorWasRefusedSaysSoInsteadOfNoEvaluationObserved()
{
// DL:TB at FSR + DLSS-G, 2026-09-06: tokens counted, DXGI-counted presents, the pacer stopping
// in the last eighth. The factor is refused (uniformity), and the qualifier must say that.
List<FlFrameRecord> s = Stream(400, 1, tagged: true, unseenFrom: 3, unseenAfter: 200);
(MeasuredFacts facts, string text) = Render(s, _fgCreated);
facts.Fg!.Refusal.Should().Contain("changed during the session");
text.Should().Contain("Presented FPS:");
text.Should().Contain("WARNING: frame generation was counted (400 application-frame token(s), and DXGI counted 600 present(s) this hook never saw, so the Displayed rate is ABOVE this number) and its factor is REFUSED");
text.Should().Contain("read it as neither Native nor Displayed");
text.Should().NotContain("no evaluation was observed");
text.Should().Contain("no FG factor: the frame-generation state changed during the session");
}
}
@@ -0,0 +1,119 @@
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Consume;
/// <summary>
/// <c>03_METRICS</c> §Upscaling, the driver-reported rung: the driver's word names DLSS only where no hook did,
/// stands beside a hook's name as agreement or a printed disagreement, and never claims more than an identity.
/// </summary>
public sealed class DriverReportedUpscalerTests
{
private const FlHookFamily _hooks =
FlHookFamily.Present | FlHookFamily.UpscalerIdentity | FlHookFamily.UpscalerParams | FlHookFamily.FgEvaluations;
private static readonly NgxDriverState _created = NgxDriverState.Parse(
"NGXSTATE status=ANSWERED sr=0x605 rr=0x90001 fg=0x90001 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664");
private static readonly NgxDriverState _notCreated = NgxDriverState.Parse(
"NGXSTATE status=ANSWERED sr=0x5 rr=0x1 fg=0x1 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664");
/// <summary>Records with, or without, a hooked upscaler identity; the hook family is installed either way.</summary>
private static List<FlFrameRecord> Stream(FlUpscaler identity)
{
List<FlFrameRecord> stream = [];
ulong qpc = 1_000_000;
ulong step = (ulong)(Stopwatch.Frequency / 60);
for (int f = 0; f < 120; f++)
{
stream.Add(new FlFrameRecord
{
Qpc = qpc,
SwapchainId = 1,
OutputW = 2560,
OutputH = 1440,
MeasuredMask = (ushort)(FlMeasured.OutputRes | FlMeasured.PresentArgs | FlMeasured.Upscaler),
Upscaler = (byte)identity,
});
qpc += step;
}
return stream;
}
private static (MeasuredFacts Facts, string Text) Render(FlUpscaler identity, NgxDriverState? ngx)
{
List<FlFrameRecord> stream = Stream(identity);
var writer = new FlWriterState { HooksInstalledMask = (uint)_hooks, RuntimeCensus = (uint)FlRuntimeCensus.Ran };
MeasuredFacts facts = MeasuredFacts.From(stream, writer, Stopwatch.Frequency, 0, 0, ngx: ngx);
return (facts, SessionReport.Render(facts));
}
[Fact]
public void LiesOfPShapeNoHookNamedAnUpscalerAndTheDriverSaysCreatedIsDlssDriverReported()
{
(MeasuredFacts facts, string text) = Render(FlUpscaler.Unknown, _created);
facts.Upscaler.Should().BeNull("the hook ran and decoded nothing on an NGX-direct title");
facts.UpscalerDriverReported.Should().Be(MeasuredFacts.UpscalerDlssDriverReported);
facts.UpscalerDriverNote.Should().BeNull("the identity line already carries the attribution");
text.Should().Contain("upscaler: Dlss (driver-reported:");
text.Should().Contain("not counted by this hook");
text.Should().NotContain("upscaler: N/A");
}
[Fact]
public void AHookedDlssBesideTheDriversCreatedWordPrintsAgreement()
{
(MeasuredFacts facts, string text) = Render(FlUpscaler.Dlss, _created);
facts.Upscaler.Should().Be("Dlss");
facts.UpscalerDriverReported.Should().BeNull("a hook's name always outranks the driver's word");
text.Should().Contain("upscaler: Dlss — the NVIDIA driver agrees");
text.Should().NotContain("driver-reported:");
}
[Fact]
public void AHookedDlssBesideTheDriversNegativeIsADisagreementPrintedNotResolved()
{
(MeasuredFacts facts, string text) = Render(FlUpscaler.Dlss, _notCreated);
facts.Upscaler.Should().Be("Dlss");
text.Should().Contain("upscaler: Dlss — WARNING: the NVIDIA driver reports NO NGX super-resolution feature created");
text.Should().Contain("printed rather than resolved");
}
[Fact]
public void NoHookNameAndTheDriversNegativeKeepsNaWithTheNegativeAttributed()
{
(MeasuredFacts facts, string text) = Render(FlUpscaler.Unknown, _notCreated);
facts.UpscalerDriverReported.Should().BeNull();
text.Should().Contain("upscaler: N/A (an upscaler hook ran");
text.Should().Contain("— the NVIDIA driver reports no NGX super-resolution feature created in this process (driver-reported; it says nothing about FSR or XeSS)");
}
[Fact]
public void AnFsrIdentityBesideTheDriversCreatedWordIsPrintedAsAlso()
{
(_, string text) = Render(FlUpscaler.Fsr3, _created);
text.Should().Contain("upscaler: Fsr3 — the NVIDIA driver also reports an NGX super-resolution feature");
}
[Fact]
public void WithoutAProbeOrWithoutAnAnswerTheLineIsByteIdenticalToBefore()
{
(_, string none) = Render(FlUpscaler.Unknown, null);
(_, string unanswered) = Render(FlUpscaler.Unknown, NgxDriverState.Parse("NGXSTATE status=UNANSWERED nvapi=-160"));
(_, string missing) = Render(FlUpscaler.Unknown, NgxDriverState.Of(NgxProbeOutcome.ProbeMissing, @"C:\nowhere\fl-probe-nvapi.exe"));
foreach (string text in new[] { none, unanswered, missing })
{
text.Should().Contain("upscaler: N/A (an upscaler hook ran");
text.Should().NotContain("NVIDIA driver");
}
}
}
@@ -0,0 +1,171 @@
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Consume;
/// <summary>
/// Displayed counted by DXGI (<c>FlFrameRecord.dxgiUnseen</c>, <c>20_OPEN_QUESTIONS</c> §H5 row P1-DXGI): on
/// Dying Light: The Beast (Streamline 2.8.0, DLSS FG ×4) the hook timed one present per application frame
/// while DXGI's own counter on the same chain moved by ≈ 3.9 — so the window counts
/// <c>Displayed = hooked + unseen</c>, says so on its own line, and every other title is byte-identical.
/// </summary>
public sealed class DxgiCountedWindowTests
{
private const FlHookFamily _hooks =
FlHookFamily.Present | FlHookFamily.UpscalerIdentity | FlHookFamily.UpscalerParams | FlHookFamily.FgEvaluations;
private const FlRuntimeCensus _dyingLightAtDlss = FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer
| FlRuntimeCensus.SlDlss | FlRuntimeCensus.SlDlssG
| FlRuntimeCensus.NvngxDlssG;
private static readonly long _step = Stopwatch.Frequency / 70;
/// <summary>
/// The DL:TB shape: one hooked present per application frame (token drained, DLSS-G identity from the
/// tags), each carrying <paramref name="unseen"/> DXGI-counted presents under the bit, or under no bit
/// when <paramref name="claim"/> is false.
/// </summary>
private static List<FlFrameRecord> Stream(int appFrames, byte unseen, bool claim = true, int from = 0, int to = int.MaxValue)
{
List<FlFrameRecord> stream = [];
ulong qpc = 1_000_000;
for (int f = 0; f < appFrames; f++)
{
bool inRange = f >= from && f < to;
byte u = inRange ? unseen : (byte)0;
stream.Add(new FlFrameRecord
{
Qpc = qpc,
SwapchainId = 1,
OutputW = 2560,
OutputH = 1440,
MeasuredMask = (ushort)(FlMeasured.OutputRes | FlMeasured.PresentArgs | FlMeasured.Upscaler
| FlMeasured.Fg | FlMeasured.FgCounts
| (claim ? FlMeasured.DxgiPresents : FlMeasured.None)),
Upscaler = (byte)FlUpscaler.Dlss,
FgEvaluations = 1,
FgMode = (byte)FlFgMode.DlssG,
FeatureFlags = (byte)FlFeatureFlags.RayReconstructionObserved,
DxgiUnseen = u,
});
qpc += (ulong)_step;
}
return stream;
}
private static RuntimeModuleSet Interposer(string version) => new(
[new RuntimeModuleInfo("sl.interposer.dll", @"D:\Games\title\sl.interposer.dll", version.Replace('.', ','),
Version.Parse(version))],
Snapshots: 1, Unreadable: 0);
private static (MeasuredFacts Facts, string Text) Render(List<FlFrameRecord> stream, uint unseenTotal, uint samples)
{
var writer = new FlWriterState
{
HooksInstalledMask = (uint)_hooks,
RuntimeCensus = (uint)_dyingLightAtDlss,
DxgiPresentsUnseen = unseenTotal,
DxgiPresentSamples = samples,
};
MeasuredFacts facts = MeasuredFacts.From(stream, writer, Stopwatch.Frequency, 0, 0,
FgWindow.From(stream, Stopwatch.Frequency), Interposer("2.8.0.0"));
return (facts, SessionReport.Render(facts));
}
[Fact]
public void ThreeUnseenPerHookedPresentMakesAFourTimesTrioLabelledDxgiCounted()
{
List<FlFrameRecord> s = Stream(200, unseen: 3);
(MeasuredFacts facts, string text) = Render(s, unseenTotal: 600, samples: 200);
FgWindow w = facts.Fg!;
w.Presents.Should().Be(200);
w.DxgiUnseen.Should().Be(600);
w.DxgiClaiming.Should().Be(200);
w.DisplayedPresents.Should().Be(800);
w.DxgiCounted.Should().BeTrue();
w.Refusal.Should().BeNull();
w.Factor.Should().BeApproximately(4.0, 0.001);
w.IsActive.Should().BeTrue();
w.PresentsPerBatch.Should().BeApproximately(4.0, 0.001);
(w.DisplayedFps / w.NativeFps).Should().BeApproximately(4.0, 0.03, "Native × factor ≈ Displayed over ONE window");
facts.NoneWithheld.Should().BeNull("the count is no longer 1.0, so there is nothing to withhold");
facts.FgMode.Should().Be("DlssG");
text.Should().Contain("Native FPS:").And.Contain("-> Displayed FPS:").And.Contain("(x4 FG)");
text.Should().Contain("over 800 present(s)");
text.Should().Contain("Displayed is DXGI-COUNTED: 600 of those present(s)");
text.Should().Contain("a count DXGI made, not this hook");
text.Should().Contain("dxgi-unseen=600");
text.Should().NotContain("WITHHELD").And.NotContain("Presented FPS:");
}
[Fact]
public void ZeroUnseenEverywhereIsByteIdenticalToTheWindowBeforeTheByteExisted()
{
List<FlFrameRecord> claimed = Stream(200, unseen: 0);
List<FlFrameRecord> unclaimed = Stream(200, unseen: 0, claim: false);
FgWindow a = FgWindow.From(claimed, Stopwatch.Frequency);
FgWindow b = FgWindow.From(unclaimed, Stopwatch.Frequency);
a.DxgiCounted.Should().BeFalse();
a.DxgiClaiming.Should().Be(200);
b.DxgiClaiming.Should().Be(0);
a.DisplayedPresents.Should().Be(200);
a.Factor.Should().Be(b.Factor);
a.DisplayedFps.Should().Be(b.DisplayedFps);
a.BucketFactors.Should().Equal(b.BucketFactors);
// And the DL:TB shape with the count at 1.0 beside a READ counter is `none` since Leg 0: DXGI itself
// counted nothing this hook did not, on the chain where the 2.8.0 pacer's presents would show.
(MeasuredFacts facts, string text) = Render(claimed, unseenTotal: 0, samples: 200);
facts.NoneWithheld.Should().BeNull();
text.Should().Contain("frame generation: none").And.Contain("DXGI's own present counter agrees")
.And.NotContain("WITHHELD").And.NotContain("DXGI-COUNTED");
}
[Fact]
public void APacerThatStopsHalfWayFailsUniformityLikeAnyOtherStateChange()
{
List<FlFrameRecord> s = Stream(400, unseen: 3, from: 0, to: 200);
FgWindow w = FgWindow.From(s, Stopwatch.Frequency);
w.DxgiUnseen.Should().Be(600);
w.Refusal.Should().Contain("changed during the session");
w.Factor.Should().BeNull();
w.BatchRefusal.Should().Contain("changed during the session", "presents/batch takes the same numerator");
}
[Fact]
public void ASaturatedByteIsASentinelAndTheFactorIsRefused()
{
List<FlFrameRecord> s = Stream(200, unseen: 3);
FlFrameRecord r = s[100];
r.DxgiUnseen = byte.MaxValue;
s[100] = r;
FgWindow w = FgWindow.From(s, Stopwatch.Frequency);
w.DxgiSaturated.Should().Be(1);
w.Refusal.Should().Contain("255");
w.Factor.Should().BeNull();
}
[Fact]
public void AByteUnderAClearBitIsNobodysCountAndAnHonestyViolation()
{
List<FlFrameRecord> s = Stream(200, unseen: 3, claim: false);
(MeasuredFacts facts, _) = Render(s, unseenTotal: 0, samples: 0);
facts.Fg!.DxgiUnseen.Should().Be(0, "an unclaimed byte is not read");
facts.Fg.Factor.Should().BeApproximately(1.0, 0.001);
facts.HonestyViolations.Should().Be(200);
}
}
@@ -0,0 +1,113 @@
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Consume;
/// <summary>
/// DXGI's own present counter in the writer state (<c>FlWriterState.dxgiPresentsUnseen / dxgiPresentSamples</c>,
/// <c>20_OPEN_QUESTIONS</c> §H5 A1.7) beside a counted <c>none</c>: since Leg 0 (2026-09-06) a READ counter
/// decides the Streamline 2.8.0 shape, and on every shape it is a second witness printed beside the count.
/// </summary>
public sealed class DxgiPresentCounterTests
{
private const FlHookFamily _countingHooks =
FlHookFamily.Present | FlHookFamily.UpscalerIdentity | FlHookFamily.FgEvaluations;
private const FlRuntimeCensus _dyingLightAtDlss = FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer
| FlRuntimeCensus.SlDlss | FlRuntimeCensus.SlDlssG
| FlRuntimeCensus.NvngxDlssG;
private static List<FlFrameRecord> Stream(int appFrames)
{
List<FlFrameRecord> stream = [];
ulong qpc = 1_000_000;
ulong step = (ulong)(Stopwatch.Frequency / 60);
for (int f = 0; f < appFrames; f++)
{
stream.Add(new FlFrameRecord
{
Qpc = qpc,
SwapchainId = 1,
MeasuredMask = (ushort)(FlMeasured.OutputRes | FlMeasured.PresentArgs | FlMeasured.Fg | FlMeasured.FgCounts),
FgEvaluations = 1,
FgMode = (byte)FlFgMode.Unknown,
});
qpc += step;
}
return stream;
}
private static RuntimeModuleSet Interposer(string version) => new(
[new RuntimeModuleInfo("sl.interposer.dll", @"D:\Games\title\sl.interposer.dll", version.Replace('.', ','),
Version.Parse(version))],
Snapshots: 1, Unreadable: 0);
private static (MeasuredFacts Facts, string Text) Render(FlRuntimeCensus census, RuntimeModuleSet? modules,
uint unseen, uint samples)
{
List<FlFrameRecord> stream = Stream(200);
var writer = new FlWriterState
{
HooksInstalledMask = (uint)_countingHooks,
RuntimeCensus = (uint)census,
DxgiPresentsUnseen = unseen,
DxgiPresentSamples = samples,
};
MeasuredFacts facts = MeasuredFacts.From(stream, writer, Stopwatch.Frequency, 0, 0,
FgWindow.From(stream, Stopwatch.Frequency), modules);
return (facts, SessionReport.Render(facts));
}
[Fact]
public void ZeroUnseenOverAReadCounterOnTheStreamline28ShapeIsNoneWithDxgiAgreeing()
{
(MeasuredFacts facts, string text) = Render(_dyingLightAtDlss, Interposer("2.8.0.0"), unseen: 0, samples: 200);
facts.DxgiUnseenPerHookedPresent.Should().Be(0.0);
facts.NoneWithheld.Should().BeNull();
facts.FgMode.Should().Be(MeasuredFacts.FgNone);
text.Should().Contain("frame generation: none");
text.Should().Contain("DXGI's own present counter agrees: 0 unseen over 200 hooked present(s)");
text.Should().NotContain("WITHHELD");
}
[Fact]
public void ACounterNeverReadStillWithholdsAndSaysSo()
{
(MeasuredFacts facts, string text) = Render(_dyingLightAtDlss, Interposer("2.8.0.0"), unseen: 0, samples: 0);
facts.DxgiUnseenPerHookedPresent.Should().BeNull("no hooked present read the counter");
facts.NoneWithheld.Should().Contain("was not read this session");
facts.NoneBesideDxgi.Should().BeNull();
text.Should().Contain("`none` is WITHHELD");
text.Should().NotContain("DXGI's own present counter");
}
[Fact]
public void UnseenPresentsInTheWriterStateButNotInTheRecordsIsAContradictionNotANone()
{
// The two words come from the same writer, so a total the records do not carry is a defect;
// it is refused rather than read as either `none` or a factor.
(MeasuredFacts facts, string text) = Render(_dyingLightAtDlss, Interposer("2.8.0.0"), unseen: 600, samples: 200);
facts.DxgiUnseenPerHookedPresent.Should().BeApproximately(3.0, 0.001);
facts.NoneWithheld.Should().Contain("disagree").And.Contain("600");
text.Should().Contain("`none` is WITHHELD");
text.Should().NotContain("frame generation: none");
}
[Fact]
public void AValidatedNoneOnStreamline27PrintsTheCounterAsASecondWitness()
{
(MeasuredFacts facts, string text) = Render(FlRuntimeCensus.Ran | FlRuntimeCensus.SlInterposer | FlRuntimeCensus.NvngxDlssG,
Interposer("2.7.1.0"), unseen: 7, samples: 200);
facts.NoneWithheld.Should().BeNull();
facts.FgMode.Should().Be(MeasuredFacts.FgNone);
text.Should().Contain("frame generation: none");
text.Should().Contain("DXGI's own present counter read 7 unseen over 200 hooked present(s), inside the `none` ceiling");
}
}
@@ -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");
}
}
@@ -66,9 +66,16 @@ public sealed partial class H5CaseThreeTests
Snapshots: 1, Unreadable: 0);
private static (MeasuredFacts Facts, string Text) Render(List<FlFrameRecord> stream, FlRuntimeCensus census,
RuntimeModuleSet? modules, FlHookFamily hooks = _countingHooks)
RuntimeModuleSet? modules, FlHookFamily hooks = _countingHooks, uint dxgiSamples = 0)
{
var writer = new FlWriterState { HooksInstalledMask = (uint)hooks, RuntimeCensus = (uint)census };
// dxgiSamples 0 is the shape every case below was written against: DXGI's counter not read,
// which since Leg 0 (2026-09-06) is the only shape the gate still withholds on.
var writer = new FlWriterState
{
HooksInstalledMask = (uint)hooks,
RuntimeCensus = (uint)census,
DxgiPresentSamples = dxgiSamples,
};
MeasuredFacts facts = MeasuredFacts.From(stream, writer, Stopwatch.Frequency, 0, 0,
FgWindow.From(stream, Stopwatch.Frequency), modules);
return (facts, SessionReport.Render(facts));
@@ -99,6 +106,32 @@ public sealed partial class H5CaseThreeTests
FgFactorShape().IsMatch(text).Should().BeFalse("a withheld none prints no factor");
}
[Fact]
public void LegZeroDlssgOffOnStreamline28IsNoneWhenDxgiCountedNothingUnseen()
{
// 2026-09-06, 07:45 and 07:55: Dying Light: The Beast with frame generation OFF, census still
// 0x25F0F (the plugin is a startup-time load), presents = tokens, `unseen=0 over samples=3659`.
// The 2.8.0 pacer's presents are DXGI presents (row P1-DXGI), so DXGI counting none is `none`.
(MeasuredFacts facts, string text) = Render(Stream(200, 1), _dyingLightAtDlss, Interposer("2.8.0.0"),
dxgiSamples: 3659);
facts.NoneWithheld.Should().BeNull();
facts.FgMode.Should().Be(MeasuredFacts.FgNone);
facts.NoneBesideDxgi.Should().Contain("agrees").And.Contain("3659");
text.Should().Contain(" FPS: ");
text.Should().Contain("frame generation: none");
text.Should().Contain("DXGI's own present counter agrees: 0 unseen over 3659 hooked present(s)");
text.Should().NotContain("WITHHELD").And.NotContain("Presented FPS:");
}
[Fact]
public void TheWithheldReasonNamesTheCounterThatWasNotRead()
{
(MeasuredFacts facts, _) = Render(Stream(200, 1), _dyingLightAtDlss, Interposer("2.8.0.0"));
facts.NoneWithheld.Should().Contain("was not read this session").And.Contain("P1-DXGI");
}
[Fact]
public void CyberpunkOnStreamline271WithNvngxDlssgLoadedKeepsNone()
{
@@ -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");
}
}
@@ -0,0 +1,86 @@
using FluentAssertions;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Tests.Consume;
/// <summary>
/// The probe's machine line, parsed and merged: the words the owner measured on 2026-09-06 are the fixtures.
/// </summary>
public sealed class NgxDriverStateTests
{
private const string _hellIsUs =
"NGXSTATE status=ANSWERED sr=0x0000000000080605 rr=0x0000000000080005 fg=0x0000000000000005 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664";
private const string _expedition33Override =
"NGXSTATE status=ANSWERED sr=0x000000000008067F rr=0x0000000000080005 fg=0x000000000000001F ratio=0.0000 mode=2 preset=11 fgcount=0 fgpreset=0 fgmode=0 driver=61664";
[Fact]
public void TheAnsweredLineIsReadWholeAndTheHumanLinesAreIgnored()
{
string output = "fl-probe-nvapi --ngx-state 12468 — the driver's NGX feedback for one process\r\n\r\n"
+ " driver 616.64 (r616_41)\r\n SR feedback 0x0000000000080605 : INITIALIZED DLL_EXISTS CREATED EVALUATE ERR_NOT_FOUND\r\n"
+ _hellIsUs + "\r\n";
NgxDriverState s = NgxDriverState.Parse(output);
s.Outcome.Should().Be(NgxProbeOutcome.Answered);
s.Sr.Should().Be(0x80605UL);
s.Rr.Should().Be(0x80005UL);
s.Fg.Should().Be(0x5UL);
s.Driver.Should().Be(61664u);
s.SrCreatedAndEvaluated.Should().BeTrue("CREATED and EVALUATE are both set on Hell Is Us without an override");
s.Readings.Should().Be(1);
s.Answered.Should().Be(1);
NgxOverrideFlags.Describe(s.Sr).Should().Be("INITIALIZED DLL_EXISTS CREATED EVALUATE ERR_NOT_FOUND");
NgxOverrideFlags.Describe(s.Fg).Should().Be("INITIALIZED DLL_EXISTS");
NgxOverrideFlags.Describe(0).Should().Be("-");
NgxOverrideFlags.Describe(1UL << 40).Should().Be("0x10000000000", "an unknown bit is printed, never dropped");
}
[Fact]
public void TheOverrideFieldsAreCarriedAndNamedAsOverrideFields()
{
NgxDriverState s = NgxDriverState.Parse(_expedition33Override);
s.PerformanceMode.Should().Be(2u);
s.RenderPreset.Should().Be(11u);
s.ScalingRatio.Should().Be(0.0);
s.SrCreatedAndEvaluated.Should().BeTrue();
s.Describe().Should().Contain("performanceMode=2 renderPreset=11").And.Contain("the OVERRIDE's values")
.And.Contain("identity, never a count or a multiplier");
}
[Fact]
public void UnansweredDegradedAndGarbageAreOutcomesNotExceptions()
{
NgxDriverState.Parse("NGXSTATE status=UNANSWERED nvapi=-160").Outcome.Should().Be(NgxProbeOutcome.Unanswered);
NgxDriverState.Parse("NGXSTATE status=DEGRADED nvapi=-2").Outcome.Should().Be(NgxProbeOutcome.Degraded);
NgxDriverState.Parse("nothing here").Outcome.Should().Be(NgxProbeOutcome.ProbeFailed);
NgxDriverState.Parse("NGXSTATE status=ANSWERED sr=zz").Outcome.Should().Be(NgxProbeOutcome.ProbeFailed);
NgxDriverState.Parse("NGXSTATE status=WHAT").Outcome.Should().Be(NgxProbeOutcome.ProbeFailed);
NgxDriverState.Parse("NGXSTATE status=UNANSWERED nvapi=-160").SrCreatedAndEvaluated.Should().BeFalse();
NgxDriverState.Parse("NGXSTATE status=UNANSWERED nvapi=-160").Describe().Should().Contain("did not answer").And.Contain("NvAPI -160");
}
[Fact]
public void MergeKeepsTheLastAnswerCountsEveryReadingAndFlagsAChange()
{
NgxDriverState before = NgxDriverState.Parse(
"NGXSTATE status=ANSWERED sr=0x5 rr=0x1 fg=0x5 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664");
NgxDriverState after = NgxDriverState.Parse(_hellIsUs);
NgxDriverState silent = NgxDriverState.Parse("NGXSTATE status=UNANSWERED nvapi=-160");
NgxDriverState merged = NgxDriverState.NotRun.Merge(before).Merge(after).Merge(silent);
merged.Outcome.Should().Be(NgxProbeOutcome.Answered, "an earlier answer outranks a later silence");
merged.Sr.Should().Be(0x80605UL, "the last ANSWERED reading is the state");
merged.Readings.Should().Be(3);
merged.Answered.Should().Be(2);
merged.Changed.Should().BeTrue("the SR word gained CREATED | EVALUATE between readings");
merged.Describe().Should().Contain("answered 2 of 3 probe(s), and the words CHANGED between readings");
NgxDriverState same = NgxDriverState.NotRun.Merge(after).Merge(after);
same.Changed.Should().BeFalse();
same.Describe().Should().Contain("answered 2 of 2 probe(s); driver 616.64");
}
}
@@ -0,0 +1,96 @@
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.CaptureHost.Consume;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost.Tests.Consume;
/// <summary>
/// The stall diagnostic: the longest intervals, placed against the host's own touches on the target.
/// </summary>
public sealed class StallReportTests
{
private static readonly long _hz = Stopwatch.Frequency;
/// <summary>A 120 FPS stream with one gap of <paramref name="gapMs"/> after <paramref name="gapAfter"/> presents.</summary>
private static List<FlFrameRecord> StreamWithGap(int presents, int gapAfter, double gapMs, out long gapStartQpc)
{
List<FlFrameRecord> s = [];
long qpc = 5_000_000;
long step = _hz / 120;
gapStartQpc = 0;
for (int i = 0; i < presents; i++)
{
s.Add(new FlFrameRecord { FrameIndex = (uint)i, Qpc = (ulong)qpc, SwapchainId = 1 });
if (i == gapAfter)
{
gapStartQpc = qpc;
qpc += (long)(gapMs / 1000.0 * _hz);
}
else
{
qpc += step;
}
}
return s;
}
[Fact]
public void TheLongestIntervalIsFoundAndPlacedInTheSession()
{
List<FlFrameRecord> s = StreamWithGap(600, 240, 1000.0, out _);
StallReport r = StallReport.From(s, _hz, []);
r.Intervals.Should().Be(599);
r.OverThreshold.Should().Be(1);
r.Longest.Should().HaveCount(3);
r.Longest[0].Milliseconds.Should().BeApproximately(1000.0, 1.0);
r.Longest[0].AtSeconds.Should().BeApproximately(2.0, 0.01, "240 presents at 120 FPS");
r.Longest[0].NearestTouchSeconds.Should().BeNull();
r.Describe().Should().Contain("1 interval(s) of 599 at or over 100 ms").And.Contain("longest: 1000 ms at t=2.00 s")
.And.Contain("no host touch recorded");
}
[Fact]
public void AHostTouchInsideTheStallNamesFrameLedgerAsASuspect()
{
List<FlFrameRecord> s = StreamWithGap(600, 240, 1000.0, out long gapStart);
long touch = gapStart + _hz / 2; // half a second into the gap
StallReport r = StallReport.From(s, _hz, [touch]);
r.Longest[0].NearestTouchSeconds.Should().Be(0.0);
r.Longest[0].NearATouch.Should().BeTrue();
r.Describe().Should().Contain("A HOST TOUCH INSIDE the interval").And.Contain("SUSPECT");
}
[Fact]
public void AHostTouchJustBeforeTheStallIsStillASuspectAndAFarOneIsNot()
{
List<FlFrameRecord> s = StreamWithGap(600, 240, 1000.0, out long gapStart);
StallReport near = StallReport.From(s, _hz, [gapStart - _hz / 4]); // 0.25 s before
StallReport far = StallReport.From(s, _hz, [gapStart + 30 * _hz]); // 30 s after
near.Longest[0].NearestTouchSeconds.Should().BeApproximately(-0.25, 0.01);
near.Longest[0].NearATouch.Should().BeTrue();
near.Describe().Should().Contain("0.25 s before it");
far.Longest[0].NearATouch.Should().BeFalse();
far.Describe().Should().Contain("not ours");
}
[Fact]
public void ASmoothStreamHasNoStallAndStillPrintsItsLongest()
{
List<FlFrameRecord> s = StreamWithGap(300, -1, 0, out _);
StallReport r = StallReport.From(s, _hz, [(long)s[10].Qpc]);
r.OverThreshold.Should().Be(0);
r.Longest[0].Milliseconds.Should().BeApproximately(1000.0 / 120, 0.05);
r.Touches.Should().Be(1);
StallReport.From([s[0]], _hz, []).Describe().Should().Contain("fewer than two presents");
}
}
@@ -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
@@ -195,12 +195,25 @@ public sealed class ShmDrainIntegrationTests
// else. In layout v3 the zero-defaults are honest by construction — FlUpscaler.NotReported and
// FlFgMode.NotReported are 0 — and the mask corroborates rather than being the sole defence.
//
// OutputRes is asserted as "no bit outside these two" rather than as an exact value, because the
// overflow fixture legitimately produces records with PresentArgs alone: past 16 swapchains the
// writer has no size to report and #57 made the bit conditional on there being one.
// OutputRes is asserted as "no bit outside these three" rather than as an exact value, because
// the overflow fixture legitimately produces records with PresentArgs alone: past 16 swapchains
// the writer has no size to report and #57 made the bit conditional on there being one. The
// third bit is DxgiPresents (2026-09-05): the present hook reads GetLastPresentCount on the chain
// it saw, and every record after a chain's first claims the delta — a zero here, which the
// byte assertion below pins, because this fixture presents only through the patched body.
records.Should().OnlyContain(
r => (r.MeasuredMask & ~(ushort)(FlMeasured.OutputRes | FlMeasured.PresentArgs)) == 0,
r => (r.MeasuredMask & ~(ushort)(FlMeasured.OutputRes | FlMeasured.PresentArgs | FlMeasured.DxgiPresents)) == 0,
"the writer must claim exactly what it measured — no more");
// ...AND A PAUSE IS NOT AN UNSEEN PRESENT. The paused-session case below lets the harness
// present ~85 times while the hook declines them; the first record after the resume claimed
// them all as "presents DXGI counted and this hook never saw" until the epoch guard in
// RecordPresent made a declined present invalidate the chain's last reading. This assertion
// runs on every fixture, so that case is the one that keeps the guard honest.
records.Should().OnlyContain(r => r.DxgiUnseen == 0,
"DXGI must count nothing this hook did not on a fixture that presents only through the patched body "
+ "— including across a pause, which the hook SAW and declined");
records.Should().Contain(r => (r.MeasuredMask & (ushort)FlMeasured.DxgiPresents) != 0,
"after a chain's first hooked present the counter has a previous value to difference against");
records.Should().OnlyContain(r => (r.MeasuredMask & (ushort)FlMeasured.PresentArgs) != 0,
"syncInterval and presentFlags are the call's own arguments; a DXGI present hook always has them");
records.Should().OnlyContain(r => r.RtFlags == 0,
@@ -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
}