Compare commits

...
25 changed files with 1921 additions and 144 deletions

No files matched your search

+9
View File
@@ -54,6 +54,15 @@ numeric core and does not move; the heading is the full version — corrected 20
### Added
- **Not in a release yet: the part inside a game can read NVIDIA's own latency report** (owner decisions D132, D136,
D138-D141). While a session records Advanced metrics, and only then, it asks the graphics driver about once a
second for its report of a frame's stages - simulation, render submit, present, driver, the operating system's
queue, the graphics card - and for its low-latency state. It is a call FrameLedger makes itself, on the thread
that presents the game's frames, through NVIDIA's `nvapi64.dll` only where the game had already loaded it;
Direct3D 12 only. A copy of that library sitting in the game's own folder is refused. A call that faults or takes
two milliseconds is the last one until the game is closed. Nothing shows these numbers yet: the Agent and the App
come next, with the legal texts.
- **For developers: room in the shared memory for NVIDIA Reflex latency** (owner decisions D136, D138). Ten reserved
words of the block that carries Advanced metrics from a game are now named for the driver's latency report -
where the read stands, and a sum for each stage of a frame. Nothing writes them yet and nothing reads them; the
+1 -1
View File
@@ -35,7 +35,7 @@ Targets:
- `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 --hold-presenting N` since the same day (P1 item 4):** a real context on a hidden window, `SwapBuffers`'d through gdi32 as a title does, on Microsoft's generic renderer — so it runs on CI.
- `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-probe-reflex` → the instrument of `spike-notes` §31 (2026-11-13, owner decision D132): the call sequence Reflex route D would put into the Overlay — find `nvapi64.dll` only if the process already holds it, resolve the driver's two getters by interface id, call them — in an unshipped probe built with the Overlay's flags. `--stub` runs it against `fl_stub_nvapi64` → `nvapi64.dll` (a stand-in with knobs for a missing getter, an empty report, an error and a call that does not return; its outputs in a directory of their own, so that its `nvapi64.lib` is never beside the vendored one's name) and is ctest `fl_reflex_probe_stub`; `--real` runs it against the installed driver on an NVIDIA adapter, with the probe setting the latency markers a game would, in its own process — a measurement, never a test. It takes the vendored NVAPI headers' include directory and **does not link `nvapi64.lib`**. Nothing shipped includes its header.
- `fl-probe-reflex` → the instrument of `spike-notes` §31 (2026-11-13, owner decision D132) — **since the owner said go (D136) it is built from the Overlay's own header, `FrameLedger.Overlay/include/fl_reflex.h`**, so its ctest runs the shipped call sequence with Control Flow Guard enforced; its `--real` also prints which image the two getter addresses lie in (`nvapi64_impl.dll`, not the `nvapi64.dll` that is asked). What it was written as: the call sequence Reflex route D would put into the Overlay — find `nvapi64.dll` only if the process already holds it, resolve the driver's two getters by interface id, call them — in an unshipped probe built with the Overlay's flags. `--stub` runs it against `fl_stub_nvapi64` → `nvapi64.dll` (a stand-in with knobs for a missing getter, an empty report, an error and a call that does not return; its outputs in a directory of their own, so that its `nvapi64.lib` is never beside the vendored one's name) and is ctest `fl_reflex_probe_stub`; `--real` runs it against the installed driver on an NVIDIA adapter, with the probe setting the latency markers a game would, in its own process — a measurement, never a test. It takes the vendored NVAPI headers' include directory and **does not link `nvapi64.lib`**. Nothing shipped includes its header.
- `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.
- `fl_stub_ffx_dx12` → `amd_fidelityfx_dx12.dll`, `fl_stub_ffx_upscaler` → `amd_fidelityfx_upscaler_dx12.dll`, `fl_stub_ffx_fg` → `amd_fidelityfx_framegeneration_dx12.dll` — the three AMD **leaves** — and `fl_stub_ffx_loader` → `amd_fidelityfx_loader_dx12.dll`, a **forwarding stand-in** bound to the two 2.x leaves through their FrameLedger-named *direct* entry — the way the real loader was measured to bypass the leaves' exports — so `--hold-presenting-ffx` can push every dispatch through a loader that is hooked along with the leaves and prove the count reads 1× (2026-09-04). Same rules as the Streamline stubs: fixtures, never shipped, vendor filenames with our version blocks. `fl_stub_ffx_fsr3_host` → `ffx_fsr3_x64.dll` (2026-09-05): the FSR 3.0 **host** facade, exporting the four names `SpeaksFsr3Host` probes for through the vendored `fsr3-v3.0.4` header's own `FFX_API`; `--ffx-topology fsr3host|fsr3host+mono` drives it, and `hookinventory-check` Pass C reads it as the export parser's second positive control.
- **`fl_fidelityfx_headers`** → an INTERFACE target over the five vendored FidelityFX ffx-api headers (`src/native/third_party/fidelityfx/`, tag v2.3.0, MIT by exception). Three include directories because upstream's headers include each other by relative path; include directories only and nothing to link — no `.lib` is vendored — and `hookinventory-check` Pass C reads the Overlay's export table because `ffx_api.h` declares its entry points `__declspec(dllexport)` unconditionally.
+14
View File
@@ -168,6 +168,20 @@ game the same lines are in `logs\overlay-<pid>-….log` — read there on 2026-1
batches, 81–262 ms for sixteen of them and 0.61 s and 1.26 s for two (`17_HOOK_ENGINE` §Unhooking, *Batches*); no
restore line yet, because no session was stopped while its game ran.
**The call into the driver (train C, 2026-11-13; in no release yet) is tested in three places, each for what the
others cannot say.** `fl_reflex_summary` (Catch2) drives `fl_adv_fields.h`'s reader on reports written by hand: the
two newest frames held back, a frame summed once, a span the driver did not report, a span no frame can have, frame
ids that start again, and the ten words of a publication. `fl_guard`'s seven `[latency]` cases inject the Overlay
into a Direct3D 12 target that has loaded a stand-in `nvapi64.dll`, and read that module's call counts from outside
through its named section (`fl_stub_nvapi_shared.h`) — so "the driver was not called" is a count: not asked → not
even asked for the addresses; asked → about one read a second, sums equal to the stand-in's, every counted read a
received call; an error; a span not reported; the request off; a second session; the stop; a call of 50 ms (the
last one); a fault (counted once, the hooks stay); a module without the getters; no module (none is loaded); a
module beside the executable (refused, never asked); Direct3D 11 (not read). `fl_reflex_probe_stub` runs the same
header, `fl_reflex.h`, in a process that **enforces Control Flow Guard** — the injected cases do not: `hook-harness`
is not a CFG image. **None of them is a driver.** `fl-probe-reflex --real` is the measurement against the installed
one, run by hand (`spike-notes` §31), and a real game is owner-only item 45.
## Tier cross-validation (accuracy regression net) — **GONE, 2026-08-28, and this is the entry to read before planning P5**
~~Run the same game session with Tier 1 and Tier 2 simultaneously where possible (ETW does not conflict with hooking) and compare frametime distributions: Avg/1% Low must agree within **1%**. Divergence beyond that means one of the two paths is wrong and blocks the release. This is also the check that would have caught the original detection-accuracy problem.~~
+32 -2
View File
@@ -172,6 +172,31 @@ Every hook must be listed here with a purpose. Anything not on this list is not
| ✅ `opengl32.dll!wglSwapBuffers` (2026-09-06, P1 item 4) | The OpenGL present hook (§Presentation). A system module, not a vendor one, so — like the row below — it is deliberately **not** in `FL_HOOK_INVENTORY` and `hookinventory-check` does not cover it; listed here so the table above and these two rows together are the whole inventory |
| ✅ `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~~ Like `wglSwapBuffers` above it, it is deliberately not in `FL_HOOK_INVENTORY` (corrected 2026-10-04):** 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) |
### Calls the Overlay makes into a driver — not hooks, and the only ones
Everything else on this page learns what it learns from the arguments of a call the game made. This is the one
place the Overlay **makes a call of its own** into code that is neither the game's nor FrameLedger's, and it is
listed here so that nobody takes it for a hook or adds a second one without the same ruling
(`CLAUDE.md` rule 4's note of 2026-11-13, owner decisions D132, D136, D138–D141).
| Call | When, where | Rule 4 | What bounds it |
|---|---|---|---|
| **NVIDIA's `NvAPI_D3D_GetLatency` and `NvAPI_D3D_GetSleepStatus`** — the driver's two read-only latency getters (Advanced metrics train C; `fl_reflex.h`; **in no release yet**) | **Only while a session asks for Advanced metrics** (D138: no switch of its own), only for a Direct3D 12 swap chain whose device is the one the Overlay holds, **about once a second, on the presenting thread, after that present's record is published**. The watchdog finds the addresses once for the process and arms one read at a time; a present pays one relaxed load. The addresses come from an `nvapi64.dll` **the game had already loaded** — asked for by name, never loaded — through its `nvapi_QueryInterface` and the two interface ids of the vendored `nvapi_interface.h`. The Overlay links no NVAPI | The owner's ruling (D132): a driver's read-only getter called with the device behind the swap chain the Overlay hooks reads the driver's report, not game memory, and writes nothing. Getters only — never a setter, a marker or a sleep (`tools/nvapi-readonly-check.ps1` holds which ids code loaded into a game may name: these two). What is read of the two structs is on `tools/overlay-allowed-fields.txt` like every other vendor member | **An `nvapi64.dll` in the executable's own folder is refused** (D140): the driver's is in Windows' directories. **A fault** in a getter is caught by a guard of its own, counted once in `faultCount`, and ends the reads for the process. **One call of 2 ms or more** ends them too (D141). **A call that has not returned after two seconds** is logged, flushed and published as stalled — nothing can stop it, and the presenting thread it holds is the game's. Each is until the game exits |
**Where the addresses are, measured** (`fl-probe-reflex --real`, driver 32.0.16.2114): System32's `nvapi64.dll` is a
shim and answers the two ids with addresses inside **`nvapi64_impl.dll`**, in the driver's own store. So an address
is accepted when it is executable code of an image the process has loaded, and **the Overlay keeps a reference on
that image as well as on `nvapi64.dll`** — two modules the game loaded, never released, for the reason
`ResolveScoped` gives: a presenting thread may be about to call. `nvapi64_impl.dll` is a Control Flow Guard image;
the probe, which enforces CFG, has made the calls from the header that ships, so on this driver the getters are
valid targets. **Not excluded**: a game that enforces CFG on a driver the probe has not been run against — a target
that were not valid is a fast-fail no guard catches.
**The gate.** One word, four states — idle, armed, reading, off (`dllmain.cpp`, above `ReadLatencyOnce`). Only the
watchdog arms; a presenting thread takes *armed* to *reading* by compare-exchange and owns the 15.4 KB report
buffer (static storage, never a game thread's stack) and the read's result until it stores *idle* or *off*; the
watchdog takes the result only when nobody is reading. No lock, and no second read while one is under way.
### Watchdog observations — not hooks, and listed here so nobody mistakes them for one
| Observation | Mechanism | Rule 4 | Why |
@@ -405,7 +430,7 @@ or version, so the question is whether the declaration ever changed:
| Hook / call | Yields |
|---|---|
| ~~`IDXGIAdapter3::QueryVideoMemoryInfo` (we **call** it, not hook it, once per second from our own thread)~~ | ~~**Per-process VRAM** `CurrentUsage` + `Budget` — previously impossible; now exact~~ **Never built; superseded 2026-10-03 (D43):** the game's memory is read from OUTSIDE the game by the Agent (`18_GPU_VENDOR_APIS` §The game process's memory), so nothing in the Overlay calls it. Only the budget would need it, and that stays open (`20_OPEN_QUESTIONS` §M11) |
| NVAPI Reflex: ~~hook `NvAPI_D3D_SetSleepMode`, `NvAPI_D3D_SetLatencyMarker`~~; call `NvAPI_D3D_GetLatency` *(**never built.** The two hooks cannot be: neither function is an export — `20_OPEN_QUESTIONS` §M14. What a call-only route would take is read through in `spike-notes` §30, 2026-11-12, and waits for the owner's go or no)* | Reflex on/off + PC latency breakdown. Declarations come from the vendored MIT NVAPI headers (`18_GPU_VENDOR_APIS` §L3); the Overlay links them like any other header. NVIDIA-only — the whole block compiles out to a no-op capability flag elsewhere |
| NVAPI Reflex: ~~hook `NvAPI_D3D_SetSleepMode`, `NvAPI_D3D_SetLatencyMarker`~~; call `NvAPI_D3D_GetLatency` and `NvAPI_D3D_GetSleepStatus` *(the two hooks cannot be: neither function is an export — `20_OPEN_QUESTIONS` §M14. **The calls are written since 2026-11-13 and in no release yet** — §Calls the Overlay makes into a driver, above; owner decisions D132, D136)* | Reflex on/off + PC latency breakdown. Declarations come from the vendored MIT NVAPI headers (`18_GPU_VENDOR_APIS` §L3); the Overlay links them like any other header. NVIDIA-only — the whole block compiles out to a no-op capability flag elsewhere |
### Explicitly not hooked
Input APIs, file I/O, network, memory allocators, window messages beyond what the overlay needs, anything game-specific. Rule 4 in CLAUDE.md.
@@ -650,7 +675,7 @@ Field notes — each of these was a defect in an earlier revision:
header — they are written by the other process, and mixing them into an
Overlay-written line reintroduces exactly the false sharing the split exists to
prevent. Layout is normative in `07_IPC` §A + B.
- **The hot path performs: one QPC read, a few field reads from cached state, one 60-byte store, two relaxed atomic stores and two compiler fences.** No syscall, no allocation, no lock, no logging. Target ≤ 1 µs per present. *(Added 2026-10-04: the summary leaves out the per-present `IDXGISwapChain::GetLastPresentCount` call (§H5, the `dxgiUnseen` count) and the display sample every 500 ms at most (region 4).)*
- **The hot path performs: one QPC read, a few field reads from cached state, one 60-byte store, two relaxed atomic stores and two compiler fences.** No syscall, no allocation, no lock, no logging. Target ≤ 1 µs per present. *(Added 2026-10-04: the summary leaves out the per-present `IDXGISwapChain::GetLastPresentCount` call (§H5, the `dxgiUnseen` count) and the display sample every 500 ms at most (region 4).)* *(Added 2026-11-13, train C, in no release yet: after the store, one relaxed load of the latency gate; and, while a session asks for Advanced metrics and the watchdog armed one, a call into the driver about once a second — §Calls the Overlay makes into a driver. That call is the one thing on this path that is not bounded by FrameLedger's own code: 0.5–2.6 µs measured against the installed driver, and a call of 2 ms or more is the last.)*
- Per-frame mutable state (current upscaler, render res, dispatch counts) lives in a small struct updated by the feature hooks and *read* by the present hook; counters reset at present.
## The watchdog thread — the only thread we add to the game
@@ -716,6 +741,7 @@ Every hook body is wrapped:
- Any SEH exception inside our code ⇒ increment `faultCount`, record which hook, **return control to the original function** so the game continues.
- 3 faults total ⇒ set `status = self_disabled`, ~~uninstall all hooks (`MH_DisableHook(MH_ALL_HOOKS)`)~~ restore each patch's prologue only while its bytes are still our jump (compare-and-restore per patch through `StopObserving`, §Unhooking, §H7 — `MH_ALL_HOOKS` would have removed an overlay chained after us; corrected 2026-09-27; since 0.1.0-beta.46 the patches that are still ours come out together, under one stop of the threads — §Unhooking, Batches), stop writing, stay dormant. The Agent sees the flag and finalizes the session as `degraded`.
- Never `__try` around the call to the original function — only around *our* code, so we never mask a game bug as ours or vice versa.
- **One exception, since train C (2026-11-13): the two driver getters the Overlay calls itself** (§Calls the Overlay makes into a driver) are under a guard of their own, `fl_reflex.h`'s, with the same filter. They are not "the original function" — the game did not make these calls, we did, so a fault in them is ours to answer for. It is counted once through `NoteFault`, and the read is switched off for the process in the same breath, so that one fault cannot become the three that self-disable. **A caught fault does not give back a lock the driver held**: the guard is containment, not safety, which is why nothing is called again after it.
- The trampoline call to the original is always executed exactly once, on every path, including error paths.
## Unhooking
@@ -878,6 +904,10 @@ No logging in hook bodies. A small fixed-size in-memory ring of structured event
> since beta.43 `FFX_CONFIGURE` — each configure type a hooked ffx module was handed, in a process where
> `ffxConfigure` is hooked at all (one asked for Advanced metrics) — and since beta.46 `PATCH_BATCH`: one line an
> apply, `install` or `restore`, `a` the microseconds it took and `b` the patches it covered (§Unhooking, Batches).
> **`LATENCY` (train C, in no release yet)**: one line each time the state of the driver read changes — `a` the
> `FlLatencyState`, the text what it means — and, when the module is found, two more with the end of the path
> `nvapi64.dll` was loaded from and of the image its getters are in. Written by the watchdog; a fault in a getter
> is a `FAULT` line from the presenting thread, as any fault is.
> **Three flush points — four since beta.42, the same note —, none on a present path:** the end of `InitThread` (so the
> file exists from the start of the session and a crash mid-session still leaves it), the watchdog when
> `FlControlBlock.logFlushRequested` changes (a counter the Agent bumps at session end; nothing clears it),
+10 -1
View File
@@ -215,7 +215,12 @@ of mine was wrong in six places — and that no other file carries yet:
an `nvapi64.dll` that is *already loaded* (never loads it), only while a session asks for Advanced metrics and a
Direct3D 12 device is held; it keeps one reference and never releases it; it refuses a module in the executable's
own folder (D140); it fetches `nvapi_QueryInterface` and the two ids under a guard and checks with `VirtualQuery`
that both addresses lie inside that module. "No module", "no getter" and "refused" are final for the process.
that both addresses lie inside ~~that module~~ an image the process has loaded. "No getter" and "refused" are
final for the process; "no module" is asked again each second. **Found when the header was run against the
installed driver: `nvapi64.dll` is a shim and the two getters are in `nvapi64_impl.dll`** (`spike-notes` §31,
*What moving the sequence into the Overlay found*) — so the check accepts another loaded image, a reference is
kept on that image as well, and the code that is called *is* a Control Flow Guard image (the plan's review had
reasoned from the shim, which is not).
- **One atomic gate with four states** — idle, armed, reading, off — not a busy flag beside accumulators (two
presenting threads could read back to back, and the watchdog could drain half a read). The watchdog drains only
when it sees *idle* and arms at most once a second by its own clock (the loader detour wakes it more often); a
@@ -228,6 +233,10 @@ of mine was wrong in six places — and that no other file carries yet:
more (D141); the watchdog finding *reading* on two ticks running — logged and flushed at once, published as
stalled, and **nothing can stop a call that does not return**. An error status or an empty report is recorded and
reading goes on.
- **What D141 costs, measured once on a busy PC** (`spike-notes` §31, *A run on a busy PC*): the 2 ms latch will
sometimes fire on a pause that was Windows' and not the driver's — a few sessions in a hundred at worst, by a
reading of one run. The owner chose one call over two knowing it errs towards the game; item 45's outcomes must
say how the two are told apart (the microseconds published with *slow*).
- **The summary**: only frames newer than the last one summed; the two newest of a report skipped (§31: not final);
a zero end point is "span not reported" (published as all ones), not a refused frame; a frame is refused for a
span that runs backwards, one over a second, or no total; frame ids that go backwards restart the sequence.
@@ -132,3 +132,48 @@ Three runs of `fl-probe-reflex --real 10` on 2026-11-13 (RTX 5080, driver 32.0.1
**What it does not say**: a game's own sleep, on a game's own threads, with a real frame's work between the sleep
and the present; frame generation's pacer; another driver. Those are what the first real title is for (D136).
### What moving the sequence into the Overlay found (2026-11-13, the same evening)
The call sequence became `FrameLedger.Overlay/include/fl_reflex.h`, with one check the candidate did not have: that
the two addresses the module answers with are code of the module. **Run against the installed driver, that check
refused the driver.** `C:\Windows\System32\nvapi64.dll` is a shim: it answers both ids with addresses inside
`nvapi64_impl.dll`, in the driver's own store (`…\DriverStore\FileRepository\nv_dispi.inf_amd64_…`), an image of
its own. Three consequences, all in the header now:
- An address is accepted when it is **executable code of an image the process has loaded** — which still refuses
the heap, a stack and nowhere — not only when it is inside `nvapi64.dll`.
- **A reference is kept on that image too.** The addresses are code only while `nvapi64_impl.dll` stays loaded, and
what the shim does with it when a game unloads NVAPI was not looked at.
- **The note above was wrong about Control Flow Guard.** It reasoned from `nvapi64.dll`, which is not a CFG image;
the code that is called is in `nvapi64_impl.dll`, which is one (`dumpbin`: instrumented, a function table of
5 332 entries). The probe enforces CFG and has made the calls from the shipped header, so on this driver the two
getters are valid targets. A game that enforces CFG, on a driver the probe was not run against, is not covered:
a target that were not valid is a fast-fail no guard catches.
The stand-in module answers with addresses of its own, which is why the stub leg could not find this; only the
real run could. The probe's `--real` now prints the image each address lies in.
### A run on a busy PC, and what it says about the 2 ms latch (D141)
The run that confirmed the corrected header (`Resolve` OK, the reads as before) was made while a native build and an
injected test ran on the same PC — the probe's own loop made 9 000 frames a second where it had made 16 000. It is
the only run so far that was not alone, and it is the nearer one to a game:
| | Alone (three runs) | Busy (one run) |
|---|---|---|
| `GetLatency` after a sleeping frame, on the thread that sleeps and presents (2000 reads) | median 2.5–2.6 µs, worst 8–67 µs | median 3.4 µs, worst 130 µs, none of 2 ms |
| From another thread without a pause, while the first sleeps: reads of 1 ms or more / of 2 ms or more | 0 / 0 in 10.3 million | **536 / 25 in 2.9 million**, worst 3.5 ms |
| The same before the sleep mode was set | 1 / 0 in 9.9 million | 6 / 2 in 3.2 million, worst 2.2 ms |
| Four reads a second for 20 s | worst 12–82 µs | worst 110 µs, none of 1 ms |
**A reading, not a measurement of a game**: a thread that does nothing but call is taken off its processor now and
then on a busy PC, and a read that was under way then is as long as the pause. Twenty-five such pauses of 2 ms or
more in ten seconds of calling is 2.5 a second; a read of 3 µs made once a second is inside one of them about once
in a hundred thousand reads. **So the latch of D141 will, on a busy PC, sometimes switch the read off for a pause
that was Windows' and not the driver's** — of the order of a few sessions in a hundred, for sessions of two hours,
if a game's presenting thread is paused as often as this probe's poller was; a presenting thread usually is not.
The session then says *stopped: slow* with the microseconds, and the next start of the game reads again. That is the
trade the owner chose with D141 (one call, not two): it errs towards the game. The number published with the state
is what tells the two apart afterwards — a driver that holds a call does it again and for longer; a pause is a few
milliseconds, once.
@@ -34,6 +34,8 @@ 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
# NVAPI's headers and NOT its library (third_party/CMakeLists.txt says why): fl_reflex.h's structs and ids.
fl_nvapi_headers
# Advapi32: the ring's DACL. User32: WindowFromDC / GetClientRect for the OpenGL
# output size. Shell32 + Ole32: SHGetKnownFolderPath for the native log's
# directory (§S21's resolution, not the environment), init/watchdog thread only.
@@ -15,6 +15,9 @@
// m const FfxApiEffectMemoryUsage& what ffxQuery wrote, after it answered OK
// q the memory query's descriptor (its out-pointer), and `desc`, its header (its type)
//
// (and since train C three more, for what the driver wrote into the Overlay's own buffers: `lr`, `lf` and `ls` --
// the section "REFLEX LATENCY" below says what they are and why they are here.)
//
// RULE 4. Each is an argument of a call the Overlay hooks, or what that call wrote
// through an out-pointer the game gave it. Nothing else is dereferenced: no
// resource, no command list, no callback, and never a camera's position, axes or
@@ -41,6 +44,7 @@
#include <atomic>
#include <bit>
#include <cstdint>
#include <fl_reflex.h>
#include <fl_shm.h>
#include <sl.h>
// After sl.h, as fl_sl_inputs.h explains: sl_dlss.h has no includes of its own.
@@ -640,6 +644,181 @@ inline void ObserveSlShutdown(Accumulators& a) noexcept {
NoteBits(a.validMask, FL_ADV_VALID_SL_SHUTDOWN);
}
// ---------------------------------------------------------------------------------------------------------------------
// REFLEX LATENCY (train C; owner decisions D132, D136, D138-D141; fl_reflex.h; fl_shm.h's latency words).
//
// THE ONE GROUP HERE THAT IS NOT AN ARGUMENT OF A HOOKED CALL. The two structs below are what the driver wrote into
// buffers the OVERLAY handed to its two read-only getters (fl_reflex.h makes the calls). The members read are on
// the same list as every other, through three more parameters with fixed names:
//
// lr const NV_LATENCY_RESULT_PARAMS& the report: sixty-four frames
// lf const NV_LATENCY_RESULT_PARAMS::FrameReport& one frame of it, handed on by index and never aliased
// ls const NV_GET_SLEEP_STATUS_PARAMS& the driver's sleep status
//
// WHAT IS NOT READ: inputSampleTime (the probe never saw it set, and "when the player pressed something" is nothing
// a frame-time tool needs), the GPU times the driver reports beside the marks, and the sleep interval -- it changes
// with every frame, so it is not a fact of a session.
//
// THE RULES A GAME NEEDS (spike-notes §31). The newest frames of a report are not final -- one run read a span of
// half an hour in the newest -- so the two newest ids are never summed. A span whose end point is zero was not
// reported, which is not a fault of the frame: without a sleep mode the driver leaves driverStartTime zero in every
// frame. A span that runs backwards or lasts more than a second is one no frame can have, and that frame is
// refused whole; so is a frame with no total. Frame ids that go backwards are a game that started counting again.
//
// The caller owns the tally and the cursor (dllmain.cpp's gate says who that is at any moment): nothing here is
// atomic, and nothing here calls out.
// ---------------------------------------------------------------------------------------------------------------------
inline constexpr uint32_t kLatSpans =
7u; // simulation, submit, present, driver, OS queue, GPU, total: the region's order
inline constexpr uint32_t kLatTotal = 6u;
inline constexpr uint32_t kLatReportFrames = 64u;
inline constexpr uint64_t kLatSpanLimitUs = 1000000u;
static_assert(sizeof(NV_LATENCY_RESULT_PARAMS::frameReport) / sizeof(NV_LATENCY_RESULT_PARAMS::FrameReport) ==
kLatReportFrames);
// What one read of the report added up to.
struct LatencyTally {
uint32_t frames = 0; // frames summed
uint32_t refused = 0; // frames refused
uint32_t sumUs[kLatSpans]{}; // microseconds, over the frames summed
uint32_t lacking = 0; // bit n: a summed frame did not report span n
};
// Where the reader is in the game's frame ids: the newest one already summed or refused. 0 = none yet.
struct LatencyCursor {
uint64_t lastFrameId = 0;
};
inline constexpr uint32_t kLatSpanReported = 0u;
inline constexpr uint32_t kLatSpanAbsent = 1u;
inline constexpr uint32_t kLatSpanImpossible = 2u;
inline uint32_t LatencySpan(uint64_t start, uint64_t end, uint32_t& us) noexcept {
us = 0u;
if (start == 0u || end == 0u) {
return kLatSpanAbsent;
}
if (end < start || end - start > kLatSpanLimitUs) {
return kLatSpanImpossible;
}
us = static_cast<uint32_t>(end - start);
return kLatSpanReported;
}
// A slot of the report the driver put nothing in.
inline bool LatencyFrameIsEmpty(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf) noexcept {
return lf.frameID == 0u && lf.simStartTime == 0u && lf.gpuRenderEndTime == 0u;
}
inline uint64_t LatencyFrameId(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf) noexcept {
return lf.frameID;
}
inline void ObserveLatencyFrame(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf, LatencyTally& tally) noexcept {
uint32_t us[kLatSpans]{};
const uint32_t kind[kLatSpans] = {
LatencySpan(lf.simStartTime, lf.simEndTime, us[0]),
LatencySpan(lf.renderSubmitStartTime, lf.renderSubmitEndTime, us[1]),
LatencySpan(lf.presentStartTime, lf.presentEndTime, us[2]),
LatencySpan(lf.driverStartTime, lf.driverEndTime, us[3]),
LatencySpan(lf.osRenderQueueStartTime, lf.osRenderQueueEndTime, us[4]),
LatencySpan(lf.gpuRenderStartTime, lf.gpuRenderEndTime, us[5]),
LatencySpan(lf.simStartTime, lf.gpuRenderEndTime, us[kLatTotal]),
};
bool refuse = kind[kLatTotal] != kLatSpanReported; // no total, or one no frame can have
for (uint32_t i = 0; i < kLatTotal; ++i) {
refuse = refuse || kind[i] == kLatSpanImpossible;
}
if (refuse) {
++tally.refused;
return;
}
++tally.frames;
for (uint32_t i = 0; i < kLatSpans; ++i) {
if (kind[i] == kLatSpanAbsent) {
tally.lacking |= 1u << i;
} else {
tally.sumUs[i] += us[i];
}
}
}
// One report: the frames newer than the cursor, the two newest left for the next read.
inline void ObserveLatencyReport(const NV_LATENCY_RESULT_PARAMS& lr, LatencyCursor& cursor,
LatencyTally& tally) noexcept {
tally = LatencyTally{};
uint64_t newest = 0u;
uint64_t second = 0u;
for (uint32_t i = 0; i < kLatReportFrames; ++i) {
if (LatencyFrameIsEmpty(lr.frameReport[i])) {
continue;
}
const uint64_t id = LatencyFrameId(lr.frameReport[i]);
if (id > newest) {
second = newest;
newest = id;
} else if (id > second && id != newest) {
second = id;
}
}
if (newest == 0u) {
return; // a report of nothing
}
if (newest < cursor.lastFrameId) {
cursor.lastFrameId = 0u; // the game's frame ids started again
}
uint64_t last = cursor.lastFrameId;
for (uint32_t i = 0; i < kLatReportFrames; ++i) {
if (LatencyFrameIsEmpty(lr.frameReport[i])) {
continue;
}
const uint64_t id = LatencyFrameId(lr.frameReport[i]);
if (id <= cursor.lastFrameId || id >= second) {
continue; // summed already, or one of the two newest
}
ObserveLatencyFrame(lr.frameReport[i], tally);
last = id > last ? id : last;
}
cursor.lastFrameId = last;
}
// The driver's sleep status: which of its five switches are on (bit n, in the struct's order -- fl_shm.h) and its
// frame-generation multiplier. The driver's words, not the game's: see FlLatencyState.
struct LatencySleep {
uint32_t on = 0;
uint32_t multiplier = 0; // its frame-generation multiplier
};
inline LatencySleep ObserveSleepStatus(const NV_GET_SLEEP_STATUS_PARAMS& ls) noexcept {
LatencySleep seen{};
seen.on = (ls.bLowLatencyMode != 0u ? 1u : 0u) | (ls.bFsVrr != 0u ? 2u : 0u) | (ls.bCplVsyncOn != 0u ? 4u : 0u) |
(ls.bUseGameSleep != 0u ? 8u : 0u) | (ls.bFullscreenIFlip != 0u ? 16u : 0u);
seen.multiplier = static_cast<uint32_t>(ls.fgMultiplier);
return seen;
}
// What the watchdog publishes of it. THE WATCHDOG'S: filled from what a read left behind while nobody is reading.
struct LatencyOut {
uint32_t state = FL_LAT_NONE; // FlLatencyState
uint32_t sleepSeenOn = 0; // switches the status showed on, since the request
uint32_t sleepSeenOff = 0; // ... and off
uint32_t multiplier = 0; // the last frame-generation multiplier the status gave
uint32_t reads = 0; // reads made since the request
uint32_t worstUs = 0; // the slowest call since the request
LatencyTally tally; // of the newest read not yet published; Publish empties it
};
inline uint32_t LatencySum(const LatencyTally& tally, uint32_t span) noexcept {
if (tally.frames == 0u) {
return 0u;
}
return (tally.lacking & (1u << span)) != 0u ? FL_LAT_SUM_NONE : tally.sumUs[span];
}
inline uint32_t Stop16(uint32_t value) noexcept {
return value > 0xFFFFu ? 0xFFFFu : value;
}
// A NEW REQUEST: the summaries start afresh, so a session's ranges, masks and
// counts are its own and not those of the session before it in the same game.
// THE WATCHDOG'S. A detour running beside it loses nothing that matters: what it
@@ -718,7 +897,11 @@ inline void Reset(Accumulators& a) noexcept {
// WATCHDOG'S, and only the watchdog's: one writer, so the seqlock is odd -> stores
// -> even with no compare-exchange. The frame-time pair is drained, so each
// publication carries the dispatches since the last one.
inline void Publish(Accumulators& a, FlAdvancedState* region, uint32_t request, uint64_t qpc) noexcept {
//
// `latency` is the watchdog's summary of the driver's latency report, or null for a caller that has none: the ten
// words are then left as they are -- zero, in a region nobody else writes.
inline void Publish(Accumulators& a, FlAdvancedState* region, uint32_t request, uint64_t qpc,
LatencyOut* latency = nullptr) noexcept {
if (region == nullptr) {
return;
}
@@ -742,6 +925,24 @@ inline void Publish(Accumulators& a, FlAdvancedState* region, uint32_t request,
put32(region->request, request);
put64(region->sampleQpc, qpc);
if (latency != nullptr) {
LatencyOut& out = *latency;
put32(region->latState, (out.state & FL_LAT_STATE_MASK) |
((out.sleepSeenOn & FL_LAT_SLEEP_BITS) << FL_LAT_SLEEP_SEEN_ON_SHIFT) |
((out.sleepSeenOff & FL_LAT_SLEEP_BITS) << FL_LAT_SLEEP_SEEN_OFF_SHIFT) |
((out.multiplier > 255u ? 255u : out.multiplier) << FL_LAT_FG_MULTIPLIER_SHIFT));
put32(region->latReads, Stop16(out.reads) | (Stop16(out.worstUs) << 16));
put32(region->latFrames, Stop16(out.tally.frames) | (Stop16(out.tally.refused) << 16));
put32(region->latSimulationSumUs, LatencySum(out.tally, 0u));
put32(region->latSubmitSumUs, LatencySum(out.tally, 1u));
put32(region->latPresentSumUs, LatencySum(out.tally, 2u));
put32(region->latDriverSumUs, LatencySum(out.tally, 3u));
put32(region->latOsQueueSumUs, LatencySum(out.tally, 4u));
put32(region->latGpuSumUs, LatencySum(out.tally, 5u));
put32(region->latTotalSumUs, LatencySum(out.tally, kLatTotal));
out.tally = LatencyTally{}; // one publication carries one read: a reader never adds two up
}
put32(region->dlssStructVersion, a.dlssStructVersion.load(relaxed));
put32(region->dlssOptionsSeen, a.dlssOptionsSeen.load(relaxed));
put32(region->dlssOutputWidth, a.dlssOutputWidth.load(relaxed));
@@ -0,0 +1,244 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// The two calls the Overlay makes into NVIDIA's driver, and how it finds them (Advanced metrics train C; owner
// decisions D132, D136, D138-D141; docs/spike-notes §30, §31; 17_HOOK_ENGINE §Memory / latency).
//
// NOT A HOOK. Every other thing the Overlay learns in a game is an argument of a call it hooks. These are calls the
// Overlay MAKES: NvAPI_D3D_GetLatency and NvAPI_D3D_GetSleepStatus, the driver's two read-only latency getters, with
// the Direct3D 12 device behind the swap chain it hooks (rule 4's note of 2026-11-13). Getters only: no marker, no
// sleep mode, no sleep, nothing that changes what the driver does.
//
// THE GAME BROUGHT THE MODULE. nvapi64.dll is looked for by name among the modules the process ALREADY holds and is
// never loaded. This file is not linked against nvapi64.lib -- that static library loads the DLL itself -- and takes
// only the vendored MIT headers' ids (nvapi_interface.h) and structs (nvapi.h). tools/nvapi-readonly-check.ps1 holds
// that the two ids below are the only NVAPI ids in code loaded into a game.
//
// A MODULE IN THE EXECUTABLE'S OWN FOLDER IS REFUSED (D140). The driver's nvapi64.dll lives in Windows' own
// directories; one beside the game is a replacement somebody put there, and FrameLedger neither calls into it on a
// presenting thread nor records its numbers as NVIDIA's.
//
// WHERE THE TWO ADDRESSES ARE (measured by the probe, driver 32.0.16.2114). System32's nvapi64.dll is a shim: it
// answers the two ids with addresses inside ANOTHER image, nvapi64_impl.dll in the driver's own store. So an address
// is accepted when it is executable code of an image the process has loaded -- never the heap, never nowhere -- and
// a reference is kept on THAT image as well, because the addresses are only code for as long as it stays loaded and
// the game may unload NVAPI while a presenting thread is about to call.
//
// SHARED WITH THE PROBE (tools/fl-probe-reflex), which is built with the Overlay's flags and enforces Control Flow
// Guard: its ctest runs THIS sequence. hook-harness does not enforce it, so the injected tests say nothing about CFG.
// nvapi64_impl.dll IS a CFG image; its getters are valid call targets, which the probe's real runs show by having
// made the calls from an enforcing process. A target that were not would be a fast-fail no guard catches: in a game
// that enforces CFG, on a driver nobody has run the probe against, that is not excluded.
#ifndef FRAMELEDGER_FL_REFLEX_H
#define FRAMELEDGER_FL_REFLEX_H
#include <windows.h>
// nvapi.h declares its Direct3D structs only after a Direct3D header, and names DXGI's swap chain in passing.
#include <d3d12.h>
#include <dxgi.h>
#include <cstdint>
#include <cstring>
#include <nvapi.h>
namespace fl::reflex {
inline constexpr unsigned int kIdGetSleepStatus = 0xaef96ca1u; // nvapi_interface.h: NvAPI_D3D_GetSleepStatus
inline constexpr unsigned int kIdGetLatency = 0x1a587f9cu; // nvapi_interface.h: NvAPI_D3D_GetLatency
inline constexpr DWORD kPathCapacity = 520;
using QueryInterfaceFn = void*(__cdecl*)(unsigned int);
// The status type under a name of its own: tools/nvapi-readonly-check.ps1 takes an `NvAPI_` name followed by a
// parenthesis for a call by name, and code loaded into a game makes none.
using Status = NvAPI_Status;
using GetLatencyFn = Status(__cdecl*)(IUnknown*, NV_LATENCY_RESULT_PARAMS*);
using GetSleepStatusFn = Status(__cdecl*)(IUnknown*, NV_GET_SLEEP_STATUS_PARAMS*);
struct Api {
GetLatencyFn getLatency = nullptr;
GetSleepStatusFn getSleepStatus = nullptr;
HMODULE nvapi = nullptr; // the nvapi64.dll that was asked; one reference is held
HMODULE owner = nullptr; // the image GetLatency's address is in; references are held
wchar_t modulePath[kPathCapacity]{}; // where nvapi64.dll was loaded from, for the log
wchar_t ownerPath[kPathCapacity]{}; // ... and the image the getters are in
};
enum class Resolved : std::uint32_t {
Ok = 0,
NoModule = 1, // the process has not loaded nvapi64.dll: nothing was called and nothing was loaded
NoQueryInterface = 2, // a module of that name without the export
NoGetter = 3, // it does not answer for both getters, or answered with an address in no loaded image
Refused = 4, // it sits in the executable's own folder, or its path could not be read (D140)
Faulted = 5, // asking it for the getters faulted
};
// The Overlay's own filter (dllmain.cpp's FlFilter): a debugger's exceptions are not ours to swallow.
inline LONG Filter(DWORD code) noexcept {
if (code == EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP) {
return EXCEPTION_CONTINUE_SEARCH;
}
return EXCEPTION_EXECUTE_HANDLER;
}
// The length of the directory part of a path, its last separator included; 0 when there is none.
inline DWORD DirectoryLength(const wchar_t* path, DWORD length) noexcept {
for (DWORD i = length; i > 0; --i) {
if (path[i - 1] == L'\\' || path[i - 1] == L'/') {
return i;
}
}
return 0;
}
// True when `nvapi` was loaded from the folder the process's executable is in -- or when either path cannot be read
// whole, which is refused the same way: what cannot be placed is not taken for the driver's.
inline bool InExecutableFolder(HMODULE nvapi, wchar_t* modulePath) noexcept {
wchar_t exePath[kPathCapacity]{};
const DWORD moduleLength = GetModuleFileNameW(nvapi, modulePath, kPathCapacity);
const DWORD exeLength = GetModuleFileNameW(nullptr, exePath, kPathCapacity);
if (moduleLength == 0 || moduleLength >= kPathCapacity || exeLength == 0 || exeLength >= kPathCapacity) {
return true;
}
const DWORD moduleDir = DirectoryLength(modulePath, moduleLength);
const DWORD exeDir = DirectoryLength(exePath, exeLength);
if (moduleDir == 0 || exeDir == 0) {
return true;
}
return CompareStringOrdinal(modulePath, static_cast<int>(moduleDir), exePath, static_cast<int>(exeDir), TRUE) ==
CSTR_EQUAL;
}
// The loaded image `address` is executable code of, with a reference taken on it -- or null. A getter's address
// comes from the module's own answer; this refuses one that is not code of an image before it is ever called, and
// keeps the image that holds it from being unloaded under a later call.
inline HMODULE OwnerImage(const void* address) noexcept {
MEMORY_BASIC_INFORMATION info{};
if (address == nullptr || VirtualQuery(address, &info, sizeof(info)) == 0) {
return nullptr;
}
const DWORD executable = PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
if (info.Type != MEM_IMAGE || info.State != MEM_COMMIT || (info.Protect & executable) == 0u) {
return nullptr;
}
HMODULE owner = nullptr;
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, static_cast<LPCWSTR>(address), &owner)) {
return nullptr;
}
return owner;
}
// The module's answers for the two ids, asked under a guard: the lookup runs the module's code.
inline bool AskForGetters(QueryInterfaceFn query, void*& latency, void*& sleepStatus, DWORD& faultCode) noexcept {
__try {
latency = query(kIdGetLatency);
sleepStatus = query(kIdGetSleepStatus);
return true;
} __except (Filter(GetExceptionCode())) {
faultCode = GetExceptionCode();
return false;
}
}
// Finds the two getters in a module the process ALREADY holds; never loads one.
//
// A REFERENCE IS TAKEN WHEN THE MODULE IS FOUND, and kept whatever is returned after that -- as the Overlay's
// ResolveScoped keeps the one on a module it patches -- so the caller must not call again once this has returned
// anything but NoModule: every other answer is final for the process. One more is taken on the image each getter is
// in. None is ever released: a presenting thread may be inside one of the calls.
inline Resolved Resolve(Api& api, DWORD& faultCode) noexcept {
api.getLatency = nullptr;
api.getSleepStatus = nullptr;
api.nvapi = nullptr;
api.owner = nullptr;
api.modulePath[0] = L'\0';
api.ownerPath[0] = L'\0';
faultCode = 0;
HMODULE nvapi = nullptr;
if (!GetModuleHandleExW(0, L"nvapi64.dll", &nvapi) || nvapi == nullptr) {
return Resolved::NoModule;
}
api.nvapi = nvapi;
if (InExecutableFolder(nvapi, api.modulePath)) {
return Resolved::Refused;
}
const auto query = reinterpret_cast<QueryInterfaceFn>(GetProcAddress(nvapi, "nvapi_QueryInterface"));
if (query == nullptr) {
return Resolved::NoQueryInterface;
}
void* latency = nullptr;
void* sleepStatus = nullptr;
if (!AskForGetters(query, latency, sleepStatus, faultCode)) {
return Resolved::Faulted;
}
const HMODULE latencyOwner = OwnerImage(latency);
const HMODULE statusOwner = OwnerImage(sleepStatus);
if (latencyOwner == nullptr || statusOwner == nullptr) {
return Resolved::NoGetter;
}
api.owner = latencyOwner;
if (const DWORD length = GetModuleFileNameW(latencyOwner, api.ownerPath, kPathCapacity);
length == 0 || length >= kPathCapacity) {
api.ownerPath[0] = L'\0';
}
api.getLatency = reinterpret_cast<GetLatencyFn>(latency);
api.getSleepStatus = reinterpret_cast<GetSleepStatusFn>(sleepStatus);
return Resolved::Ok;
}
inline Resolved Resolve(Api& api) noexcept {
DWORD faultCode = 0;
return Resolve(api, faultCode);
}
// What a read returns when the driver's code faulted under it: not one of NVAPI's own codes.
inline constexpr NvAPI_Status kFaulted = static_cast<NvAPI_Status>(-9999);
// One read of the driver's report. Guarded -- the first guard the Overlay puts around code that is not its own
// (17_HOOK_ENGINE §Fault policy says why this one is). A guard does not bound a call that never returns, and a
// caught fault does not give back a lock the driver held: the caller makes no second call after either.
inline NvAPI_Status ReadLatency(const Api& api, IUnknown* device, NV_LATENCY_RESULT_PARAMS& out,
DWORD& faultCode) noexcept {
std::memset(&out, 0, sizeof(out));
out.version = NV_LATENCY_RESULT_PARAMS_VER1;
if (api.getLatency == nullptr || device == nullptr) {
return NVAPI_INVALID_ARGUMENT;
}
__try {
return api.getLatency(device, &out);
} __except (Filter(GetExceptionCode())) {
faultCode = GetExceptionCode();
return kFaulted;
}
}
inline NvAPI_Status ReadSleepStatus(const Api& api, IUnknown* device, NV_GET_SLEEP_STATUS_PARAMS& out,
DWORD& faultCode) noexcept {
std::memset(&out, 0, sizeof(out));
out.version = NV_GET_SLEEP_STATUS_PARAMS_VER1;
if (api.getSleepStatus == nullptr || device == nullptr) {
return NVAPI_INVALID_ARGUMENT;
}
__try {
return api.getSleepStatus(device, &out);
} __except (Filter(GetExceptionCode())) {
faultCode = GetExceptionCode();
return kFaulted;
}
}
inline NvAPI_Status ReadLatency(const Api& api, IUnknown* device, NV_LATENCY_RESULT_PARAMS& out) noexcept {
DWORD faultCode = 0;
return ReadLatency(api, device, out, faultCode);
}
inline NvAPI_Status ReadSleepStatus(const Api& api, IUnknown* device, NV_GET_SLEEP_STATUS_PARAMS& out) noexcept {
DWORD faultCode = 0;
return ReadSleepStatus(api, device, out, faultCode);
}
} // namespace fl::reflex
#endif // FRAMELEDGER_FL_REFLEX_H
+287 -4
View File
@@ -165,6 +165,7 @@ enum FlLogCode : uint32_t {
kLogRuntimeCensus,
kLogFfxConfigureType,
kLogPatchBatch,
kLogLatency,
};
const char* LogCodeName(uint32_t code) noexcept {
@@ -207,6 +208,8 @@ const char* LogCodeName(uint32_t code) noexcept {
return "FFX_CONFIGURE";
case kLogPatchBatch:
return "PATCH_BATCH";
case kLogLatency:
return "LATENCY";
default:
return "?";
}
@@ -580,6 +583,9 @@ struct SwapChainSlot {
uint32_t swapEffect = 0; // DXGI_SWAP_EFFECT + 1 (fl_shm.h §Region 4: DISCARD is 0); 0 = not read
uint32_t swapFlags = 0; // DXGI_SWAP_CHAIN_DESC.Flags
uint64_t displayQpc = 0; // the QPC of this chain's last display sample
// This chain's device is the one g_d3d12Device holds -- the first Direct3D 12 device seen, which is not "this
// chain's" for a title with two. The driver's latency report is read only at such a chain's present.
bool heldDevice = false;
};
// Region 4 (fl_shm.h, layout 4, beta.10): set in InitThread beside g_state, written only through PublishDisplay.
@@ -735,6 +741,268 @@ void PublishD3D12Device(ID3D12Device* device) noexcept {
}
}
// ---------------------------------------------------------------------------------------------------------------------
// REFLEX LATENCY: THE ONE CALL THE OVERLAY MAKES INTO A DRIVER (Advanced metrics train C; owner decisions D132, D136,
// D138-D141; fl_reflex.h; spike-notes §31; 17_HOOK_ENGINE §Memory / latency).
//
// While a session asks for Advanced metrics, and only then, the driver's two read-only latency getters are called
// about once a second with the Direct3D 12 device held above -- through an nvapi64.dll THE GAME had already loaded.
// Nothing is hooked for it and nothing is loaded for it.
//
// WHO DOES WHAT. The WATCHDOG finds the module and the two addresses, once for the process, and arms the gate at
// most once a second. A PRESENTING THREAD that finds the gate armed makes the read, after its frame's record is
// published: a call the driver holds stops the thread that made it, and the watchdog -- which supervises, installs
// and flushes -- must never be that thread (spike-notes §31, M2). So the call delays one present a second by its own
// length: 0.5-2.6 us measured, and one of 2 ms or more is the last one this process makes (D141).
//
// THE GATE, four states in one word, is what makes that safe without a lock:
// idle nobody is reading. g_latRead is the watchdog's: it takes what the last read left, then may arm.
// armed one read is wanted. Only the watchdog stores this.
// reading a presenting thread took `armed` by compare-exchange and is inside the read. g_latRead and
// g_latReport are that thread's. Two presenting threads cannot both be here, and the watchdog reads
// nothing of theirs while one is.
// off a read ended in a fault or took too long. Final for the process; g_latRead is the watchdog's again.
// A present pays one relaxed load for all of it.
//
// WHAT STOPS IT, each until the game exits: a fault in a getter (guarded, counted once in faultCount -- with the
// gate off it cannot be counted again, so it cannot reach the three that self-disable); a call of 2 ms or more; and
// a call that has not returned after two seconds, which nothing can stop -- that one is logged, flushed at once and
// published as stalled, and the gate is left where the stuck thread holds it.
// ---------------------------------------------------------------------------------------------------------------------
constexpr uint32_t kLatGateIdle = 0u;
constexpr uint32_t kLatGateArmed = 1u;
constexpr uint32_t kLatGateReading = 2u;
constexpr uint32_t kLatGateOff = 3u;
constexpr uint32_t kLatSlowMicros = 2000u; // owner decision D141
std::atomic<uint32_t> g_latGate{kLatGateIdle};
// Written by the watchdog before the gate is first armed, and never after.
fl::reflex::Api g_latApi;
// What one read left behind. Owned by whoever the gate says (above).
struct LatencyRead {
fl::adv::LatencyTally tally;
fl::adv::LatencyCursor cursor;
uint32_t fresh = 0; // a read finished since the watchdog last looked
uint32_t ok = 0; // its report came back NVAPI_OK
uint32_t state = 0; // FL_LAT_READING, _ERROR, _SLOW or _FAULTED after it
uint32_t micros = 0; // the slower of its two calls
uint32_t sleepValid = 0; // the sleep status came back NVAPI_OK
fl::adv::LatencySleep sleep;
};
LatencyRead g_latRead;
// 15.4 KB, in static storage: the report is never on a game thread's stack.
NV_LATENCY_RESULT_PARAMS g_latReport;
// The watchdog's own.
fl::adv::LatencyOut g_latOut;
bool g_latResolved = false; // the two addresses are in g_latApi
bool g_latFinal = false; // the module was looked at and will not be read; g_latOut.state says why
bool g_latStalled = false;
int64_t g_latArmedQpc = 0;
int64_t g_latReadingSinceQpc = 0;
uint32_t g_latLoggedState = FL_LAT_NONE;
// One read, on a presenting thread that found the gate armed. Not inlined: RecordPresent stays as small as it was.
__declspec(noinline) void ReadLatencyOnce() noexcept {
uint32_t armed = kLatGateArmed;
if (!g_latGate.compare_exchange_strong(armed, kLatGateReading, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
return; // another presenting thread has it
}
auto* device = static_cast<IUnknown*>(g_d3d12Device.load(std::memory_order_acquire));
LatencyRead& read = g_latRead;
read.fresh = 1u;
read.ok = 0u;
read.sleepValid = 0u;
read.tally = fl::adv::LatencyTally{};
DWORD fault = 0;
const int64_t began = QpcNow();
const NvAPI_Status status = fl::reflex::ReadLatency(g_latApi, device, g_latReport, fault);
uint32_t micros = MicrosSince(began);
if (status == fl::reflex::kFaulted) {
read.state = FL_LAT_FAULTED;
read.micros = micros;
g_latGate.store(kLatGateOff, std::memory_order_release);
NoteFault(fault, "NvAPI_D3D_GetLatency (the driver's)");
return;
}
if (status == NVAPI_OK) {
fl::adv::ObserveLatencyReport(g_latReport, read.cursor, read.tally);
read.ok = 1u;
read.state = FL_LAT_READING;
} else {
read.state = FL_LAT_ERROR;
}
if (micros < kLatSlowMicros) {
NV_GET_SLEEP_STATUS_PARAMS sleepStatus; // 128 bytes
const int64_t beganStatus = QpcNow();
const NvAPI_Status second = fl::reflex::ReadSleepStatus(g_latApi, device, sleepStatus, fault);
const uint32_t microsStatus = MicrosSince(beganStatus);
micros = microsStatus > micros ? microsStatus : micros;
if (second == fl::reflex::kFaulted) {
read.state = FL_LAT_FAULTED;
read.micros = micros;
g_latGate.store(kLatGateOff, std::memory_order_release);
NoteFault(fault, "NvAPI_D3D_GetSleepStatus (the driver's)");
return;
}
if (second == NVAPI_OK) {
read.sleep = fl::adv::ObserveSleepStatus(sleepStatus);
read.sleepValid = 1u;
}
}
read.micros = micros;
if (micros >= kLatSlowMicros) {
read.state = FL_LAT_SLOW;
g_latGate.store(kLatGateOff, std::memory_order_release);
return;
}
g_latGate.store(kLatGateIdle, std::memory_order_release);
}
const char* LatencyStateName(uint32_t state) noexcept {
switch (state) {
case FL_LAT_NO_DEVICE:
return "no Direct3D 12 device behind a hooked swap chain";
case FL_LAT_NO_MODULE:
return "the game has not loaded nvapi64.dll";
case FL_LAT_REFUSED:
return "refused: nvapi64.dll is in the game's own folder";
case FL_LAT_NO_GETTER:
return "nvapi64.dll does not answer for the two getters";
case FL_LAT_READING:
return "reading the driver's latency report";
case FL_LAT_ERROR:
return "the driver answered with an error";
case FL_LAT_SLOW:
return "off: a call into the driver was slow";
case FL_LAT_FAULTED:
return "off: a call into the driver faulted";
case FL_LAT_STALLED:
return "off: a call into the driver has not returned";
default:
return "not asked";
}
}
// THE WATCHDOG'S HALF, once a tick while a session asks. `now` is this tick's QPC.
void TickLatency(bool newRequest, int64_t now) noexcept {
if (newRequest) {
// A session's counts are its own; where the read stands is the process's and stays.
g_latOut.reads = 0u;
g_latOut.worstUs = 0u;
g_latOut.sleepSeenOn = 0u;
g_latOut.sleepSeenOff = 0u;
g_latOut.multiplier = 0u;
g_latOut.tally = fl::adv::LatencyTally{};
}
if (g_latStalled) {
return; // the gate belongs to a thread that is not coming back; nothing of g_latRead is read again
}
const uint32_t gate = g_latGate.load(std::memory_order_acquire);
if (gate == kLatGateReading) {
if (g_latReadingSinceQpc == 0) {
g_latReadingSinceQpc = now;
} else if (static_cast<uint64_t>(now - g_latReadingSinceQpc) >= 2u * g_logQpcFreq) {
g_latStalled = true;
g_latOut.state = FL_LAT_STALLED;
g_latLoggedState = FL_LAT_STALLED;
LogNote(kLogLatency, LatencyStateName(FL_LAT_STALLED), FL_LAT_STALLED, 0u);
FlushLog(); // the game is about to be closed by hand: what is known is written now
}
return;
}
g_latReadingSinceQpc = 0;
// Idle, armed or off: nobody is reading. What the last read left is taken here.
if (gate != kLatGateArmed && g_latRead.fresh != 0u) {
g_latRead.fresh = 0u;
g_latOut.reads += 1u;
g_latOut.worstUs = g_latRead.micros > g_latOut.worstUs ? g_latRead.micros : g_latOut.worstUs;
g_latOut.state = g_latRead.state;
if (g_latRead.ok != 0u) {
g_latOut.tally = g_latRead.tally;
fl::adv::NoteBits(g_adv.validMask, FL_ADV_VALID_LATENCY);
}
if (g_latRead.sleepValid != 0u) {
g_latOut.sleepSeenOn |= g_latRead.sleep.on & FL_LAT_SLEEP_BITS;
g_latOut.sleepSeenOff |= ~g_latRead.sleep.on & FL_LAT_SLEEP_BITS;
g_latOut.multiplier = g_latRead.sleep.multiplier;
}
if (g_latOut.state != g_latLoggedState) {
g_latLoggedState = g_latOut.state;
LogNote(kLogLatency, LatencyStateName(g_latOut.state), g_latOut.state, g_latRead.micros);
}
}
if (gate != kLatGateIdle || g_latFinal) {
return; // armed and waiting for a present, or off for good
}
if (!g_latResolved) {
uint32_t state = FL_LAT_NO_DEVICE;
if (g_d3d12Device.load(std::memory_order_acquire) != nullptr) {
DWORD fault = 0;
switch (fl::reflex::Resolve(g_latApi, fault)) {
case fl::reflex::Resolved::Ok:
g_latResolved = true;
state = FL_LAT_READING;
break;
case fl::reflex::Resolved::NoModule:
state = FL_LAT_NO_MODULE; // asked again next tick: a game may load it late
break;
case fl::reflex::Resolved::Refused:
g_latFinal = true;
state = FL_LAT_REFUSED;
break;
case fl::reflex::Resolved::Faulted:
g_latFinal = true;
state = FL_LAT_FAULTED;
NoteFault(fault, "nvapi_QueryInterface (the driver's)");
break;
case fl::reflex::Resolved::NoQueryInterface:
case fl::reflex::Resolved::NoGetter:
g_latFinal = true;
state = FL_LAT_NO_GETTER;
break;
}
}
g_latOut.state = state;
if (state != g_latLoggedState) {
g_latLoggedState = state;
LogNote(kLogLatency, LatencyStateName(state), state, reinterpret_cast<uint64_t>(g_latApi.nvapi));
// Where nvapi64.dll was loaded from, and the image its getters are in (the driver's own
// nvapi64_impl.dll on the driver the probe ran against): the end of each path, which is what fits a line.
const size_t room = sizeof(FlLogEvent::text) - 1u;
for (const wchar_t* path : {g_latApi.modulePath, g_latApi.ownerPath}) {
if (path[0] != L'\0') {
// Bounded by the buffer both paths live in (fl_reflex.h): never a walk off its end.
const size_t length = wcsnlen(path, fl::reflex::kPathCapacity);
LogNoteW(kLogLatency, path + (length > room ? length - room : 0u), state,
reinterpret_cast<uint64_t>(path == g_latApi.modulePath ? g_latApi.nvapi : g_latApi.owner));
}
}
}
if (!g_latResolved) {
return;
}
}
if (g_latArmedQpc == 0 || static_cast<uint64_t>(now - g_latArmedQpc) >= g_logQpcFreq) {
g_latArmedQpc = now;
g_latGate.store(kLatGateArmed, std::memory_order_release);
}
}
// The request went off: a read that was wanted and not yet made is not made in a session that never asked.
void DisarmLatency() noexcept {
uint32_t armed = kLatGateArmed;
g_latGate.compare_exchange_strong(armed, kLatGateIdle, std::memory_order_acq_rel, std::memory_order_relaxed);
}
// Which API this swapchain belongs to, asked of the swapchain itself.
//
// One hook sees every swapchain in the process, and a D3D11 title and a D3D12
@@ -750,7 +1018,8 @@ void PublishD3D12Device(ID3D12Device* device) noexcept {
// FL_API_UNKNOWN when neither answers. 0 is the honest value for "we could not
// tell", and it is what the enum reserves it for -- guessing D3D11 is how the
// field became wrong in the first place.
uint8_t ResolveApi(IDXGISwapChain* sc) noexcept {
uint8_t ResolveApi(IDXGISwapChain* sc, bool& heldDevice) noexcept {
heldDevice = false;
IUnknown* dev = nullptr;
if (FAILED(sc->GetDevice(__uuidof(IUnknown), reinterpret_cast<void**>(&dev))) || dev == nullptr) {
return FL_API_UNKNOWN;
@@ -776,6 +1045,7 @@ uint8_t ResolveApi(IDXGISwapChain* sc) noexcept {
// installer needs a live device to read a command list's vtable off, and it
// runs on the watchdog thread, which has no swapchain of its own.
PublishD3D12Device(d12);
heldDevice = g_d3d12Device.load(std::memory_order_acquire) == static_cast<void*>(d12);
d12->Release();
} else if (SUCCEEDED(dev->QueryInterface(__uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&queue))) &&
queue != nullptr) {
@@ -807,7 +1077,7 @@ SwapChainSlot* FindOrAdd(IDXGISwapChain* sc) noexcept {
if (SUCCEEDED(sc->GetDesc(&desc))) {
RememberDesc(s, desc);
}
s.api = ResolveApi(sc);
s.api = ResolveApi(sc, s.heldDevice);
// apiMask records what we have ACTUALLY seen present, not what the
// process happens to have loaded: a game can link d3d12.dll and
// present through D3D11.
@@ -3291,7 +3561,8 @@ DWORD WatchdogLoop() noexcept {
// a count never spans two sessions of a game that kept running.
std::atomic_ref<uint32_t> advancedReq{g_control->advancedRequested};
const uint32_t advancedNow = advancedReq.load(std::memory_order_acquire);
if (advancedNow != 0u && advancedNow != g_advancedSeen) {
const bool advancedIsNew = advancedNow != 0u && advancedNow != g_advancedSeen;
if (advancedIsNew) {
fl::adv::Reset(g_adv);
g_advancedSeen = advancedNow;
}
@@ -3300,7 +3571,12 @@ DWORD WatchdogLoop() noexcept {
// Initialised through QuadPart, the member read below, so that it is the active one (cpp:S6232).
LARGE_INTEGER advancedQpc{.QuadPart = 0};
QueryPerformanceCounter(&advancedQpc);
fl::adv::Publish(g_adv, g_advanced, advancedNow, static_cast<uint64_t>(advancedQpc.QuadPart));
// The driver's latency report (train C): what the last read left is taken, and the next one armed,
// BEFORE the publication -- so the publication carries the read, and carries it once.
TickLatency(advancedIsNew, advancedQpc.QuadPart);
fl::adv::Publish(g_adv, g_advanced, advancedNow, static_cast<uint64_t>(advancedQpc.QuadPart), &g_latOut);
} else {
DisarmLatency();
}
// The in-process stop, for a title that is NOT presenting (menu, hung,
@@ -3952,6 +4228,13 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
// a writer that FORGETS is now honest by construction.
g_writer.Publish(rec);
// THE DRIVER'S LATENCY REPORT (train C), after the record: one relaxed load a present, and a call only when the
// watchdog armed one -- about once a second, while a session asks for Advanced metrics, at a chain whose device
// is the one held. See ReadLatencyOnce.
if (g_latGate.load(std::memory_order_relaxed) == kLatGateArmed && slot != nullptr && slot->heldDevice) {
ReadLatencyOnce();
}
}
// ---------------------------------------------------------------------------
+17 -1
View File
@@ -148,12 +148,16 @@ target_compile_definitions(fl_guard_test PRIVATE
FL_STUB_SL_INTERPOSER=L"$<TARGET_FILE:fl_stub_sl_interposer>"
# The ffx-api loader stub, so a test can read one of its exports' first bytes out of a target (0.1.0-beta.43).
FL_STUB_FFX_LOADER=L"$<TARGET_FILE:fl_stub_ffx_loader>"
# The stand-in nvapi64.dll (train C): the target loads it, and the tests turn its knobs and read its call counts
# through the named section fl_stub_nvapi_shared.h describes.
FL_STUB_NVAPI64=L"$<TARGET_FILE:fl_stub_nvapi64>"
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.
FL_OVERLAY_DLL_ELSEWHERE=L"$<TARGET_FILE:FrameLedger.Overlay>"
)
add_dependencies(fl_guard_test hook-harness FrameLedger.Overlay fl_stage_overlay_payload)
add_dependencies(fl_guard_test hook-harness FrameLedger.Overlay fl_stage_overlay_payload fl_stub_nvapi64)
target_include_directories(fl_guard_test PRIVATE "${CMAKE_SOURCE_DIR}/tools/vendor-stubs")
add_test(NAME fl_guard COMMAND fl_guard_test)
fl_catch2_test_completes(fl_guard)
@@ -191,6 +195,18 @@ target_compile_definitions(fl_unhook_inline_test PRIVATE WIN32_LEAN_AND_MEAN NOM
add_test(NAME fl_unhook_inline COMMAND fl_unhook_inline_test)
fl_catch2_test_completes(fl_unhook_inline)
# fl_adv_fields.h's reader of the driver's latency report (Advanced metrics train C): the header the Overlay
# compiles, on reports written by hand -- the two newest frames held back, a span the driver did not report, a span
# no frame can have, frame ids that start again, and the ten words of a publication.
add_executable(fl_reflex_summary_test reflex_summary_test.cpp)
target_include_directories(fl_reflex_summary_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include")
target_link_libraries(fl_reflex_summary_test PRIVATE FrameLedger.Shm fl_native_flags fl_streamline_headers
fl_fidelityfx_headers fl_nvapi_headers Catch2::Catch2WithMain)
target_compile_options(fl_reflex_summary_test PRIVATE /EHsc)
target_compile_definitions(fl_reflex_summary_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
add_test(NAME fl_reflex_summary COMMAND fl_reflex_summary_test)
fl_catch2_test_completes(fl_reflex_summary)
# fl_ffx_types.h (0.1.0-beta.42, D121): the descriptor types an ffx-api module was handed, kept by the detours for
# the native log. The header the Overlay compiles, driven without the Overlay -- including from eight threads.
add_executable(fl_ffx_types_test ffx_types_test.cpp)
+455
View File
@@ -1843,6 +1843,7 @@ TEST_CASE(
// to, which is the only part of this suite that has a live Overlay to inspect.
#include <fl_ring.h>
#include <fl_shm.h>
#include <fl_stub_nvapi_shared.h>
#include <fl_tolerance.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.
@@ -7654,3 +7655,457 @@ TEST_CASE("region 5 carries what a Streamline title chains into its evaluation,
WARN("the stop's one apply restored " << restoredByBatch << " patches in " << restoreMicros << " us");
CHECK(restoreMicros < 1000000ull);
}
// =====================================================================================================================
// REFLEX LATENCY (Advanced metrics train C; owner decisions D132, D136, D138-D141; fl_reflex.h; fl_shm.h's latency
// words). The one thing the Overlay does in a game that is not reading a hooked call's arguments: a call of its own
// into the driver, once a second, on the presenting thread. Against a Direct3D 12 target that has loaded a stand-in
// nvapi64.dll (tools/vendor-stubs/stub_nvapi64.cpp), whose knobs and call counts the test reads from outside through
// the stub's named section -- so "the driver was not called" is a count, not an inference.
//
// NOT PROVEN HERE: anything about Control Flow Guard (hook-harness does not enforce it; ctest fl_reflex_probe_stub
// runs the same header in a process that does), and anything about a real driver.
// =====================================================================================================================
namespace {
struct StubNv {
HANDLE section = nullptr;
fl::stubnv::Shared* words = nullptr;
~StubNv() {
if (words != nullptr) {
UnmapViewOfFile(words);
}
if (section != nullptr) {
CloseHandle(section);
}
}
};
bool OpenStubNv(DWORD pid, StubNv& stub) {
wchar_t name[64]{};
if (_snwprintf_s(name, _TRUNCATE, fl::stubnv::kSectionFormat, pid) <= 0) {
return false;
}
for (int i = 0; i < 100 && stub.section == nullptr; ++i) {
stub.section = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (stub.section == nullptr) {
Sleep(50);
}
}
if (stub.section == nullptr) {
return false;
}
stub.words = static_cast<fl::stubnv::Shared*>(
MapViewOfFile(stub.section, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, sizeof(fl::stubnv::Shared)));
return stub.words != nullptr;
}
uint32_t StubWord(const uint32_t& word) {
return std::atomic_ref<const uint32_t>{word}.load(std::memory_order_relaxed);
}
void SetStubWord(uint32_t& word, uint32_t value) {
std::atomic_ref<uint32_t>{word}.store(value, std::memory_order_relaxed);
}
struct LatencyTarget {
Child child;
MappedRing r;
StubNv stub;
};
// The harness -- `exe`, or the built one -- started with `args`, injected, its ring opened; and the stub's section
// opened when the target was told to load one.
bool StartLatencyTarget(LatencyTarget& t, const std::wstring& args, bool withStub,
const wchar_t* exe = FL_HARNESS_EXE) {
std::wstring cmd = std::wstring(L"\"") + exe + L"\" " + args;
STARTUPINFOW si{};
si.cb = sizeof(si);
if (!CreateProcessW(exe, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
&t.child.pi)) {
return false;
}
Sleep(800);
if (WaitForSingleObject(t.child.pi.hProcess, 0) != WAIT_TIMEOUT) {
return false;
}
if (withStub && !OpenStubNv(t.child.pi.dwProcessId, t.stub)) {
return false;
}
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {t.child.pi.dwProcessId};
if (!GuardedInjectWithSources(t.child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed()) {
return false;
}
return OpenRingFor(t.child.pi.dwProcessId, t.r) && t.r.st != nullptr && t.r.ctl != nullptr;
}
std::wstring LatencyArgs(const wchar_t* presenting) {
return std::wstring(L"--real --load \"") + FL_STUB_NVAPI64 + L"\" " + presenting;
}
uint32_t LatStateOf(const fl::FlAdvancedState& a) {
return a.latState & FL_LAT_STATE_MASK;
}
// A consistent copy of region 5 as it is now, or false while the watchdog is inside it.
bool CopyAdvanced(const MappedRing& r, fl::FlAdvancedState& out) {
fl::FlAdvancedState* region = RegionFive(r);
std::atomic_ref<uint32_t> seq{region->seq};
const uint32_t before = seq.load(std::memory_order_acquire);
if (before == 0u || (before & 1u) != 0u) {
return false;
}
fl::FlAdvancedState copy{};
std::memcpy(&copy, region, sizeof(copy));
std::atomic_thread_fence(std::memory_order_seq_cst);
if (seq.load(std::memory_order_acquire) != before) {
return false;
}
out = copy;
return true;
}
// Waits, bounded, for a publication that answers `request` and whose latency state is `want`.
bool WaitForLatState(const MappedRing& r, uint32_t request, uint32_t want, fl::FlAdvancedState& out) {
uint32_t after = 0u;
for (int i = 0; i < 14; ++i) {
fl::FlAdvancedState a{};
if (!ReadAdvanced(r, request, a, after)) {
return false;
}
after = a.samples;
if (LatStateOf(a) == want) {
out = a;
return true;
}
}
return false;
}
// What a run of publications showed: every one that carried frames carried the stub's numbers.
struct LatencySeen {
uint32_t withFrames = 0;
uint32_t reads = 0;
uint32_t state = 0;
bool framesRight = true;
bool sumsRight = true;
bool driverSpanAbsent = false;
};
void WatchLatency(const MappedRing& r, uint32_t request, int ms, LatencySeen& seen) {
uint32_t lastSamples = 0u;
for (int waited = 0; waited < ms; waited += 50) {
++r.ctl->guardTicks;
fl::FlAdvancedState a{};
if (CopyAdvanced(r, a) && a.request == request && a.samples != lastSamples) {
lastSamples = a.samples;
seen.state = LatStateOf(a);
seen.reads = a.latReads & 0xFFFFu;
const uint32_t frames = a.latFrames & 0xFFFFu;
if (frames != 0u) {
++seen.withFrames;
// Sixty-four frames less the two newest the first time; after that the ten the stub moved on by.
seen.framesRight = seen.framesRight && (frames == 62u || frames == fl::stubnv::kFrameIdStep) &&
(a.latFrames >> 16) == 0u;
seen.driverSpanAbsent = seen.driverSpanAbsent || a.latDriverSumUs == FL_LAT_SUM_NONE;
seen.sumsRight =
seen.sumsRight && a.latSimulationSumUs == frames * fl::stubnv::kSimulationUs &&
a.latSubmitSumUs == frames * fl::stubnv::kSubmitUs &&
a.latPresentSumUs == frames * fl::stubnv::kPresentUs &&
(a.latDriverSumUs == frames * fl::stubnv::kDriverUs || a.latDriverSumUs == FL_LAT_SUM_NONE) &&
a.latOsQueueSumUs == frames * fl::stubnv::kOsQueueUs &&
a.latGpuSumUs == frames * fl::stubnv::kGpuUs && a.latTotalSumUs == frames * fl::stubnv::kTotalUs;
}
}
Sleep(50);
}
}
// The present hook is recording: these targets load no upscaler, so there is no hook family to wait for.
bool WaitForRecords(const MappedRing& r) {
for (int i = 0; i < 120; ++i) {
++r.ctl->guardTicks;
if (r.st->writeIndex >= 10u) {
return true;
}
Sleep(50);
}
return false;
}
bool TargetHasModule(HANDLE process, const wchar_t* leaf) {
HMODULE modules[1024]{};
DWORD needed = 0;
if (!EnumProcessModules(process, modules, sizeof(modules), &needed)) {
return false;
}
const DWORD count = needed / sizeof(HMODULE) < 1024u ? needed / sizeof(HMODULE) : 1024u;
for (DWORD i = 0; i < count; ++i) {
wchar_t name[MAX_PATH]{};
if (GetModuleBaseNameW(process, modules[i], name, MAX_PATH) != 0 && _wcsicmp(name, leaf) == 0) {
return true;
}
}
return false;
}
} // namespace
TEST_CASE("the driver's latency report is read only while a session asks, once a second, and stops with the request "
"and with the hooks",
"[guard][inject][shm][advanced][latency]") {
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, LatencyArgs(L"--hold-presenting-d3d12 45"), true));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub == nullptr || r.st == nullptr || r.ctl == nullptr) {
return; // not reached after the REQUIRE; said in the form a static analyser follows (cpp:S2259)
}
REQUIRE(WaitForRecords(r));
// ---- 1. NOT ASKED. The module is there, the device is there, the chain presents -- and nothing is asked of the
// module, not even for the two addresses.
const std::uint64_t atHooks = r.st->writeIndex;
TickFor(r, 3200);
REQUIRE(r.st->writeIndex > atHooks + 30u);
CHECK(RegionFiveIsZero(r));
CHECK(StubWord(stub->queries) == 0u);
CHECK(StubWord(stub->latencyCalls) == 0u);
CHECK(StubWord(stub->sleepStatusCalls) == 0u);
// ---- 2. ASKED. The first publication with the bit carries a read.
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState a{};
REQUIRE(ReadAdvanced(r, 7u, a, 0u, fl::FL_ADV_VALID_LATENCY));
CHECK(LatStateOf(a) == fl::FL_LAT_READING);
CHECK(((a.latState >> FL_LAT_SLEEP_SEEN_ON_SHIFT) & FL_LAT_SLEEP_BITS) == (1u | 8u)); // the stub's status
CHECK(((a.latState >> FL_LAT_SLEEP_SEEN_OFF_SHIFT) & FL_LAT_SLEEP_BITS) == (2u | 4u | 16u));
CHECK((a.latState >> FL_LAT_FG_MULTIPLIER_SHIFT) == 2u);
CHECK((a.latReads >> 16) < 2000u); // no call of two milliseconds: that would have been the last one
LatencySeen seen;
WatchLatency(r, 7u, 5200, seen);
INFO("publications with frames " << seen.withFrames << ", reads " << seen.reads << ", stub calls "
<< StubWord(stub->latencyCalls) << ", state " << seen.state);
CHECK(seen.state == fl::FL_LAT_READING);
CHECK(seen.withFrames >= 2u);
CHECK(seen.framesRight);
CHECK(seen.sumsRight);
// ABOUT ONCE A SECOND: some seven seconds since the request. Not ten, and not hundreds.
CHECK(seen.reads >= 3u);
CHECK(seen.reads <= 9u);
// Every read the Overlay counts is a call the stub received, and at most one more is on its way to be counted.
const uint32_t calls = StubWord(stub->latencyCalls);
CHECK(calls >= seen.reads);
CHECK(calls <= seen.reads + 2u);
CHECK(StubWord(stub->queries) == 2u); // the two addresses, asked for once
CHECK(r.st->faultCount == 0u);
CHECK(r.st->status == fl::FL_STATUS_READY);
REQUIRE(ReadAdvanced(r, 7u, a, a.samples));
WARN("the slowest of " << (a.latReads & 0xFFFFu) << " reads took " << (a.latReads >> 16) << " us");
// ---- 3. A span the driver does not report reads "none", and its frames are still summed; an error is an error,
// and reading goes on after it.
SetStubWord(stub->mode, fl::stubnv::kModeNoDriverSpan);
LatencySeen withoutDriverSpan;
WatchLatency(r, 7u, 3200, withoutDriverSpan);
CHECK(withoutDriverSpan.driverSpanAbsent);
CHECK(withoutDriverSpan.sumsRight);
SetStubWord(stub->mode, fl::stubnv::kModeError);
REQUIRE(WaitForLatState(r, 7u, fl::FL_LAT_ERROR, a));
CHECK((a.validMask & fl::FL_ADV_VALID_LATENCY) != 0u); // a read did return OK in this session
SetStubWord(stub->mode, fl::stubnv::kModeReports);
REQUIRE(WaitForLatState(r, 7u, fl::FL_LAT_READING, a));
// ---- 4. NOT ASKED AGAIN. No further call.
SetAdvancedRequest(r, 0u);
TickFor(r, 2500); // the watchdog has seen the zero, and a read already under way has ended
const uint32_t callsWhenOff = StubWord(stub->latencyCalls);
TickFor(r, 3000);
CHECK(StubWord(stub->latencyCalls) == callsWhenOff);
// ---- 5. A SECOND SESSION of a target that kept running: its count is its own, and the module is not asked for
// the addresses again.
SetAdvancedRequest(r, 9u);
REQUIRE(ReadAdvanced(r, 9u, a, 0u, fl::FL_ADV_VALID_LATENCY));
CHECK(LatStateOf(a) == fl::FL_LAT_READING);
CHECK((a.latReads & 0xFFFFu) <= 3u);
CHECK(StubWord(stub->queries) == 2u);
// ---- 6. THE STOP while a session asks: nothing is called after it.
r.ctl->unhookRequested = 1;
for (int i = 0; i < 100 && r.st->status != fl::FL_STATUS_UNHOOKED; ++i) {
Sleep(50);
}
REQUIRE(r.st->status == fl::FL_STATUS_UNHOOKED);
Sleep(300); // a read that was under way when the stop landed
const uint32_t callsWhenStopped = StubWord(stub->latencyCalls);
Sleep(2500);
CHECK(StubWord(stub->latencyCalls) == callsWhenStopped);
CHECK(r.st->faultCount == 0u);
}
TEST_CASE("a call into the driver that takes fifty milliseconds is the last one, and the game goes on",
"[guard][inject][shm][advanced][latency]") {
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, LatencyArgs(L"--hold-presenting-d3d12 16"), true));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub == nullptr || r.st == nullptr || r.ctl == nullptr) {
return;
}
REQUIRE(WaitForRecords(r));
SetStubWord(stub->blockMs, 50u);
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState a{};
REQUIRE(WaitForLatState(r, 7u, fl::FL_LAT_SLOW, a)); // owner decision D141: one call of 2 ms or more
CHECK((a.latReads >> 16) >= 40000u); // the microseconds it took are published
CHECK(StubWord(stub->latencyCalls) == 1u);
CHECK(StubWord(stub->sleepStatusCalls) == 0u); // nor the second getter after a slow first
const std::uint64_t index = r.st->writeIndex;
TickFor(r, 3000);
CHECK(StubWord(stub->latencyCalls) == 1u);
CHECK(r.st->writeIndex > index + 30u); // presents are still recorded
CHECK(r.st->status == fl::FL_STATUS_READY);
CHECK(r.st->faultCount == 0u);
fl::FlAdvancedState later{};
REQUIRE(ReadAdvanced(r, 7u, later, a.samples));
CHECK(LatStateOf(later) == fl::FL_LAT_SLOW);
}
TEST_CASE("a fault inside the driver's getter is caught, counted once, and ends the reads; the hooks stay",
"[guard][inject][shm][advanced][latency]") {
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, LatencyArgs(L"--hold-presenting-d3d12 16"), true));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub == nullptr || r.st == nullptr || r.ctl == nullptr) {
return;
}
REQUIRE(WaitForRecords(r));
SetStubWord(stub->mode, fl::stubnv::kModeFault);
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState a{};
REQUIRE(WaitForLatState(r, 7u, fl::FL_LAT_FAULTED, a));
CHECK((a.validMask & fl::FL_ADV_VALID_LATENCY) == 0u); // no read ever returned OK
CHECK(r.st->faultCount == 1u);
CHECK(StubWord(stub->latencyCalls) == 1u);
const std::uint64_t index = r.st->writeIndex;
TickFor(r, 3200);
CHECK(StubWord(stub->latencyCalls) == 1u); // not called again: one fault cannot become three
CHECK(r.st->faultCount == 1u);
CHECK(r.st->status == fl::FL_STATUS_READY); // the Overlay did not disable itself
CHECK(r.st->writeIndex > index + 30u);
}
TEST_CASE("a module that does not answer for the getters is asked once and never called",
"[guard][inject][shm][advanced][latency]") {
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, LatencyArgs(L"--hold-presenting-d3d12 14"), true));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub == nullptr || r.st == nullptr || r.ctl == nullptr) {
return;
}
REQUIRE(WaitForRecords(r));
SetStubWord(stub->hideGetters, 1u);
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState a{};
REQUIRE(WaitForLatState(r, 7u, fl::FL_LAT_NO_GETTER, a));
CHECK(StubWord(stub->queries) == 2u);
SetStubWord(stub->hideGetters, 0u); // too late, by design: the answer was final for the process
TickFor(r, 2600);
CHECK(StubWord(stub->queries) == 2u);
CHECK(StubWord(stub->latencyCalls) == 0u);
REQUIRE(ReadAdvanced(r, 7u, a, a.samples));
CHECK(LatStateOf(a) == fl::FL_LAT_NO_GETTER);
CHECK(r.st->faultCount == 0u);
}
TEST_CASE("a game that has not loaded nvapi64.dll is not given one", "[guard][inject][shm][advanced][latency]") {
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, L"--real --hold-presenting-d3d12 12", false));
const MappedRing& r = t.r;
if (r.st == nullptr || r.ctl == nullptr) {
return;
}
REQUIRE(WaitForRecords(r));
REQUIRE_FALSE(TargetHasModule(t.child.pi.hProcess, L"nvapi64.dll")); // or this case proves nothing
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState a{};
REQUIRE(WaitForLatState(r, 7u, fl::FL_LAT_NO_MODULE, a));
CHECK((a.validMask & fl::FL_ADV_VALID_LATENCY) == 0u);
TickFor(r, 2200);
CHECK_FALSE(TargetHasModule(t.child.pi.hProcess, L"nvapi64.dll")); // asked for by name, never loaded
CHECK(r.st->faultCount == 0u);
}
TEST_CASE("an nvapi64.dll in the executable's own folder is refused and never asked anything",
"[guard][inject][shm][advanced][latency]") {
// Owner decision D140. The driver's module lives in Windows' own directories; one beside the game is a
// replacement. A copy of the harness with a copy of the stand-in beside it is that arrangement.
FILETIME started{};
GetSystemTimeAsFileTime(&started);
wchar_t temp[MAX_PATH]{};
REQUIRE(GetTempPathW(MAX_PATH, temp) != 0);
const std::wstring dir = std::wstring(temp) + L"fl-latency-" + std::to_wstring(GetCurrentProcessId()) + L"-" +
std::to_wstring(GetTickCount64());
REQUIRE(CreateDirectoryW(dir.c_str(), nullptr));
const std::wstring exe = dir + L"\\hook-harness.exe";
const std::wstring beside = dir + L"\\nvapi64.dll";
REQUIRE(CopyFileW(FL_HARNESS_EXE, exe.c_str(), TRUE));
REQUIRE(CopyFileW(FL_STUB_NVAPI64, beside.c_str(), TRUE));
{
LatencyTarget t;
REQUIRE(
StartLatencyTarget(t, L"--real --load \"" + beside + L"\" --hold-presenting-d3d12 12", true, exe.c_str()));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub != nullptr && r.st != nullptr && r.ctl != nullptr) {
REQUIRE(WaitForRecords(r));
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState a{};
CHECK(WaitForLatState(r, 7u, fl::FL_LAT_REFUSED, a));
TickFor(r, 2200);
CHECK(StubWord(stub->queries) == 0u); // not even asked for the addresses
CHECK(StubWord(stub->latencyCalls) == 0u);
CHECK(r.st->faultCount == 0u);
}
} // the target is gone before its files are removed
// The run's sweep removes the logs of THIS BUILD'S harness by its path; this copy has another, so its log is
// removed here -- or it would be left in the real data folder, which tools/test-artifacts-check.ps1 fails.
if (std::wstring logs; fl::testing::RealOverlayLogsDir(logs)) {
static_cast<void>(fl::testing::SweepHarnessLogs(logs, started, exe));
}
DeleteFileW(beside.c_str());
DeleteFileW(exe.c_str());
RemoveDirectoryW(dir.c_str());
}
TEST_CASE("a Direct3D 11 title is not read: the Overlay holds no device of its",
"[guard][inject][shm][advanced][latency]") {
LatencyTarget t;
REQUIRE(StartLatencyTarget(t, LatencyArgs(L"--hold-presenting 12"), true));
const MappedRing& r = t.r;
fl::stubnv::Shared* stub = t.stub.words;
if (stub == nullptr || r.st == nullptr || r.ctl == nullptr) {
return;
}
REQUIRE(WaitForRecords(r));
SetAdvancedRequest(r, 7u);
fl::FlAdvancedState a{};
REQUIRE(WaitForLatState(r, 7u, fl::FL_LAT_NO_DEVICE, a));
TickFor(r, 2600);
CHECK(StubWord(stub->queries) == 0u);
CHECK(StubWord(stub->latencyCalls) == 0u);
CHECK((a.validMask & fl::FL_ADV_VALID_LATENCY) == 0u);
}
+243
View File
@@ -0,0 +1,243 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// fl_adv_fields.h's reader of the driver's latency report (Advanced metrics train C; spike-notes §31), driven
// without the Overlay and without a driver: the header the Overlay compiles, on reports written here by hand.
//
// What it holds is what a real report made necessary. The newest frames of a report are not final -- one run of the
// probe read a span of half an hour in the newest -- so the two newest are never summed. An end point of zero is a
// span the driver did not report, not a fault of the frame: without a sleep mode it leaves driverStartTime zero in
// every frame, and a reader that refused those frames would refuse every frame of such a game. A span that runs
// backwards or lasts over a second is refused with its frame. And a game whose frame ids start again must not be
// read as a game that has stopped.
#include <catch2/catch_test_macros.hpp>
#include <cstdint>
#include <fl_adv_fields.h>
#include <memory>
namespace {
using Frame = NV_LATENCY_RESULT_PARAMS::FrameReport;
// A frame as the stand-in module writes one: every span reported, 7500 us from simulation start to the GPU's end.
Frame Whole(std::uint64_t id) {
Frame f{};
const std::uint64_t t = 1'000'000ull + id * 4200ull;
f.frameID = id;
f.simStartTime = t + 100u;
f.simEndTime = t + 900u; // 800
f.renderSubmitStartTime = t + 950u;
f.renderSubmitEndTime = t + 2100u; // 1150
f.presentStartTime = t + 2150u;
f.presentEndTime = t + 2300u; // 150
f.driverStartTime = t + 2300u;
f.driverEndTime = t + 2700u; // 400
f.osRenderQueueStartTime = t + 2700u;
f.osRenderQueueEndTime = t + 3900u; // 1200
f.gpuRenderStartTime = t + 3900u;
f.gpuRenderEndTime = t + 7600u; // 3700; total 7500
return f;
}
// The report is 15 KB: on the heap here, as it is in static storage in the Overlay.
std::unique_ptr<NV_LATENCY_RESULT_PARAMS> Report(std::uint64_t firstId, std::uint32_t frames = 64u) {
auto report = std::make_unique<NV_LATENCY_RESULT_PARAMS>();
for (std::uint32_t i = 0; i < frames; ++i) {
report->frameReport[64u - frames + i] = Whole(firstId + i); // the newest last, as the driver writes it
}
return report;
}
} // namespace
TEST_CASE("a report's two newest frames are left for the next read, and a frame is summed once", "[latency]") {
fl::adv::LatencyCursor cursor;
fl::adv::LatencyTally tally;
auto first = Report(5000u);
fl::adv::ObserveLatencyReport(*first, cursor, tally);
CHECK(tally.frames == 62u); // 5000..5061; 5062 and 5063 are not final yet
CHECK(tally.refused == 0u);
CHECK(tally.lacking == 0u);
CHECK(tally.sumUs[0] == 62u * 800u);
CHECK(tally.sumUs[1] == 62u * 1150u);
CHECK(tally.sumUs[2] == 62u * 150u);
CHECK(tally.sumUs[3] == 62u * 400u);
CHECK(tally.sumUs[4] == 62u * 1200u);
CHECK(tally.sumUs[5] == 62u * 3700u);
CHECK(tally.sumUs[fl::adv::kLatTotal] == 62u * 7500u);
CHECK(cursor.lastFrameId == 5061u);
// The same report again: nothing is new.
fl::adv::ObserveLatencyReport(*first, cursor, tally);
CHECK(tally.frames == 0u);
CHECK(tally.refused == 0u);
CHECK(cursor.lastFrameId == 5061u);
// Ten frames further on: the two that were held back and eight more, and again not the two newest.
auto second = Report(5010u);
fl::adv::ObserveLatencyReport(*second, cursor, tally);
CHECK(tally.frames == 10u); // 5062..5071
CHECK(tally.sumUs[fl::adv::kLatTotal] == 10u * 7500u);
CHECK(cursor.lastFrameId == 5071u);
}
TEST_CASE("a report of nothing, of one frame and of two sums nothing", "[latency]") {
fl::adv::LatencyCursor cursor;
fl::adv::LatencyTally tally;
tally.frames = 9u; // whatever was there is replaced, not added to
auto empty = Report(0u, 0u);
fl::adv::ObserveLatencyReport(*empty, cursor, tally);
CHECK(tally.frames == 0u);
CHECK(cursor.lastFrameId == 0u);
auto one = Report(700u, 1u);
fl::adv::ObserveLatencyReport(*one, cursor, tally);
CHECK(tally.frames == 0u);
auto two = Report(700u, 2u);
fl::adv::ObserveLatencyReport(*two, cursor, tally);
CHECK(tally.frames == 0u);
CHECK(tally.refused == 0u);
auto three = Report(700u, 3u);
fl::adv::ObserveLatencyReport(*three, cursor, tally);
CHECK(tally.frames == 1u); // 700; 701 and 702 wait
CHECK(cursor.lastFrameId == 700u);
}
TEST_CASE("an end point of zero is a span the driver did not report: the frame is summed and the span reads none",
"[latency]") {
fl::adv::LatencyCursor cursor;
fl::adv::LatencyTally tally;
auto report = Report(100u);
for (auto& f : report->frameReport) {
f.driverStartTime = 0u; // what the driver gives a game that sets markers and no sleep mode
}
fl::adv::ObserveLatencyReport(*report, cursor, tally);
CHECK(tally.frames == 62u);
CHECK(tally.refused == 0u);
CHECK(tally.lacking == (1u << 3));
CHECK(tally.sumUs[3] == 0u);
CHECK(tally.sumUs[fl::adv::kLatTotal] == 62u * 7500u);
// What is published for it: the sum of a span some summed frame lacked is all ones, never a smaller number.
CHECK(fl::adv::LatencySum(tally, 3u) == FL_LAT_SUM_NONE);
CHECK(fl::adv::LatencySum(tally, 0u) == 62u * 800u);
CHECK(fl::adv::LatencySum(fl::adv::LatencyTally{}, 0u) == 0u); // no frame: zero, not "none"
}
TEST_CASE("a span no frame can have refuses the frame whole, and so does a frame with no total", "[latency]") {
fl::adv::LatencyCursor cursor;
fl::adv::LatencyTally tally;
auto report = Report(100u);
report->frameReport[0].presentEndTime = report->frameReport[0].presentStartTime - 50u; // backwards
report->frameReport[1].gpuRenderEndTime = report->frameReport[1].simStartTime + 1'844'674'519ull; // half an hour
report->frameReport[2].gpuRenderEndTime = 0u; // no total
report->frameReport[3].simStartTime = 0u; // no total
report->frameReport[4].osRenderQueueEndTime = report->frameReport[4].osRenderQueueStartTime + 1'000'001ull;
report->frameReport[5].osRenderQueueEndTime = report->frameReport[5].osRenderQueueStartTime + 1'000'000ull;
fl::adv::ObserveLatencyReport(*report, cursor, tally);
CHECK(tally.refused == 5u);
CHECK(tally.frames == 57u); // 62 that are not the two newest, less the five; frame 5's second is still a span
CHECK(tally.lacking == 0u);
CHECK(tally.sumUs[2] == 57u * 150u); // the backwards present added nothing
CHECK(tally.sumUs[4] == 56u * 1200u + 1'000'000u); // exactly a second is allowed; a microsecond more is not
CHECK(cursor.lastFrameId == 161u); // a refused frame is not looked at again either
}
TEST_CASE("frame ids that start again restart the reader instead of silencing it", "[latency]") {
fl::adv::LatencyCursor cursor;
fl::adv::LatencyTally tally;
auto late = Report(90'000u);
fl::adv::ObserveLatencyReport(*late, cursor, tally);
REQUIRE(cursor.lastFrameId == 90'061u);
auto again = Report(1u); // the game went back to its menu and counts from one
fl::adv::ObserveLatencyReport(*again, cursor, tally);
CHECK(tally.frames == 62u);
CHECK(cursor.lastFrameId == 62u);
}
TEST_CASE("the frames are found whatever order the driver left them in", "[latency]") {
fl::adv::LatencyCursor cursor;
fl::adv::LatencyTally tally;
auto report = Report(300u);
const Frame newest = report->frameReport[63];
report->frameReport[63] = report->frameReport[10];
report->frameReport[10] = newest; // the newest id is in the middle now
fl::adv::ObserveLatencyReport(*report, cursor, tally);
CHECK(tally.frames == 62u);
CHECK(cursor.lastFrameId == 361u); // 362 and 363 are the two newest wherever they sit
}
TEST_CASE("the sleep status is the driver's five switches and its multiplier, and nothing else of it", "[latency]") {
NV_GET_SLEEP_STATUS_PARAMS status{};
CHECK(fl::adv::ObserveSleepStatus(status).on == 0u);
status.bLowLatencyMode = 1;
status.bCplVsyncOn = 1;
status.bFullscreenIFlip = 1;
status.fgMultiplier = 3;
status.sleepIntervalUs = 4166u; // changes with every frame: not kept
const fl::adv::LatencySleep seen = fl::adv::ObserveSleepStatus(status);
CHECK(seen.on == (1u | 4u | 16u));
CHECK(seen.multiplier == 3u);
status = NV_GET_SLEEP_STATUS_PARAMS{};
status.bFsVrr = 1;
status.bUseGameSleep = 1;
CHECK(fl::adv::ObserveSleepStatus(status).on == (2u | 8u));
}
TEST_CASE("a publication carries one read, packed as fl_shm.h says, and carries it once", "[latency]") {
fl::adv::Accumulators a;
fl::FlAdvancedState region{};
fl::adv::LatencyOut out;
out.state = fl::FL_LAT_READING;
out.sleepSeenOn = 1u | 8u;
out.sleepSeenOff = 2u | 4u | 16u;
out.multiplier = 2u;
out.reads = 70'000u; // stops at 65535
out.worstUs = 66u;
out.tally.frames = 10u;
out.tally.refused = 1u;
for (std::uint32_t i = 0; i < fl::adv::kLatSpans; ++i) {
out.tally.sumUs[i] = 1000u * (i + 1u);
}
out.tally.lacking = 1u << 3;
fl::adv::Publish(a, &region, 7u, 1234u, &out);
CHECK((region.latState & FL_LAT_STATE_MASK) == fl::FL_LAT_READING);
CHECK(((region.latState >> FL_LAT_SLEEP_SEEN_ON_SHIFT) & FL_LAT_SLEEP_BITS) == (1u | 8u));
CHECK(((region.latState >> FL_LAT_SLEEP_SEEN_OFF_SHIFT) & FL_LAT_SLEEP_BITS) == (2u | 4u | 16u));
CHECK((region.latState >> FL_LAT_FG_MULTIPLIER_SHIFT) == 2u);
CHECK((region.latReads & 0xFFFFu) == 0xFFFFu);
CHECK((region.latReads >> 16) == 66u);
CHECK((region.latFrames & 0xFFFFu) == 10u);
CHECK((region.latFrames >> 16) == 1u);
CHECK(region.latSimulationSumUs == 1000u);
CHECK(region.latSubmitSumUs == 2000u);
CHECK(region.latPresentSumUs == 3000u);
CHECK(region.latDriverSumUs == FL_LAT_SUM_NONE);
CHECK(region.latOsQueueSumUs == 5000u);
CHECK(region.latGpuSumUs == 6000u);
CHECK(region.latTotalSumUs == 7000u);
CHECK(region.request == 7u);
// The next publication, with no read in between: the state stands, the frames and the sums are gone.
fl::adv::Publish(a, &region, 7u, 1235u, &out);
CHECK((region.latState & FL_LAT_STATE_MASK) == fl::FL_LAT_READING);
CHECK(region.latFrames == 0u);
CHECK(region.latTotalSumUs == 0u);
CHECK(region.latDriverSumUs == 0u);
CHECK((region.latReads >> 16) == 66u);
// A caller with no latency summary leaves the ten words alone.
fl::FlAdvancedState untouched{};
fl::adv::Publish(a, &untouched, 7u, 1236u);
CHECK(untouched.latState == 0u);
CHECK(untouched.latReads == 0u);
CHECK(untouched.latTotalSumUs == 0u);
}
+10
View File
@@ -156,6 +156,16 @@ add_library(fl_nvapi INTERFACE)
target_include_directories(fl_nvapi SYSTEM INTERFACE
"${CMAKE_CURRENT_SOURCE_DIR}/nvapi"
)
# THE HEADERS ALONE, for code that is loaded into a game (Advanced metrics train C, owner decision D136). The Overlay
# calls two of the driver's getters through an nvapi64.dll the GAME had already loaded (fl_reflex.h); it takes the
# vendored MIT headers' structs and ids and must never link nvapi64.lib, whose first call loads the DLL. So this is
# the include directory and nothing else. tools/hookinventory-check.ps1 Pass C reads the built Overlay's import table
# for an nvapi module, and tools/nvapi-readonly-check.ps1 holds which ids the Overlay may name.
add_library(fl_nvapi_headers INTERFACE)
target_include_directories(fl_nvapi_headers SYSTEM INTERFACE
"${CMAKE_CURRENT_SOURCE_DIR}/nvapi"
)
target_link_libraries(fl_nvapi INTERFACE
"${CMAKE_CURRENT_SOURCE_DIR}/nvapi/amd64/nvapi64.lib"
)
@@ -1,16 +1,18 @@
# fl-probe-reflex -- the instrument of docs/spike-notes §31 (Reflex route D, owner decision D132). A tool, NOT
# SHIPPED, and it touches no game.
#
# BUILT WITH THE OVERLAY'S OWN FLAGS (fl_hostile_env_flags), as fl-probe-hookprofile is: fl_reflex_candidate.h is the
# call sequence that would move into the Overlay if the owner says go, and a probe built otherwise would prove
# nothing about it there.
# BUILT WITH THE OVERLAY'S OWN FLAGS (fl_hostile_env_flags), as fl-probe-hookprofile is, AND FROM THE OVERLAY'S OWN
# HEADER: the call sequence is FrameLedger.Overlay/include/fl_reflex.h since the owner said go (D136), and this probe
# includes it. So its ctest runs what ships, with Control Flow Guard enforced -- which hook-harness, the target of
# the injected tests, does not enforce.
#
# THE NVAPI HEADERS, NOT THE NVAPI LIBRARY. The include directory of the vendored MIT headers is taken by itself;
# fl_nvapi -- which also links nvapi64.lib -- is deliberately not: the static library loads nvapi64.dll itself, from
# a trusted location, with a signature check, and route D's shape is that the process already has the module.
add_executable(fl-probe-reflex main.cpp)
target_link_libraries(fl-probe-reflex PRIVATE fl_native_flags fl_hostile_env_flags d3d11 d3d12 dxgi)
target_include_directories(fl-probe-reflex SYSTEM PRIVATE "${CMAKE_SOURCE_DIR}/third_party/nvapi")
target_link_libraries(fl-probe-reflex PRIVATE fl_nvapi_headers)
target_include_directories(fl-probe-reflex PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include")
target_compile_definitions(fl-probe-reflex PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
add_dependencies(fl-probe-reflex fl_stub_nvapi64)
@@ -1,102 +1,21 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// The call sequence Reflex route D would put into the Overlay (docs/spike-notes §30, §31; owner decision D132) --
// HERE, IN A PROBE, AND NOWHERE THAT SHIPS. Nothing loaded into a game includes this file. If the owner says go after
// the spike, this is what moves; until then it exists to be measured.
// What the probe adds to the call sequence it measures (docs/spike-notes §30, §31).
//
// WHAT IT DOES: finds NVIDIA's nvapi64.dll in the process IF IT IS ALREADY LOADED -- it never loads it -- asks its one
// export for the two getters by their interface ids, and calls them with a Direct3D device. Getters only: no marker,
// no sleep mode, no sleep, nothing that changes what the driver does (rule 4's note of 2026-11-13).
//
// NOT LINKED AGAINST nvapi64.lib. The static library loads the DLL itself, from a trusted location and with a
// signature check, on its first call; route D's whole shape is that the game brought the module and FrameLedger adds
// nothing to the process. The ids are the vendored header's (nvapi_interface.h), the structs nvapi.h's.
// THE SEQUENCE ITSELF MOVED. Until the owner said go (D136) the candidate lived here and nowhere that ships; it is now
// FrameLedger.Overlay/include/fl_reflex.h, the header the Overlay is built from, and this probe includes that one --
// so its ctest keeps running the shipped sequence, under the Overlay's flags and with Control Flow Guard enforced.
// What stays here is the probe's own way of printing a report, which the Overlay does not use: its reader is
// fl_adv_fields.h's, with the rules a game needs (the newest frames are not final, an impossible span is refused).
#ifndef FRAMELEDGER_FL_REFLEX_CANDIDATE_H
#define FRAMELEDGER_FL_REFLEX_CANDIDATE_H
#include <windows.h>
#include <d3d11.h>
#include <cstdint>
#include <cstring>
#include <nvapi.h>
#include <fl_reflex.h>
namespace fl::reflex {
inline constexpr unsigned int kIdGetSleepStatus = 0xaef96ca1u; // nvapi_interface.h: NvAPI_D3D_GetSleepStatus
inline constexpr unsigned int kIdGetLatency = 0x1a587f9cu; // nvapi_interface.h: NvAPI_D3D_GetLatency
using QueryInterfaceFn = void*(__cdecl*)(unsigned int);
using GetLatencyFn = NvAPI_Status(__cdecl*)(IUnknown*, NV_LATENCY_RESULT_PARAMS*);
using GetSleepStatusFn = NvAPI_Status(__cdecl*)(IUnknown*, NV_GET_SLEEP_STATUS_PARAMS*);
struct Api {
GetLatencyFn getLatency = nullptr;
GetSleepStatusFn getSleepStatus = nullptr;
};
enum class Resolved : std::uint32_t {
Ok = 0,
NoModule = 1, // the process has not loaded nvapi64.dll: nothing was called and nothing was loaded
NoQueryInterface = 2, // a module of that name without the export
NoGetter = 3, // the module does not have one of the two getters
};
// Finds the two getters in a module the process ALREADY holds. Takes a reference on it (as the Overlay's
// ResolveScoped does on a module it patches) so the addresses stay valid; never loads a module.
inline Resolved Resolve(Api& api) noexcept {
api = Api{};
HMODULE nvapi = nullptr;
if (!GetModuleHandleExW(0, L"nvapi64.dll", &nvapi) || nvapi == nullptr) {
return Resolved::NoModule;
}
const auto query = reinterpret_cast<QueryInterfaceFn>(GetProcAddress(nvapi, "nvapi_QueryInterface"));
if (query == nullptr) {
return Resolved::NoQueryInterface;
}
api.getLatency = reinterpret_cast<GetLatencyFn>(query(kIdGetLatency));
api.getSleepStatus = reinterpret_cast<GetSleepStatusFn>(query(kIdGetSleepStatus));
if (api.getLatency == nullptr || api.getSleepStatus == nullptr) {
api = Api{};
return Resolved::NoGetter;
}
return Resolved::Ok;
}
// What a read returns when the driver's code faulted under it: not one of NVAPI's own codes.
inline constexpr NvAPI_Status kFaulted = static_cast<NvAPI_Status>(-9999);
// One read of the driver's report. SEH-guarded as every call the Overlay makes into foreign code is; a guard does not
// bound a call that never returns, which is why the probe measures that separately.
inline NvAPI_Status ReadLatency(const Api& api, IUnknown* device, NV_LATENCY_RESULT_PARAMS& out) noexcept {
std::memset(&out, 0, sizeof(out));
out.version = NV_LATENCY_RESULT_PARAMS_VER1;
if (api.getLatency == nullptr || device == nullptr) {
return NVAPI_INVALID_ARGUMENT;
}
__try {
return api.getLatency(device, &out);
} __except (EXCEPTION_EXECUTE_HANDLER) {
return kFaulted;
}
}
inline NvAPI_Status ReadSleepStatus(const Api& api, IUnknown* device, NV_GET_SLEEP_STATUS_PARAMS& out) noexcept {
std::memset(&out, 0, sizeof(out));
out.version = NV_GET_SLEEP_STATUS_PARAMS_VER1;
if (api.getSleepStatus == nullptr || device == nullptr) {
return NVAPI_INVALID_ARGUMENT;
}
__try {
return api.getSleepStatus(device, &out);
} __except (EXCEPTION_EXECUTE_HANDLER) {
return kFaulted;
}
}
// What a report holds, in numbers: how many of its sixty-four frames carry anything, and the newest one's id and
// two spans in the report's own unit -- simulation start to present end (the game's side) and to the end of GPU work.
struct Digest {
+16
View File
@@ -729,6 +729,22 @@ int RunReal(int pollSeconds) noexcept {
static NV_LATENCY_RESULT_PARAMS report;
NV_GET_SLEEP_STATUS_PARAMS sleep{};
// WHERE THE TWO ADDRESSES ARE. The module answers with addresses that need not be its own: the image each one
// lies in is printed, because the Overlay refuses an address that is in no image at all (fl_reflex.h, InImage).
const unsigned int getterIds[2] = {fl::reflex::kIdGetLatency, fl::reflex::kIdGetSleepStatus};
for (const unsigned int id : getterIds) {
const void* address = query(id);
MEMORY_BASIC_INFORMATION info{};
wchar_t owner[MAX_PATH]{};
if (address != nullptr && VirtualQuery(address, &info, sizeof(info)) != 0) {
GetModuleFileNameW(static_cast<HMODULE>(info.AllocationBase), owner, MAX_PATH);
}
std::printf("id 0x%08x -> %p: type 0x%lx, protect 0x%lx, in %ls%s\n", id, address,
static_cast<unsigned long>(info.Type), static_cast<unsigned long>(info.Protect),
owner[0] != 0 ? owner : L"(no image)",
info.AllocationBase == static_cast<void*>(nvapi) ? " (nvapi64.dll itself)" : "");
}
// R0. THE GETTERS BEFORE NvAPI_Initialize -- a game that has the module but has not initialised it.
std::printf("Resolve with the module loaded: %u (0 = Ok)\n", static_cast<unsigned>(fl::reflex::Resolve(api)));
PrintDigest("R0 before NvAPI_Initialize:", fl::reflex::ReadLatency(api, dx11.device, report), report);
+1 -1
View File
@@ -19,7 +19,7 @@ add_executable(hook-harness main.cpp vk_hold.cpp gl_hold.cpp hwnd_hold.cpp proxy
# --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_vulkan_headers opengl32 gdi32)
fl_fidelityfx_headers fl_fsr3_host_headers fl_vulkan_headers fl_nvapi_headers opengl32 gdi32)
target_include_directories(hook-harness PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include")
target_compile_definitions(hook-harness PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// The knobs and counters of the stand-in nvapi64.dll (stub_nvapi64.cpp), as a named section another process can open.
//
// WHY A SECTION. The probe loads the stub into itself and calls its exports. The injected tests cannot: the stub is
// in the harness's process, and a test that asks "did the Overlay call the driver at all" has to read the stub's
// count from outside -- the harness's output is not captured. The stub creates `Local\FrameLedger.StubNvapi.<pid>`
// when it is loaded and keeps every knob and count in it; the exports the probe calls write the same words.
//
// A TEST FIXTURE'S, in a fixture's own namespace of names. Nothing shipped opens it.
#ifndef FRAMELEDGER_FL_STUB_NVAPI_SHARED_H
#define FRAMELEDGER_FL_STUB_NVAPI_SHARED_H
#include <cstdint>
namespace fl::stubnv {
// What GetLatency does (`mode`).
enum Mode : std::uint32_t {
kModeReports = 0, // sixty-four frames, their ids ten further on at every call
kModeNothing = 1, // OK and a report of nothing: a game that sets no marker
kModeError = 2, // NVAPI_ERROR, from both getters
kModeFault = 3, // an access violation inside GetLatency
kModeNoDriverSpan = 4, // reports whose driverStartTime is zero: what the driver gives without a sleep mode
kModeImpossible = 5, // reports whose present ends before it starts
};
// One frame of kModeReports, in microseconds: every frame has these spans.
inline constexpr std::uint32_t kSimulationUs = 800u;
inline constexpr std::uint32_t kSubmitUs = 1150u;
inline constexpr std::uint32_t kPresentUs = 150u;
inline constexpr std::uint32_t kDriverUs = 400u;
inline constexpr std::uint32_t kOsQueueUs = 1200u;
inline constexpr std::uint32_t kGpuUs = 3700u;
inline constexpr std::uint32_t kTotalUs = 7500u;
inline constexpr std::uint32_t kFirstFrameId = 5000u;
inline constexpr std::uint32_t kFrameIdStep = 10u; // how far the ids move on at each call
// Plain words, read and written with interlocked operations on both sides.
struct Shared {
std::uint32_t mode; // Mode
std::uint32_t blockMs; // GetLatency sleeps this long before it answers
std::uint32_t hideGetters; // nvapi_QueryInterface answers null for both getters
std::uint32_t queries; // nvapi_QueryInterface calls
std::uint32_t latencyCalls; // GetLatency calls
std::uint32_t sleepStatusCalls; // GetSleepStatus calls
std::uint32_t reserved[2];
};
inline constexpr wchar_t kSectionFormat[] = L"Local\\FrameLedger.StubNvapi.%lu";
} // namespace fl::stubnv
#endif // FRAMELEDGER_FL_STUB_NVAPI_SHARED_H
+83 -31
View File
@@ -1,16 +1,21 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// A stand-in for NVIDIA's nvapi64.dll, for the spike of Reflex route D (docs/spike-notes §31, owner decision D132).
// A stand-in for NVIDIA's nvapi64.dll, for Reflex route D (docs/spike-notes §31; owner decisions D132, D136).
//
// NOT A VENDOR LIBRARY AND NOT SHIPPED. It carries the one name the real module's callers resolve everything through
// -- nvapi_QueryInterface -- and answers two interface ids, the two getters route D would call:
// -- nvapi_QueryInterface -- and answers two interface ids, the two getters route D calls:
// NvAPI_D3D_GetLatency and NvAPI_D3D_GetSleepStatus. The ids and the structs are the vendored MIT headers' own
// (nvapi_interface.h, nvapi.h), so the probe and this stub cannot disagree about either.
// (nvapi_interface.h, nvapi.h), so its callers and this stub cannot disagree about either.
//
// WHAT IT IS FOR: the things a real driver cannot be made to do on demand. A getter that is not there, a report of
// nothing, an error, and a call that does not come back for seconds -- so that the probe can show each is harmless
// before anything is tried against a driver, and long before anything is tried in a game.
// nothing, an error, a fault, a span the driver did not report, a span no frame can have, and a call that does not
// come back for a while -- so that each can be shown harmless before anything is tried against a driver, and long
// before anything is tried in a game.
//
// TWO CALLERS. The probe (tools/fl-probe-reflex) loads it into itself and turns its knobs through the exports
// below. The injected tests load it into hook-harness and turn the same knobs, and read the same counts, through the
// named section fl_stub_nvapi_shared.h describes.
#include <windows.h>
@@ -18,7 +23,9 @@
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fl_stub_nvapi_shared.h>
#include <nvapi.h>
namespace {
@@ -27,21 +34,45 @@ constexpr unsigned int kIdInitialize = 0x0150e828u;
constexpr unsigned int kIdGetSleepStatus = 0xaef96ca1u;
constexpr unsigned int kIdGetLatency = 0x1a587f9cu;
// 0: sixty-four reports. 1: a report of nothing (what the header says a game without markers gets). 2: an error.
std::atomic<std::uint32_t> g_mode{0};
std::atomic<std::uint32_t> g_blockMs{0};
std::atomic<std::uint32_t> g_hideGetters{0};
std::atomic<std::uint32_t> g_queries{0};
std::atomic<std::uint32_t> g_latencyCalls{0};
std::atomic<std::uint32_t> g_sleepStatusCalls{0};
std::atomic<void*> g_lastDevice{nullptr};
// The section when it could be made, this otherwise: the stub works either way, only nobody outside can see it.
fl::stubnv::Shared g_local{};
fl::stubnv::Shared* g_shared = &g_local;
HANDLE g_section = nullptr;
std::atomic<void*> g_lastDevice{nullptr};
std::uint32_t Get(const std::uint32_t& word) noexcept {
return std::atomic_ref<const std::uint32_t>{word}.load(std::memory_order_relaxed);
}
std::uint32_t Bump(std::uint32_t& word) noexcept {
return std::atomic_ref<std::uint32_t>{word}.fetch_add(1u, std::memory_order_relaxed);
}
void Put(std::uint32_t& word, std::uint32_t value) noexcept {
std::atomic_ref<std::uint32_t>{word}.store(value, std::memory_order_relaxed);
}
void OpenSection() noexcept {
wchar_t name[64]{};
if (_snwprintf_s(name, _TRUNCATE, fl::stubnv::kSectionFormat, GetCurrentProcessId()) <= 0) {
return;
}
g_section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(fl::stubnv::Shared), name);
if (g_section == nullptr) {
return;
}
void* view = MapViewOfFile(g_section, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, sizeof(fl::stubnv::Shared));
if (view != nullptr) {
g_shared = static_cast<fl::stubnv::Shared*>(view);
}
}
NvAPI_Status __cdecl StubInitialize() {
return NVAPI_OK;
}
NvAPI_Status __cdecl StubGetLatency(IUnknown* device, NV_LATENCY_RESULT_PARAMS* out) {
g_latencyCalls.fetch_add(1u, std::memory_order_relaxed);
const std::uint32_t call = Bump(g_shared->latencyCalls); // 0 for the first call
g_lastDevice.store(device, std::memory_order_relaxed);
if (out == nullptr) {
return NVAPI_INVALID_ARGUMENT;
@@ -49,22 +80,30 @@ NvAPI_Status __cdecl StubGetLatency(IUnknown* device, NV_LATENCY_RESULT_PARAMS*
if (out->version != NV_LATENCY_RESULT_PARAMS_VER1) {
return NVAPI_INCOMPATIBLE_STRUCT_VERSION;
}
const std::uint32_t block = g_blockMs.load(std::memory_order_relaxed);
const std::uint32_t block = Get(g_shared->blockMs);
if (block != 0u) {
Sleep(block);
}
const std::uint32_t mode = g_mode.load(std::memory_order_relaxed);
if (mode == 2u) {
const std::uint32_t mode = Get(g_shared->mode);
if (mode == fl::stubnv::kModeError) {
return NVAPI_ERROR;
}
if (mode == 1u) {
if (mode == fl::stubnv::kModeNothing) {
return NVAPI_OK; // the caller's zeros are left as they are
}
// Sixty-four frames a little over four milliseconds apart, the newest last (nvapi.h: "element 63").
if (mode == fl::stubnv::kModeFault) {
volatile std::uint32_t* nowhere = nullptr;
*nowhere = 1u; // the fault a driver cannot be asked for
}
// Sixty-four frames a little over four milliseconds apart, the newest last (nvapi.h: "element 63"), and ten
// frames further on at every call -- so a caller that reads twice finds ten new frames, not the same sixty-four.
const std::uint64_t firstId =
fl::stubnv::kFirstFrameId + static_cast<std::uint64_t>(call) * fl::stubnv::kFrameIdStep;
for (std::uint32_t i = 0; i < 64u; ++i) {
auto& r = out->frameReport[i];
const std::uint64_t t = 1'000'000ull + static_cast<std::uint64_t>(i) * 4200ull;
r.frameID = 5000ull + i;
const std::uint64_t id = firstId + i;
const std::uint64_t t = 1'000'000ull + (id - fl::stubnv::kFirstFrameId) * 4200ull;
r.frameID = id;
r.inputSampleTime = t;
r.simStartTime = t + 100u;
r.simEndTime = t + 900u;
@@ -80,12 +119,18 @@ NvAPI_Status __cdecl StubGetLatency(IUnknown* device, NV_LATENCY_RESULT_PARAMS*
r.gpuRenderEndTime = t + 7600u;
r.gpuActiveRenderTimeUs = 3500u;
r.gpuFrameTimeUs = 4200u;
if (mode == fl::stubnv::kModeNoDriverSpan) {
r.driverStartTime = 0u;
}
if (mode == fl::stubnv::kModeImpossible) {
r.presentEndTime = r.presentStartTime - 50u;
}
}
return NVAPI_OK;
}
NvAPI_Status __cdecl StubGetSleepStatus(IUnknown* device, NV_GET_SLEEP_STATUS_PARAMS* out) {
g_sleepStatusCalls.fetch_add(1u, std::memory_order_relaxed);
Bump(g_shared->sleepStatusCalls);
g_lastDevice.store(device, std::memory_order_relaxed);
if (out == nullptr) {
return NVAPI_INVALID_ARGUMENT;
@@ -93,7 +138,7 @@ NvAPI_Status __cdecl StubGetSleepStatus(IUnknown* device, NV_GET_SLEEP_STATUS_PA
if (out->version != NV_GET_SLEEP_STATUS_PARAMS_VER1) {
return NVAPI_INCOMPATIBLE_STRUCT_VERSION;
}
if (g_mode.load(std::memory_order_relaxed) == 2u) {
if (Get(g_shared->mode) == fl::stubnv::kModeError) {
return NVAPI_ERROR;
}
out->bLowLatencyMode = 1;
@@ -105,15 +150,22 @@ NvAPI_Status __cdecl StubGetSleepStatus(IUnknown* device, NV_GET_SLEEP_STATUS_PA
} // namespace
BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) {
OpenSection(); // kernel32 only, and nothing that takes another module's lock
}
return TRUE;
}
extern "C" {
// The real module's one way in: an address for an interface id, or null for one it does not have.
__declspec(dllexport) void* __cdecl nvapi_QueryInterface(unsigned int id) {
g_queries.fetch_add(1u, std::memory_order_relaxed);
Bump(g_shared->queries);
if (id == kIdInitialize) {
return reinterpret_cast<void*>(&StubInitialize);
}
if (g_hideGetters.load(std::memory_order_relaxed) != 0u) {
if (Get(g_shared->hideGetters) != 0u) {
return nullptr;
}
if (id == kIdGetLatency) {
@@ -127,22 +179,22 @@ __declspec(dllexport) void* __cdecl nvapi_QueryInterface(unsigned int id) {
// The probe's knobs and counters. Names nobody else exports.
__declspec(dllexport) void __cdecl FlStubNvSetMode(std::uint32_t mode) {
g_mode.store(mode, std::memory_order_relaxed);
Put(g_shared->mode, mode);
}
__declspec(dllexport) void __cdecl FlStubNvSetBlockMs(std::uint32_t milliseconds) {
g_blockMs.store(milliseconds, std::memory_order_relaxed);
Put(g_shared->blockMs, milliseconds);
}
__declspec(dllexport) void __cdecl FlStubNvHideGetters(std::uint32_t hide) {
g_hideGetters.store(hide, std::memory_order_relaxed);
Put(g_shared->hideGetters, hide);
}
__declspec(dllexport) std::uint32_t __cdecl FlStubNvQueries() {
return g_queries.load(std::memory_order_relaxed);
return Get(g_shared->queries);
}
__declspec(dllexport) std::uint32_t __cdecl FlStubNvLatencyCalls() {
return g_latencyCalls.load(std::memory_order_relaxed);
return Get(g_shared->latencyCalls);
}
__declspec(dllexport) std::uint32_t __cdecl FlStubNvSleepStatusCalls() {
return g_sleepStatusCalls.load(std::memory_order_relaxed);
return Get(g_shared->sleepStatusCalls);
}
__declspec(dllexport) void* __cdecl FlStubNvLastDevice() {
return g_lastDevice.load(std::memory_order_relaxed);
+6 -1
View File
@@ -186,7 +186,10 @@ function Get-ImportName([string]$DumpbinText) {
function Get-ForbiddenImport([string[]]$ImportNames) {
$bad = @()
foreach ($n in $ImportNames) {
if ($n -match '^(sl\.|_?nvngx|libxess|ffx_|amd_fidelityfx)') { $bad += $n }
# `nvapi` since Advanced metrics train C: the Overlay calls two getters of an nvapi64.dll the GAME loaded and
# must never be what loads it - linking nvapi64.lib would not show here (it is static and loads the DLL at
# its first call; tools/nvapi-readonly-check.ps1 refuses the call tokens), a real import would.
if ($n -match '^(sl\.|_?nvngx|libxess|ffx_|amd_fidelityfx|nvapi)') { $bad += $n }
}
return , $bad
}
@@ -270,6 +273,8 @@ if ($SelfTest) {
Got = ((Get-ImportName " Summary`r`n`r`n 1000 .data`r`n").Count -eq 0); Want = $true }
@{ Name = 'a clean import list is clean'
Got = ((Get-ForbiddenImport @('KERNEL32.dll', 'd3d11.dll', 'd3d12.dll', 'dxgi.dll')).Count -eq 0); Want = $true }
@{ Name = 'an imported nvapi64.dll is caught, and a module that only ends in the name is not'
Got = (((Get-ForbiddenImport @('KERNEL32.dll', 'nvapi64.dll', 'NVAPI64.DLL', 'mynvapi.dll')) -join ',') -eq 'nvapi64.dll,NVAPI64.DLL'); Want = $true }
@{ Name = 'a LINKED sl.interposer.dll is caught - the whole reason Pass C exists'
Got = ((Get-ForbiddenImport @('KERNEL32.dll', 'sl.interposer.dll')) -contains 'sl.interposer.dll'); Want = $true }
@{ Name = 'the driver-store NGX core is caught despite its leading underscore'
+126 -7
View File
@@ -28,9 +28,13 @@
WHAT IT DOES NOT DO. It reads names, not arguments: an entry point that reads or writes depending on a command
argument (NvAPI_Disp_ColorControl, NvAPI_Disp_HdrColorControl) could not be told apart by it, which is why rule 3
refuses every name ending in Control outright. It does not look at the other native targets: no other shipped
target links nvapi64.lib (the Overlay links none of it - tools/vendor-exports and the package closure hold that),
and the probe tools are not shipped.
refuses every name ending in Control outright. No other shipped target links nvapi64.lib, and the probe tools
are not shipped.
THE OVERLAY, since Advanced metrics train C (owner decisions D132, D136): it links none of NVAPI and calls two
of the driver's getters through addresses it asks an already-loaded nvapi64.dll for, by interface id. Rules 5 to
7, above Test-Overlay, hold which ids code loaded into a game may name - against tools/overlay-nvapi-allowed.txt
and the vendored nvapi_interface.h.
-SelfTest proves every rule in both directions on in-memory sources.
#>
@@ -47,14 +51,16 @@ $ErrorActionPreference = 'Stop'
# end after it. So "SetSetting", "ClientRegisterFor..." and "ColorControl" match, and "GetThermalSettings",
# "LoadSettings", "GetSetting" and "GetAllClockFrequencies" do not. It errs towards red: a noun that happens to end
# in one of these words is refused until it is named below.
$script:WriterVerb = '(Set|Save|Restore|Delete|Remove|Register|Unregister|Reset|Enable|Disable|Flash|Write|Apply|Lock|Unlock|Create|Destroy|Control)(?=[A-Z_]|$)'
# `Sleep` since train C: NvAPI_D3D_Sleep stops the calling thread, and the Overlay's list is judged by this too.
$script:WriterVerb = '(Set|Save|Restore|Delete|Remove|Register|Unregister|Reset|Enable|Disable|Flash|Write|Apply|Lock|Unlock|Create|Destroy|Control|Sleep)(?=[A-Z_]|$)'
# The names the verb rule would refuse and that are reads. Named here one by one, each with its reason - never by a
# pattern, so an exemption cannot grow to cover a writer.
$script:WriterExempt = @(
'NvAPI_DRS_CreateSession', # the handle of a settings session that is only ever read from
'NvAPI_DRS_DestroySession', # ... and its release
'NvAPI_SYS_GetChipSetInfo' # "ChipSet" is a noun: the chipset's vendor and name
'NvAPI_SYS_GetChipSetInfo', # "ChipSet" is a noun: the chipset's vendor and name
'NvAPI_D3D_GetSleepStatus' # reads what the driver's low-latency state is; it sets none and sleeps nobody
)
# D104. NVAPI's entry points that return something identifying a device, a person or another program.
@@ -110,6 +116,70 @@ function Test-Bridge([string]$Source, [string]$ListText) {
return , @($problems)
}
# ---------------------------------------------------------------------------------------------------------------------
# THE OVERLAY (Advanced metrics train C; owner decisions D132, D136). Code loaded into a game links no NVAPI and
# calls no NvAPI_* function by name: it asks an nvapi64.dll the game had already loaded for two addresses, by
# interface id (FrameLedger.Overlay/include/fl_reflex.h). A call through such an address carries no NvAPI_ token, so
# the bridge's rules cannot see it. These can:
#
# 5. no NvAPI_* call token in any Overlay or Vulkan-layer source;
# 6. every 8-digit hex literal there that IS one of the vendored nvapi_interface.h's ids belongs to a name on
# tools/overlay-nvapi-allowed.txt, and every name on that list has its id in the sources;
# 7. the names on that list are judged as the bridge's are - no writer, no identifier - and, for code inside a
# game, `Sleep` is a writer verb too: NvAPI_D3D_Sleep stops the thread that calls it.
#
# WHAT IT DOES NOT DO: it cannot see an id that is computed, or one written in another base. No code does either.
# ---------------------------------------------------------------------------------------------------------------------
# name -> id (lower-case hex, no prefix), from the vendored nvapi_interface.h: { "NvAPI_X", 0x........ },
function Read-InterfaceTable([string]$Text) {
$byId = @{}
foreach ($m in [regex]::Matches($Text, '\{\s*"(NvAPI_\w+)"\s*,\s*0x([0-9A-Fa-f]{1,8})\s*\}')) {
$id = $m.Groups[2].Value.ToLowerInvariant().PadLeft(8, '0')
if (-not $byId.ContainsKey($id)) { $byId[$id] = [System.Collections.Generic.List[string]]::new() }
$byId[$id].Add($m.Groups[1].Value)
}
return $byId
}
# $Sources: file name -> source, for every Overlay and Vulkan-layer source.
function Test-Overlay([hashtable]$Sources, [string]$InterfaceText, [string]$ListText) {
$problems = [System.Collections.Generic.List[string]]::new()
$list = Read-AllowedList $ListText
foreach ($p in $list.Problems) { $problems.Add($p) }
$allowed = $list.Names
$byId = Read-InterfaceTable $InterfaceText
if ($byId.Count -eq 0) { $problems.Add('no interface id was read from nvapi_interface.h: the check read the wrong file, or nothing') }
$found = [System.Collections.Generic.SortedSet[string]]::new([StringComparer]::Ordinal)
foreach ($key in ($Sources.Keys | Sort-Object)) {
foreach ($name in (Get-NvapiCall $Sources[$key])) {
$problems.Add("$key calls $name by name: code loaded into a game links no NVAPI")
}
$code = [regex]::Replace($Sources[$key], '/\*.*?\*/', ' ', 'Singleline')
$code = [regex]::Replace($code, '//[^\r\n]*', ' ')
$code = [regex]::Replace($code, '"(\\.|[^"\\\r\n])*"', '""')
foreach ($m in [regex]::Matches($code, '(?<![\w])0[xX]([0-9A-Fa-f]{8})(?![0-9A-Fa-f])')) {
$id = $m.Groups[1].Value.ToLowerInvariant()
if (-not $byId.ContainsKey($id)) { continue }
foreach ($name in $byId[$id]) {
[void]$found.Add($name)
if ($allowed -cnotcontains $name) { $problems.Add("$key names the interface id of $name (0x$id), which the Overlay's list does not allow") }
}
}
}
foreach ($name in $allowed) {
if (-not $found.Contains($name)) { $problems.Add("the Overlay's list allows $name, whose interface id is in no Overlay source") }
if ($name -cmatch $script:WriterVerb -and $script:WriterExempt -cnotcontains $name) {
$problems.Add("$name changes something (its name carries '$($Matches[1])'): nothing loaded into a game calls a writer, whatever the list says")
}
if ($name -cmatch $script:Identifier) {
$problems.Add("$name returns an identifier ('$($Matches[1])'): never read (D104), whatever the list says")
}
}
return , @($problems)
}
if ($SelfTest) {
$failed = 0
$goodSource = @'
@@ -148,8 +218,34 @@ int Read() {
Write-Host (" {0,-4} {1}{2}" -f ($(if ($ok) { 'ok' } else { 'FAIL' })), $c.Name, ($(if (-not $ok) { " -> $($problems.Count): $($problems -join '; ')" } else { '' }))) -ForegroundColor ($(if ($ok) { 'DarkGray' } else { 'Red' }))
if (-not $ok) { $failed++ }
}
# The Overlay's rules, on a table of four ids and sources written here.
$table = @'
{ "NvAPI_D3D_GetLatency", 0x1a587f9c },
{ "NvAPI_D3D_GetSleepStatus", 0xaef96ca1 },
{ "NvAPI_D3D_SetSleepMode", 0xac1ca9e0 },
{ "NvAPI_D3D_Sleep", 0x852cd1d2 },
'@
$goodOverlay = @{ 'fl_reflex.h' = "// 0xac1ca9e0 is NvAPI_D3D_SetSleepMode and is never asked for`ninline constexpr unsigned int kA = 0x1a587f9cu; inline constexpr unsigned int kB = 0xAEF96CA1u; const uint32_t none = 0xFFFFFFFFu; Log(`"0x852cd1d2`");" }
$goodOverlayList = "# the two getters`nNvAPI_D3D_GetLatency`nNvAPI_D3D_GetSleepStatus`n"
$overlayCases = @(
@{ Name = 'the two getters by id, a setter''s id only in a comment and a string, pass'; Sources = $goodOverlay; List = $goodOverlayList; Expect = 0 },
@{ Name = 'the id of a setter in Overlay code FAILS'; Sources = @{ 'fl_reflex.h' = $goodOverlay['fl_reflex.h']; 'dllmain.cpp' = 'void* p = query(0xac1ca9e0u);' }; List = $goodOverlayList; Expect = 1 },
@{ Name = 'the id of the sleep FAILS when it is listed: a writer verb, whatever the list says'; Sources = @{ 'fl_reflex.h' = $goodOverlay['fl_reflex.h'] + ' void* s = query(0x852cd1d2);' }; List = $goodOverlayList + "NvAPI_D3D_Sleep`n"; Expect = 1 },
@{ Name = 'a setter FAILS even when it is listed and its id is named'; Sources = @{ 'fl_reflex.h' = $goodOverlay['fl_reflex.h'] + ' void* s = query(0xac1ca9e0);' }; List = $goodOverlayList + "NvAPI_D3D_SetSleepMode`n"; Expect = 1 },
@{ Name = 'a name on the list whose id nothing names FAILS'; Sources = @{ 'fl_reflex.h' = 'inline constexpr unsigned int kA = 0x1a587f9cu;' }; List = $goodOverlayList; Expect = 1 },
@{ Name = 'an NvAPI function called by name in the Overlay FAILS'; Sources = @{ 'fl_reflex.h' = $goodOverlay['fl_reflex.h']; 'dllmain.cpp' = 'void X() { NvAPI_D3D_GetLatency(dev, &out); }' }; List = $goodOverlayList; Expect = 1 },
@{ Name = 'a hex literal that is no interface id passes'; Sources = @{ 'fl_reflex.h' = $goodOverlay['fl_reflex.h']; 'layer.cpp' = 'const uint32_t magic = 0x7F800000u; const uint64_t wide = 0x1a587f9c00000000ull;' }; List = $goodOverlayList; Expect = 0 },
@{ Name = 'an interface table nobody could read FAILS'; Sources = $goodOverlay; List = $goodOverlayList; Table = '// nothing'; Expect = 3 }
)
foreach ($c in $overlayCases) {
$tableText = if ($c.ContainsKey('Table')) { $c.Table } else { $table }
$problems = Test-Overlay $c.Sources $tableText $c.List
$ok = $problems.Count -eq $c.Expect
Write-Host (" {0,-4} {1}{2}" -f ($(if ($ok) { 'ok' } else { 'FAIL' })), $c.Name, ($(if (-not $ok) { " -> $($problems.Count): $($problems -join '; ')" } else { '' }))) -ForegroundColor ($(if ($ok) { 'DarkGray' } else { 'Red' }))
if (-not $ok) { $failed++ }
}
if ($failed -gt 0) { Write-Host "nvapi-readonly-check self-test FAILED ($failed)" -ForegroundColor Red; exit 1 }
Write-Host "nvapi-readonly-check self-test: $($cases.Count) cases, both directions" -ForegroundColor Green
Write-Host "nvapi-readonly-check self-test: $($cases.Count + $overlayCases.Count) cases, both directions" -ForegroundColor Green
exit 0
}
@@ -165,5 +261,28 @@ if ($problems.Count -gt 0) {
exit 1
}
$count = (Get-NvapiCall (Get-Content -LiteralPath $sourcePath -Raw)).Count
Write-Host "nvapi-readonly-check OK - the bridge calls $count NVAPI entry points, each on the list, none a writer or an identifier" -ForegroundColor Green
# The Overlay and the Vulkan layer: what is loaded into a game.
$interfacePath = Join-Path $RepoRoot 'src/native/third_party/nvapi/nvapi_interface.h'
$overlayListPath = Join-Path $RepoRoot 'tools/overlay-nvapi-allowed.txt'
foreach ($path in $interfacePath, $overlayListPath) {
if (-not (Test-Path -LiteralPath $path)) { Write-Host "NVAPI READ-ONLY CHECK FAILED: $path is missing" -ForegroundColor Red; exit 1 }
}
$overlaySources = @{}
foreach ($dir in 'src/native/FrameLedger.Overlay', 'src/native/FrameLedger.VkLayer') {
$root = Join-Path $RepoRoot $dir
if (-not (Test-Path -LiteralPath $root)) { Write-Host "NVAPI READ-ONLY CHECK FAILED: $root is missing" -ForegroundColor Red; exit 1 }
foreach ($file in Get-ChildItem -LiteralPath $root -Recurse -File -Include '*.cpp', '*.h', '*.inl') {
$overlaySources[[IO.Path]::GetRelativePath($RepoRoot, $file.FullName).Replace('\', '/')] = Get-Content -LiteralPath $file.FullName -Raw
}
}
if ($overlaySources.Count -eq 0) { Write-Host 'NVAPI READ-ONLY CHECK FAILED: no Overlay or Vulkan-layer source was found' -ForegroundColor Red; exit 1 }
$overlayProblems = Test-Overlay $overlaySources (Get-Content -LiteralPath $interfacePath -Raw) (Get-Content -LiteralPath $overlayListPath -Raw)
if ($overlayProblems.Count -gt 0) {
Write-Host 'NVAPI READ-ONLY CHECK FAILED (the Overlay):' -ForegroundColor Red
foreach ($p in $overlayProblems) { Write-Host " - $p" -ForegroundColor Red }
exit 1
}
$overlayNames = (Read-AllowedList (Get-Content -LiteralPath $overlayListPath -Raw)).Names
Write-Host "nvapi-readonly-check OK - the bridge calls $count NVAPI entry points, each on the list, none a writer or an identifier; the Overlay names $($overlayNames.Count) interface ids ($($overlayNames -join ', ')), calls no NvAPI function by name, and $($overlaySources.Count) of its sources were read" -ForegroundColor Green
exit 0
+26
View File
@@ -92,3 +92,29 @@ ffxQueryDescHeader::type
ffxQueryDescUpscaleGetGPUMemoryUsage::gpuMemoryUsageUpscaler
FfxApiEffectMemoryUsage::totalUsageInBytes
FfxApiEffectMemoryUsage::aliasableUsageInBytes
# NVIDIA's latency report and sleep status (parameters `lr`, `lf`, `ls`; Advanced metrics train C, owner decisions
# D132, D136). NOT arguments of a hooked call: what the driver wrote into buffers the Overlay handed to its two
# read-only getters (fl_reflex.h). Of a frame: its id and the six pairs of times the spans are made of. Not read:
# `inputSampleTime`, the GPU times the driver reports beside the marks, the frame-generation and cross-adapter
# times. Of the sleep status: the five switches and the frame-generation multiplier; the sleep interval is not read.
NV_LATENCY_RESULT_PARAMS::frameReport
NV_LATENCY_RESULT_PARAMS::FrameReport::frameID
NV_LATENCY_RESULT_PARAMS::FrameReport::simStartTime
NV_LATENCY_RESULT_PARAMS::FrameReport::simEndTime
NV_LATENCY_RESULT_PARAMS::FrameReport::renderSubmitStartTime
NV_LATENCY_RESULT_PARAMS::FrameReport::renderSubmitEndTime
NV_LATENCY_RESULT_PARAMS::FrameReport::presentStartTime
NV_LATENCY_RESULT_PARAMS::FrameReport::presentEndTime
NV_LATENCY_RESULT_PARAMS::FrameReport::driverStartTime
NV_LATENCY_RESULT_PARAMS::FrameReport::driverEndTime
NV_LATENCY_RESULT_PARAMS::FrameReport::osRenderQueueStartTime
NV_LATENCY_RESULT_PARAMS::FrameReport::osRenderQueueEndTime
NV_LATENCY_RESULT_PARAMS::FrameReport::gpuRenderStartTime
NV_LATENCY_RESULT_PARAMS::FrameReport::gpuRenderEndTime
NV_GET_SLEEP_STATUS_PARAMS::bLowLatencyMode
NV_GET_SLEEP_STATUS_PARAMS::bFsVrr
NV_GET_SLEEP_STATUS_PARAMS::bCplVsyncOn
NV_GET_SLEEP_STATUS_PARAMS::bUseGameSleep
NV_GET_SLEEP_STATUS_PARAMS::bFullscreenIFlip
NV_GET_SLEEP_STATUS_PARAMS::fgMultiplier
+13 -2
View File
@@ -60,6 +60,11 @@ $script:Parameter = [ordered]@{
g = 'ffxConfigureDescFrameGeneration'
fv = 'sl::FeatureVersion'
fr = 'sl::FeatureRequirements'
# Train C: what NVIDIA's driver wrote into the Overlay's own buffers (fl_reflex.h makes the two calls). `lf` is
# one frame of the report, handed on by index - `lr.frameReport[i]` - and never bound to a name of its own.
lr = 'NV_LATENCY_RESULT_PARAMS'
lf = 'NV_LATENCY_RESULT_PARAMS::FrameReport'
ls = 'NV_GET_SLEEP_STATUS_PARAMS'
desc = 'ffxQueryDescHeader'
}
@@ -81,7 +86,9 @@ $script:CameraStruct = @('sl::Constants', 'ffxDispatchDescFrameGenerationPrepare
# Member names every struct has. The header's reads of them are held to the list like any other; what rule 3 cannot do
# is refuse them elsewhere, where they are members of the Overlay's own structs and of descriptors read since 0.1.0.
$script:SharedMember = @('structVersion', 'type', 'flags', 'reset')
# `frameID` joined them with train C: the driver's latency report has one, and so has the frame-generation prepare
# descriptor the Overlay has read since 0.1.0 (dllmain.cpp counts application frames by it).
$script:SharedMember = @('structVersion', 'type', 'flags', 'reset', 'frameID')
# A C++ source without its comments and string literals: a camera named in the comment that says it is never read is
# not a read.
@@ -112,7 +119,7 @@ function Get-HeaderRead([string]$Code) {
$reads = [System.Collections.Generic.SortedSet[string]]::new([StringComparer]::Ordinal)
$problems = [System.Collections.Generic.List[string]]::new()
foreach ($m in [regex]::Matches($Code, '(?<![\w.>:])(o|d|m|q|k|g|fv|fr)\b(\s*\.\s*([A-Za-z_]\w*))?')) {
foreach ($m in [regex]::Matches($Code, '(?<![\w.>:])(o|d|m|q|k|g|fv|fr|lr|lf|ls)\b(\s*\.\s*([A-Za-z_]\w*))?')) {
$name = $m.Groups[1].Value
if ($m.Groups[3].Success) {
[void]$reads.Add("$($script:Parameter[$name])::$($m.Groups[3].Value)")
@@ -234,6 +241,10 @@ inline void Publish(Accumulators& a, FlAdvancedState* region) noexcept { region-
@{ Name = 'the adapter a game asks about, forwarded by its parameter and never looked into, passes'; Header = $goodHeader; List = $goodList; Other = @{ 'dllmain.cpp' = 'sl::Result Hook(sl::Feature feature, const sl::AdapterInfo& adapterInfo) { return g_orig(feature, adapterInfo); } // never adapterInfo.deviceLUID' }; Expect = 0 },
@{ Name = 'the adapter''s LUID read in the detour FAILS'; Header = $goodHeader; List = $goodList; Other = @{ 'dllmain.cpp' = 'sl::Result Hook(sl::Feature feature, const sl::AdapterInfo& adapterInfo) { Keep(adapterInfo.deviceLUID[0]); return g_orig(feature, adapterInfo); }' }; Expect = 1 },
@{ Name = 'a Vulkan physical device taken from the adapter in the layer FAILS'; Header = $goodHeader; List = $goodList; Other = @{ 'layer.cpp' = 'void* device = info->vkPhysicalDevice;' }; Expect = 1 },
@{ Name = 'the driver''s latency report read through its parameters, a frame handed on by index, passes'; Header = $goodHeader + "`ninline uint64_t IdOf(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf) noexcept { return lf.frameID + lf.simStartTime; }`ninline void ObserveL(const NV_LATENCY_RESULT_PARAMS& lr, Tally& t) noexcept { t.n += IdOf(lr.frameReport[3]); }`ninline uint32_t ObserveS(const NV_GET_SLEEP_STATUS_PARAMS& ls) noexcept { return ls.bLowLatencyMode; }"; List = $goodList + "NV_LATENCY_RESULT_PARAMS::frameReport`nNV_LATENCY_RESULT_PARAMS::FrameReport::frameID`nNV_LATENCY_RESULT_PARAMS::FrameReport::simStartTime`nNV_GET_SLEEP_STATUS_PARAMS::bLowLatencyMode`n"; Other = $goodOther; Expect = 0 },
@{ Name = 'a member of a latency frame the list does not allow FAILS'; Header = $goodHeader + "`ninline uint64_t IdOf(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf) noexcept { return lf.frameID + lf.inputSampleTime; }"; List = $goodList + "NV_LATENCY_RESULT_PARAMS::FrameReport::frameID`n"; Other = $goodOther; Expect = 1 },
@{ Name = 'a frame of the report bound to a name of its own FAILS'; Header = $goodHeader + "`ninline void ObserveL(const NV_LATENCY_RESULT_PARAMS& lr) noexcept { const auto& f = lr.frameReport[0]; Keep(f.simStartTime); const auto& whole = lr; Keep(whole); }"; List = $goodList + "NV_LATENCY_RESULT_PARAMS::frameReport`n"; Other = $goodOther; Expect = 1 },
@{ Name = 'the frame id, which the prepare descriptor has too, is read outside the header; a time of the report is not'; Header = $goodHeader + "`ninline uint64_t IdOf(const NV_LATENCY_RESULT_PARAMS::FrameReport& lf) noexcept { return lf.frameID + lf.simStartTime; }"; List = $goodList + "NV_LATENCY_RESULT_PARAMS::FrameReport::frameID`nNV_LATENCY_RESULT_PARAMS::FrameReport::simStartTime`n"; Other = @{ 'dllmain.cpp' = 'void Hook() { Keep(prep->frameID); Keep(report.frameReport); Keep(r.simStartTime); }' }; Expect = 1 },
@{ Name = 'a header with no read at all FAILS'; Header = '// o.outputWidth is somewhere else'; List = "# nothing`n"; Other = $goodOther; Expect = 1 }
)
foreach ($c in $cases) {
+10
View File
@@ -0,0 +1,10 @@
# The NVAPI interface ids that code loaded into a game may name (Advanced metrics train C; owner decisions D132,
# D136; rule 4's note of 2026-11-13). The Overlay links no NVAPI: it asks an nvapi64.dll the game had already
# loaded for these two addresses, by the ids nvapi_interface.h gives them, and calls them with the Direct3D 12
# device behind the swap chain it hooks (FrameLedger.Overlay/include/fl_reflex.h).
#
# tools/nvapi-readonly-check.ps1 fails the build when an Overlay or Vulkan-layer source names the id of any other
# NVAPI function, when a name here has no id in those sources, or when a name here is a writer - a setter, a
# marker, a sleep - or returns an identifier. Getters only.
NvAPI_D3D_GetLatency
NvAPI_D3D_GetSleepStatus