Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.2 671159875f fix(probe): what SonarCloud reported on the Reflex probe - the counter read through the union member it was initialised with, a guard for an empty measurement, NvU32 printed as what it is, a variable no longer named module; and the note says what a fourth run measured (1.5 us a call, 70 us at worst)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 18:42:45 +07:00
poli0981andClaude Fable 5.2 fac2cb7e20 fix(probe): the Reflex probe's Measure takes its callable by const reference - a forwarding reference it never forwarded (Qodana native, cppcoreguidelines-missing-std-forward)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 18:16:30 +07:00
poli0981andClaude Fable 5.2 c049892b38 docs(spike): HANDOFF says the route D spike is done and what a plan must keep from it; the changelog names the probe as a developer's tool
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 17:53:20 +07:00
poli0981andClaude Fable 5.2 8350ee9fe2 docs(spike): §31 in the index, §M14 and §30 point at what the harness spike showed; the probe and its stub in the build document and CLAUDE.md's tools list
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 17:52:29 +07:00
poli0981andClaude Fable 5.2 06a1d19ed2 spike: Reflex route D on the harness - the driver's two getters called from an unshipped probe, against a stand-in nvapi64.dll and against the installed driver; a decision table written before the runs, and what they showed (spike-notes §31; D132)
No shipped code changes and no game was touched.

- tools/fl-probe-reflex: fl_reflex_candidate.h, the call sequence that would move into the Overlay (find
  nvapi64.dll only if the process already holds it, resolve NvAPI_D3D_GetLatency and NvAPI_D3D_GetSleepStatus by
  interface id, call them SEH-guarded); --stub against tools/vendor-stubs/stub_nvapi64.cpp (ctest
  fl_reflex_probe_stub); --real against the installed driver with the probe playing the game's part - it sets
  latency markers on its own device, in its own process.
- docs/spike-notes/31-reflex-route-d-harness.md: nine pre-committed measurements and their results. No fault
  before initialisation, without markers, or beside a marker-setting thread (38 million reads); a call costs half
  a microsecond; the Direct3D 12 device the Overlay holds is the object the driver takes; the report's unit is
  microseconds. The call belongs on the presenting thread once a second, not on the watchdog. The newest frames
  of a report are not final. Ends in the owner's go or no for one real title.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 17:52:29 +07:00
14 changed files with 1152 additions and 7 deletions

No files matched your search

+9
View File
@@ -35,6 +35,15 @@ numeric core and does not move; the heading is the full version — corrected 20
## [Unreleased]
### Added
- **For developers, nothing a user installs: a probe for NVIDIA Reflex latency** (owner decision D132). An
unshipped tool, `fl-probe-reflex`, and a stand-in `nvapi64.dll` among the test fixtures measure what it would take
to read the driver's latency report from inside a game - on FrameLedger's own test program and against the
installed driver, never in a game. What it found is `docs/spike-notes/31-reflex-route-d-harness.md`; whether a
real game is tried next is the owner's decision. Nothing in the App, the Agent or the part that runs inside a
game changed.
## Releases
Newest first. Each file holds that release's section exactly as it stood here.
+2
View File
@@ -205,6 +205,8 @@ tools/ # accuracy-check, changelog-check, chokepoint-che
# (--vulkan since #140, --opengl since #141)
# fl-probe-* -> guard, hook profile, interposer, NVAPI, process
# stats, signer, Vulkan layer; fl-baseline-probe;
# and fl-probe-reflex (2026-11-13, D132: the spike of Reflex route D,
# spike-notes §31 - unshipped, with a stand-in nvapi64.dll among the stubs);
# vendor-stubs/ -> fixture DLLs with the vendors' export names
rules/detection-rules.json # engine/platform/capability + anticheat blocklist
guide/ # the user guide (beta.12, D44): ~~eight~~ short English pages for players, embedded in the
+1
View File
@@ -35,6 +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_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.
+1 -1
View File
@@ -1870,7 +1870,7 @@ Moved verbatim, in this order.
| M12 ❓ | **Advanced metrics — which NVAPI rows answer on real hardware (D101, 2026-11-11).** `18_GPU_VENDOR_APIS` §The inventory lists sixty `nvapi.` rows whose reach is `Agent`. They are declared in the vendored headers; **none has been called on a GPU**, and CI has no driver, so it never takes that branch. Unknown per row: whether the RTX 5080 on the current driver answers or returns `NVAPI_NOT_SUPPORTED` (the memory-temperature target already does not exist on that card). | **The measurement is the bridge's probe on the owner's PC**, then the page itself (the release's owner-only item). Pre-committed: a call that does not answer → that row is N/A with NVAPI's own status as the reason, and nothing is put in its place; a call that hangs or faults twice → the row is off for the session (§Runtime policy); a value that contradicts the vendor's own tool → the row is withheld until it is explained. **Half answered the same day, by the bridge's own test on the dev box** (ctest `fl_nvapi_bridge`, AVAILABLE branch; RTX 5080): every fact answers (`present = 0xFFFFF`), eight of ten live groups answer (`0x33F` — no board and no power-supply temperature sensor on this card: N/A, by the first pre-committed outcome), the display answers its four groups, the global profile lists 24 settings; figures in `18_GPU_VENDOR_APIS` §L3. **Still open**: the same values on the page beside the vendor's own tool, and the session rows (`nvapi.session.*`), which need a game. **And one thing seen once and not explained**: in one test run of about a dozen that day, `FlNvReadLive` came back with no field at all although `FlNvReadFacts`, a moment earlier in the same process, had answered everything; nine further runs did not show it. A handle the driver invalidated is the usual cause of that shape, and nothing here re-enumerates after `FlNvInit`. Pre-committed for the reader that owns the thread: two readings in a row with no field → release and initialise the bridge again, once, and say so in the log; if that does not bring the fields back the layer is off for the session, as any layer that fails twice is. |
| M13 ❓ | **Advanced metrics — LibreHardwareMonitor's CPU, memory, motherboard and storage groups, elevated, with PawnIO (D103, 2026-11-11).** Never opened by any build: §M10's elevated run has not been taken either, and this is a larger surface — a sensor chip on the LPC bus, the embedded controller, SPD over SMBus, SMART. Unknown: whether each group opens on the owner's board, what a refresh costs, whether opening the storage group touches removable drives (this PC once had a failing USB drive), and whether any group enables a privilege (`PrivilegeFootprintTests`). | **One elevated run with the probe verb, before the option exists.** Pre-committed: the storage group cannot be opened without touching removable drives → `lhm.storage.*` stays N/A in beta.39 and its reach reads `Deferred`; a node that throws twice → skipped for the session; the Agent above 1% of one core or 150 MB with the option on (NFR-2) → the slow groups are read less often or dropped before the release; a privilege enabled by a group → that group is not opened, and the owner is asked. **Two of the four answered 2026-11-11, before the option exists.** (1) **Storage: not opened, by the first outcome.** LibreHardwareMonitor 0.9.6's `StorageGroup` lists every drive through DiskInfoToolkit's `ReloadStorages` with no filter by bus and follows drives plugged in later — it cannot be opened without touching removable drives. `lhm.storage.*` reads `Deferred`, and `LhmGroups` has no member for it. (2) **Cost, unelevated, measured with `probe-advanced`** on the dev box: one refresh of the graphics-card group alone is 14 ms of processor time (62 ms elapsed) — 1.4% of one core at one a second, above NFR-2 — and one NVAPI read 0.4 ms. By the third outcome the sensor library is read every fifth tick (0.28%). **Still open, and the owner's**: the same probe as administrator with PawnIO — whether the processor, memory and motherboard groups open on this board, what they cost, and `PrivilegeFootprintTests`' new case on a token that holds the privileges (CI's does; the dev box's unelevated run passes by construction). **The first run was taken on 2026-11-12, by the owner, in ordinary use** (0.1.0-beta.40, the Agent as administrator with PawnIO, an i7-14700KF on a board with an IT8689E chip, an RTX 5080), and read here from a copy of the ledger and the Agent's log, not from a probe. **The groups open and read**: nine of ten sessions stored 119 processor series (a clock and a load per thread, temperatures, powers, voltages), 14 memory series and 21 motherboard series (six fans, six temperatures, nine voltages) beside the card's 41 — 195 from the sensor library in all. **No value was compared with another tool**; that is still the owner's. **Two faults, one cause** (`Infrastructure.Telemetry.LhmLibrary`): the Agent held up to three `Computer`s at once, and the library keeps the driver it reads the processor through and its bus mutexes per process — closing one `Computer` let go of them under the others. After seven sessions the Advanced reader's processor device threw `NullReferenceException` twice and was left alone (the page lost the processor until the reader reopened); once a session's start met another instance's close, the reader's `Open` threw `ObjectDisposedException`, and that session stored 17 series instead of 212. **Fixed 2026-11-12**: opens and closes are serialised and a `Computer` is parked, not closed, while another is in use. The cause is read from the log's timing and was not reproduced — it needs this elevation — so **whether the faults are gone is the owner's next sessions to show**: no `advanced: a device is left alone` and no `did not open` in the Agent's log. **First evidence, 2026-11-12, 0.1.0-beta.41, the same PC:** seven sessions between 06:38 and 07:01 with no `advanced:` line at all, each with the option on storing 212 or 213 series; on beta.40 that morning the processor device faulted out after each of six sessions (04:34–05:07) — thirteen of sixteen over the night. The reader failing to open was seen once in sixteen, so this is not yet enough to call that one gone. Still open: any value beside another tool. |
| M16 ✅ | **The L2 telemetry layer's cost — the first number, and it is above NFR-2 (found 2026-11-11, measuring something else).** `LhmTelemetrySource` refreshes LibreHardwareMonitor's graphics-card group once a second in every recorded session. `probe-advanced` measured that refresh, through the same library and the same group, at **14 ms of processor time** on the dev box (RTX 5080, 41 mapped sensors, about twenty of them the Direct3D engine nodes the library enumerates per card) — 1.4% of one core, where NFR-2 allows the whole Agent 1% during capture and `14_TESTING` §Hook overhead's Agent figure has never been measured. This is a measurement of the call, not yet of a session: L2's own poller was not instrumented. | **Measure L2 in a session** (the Agent's processor time over a ten-minute capture, telemetry at 1000 ms and at 2000 ms). Pre-committed: at or under 1% → this row closes with the number; above → the owner chooses between a slower default for `telemetry.interval_ms`, reading the sensors the layer keeps from NVAPI on NVIDIA cards (L3 already has most, at 0.4 ms), or amending NFR-2 to what is measured. Not decided here, and nothing about L2 changes in the Advanced-metrics train. **Measured in a real Agent, 2026-11-11 (owner decision D110), and answered (D117).** `tools/agent-cost.ps1` runs the shipped `FrameLedger.Agent.exe --console capture` against a copy of hook-harness in a scratch data folder — a session that is not hooked, so the telemetry poller runs as in every session and nothing drains frames — and reads the Agent process's own processor time at exit; the cost per second is the slope between a 45 s and a 165 s session, two runs of each. Dev box (RTX 5080, not elevated, layers `l1+lhm+nvapi`): **19.3 ms of processor time per second of session = 1.93 % of one core with Advanced metrics off** (2,312 and 2,312 ms over 45 s; 4,594 and 4,656 ms over 165 s), **20.4 ms = 2.04 % with it on** (2,984 and 3,000; 5,547 and 5,344); peak working set 113 MiB and 119 MiB. A first pass with 30 s and 90 s sessions gave 1.56 % and 2.21 % — its two short runs differed by 670 ms, which is why the lengths were raised. So the probe's number holds in a session: the Agent's steady cost is about twice NFR-2's 1 %, nearly all of it the layer every session has always used, and the new option adds about a tenth of a percent. **The owner's answer: NFR-2 is amended to ≤ 2.5 % of one core** — the limit had never been measured, the sensors keep their one reading a second, and nothing in the code changes. Not measured: a hooked session (the drain's cost on top), a session with the Agent elevated and PawnIO's groups open, another PC. |
| M14 ❓ | **Reflex latency per frame — is there a route within rules 4 and 5? (Train C, 2026-11-11.)** `17_HOOK_ENGINE` §Memory / latency names hooks on `NvAPI_D3D_SetSleepMode` / `SetLatencyMarker` and a call to `NvAPI_D3D_GetLatency`. NVAPI resolves all three through `nvapi_QueryInterface` by id — they are not exports, so a hook on them is a patch at an address learned at run time, the class refused on 2026-08-09. The route to try first needs no hook: the Overlay's own background thread **calls** `GetLatency` with the device of the swap chain it already hooks, once a second (the call returns the last 64 frames' reports). Unknown: whether calling into the driver from that thread is safe on every device kind, what it costs, what it returns when the game never enabled Reflex, and what it means for the Disclaimer's sentence about that thread. | **A spike on `hook-harness` and a stub first, then one real title.** Pre-committed: no route without a patch at a run-time address or a loader-lock call on the game's thread → Reflex stays N/A and the page says why; overhead above NFR-1 → the same. The owner says go or no on the spike's result. **2026-11-12 — the reading that comes before that spike is `spike-notes` §30** (owner decision D130: a document first, beside 0.1.0-beta.45; nothing was run). It finds: a hook on NVAPI's latency functions is the refused class, and a hook on Streamline's Reflex and PCL functions is train D's wrapper (§M15) — and would miss a game that fetched them before the attach, as `slInit` is missed (D129); the Overlay calling `slReflexGetState` itself breaks the thread contract the vendor's header states; **what remains is the route named in this row**, the Overlay calling two driver getters with the game's device, and a no-injection ETW route that gives the game-side markers only and makes the game post messages to its own window. Corrected there: `nvapi64.dll` exports **two** functions on the dev box (`nvapi_Direct_GetMethod` beside `nvapi_QueryInterface`), not one. The go or no is the owner's, and a go needs the owner's ruling that calling a driver getter with the game's device is inside rule 4. **2026-11-13 — the owner answered (D132, D133).** Route D goes to the spike this row names, on `hook-harness` and a stub `nvapi64.dll`, with the ruling: a driver's read-only getter called with the device of the swap chain the Overlay hooks is inside rule 4 (`CLAUDE.md`, the rule's note of that day). No real game before the owner has seen the result, and nothing shipped changes for the spike (`spike-notes` §31, written after 0.1.0-beta.46). Route C is **refused**; the ETW route **stays closed**, and §G is not reopened. |
| M14 ❓ | **Reflex latency per frame — is there a route within rules 4 and 5? (Train C, 2026-11-11.)** `17_HOOK_ENGINE` §Memory / latency names hooks on `NvAPI_D3D_SetSleepMode` / `SetLatencyMarker` and a call to `NvAPI_D3D_GetLatency`. NVAPI resolves all three through `nvapi_QueryInterface` by id — they are not exports, so a hook on them is a patch at an address learned at run time, the class refused on 2026-08-09. The route to try first needs no hook: the Overlay's own background thread **calls** `GetLatency` with the device of the swap chain it already hooks, once a second (the call returns the last 64 frames' reports). Unknown: whether calling into the driver from that thread is safe on every device kind, what it costs, what it returns when the game never enabled Reflex, and what it means for the Disclaimer's sentence about that thread. | **A spike on `hook-harness` and a stub first, then one real title.** Pre-committed: no route without a patch at a run-time address or a loader-lock call on the game's thread → Reflex stays N/A and the page says why; overhead above NFR-1 → the same. The owner says go or no on the spike's result. **2026-11-12 — the reading that comes before that spike is `spike-notes` §30** (owner decision D130: a document first, beside 0.1.0-beta.45; nothing was run). It finds: a hook on NVAPI's latency functions is the refused class, and a hook on Streamline's Reflex and PCL functions is train D's wrapper (§M15) — and would miss a game that fetched them before the attach, as `slInit` is missed (D129); the Overlay calling `slReflexGetState` itself breaks the thread contract the vendor's header states; **what remains is the route named in this row**, the Overlay calling two driver getters with the game's device, and a no-injection ETW route that gives the game-side markers only and makes the game post messages to its own window. Corrected there: `nvapi64.dll` exports **two** functions on the dev box (`nvapi_Direct_GetMethod` beside `nvapi_QueryInterface`), not one. The go or no is the owner's, and a go needs the owner's ruling that calling a driver getter with the game's device is inside rule 4. **2026-11-13 — the owner answered (D132, D133).** Route D goes to the spike this row names, on `hook-harness` and a stub `nvapi64.dll`, with the ruling: a driver's read-only getter called with the device of the swap chain the Overlay hooks is inside rule 4 (`CLAUDE.md`, the rule's note of that day). No real game before the owner has seen the result, and nothing shipped changes for the spike (`spike-notes` §31, written after 0.1.0-beta.46). Route C is **refused**; the ETW route **stays closed**, and §G is not reopened. **2026-11-13 — the harness spike is done (`spike-notes` §31), and none of its stop conditions fired.** With a stand-in module: nothing is called or loaded when `nvapi64.dll` is absent, a missing getter is refused whole, an error and a report of nothing read as what they are, and a call the driver holds for seconds stops only the thread that made it — so not the watchdog. With the installed driver (32.0.16.2114, RTX 5080), in the probe's own process and with the probe setting the markers a game would: no fault before `NvAPI_Initialize`, without markers, or across 38 million reads beside a marker-setting thread; a call costs half a microsecond to a microsecond and a half; the report is readable from markers alone, in microseconds; and the Direct3D 12 **device** — the object the Overlay already holds — is what the driver takes. What only a game can say is unanswered: a game's own device, a real report, another driver. **The owner's next word is go or no for one real title**; a go is a plan of its own first. |
| M15 ❓ | **The Streamline state behind `slGetFeatureFunction` — re-examined, not reopened (Train D, 2026-11-11).** The owner asked for the refusal in `handoff/history/p0-queue-1-6.md` to be looked at again. `18_GPU_VENDOR_APIS` §The trains states the route to try (hook the export, hand back a wrapper for a fixed list of names) and what it raises: the wrapper is a write to what the game receives, which rule 4 forbids as written; a wrapper must outlive the Overlay's unhook; a game that fetched its functions before the hook existed is never seen. | **A written design against each of the five grounds, then a spike.** Pre-committed: any ground unanswered → the route stays refused, and `sl.dlssg.*`, `sl.reflex.*` and the rest of that block read N/A with "refused" as the reason. Proceeding needs the owner's amendment of rule 4, asked with the rule quoted. |
| M10 ✅ | ~~PDH `\GPU Engine(*)\Utilization Percentage` summed across engines does not reproduce the Task Manager figure the doc invokes. Decide what we actually report and label it accordingly~~ **Decided 2026-09-09 (PR-E1): L1 does not read the engine counters at all.** `LoadPct` is L2's vendor-reported `GPU Core` load (measured ✓ on NVIDIA, §M5 row R1) and is labelled *GPU load (vendor)* wherever it is shown; on a machine without L2 the field is N/A, never a sum that is not the number the user expects. What L1 does read from PDH is one counter, `\GPU Adapter Memory(luid_…_phys_0)\Dedicated Usage`, bound by LUID — the figure Task Manager labels "Dedicated GPU memory", measured 1301 MB at an idle desktop on the RTX 5080. Reopening this needs a measurement of `max(engine)` against Task Manager's own number, not a decision |
+13 -5
View File
@@ -127,8 +127,13 @@ makes dangerous and what was measured is [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md
Advanced request to its families includes the wait for the watchdog's tick, and batching changes the tick's
phase, so that number went *up* in the test while the install itself went from 0.6 s to 0.08 s. The install is
asserted by count — every lazily installed patch under a `PATCH_BATCH` line — not by time.
- **The spike of route D is still to be written** (`spike-notes` §31): a stub `nvapi64.dll`, an unshipped probe,
a decision table before the runs. Rule 4's note (D132) is in `CLAUDE.md`; nothing shipped calls a driver.
- ~~**The spike of route D is still to be written**~~ **The spike of route D was run the same day** (`spike-notes`
§31; `tools/fl-probe-reflex`, ctest `fl_reflex_probe_stub`): a decision table written before the runs, a stand-in
`nvapi64.dll`, then the installed driver in the probe's own process. None of §30's stop conditions fired. Two
things it decided that a plan must keep: **the call belongs on the presenting thread, once a second** — a call
the driver holds stops the thread that made it, so not the watchdog, and at a microsecond or so it needs no thread
of its own — and **the newest frames of a report are not final** (one run read a span of half an hour in the
newest frame). Rule 4's note (D132) is in `CLAUDE.md`; nothing shipped calls a driver.
### Traps this train left
@@ -153,8 +158,11 @@ makes dangerous and what was measured is [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md
1. **The owner runs item 44** — the first real games on the batches, and the first stop while a game runs since
beta.43. Not first on a game under the user-mode exception's trial (D38).
2. **The spike of Reflex route D on `hook-harness`** (D132): `spike-notes` §31, unshipped code only, ending in the
owner's go or no for one real title. Routes C and E are closed (D133).
2. ~~**The spike of Reflex route D on `hook-harness`**~~ **Done 2026-11-13** (`spike-notes` §31): on the harness
and against the installed driver the two getters are harmless, cost about a microsecond and return a readable
report, and the Direct3D 12 device the Overlay holds is what the driver takes. **The owner's next word is go or no
for one real title** — a go is a plan of its own before any code (where the numbers go, the Disclaimer's and the
Privacy Policy's wording, `nvapi-readonly-check` over the Overlay). Routes C and E are closed (D133).
3. **`slAllocateResources`** keeps its patch (D135); looked at again when there are more sessions.
4. **Train D** after train C, the same way: a spike first — and §30 found its hook would miss a game that fetched
its functions before the attach.
@@ -180,7 +188,7 @@ makes dangerous and what was measured is [`17_HOOK_ENGINE.md`](17_HOOK_ENGINE.md
- **`LIMITATIONS.md` and the accuracy statement still say the processor's, the memory's and the motherboard's
sensors "have never been read on real hardware"** — the owner's to reword. The alpha line still rests (D98).
**Owner-only:** item 44; the go or no on `spike-notes` §31 when it is written; one session each of Valor Mortis and
**Owner-only:** item 44; the go or no on `spike-notes` §31 (one real title); one session each of Valor Mortis and
Black Myth: Wukong with hooking off; what item 41 left unexercised; item 40 (d).
## Owner-only — no PR can close these
+1
View File
@@ -54,3 +54,4 @@ Each section below lives in its own file under `docs/spike-notes/`, moved verbat
| §28 | The main line on .NET 11's release — the whole gate, and what the analyses read (2026-11-11, beta.37, D94–D96) | [`spike-notes/28-dotnet11-main.md`](spike-notes/28-dotnet11-main.md) |
| §29 | C# 15 against the checks — the canary, and where its constructs would go (2026-11-11, beta.37, D96) | [`spike-notes/29-csharp15-canary.md`](spike-notes/29-csharp15-canary.md) |
| §30 | Reflex latency per frame — the routes there are, and what each would cost; a reading, nothing run (2026-11-12, beside beta.45, D130; §M14) | [`spike-notes/30-reflex-latency.md`](spike-notes/30-reflex-latency.md) |
| §31 | Reflex route D on the harness — the driver's two getters called from an unshipped probe, against a stand-in module and the installed driver; no game touched (2026-11-13, after beta.46, D132; §M14) | [`spike-notes/31-reflex-route-d-harness.md`](spike-notes/31-reflex-route-d-harness.md) |
+2 -1
View File
@@ -173,4 +173,5 @@ route.
2. **Route C: refused.**
3. **Route E: left closed**; §G is not reopened.
The spike is `spike-notes` §31, written after 0.1.0-beta.46 is tagged.
The spike is [`spike-notes` §31](31-reflex-route-d-harness.md), run on 2026-11-13: none of the stop conditions
above fired on the harness, and it ends in the question of one real title.
@@ -0,0 +1,96 @@
## 31 · Reflex route D on the harness — the driver's two getters, called from a probe *(2026-11-13, after 0.1.0-beta.46, owner decisions D132, D133; `20_OPEN_QUESTIONS` §M14)*
**Why this was measured.** §30 read the routes to Reflex latency per frame and left one that needs no patch: the
Overlay calling the driver's two getters, `NvAPI_D3D_GetLatency` and `NvAPI_D3D_GetSleepStatus`, with the device of
the swap chain it hooks. The owner said go on 2026-11-13 (D132) — **to a spike on the harness first** — and ruled
that such a call is inside rule 4 (`CLAUDE.md`, the rule's note). This is that spike. **No shipped code changed and
no game was touched**: the call sequence lives in an unshipped probe, and nothing loaded into a game includes it.
**The instrument.** `src/native/tools/fl-probe-reflex` (built with the Overlay's flags; ctest
`fl_reflex_probe_stub` for the half a build machine can run):
- `fl_reflex_candidate.h` — what would move into the Overlay: find `nvapi64.dll` **if the process already holds
it** (never load it), ask its export `nvapi_QueryInterface` for the two getters by the ids of the vendored
`nvapi_interface.h`, call them SEH-guarded, summarise the sixty-four frames. It does not link `nvapi64.lib`:
the static library loads the DLL itself, from a trusted location and with a signature check.
- `--stub`: against `tools/vendor-stubs/stub_nvapi64.cpp`, a stand-in module with knobs for what a driver cannot be
made to do on demand.
- `--real`: against the installed driver on this PC's NVIDIA adapter, **with the probe playing the game's part** —
it loads `nvapi64.dll`, calls `NvAPI_Initialize`, and **sets latency markers on its own device** for a few
hundred frames. That is a write, and it is said here plainly: a getter has nothing to return without it, the
process is the probe's own, and no shipped binary contains the call (D108's read-only rule is about the Agent's
bridge; rule 4's note is about a game). The owner was told and approved it with the plan.
### The decision table, written before any run
| # | Measured | Outcome → consequence |
|---|---|---|
| M1 | Stub: the module absent; a getter absent; an error; a report of nothing; sixty-four reports; both device kinds | Anything called or loaded when the module is absent, or a wrong classification → the candidate is wrong and is fixed before any driver run. Otherwise: these cases are harmless as written. |
| M2 | Stub: a call that does not return for 1.5 s, made on a thread of its own and made by a thread that has other work | Made by the busy thread, that thread stands still → **the call may not be made on the Overlay's watchdog** (it supervises, installs and flushes): a thread of its own, or the presenting thread if M6 allows. A thread of its own is a second background thread, and the Disclaimer's sentence about "one" changes. |
| M3 | Real: the getters **before** `NvAPI_Initialize` | A fault → a game that holds the module but has not initialised it would fault under us, and the Overlay cannot initialise NVAPI itself (not a getter): **route D stops** unless initialisation can be known without a call. An error status → harmless: read as "not available". |
| M4 | Real: initialised, 120 frames, **no marker** | Zero frames or an error → as the header says: a game that does not use Reflex reads N/A. Frames with content → record what the driver fills in by itself. |
| M5 | Real: 300 frames **with markers** | Frames with sensible spans → the report is readable by a third party in the process. Zero frames → markers alone are not enough (a sleep mode is needed too): route D reads only games that set one, and the note says so. |
| M6 | Real: the cost of one call (2000 calls, on the presenting thread) | NFR-1 allows 1 µs a present. Once a second on the presenting thread costs `call / presents-a-second` a present: at 60 a second a call may cost 60 µs. Median within that → the presenting thread, once a second, is allowed. Above it, or a worst case over 1 ms → **never on the presenting thread**; a thread of its own (M2). |
| M7 | Real: the getters on another thread four times a second for 60 s, beside a thread that presents and sets markers | **Any fault → route D stops** (pre-committed, §30). Error statuses or empty reports → recorded; they decide whether a read is trusted. Frames a second beside the poller more than 0.5 % below alone → the rate is too high or the route too costly: lower it and measure again, or stop. |
| M8 | Real, Direct3D 12: read with the device, read with the queue, markers on each | The device works → the Overlay already holds it (`g_d3d12Device`). **Only the queue works → Direct3D 12 is out of reach**: the Overlay does not hold the queue (`ResolveApi`: `GetDevice` does not return it) and may not go looking for it. Route D would then be Direct3D 11 only. |
| M9 | Real: the unit of the report's times | The gap between two frames' `simStartTime` against the probe's own frame time. Whatever it is, is recorded; a unit that cannot be told → the spans are not shown as times. |
Not in this spike, whatever it shows: anything in a game; where the numbers would go (shared memory, the Agent, the
page); the wording of the Disclaimer and the Privacy Policy. Those are a plan of their own, after the owner's go.
### Results
**Where.** The dev box of §Environment: Windows 11 Pro build 29648, RTX 5080, NVIDIA driver 32.0.16.2114
(`nvapi64.dll` of the same version), 2026-11-13. `--stub` on software devices; `--real` three times (and a fourth,
shorter, after a fix to the probe — row M6), on the NVIDIA
adapter, each with a 256×256 composition swap chain presented without a wait — some 14,000 to 17,000 frames a
second, which is what makes the cost of anything beside it visible and is nothing like a game.
| # | What was seen | Against the table |
|---|---|---|
| M1 | Stub, all 20 checks pass: with the module absent `Resolve` says so, calls nothing and loads nothing; a module without the getters is refused whole; an error comes back as the error; a report of nothing is zero frames; sixty-four reports are read as the header lays them out; the driver is handed the device and only the device, Direct3D 11 and Direct3D 12 alike; no device, no call. | Harmless as written. |
| M2 | A call held for 1.5 s on a thread of its own: another thread ticked 16 times in its first second. The same call made by that ticking thread: **0 ticks** in the second. | **Not on the watchdog.** A thread of its own, or the presenting thread (M6). |
| M3 | The getters **before** `NvAPI_Initialize`, with the module loaded: both resolve, `GetLatency` returns `NVAPI_OK` and sixty-four empty frames. No fault, three runs. | Harmless: an uninitialised NVAPI reads as "nothing reported". |
| M4 | Initialised, 120 frames, no marker: `NVAPI_OK`, zero frames with anything; the sleep status is `NVAPI_OK` with every field zero. | As the header says. A game that does not use Reflex reads N/A, and the read costs it nothing else. |
| M5 | 300 frames with markers, **no sleep mode set**: sixty-four frames, the newest one or two ids behind the last frame drawn. Per frame the driver fills simulation end, render submit start/end, present start/end, driver end, OS queue start/end and GPU start/end; `inputSampleTime` and `driverStartTime` stay zero (the probe sets no input marker). | **Readable by a third party in the process, from markers alone.** |
| M6 | 2000 calls back to back on the presenting thread: `GetLatency` median **0.50 µs** in the three runs (mean 0.53–0.54, worst 1.2 / 1.5 / 3.0 µs) and **1.50 µs in a fourth**, made that evening after a fix to the probe, with the PC doing other things (mean 1.54, worst 70 µs); `GetSleepStatus` median 0.10 µs in all four, worst 0.7 / 0.8 / 62 / 12 µs. | **Far within NFR-1 once a second**: at 60 presents a second a call may cost 60 µs, and the medians are 0.5–1.5. **Not within it at every present**: the fourth run's median alone is over the microsecond NFR-1 allows a present, and single calls of 62 and 70 µs were seen. Once a second is what is proposed. |
| M7 | 60 s, four reads a second from another thread beside the presenting, marker-setting thread, three runs: **228 reads each, none not OK, none faulted, none empty**; worst read 103 / 112 / 248 µs on the polling thread; no marker error. Frames a second beside the poller against alone: −1.3 % (one 60 s leg against one 5 s leg), then in six alternating 10 s legs −1.4 % and −0.6 % — **with single legs between +5.9 % and −9.9 %**. | **No fault: the route does not stop.** The half-percent line cannot be read off this: the loop's own drift from leg to leg is ten times it, in both directions. So a dose was measured instead — next row. |
| M7b | The same poller **never pausing**: 38.3 million reads in 30 s (**1.28 million a second**), none not OK, none faulted, worst read 2.7 ms; frames a second −3.3 % (legs −1.1 %, −5.3 %, −3.7 %). | Three hundred thousand times the proposed rate costs about three percent of an uncapped loop. Four reads a second is that divided by 320,000: not measurable, and not half a percent. **The driver also took 38 million reads beside some three million marker calls without an error** — the concurrency §30 could only infer. |
| M8 | Direct3D 12: markers set with the **device** — no error; read with the device and read with the queue both return the same sixty-four frames; the sleep status is `NVAPI_OK` with either; markers set with the queue work as well and are read back with the device. | **The device works**, and it is the object the Overlay already holds. |
| M9 | `simStartTime` of two neighbouring frames 91 and 43 apart in two runs where the probe measured 81 and 64 µs a frame, and the absolute values are the time of day (1 794 560 148 756 529 on 2026-11-13). | **Microseconds, on the clock of the Unix epoch.** Spans are differences of two of them. |
**One thing seen that is not understood.** In the first of the three runs the newest frame of the Direct3D 11
report had a `presentEndTime` 1 844 674 519 µs — half an hour — after its own `simStartTime`; the other two runs
show 36–72 µs there, and the Direct3D 12 reads 46–51 µs every time. The frame was the newest in the report, read
within microseconds of being presented. Whatever it was, **the newest frames of a report are not final**: a reader
must not take the last few as complete, and must refuse a span that no frame can have.
### What this settles, and what it does not
- **Settled, on this driver and this adapter**: the two getters can be found without loading anything and called
with a Direct3D 11 device or the Direct3D 12 device the Overlay holds; they do not fault before initialisation,
without markers, or beside a thread that sets markers at 16,000 frames a second; a call costs half a microsecond
to a microsecond and a half;
the report is readable from markers alone and its unit is known. None of §30's stop conditions fired: no fault or
hang attributable to the call, no overhead near NFR-1, and the Direct3D 12 device is the one already held.
- **Decided by M2 and M6 together**: the call belongs on the **presenting thread, once a second** — a microsecond
or so a second, with a worst case seen of 70 µs — not on the watchdog and not on a new thread. So the Disclaimer's "one background thread"
would not change; what would change is its list of what the part inside the game does at a present.
- **Not settled, because only a game can say**: a game's own device — many threads, deferred contexts, a device a
game is about to release; what a real title's report holds (input sample, the GPU times of a real frame, frame
generation's `aiFrameTimeUs`); whether a title that uses Reflex through Streamline alone leaves `nvapi64.dll`
findable by name (not looked at); a driver other than 32.0.16.2114, and any card but this
one; a call that blocks — the stub shows what a block does to its thread, and nothing here made the driver block.
- **Not looked into**: Direct3D 11 in the Overlay, which keeps no D3D11 device today (`ResolveApi` releases it):
reading there means holding one, a reference the Overlay does not take now; and the incomplete newest frame above.
### The question for the owner
**Go to one real title, or stop here?** A go means a plan of its own before any code: the two calls in the present
detour once a second, **only while a session asks for Advanced metrics** (D111), only where the game already
loaded `nvapi64.dll`, Direct3D 12 first (the device is already held); a place for the numbers — a series beside the
frames, since a report arrives after its frame's record is written (§30); `nvapi-readonly-check` extended to the
Overlay and taught that `Sleep` is a writer; the Disclaimer's and the Privacy Policy's wording; the first run on a
title of the owner's choosing that is not inside the anti-cheat exception's trial (D38), with what each outcome
means written before it. A no leaves `nvapi.reflex.*` and `sl.reflex.*` at N/A with the reason, and this note as
the record of why it was within reach.
+1
View File
@@ -8,4 +8,5 @@ add_subdirectory(fl-probe-processstats)
add_subdirectory(fl-probe-signer)
add_subdirectory(fl-probe-vklayer)
add_subdirectory(vendor-stubs)
add_subdirectory(fl-probe-reflex)
add_subdirectory(hook-harness)
@@ -0,0 +1,22 @@
# 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.
#
# 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_compile_definitions(fl-probe-reflex PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
add_dependencies(fl-probe-reflex fl_stub_nvapi64)
# The half a build machine can run: the candidate against the stand-in module -- absent, without its getters, a
# report of nothing, an error, sixty-four reports, both device kinds, a call that does not come back for a while.
# Software devices; exit 77 where there is no Direct3D 11 at all. `--real` (the installed driver, an NVIDIA adapter)
# is a measurement the note records, never a test.
add_test(NAME fl_reflex_probe_stub COMMAND fl-probe-reflex --stub "$<TARGET_FILE:fl_stub_nvapi64>")
set_tests_properties(fl_reflex_probe_stub PROPERTIES SKIP_RETURN_CODE 77)
@@ -0,0 +1,128 @@
// 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 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.
#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>
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 {
std::uint32_t valid = 0;
std::uint64_t newestFrameId = 0;
std::uint64_t newestSimToPresentEnd = 0;
std::uint64_t newestSimToGpuEnd = 0;
std::uint32_t newestGpuActiveUs = 0;
};
inline Digest Summarise(const NV_LATENCY_RESULT_PARAMS& report) noexcept {
Digest d{};
for (int i = 0; i < 64; ++i) {
const auto& r = report.frameReport[i];
if (r.frameID == 0u && r.simStartTime == 0u && r.gpuRenderEndTime == 0u) {
continue;
}
++d.valid;
d.newestFrameId = r.frameID;
d.newestSimToPresentEnd = r.presentEndTime >= r.simStartTime ? r.presentEndTime - r.simStartTime : 0u;
d.newestSimToGpuEnd = r.gpuRenderEndTime >= r.simStartTime ? r.gpuRenderEndTime - r.simStartTime : 0u;
d.newestGpuActiveUs = r.gpuActiveRenderTimeUs;
}
return d;
}
} // namespace fl::reflex
#endif // FRAMELEDGER_FL_REFLEX_CANDIDATE_H
+708
View File
@@ -0,0 +1,708 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
// fl-probe-reflex -- the instrument of docs/spike-notes §31 (Reflex route D, owner decision D132). NOT SHIPPED, and it
// touches no game: it runs the call sequence of fl_reflex_candidate.h in its own process, against two things.
//
// --stub <path> a stand-in nvapi64.dll (tools/vendor-stubs/stub_nvapi64.cpp): the module absent, a getter absent,
// a report of nothing, an error, sixty-four reports, both device kinds, and a call that does not come
// back for seconds. ctest fl_reflex_probe_stub. Software devices are enough: the stub does not look.
// --real the installed driver, on this PC's NVIDIA adapter, with the probe playing the game's part: it
// loads nvapi64.dll itself, initialises it, and SETS LATENCY MARKERS ON ITS OWN DEVICE for a few
// hundred frames -- a write, made here because a getter has nothing to return without it, in a
// process that is nobody's game. Then it measures what route D would do: the two getters. A
// measurement, not a test: exit 77 where there is no NVIDIA adapter.
//
// Built with the Overlay's own flags, because the candidate is the Overlay's code-to-be.
#include <windows.h>
#include <d3d11.h>
#include <d3d12.h>
#include <dxgi1_4.h>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include "fl_reflex_candidate.h"
namespace {
int g_failures = 0;
void Check(bool ok, const char* what) noexcept {
std::printf("%s %s\n", ok ? "PASS" : "FAIL", what);
if (!ok) {
++g_failures;
}
}
template <class T>
void ReleaseIf(T*& p) noexcept {
if (p != nullptr) {
p->Release();
p = nullptr;
}
}
double QpcSeconds() noexcept {
// QuadPart named in the initialiser, so the member read back is the one the union holds (cpp:S6232).
LARGE_INTEGER f{.QuadPart = 0};
LARGE_INTEGER c{.QuadPart = 0};
QueryPerformanceFrequency(&f);
QueryPerformanceCounter(&c);
return static_cast<double>(c.QuadPart) / static_cast<double>(f.QuadPart);
}
// ---------------------------------------------------------------------------------------------------------------------
// Devices. `nvidia` picks this PC's NVIDIA adapter (vendor 0x10DE) or fails; otherwise the software adapter.
// ---------------------------------------------------------------------------------------------------------------------
IDXGIAdapter1* FindAdapter(IDXGIFactory4* factory, bool nvidia) noexcept {
if (!nvidia) {
IDXGIAdapter1* warp = nullptr;
factory->EnumWarpAdapter(__uuidof(IDXGIAdapter1), reinterpret_cast<void**>(&warp));
return warp;
}
for (UINT i = 0;; ++i) {
IDXGIAdapter1* adapter = nullptr;
if (factory->EnumAdapters1(i, &adapter) != S_OK) {
return nullptr;
}
DXGI_ADAPTER_DESC1 desc{};
if (SUCCEEDED(adapter->GetDesc1(&desc)) && desc.VendorId == 0x10DEu &&
(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0u) {
return adapter;
}
adapter->Release();
}
}
struct Dx11 {
ID3D11Device* device = nullptr;
ID3D11DeviceContext* context = nullptr;
IDXGISwapChain1* chain = nullptr;
ID3D11RenderTargetView* target = nullptr;
};
bool MakeDx11(IDXGIFactory4* factory, IDXGIAdapter1* adapter, Dx11& out) noexcept {
if (FAILED(D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr,
0, D3D11_SDK_VERSION, &out.device, nullptr, &out.context))) {
return false;
}
DXGI_SWAP_CHAIN_DESC1 desc{};
desc.Width = 256;
desc.Height = 256;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = 2;
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
if (FAILED(factory->CreateSwapChainForComposition(out.device, &desc, nullptr, &out.chain))) {
return false;
}
ID3D11Texture2D* back = nullptr;
if (FAILED(out.chain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&back)))) {
return false;
}
const HRESULT hr = out.device->CreateRenderTargetView(back, nullptr, &out.target);
back->Release();
return SUCCEEDED(hr);
}
void FreeDx11(Dx11& d) noexcept {
ReleaseIf(d.target);
ReleaseIf(d.chain);
ReleaseIf(d.context);
ReleaseIf(d.device);
}
struct Dx12 {
ID3D12Device* device = nullptr;
ID3D12CommandQueue* queue = nullptr;
IDXGISwapChain1* chain = nullptr;
};
bool MakeDx12(IDXGIFactory4* factory, IDXGIAdapter1* adapter, Dx12& out) noexcept {
if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device),
reinterpret_cast<void**>(&out.device)))) {
return false;
}
D3D12_COMMAND_QUEUE_DESC q{};
q.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
if (FAILED(
out.device->CreateCommandQueue(&q, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&out.queue)))) {
return false;
}
DXGI_SWAP_CHAIN_DESC1 desc{};
desc.Width = 256;
desc.Height = 256;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = 2;
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
return SUCCEEDED(factory->CreateSwapChainForComposition(out.queue, &desc, nullptr, &out.chain));
}
void FreeDx12(Dx12& d) noexcept {
ReleaseIf(d.chain);
ReleaseIf(d.queue);
ReleaseIf(d.device);
}
// ---------------------------------------------------------------------------------------------------------------------
// --stub
// ---------------------------------------------------------------------------------------------------------------------
using SetU32Fn = void(__cdecl*)(std::uint32_t);
using GetU32Fn = std::uint32_t(__cdecl*)();
using GetPtrFn = void*(__cdecl*)();
struct BlockedCall {
fl::reflex::Api api;
IUnknown* device;
NvAPI_Status status;
};
DWORD WINAPI BlockedCallThread(LPVOID p) noexcept {
auto* call = static_cast<BlockedCall*>(p);
static NV_LATENCY_RESULT_PARAMS report; // 15 KB: not on a new thread's stack for no reason
call->status = fl::reflex::ReadLatency(call->api, call->device, report);
return 0;
}
// A stand-in for the Overlay's watchdog: a loop that ticks every 50 ms and, when told, makes the call ITSELF.
struct Ticker {
std::atomic<std::uint32_t> ticks{0};
std::atomic<std::uint32_t> callNow{0};
std::atomic<std::uint32_t> quit{0};
fl::reflex::Api api;
IUnknown* device = nullptr;
};
DWORD WINAPI TickerThread(LPVOID p) noexcept {
auto* t = static_cast<Ticker*>(p);
static NV_LATENCY_RESULT_PARAMS report;
while (t->quit.load(std::memory_order_acquire) == 0u) {
if (t->callNow.exchange(0u, std::memory_order_acq_rel) != 0u) {
fl::reflex::ReadLatency(t->api, t->device, report);
}
t->ticks.fetch_add(1u, std::memory_order_relaxed);
Sleep(50);
}
return 0;
}
int RunStub(const wchar_t* stubPath) noexcept {
using fl::reflex::Resolved;
fl::reflex::Api api{};
// 1. The module is not in the process: nothing is called, and nothing gets loaded by asking.
Check(GetModuleHandleW(L"nvapi64.dll") == nullptr, "before: no nvapi64.dll in this process");
Check(fl::reflex::Resolve(api) == Resolved::NoModule, "module absent -> NoModule");
Check(GetModuleHandleW(L"nvapi64.dll") == nullptr, "resolving loaded nothing");
Check(api.getLatency == nullptr && api.getSleepStatus == nullptr, "no address was kept");
HMODULE stub = LoadLibraryExW(stubPath, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (stub == nullptr) {
std::printf("FAIL the stub did not load (%lu)\n", GetLastError());
return 1;
}
const auto setMode = reinterpret_cast<SetU32Fn>(GetProcAddress(stub, "FlStubNvSetMode"));
const auto setBlock = reinterpret_cast<SetU32Fn>(GetProcAddress(stub, "FlStubNvSetBlockMs"));
const auto hide = reinterpret_cast<SetU32Fn>(GetProcAddress(stub, "FlStubNvHideGetters"));
const auto latencyCalls = reinterpret_cast<GetU32Fn>(GetProcAddress(stub, "FlStubNvLatencyCalls"));
const auto lastDevice = reinterpret_cast<GetPtrFn>(GetProcAddress(stub, "FlStubNvLastDevice"));
if (setMode == nullptr || setBlock == nullptr || hide == nullptr || latencyCalls == nullptr ||
lastDevice == nullptr) {
std::printf("FAIL the module at that path is not the stub\n");
return 1;
}
// 2. A module that does not have the getters.
hide(1u);
Check(fl::reflex::Resolve(api) == Resolved::NoGetter, "a getter the module does not have -> NoGetter");
Check(api.getLatency == nullptr, "and nothing half-resolved is kept");
hide(0u);
Check(fl::reflex::Resolve(api) == Resolved::Ok, "both getters resolved by interface id");
IDXGIFactory4* factory = nullptr;
if (FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory)))) {
std::printf("SKIP no DXGI factory\n");
return 77;
}
IDXGIAdapter1* adapter = FindAdapter(factory, false);
Dx11 dx11{};
Dx12 dx12{};
const bool have11 = MakeDx11(factory, adapter, dx11);
const bool have12 = MakeDx12(factory, adapter, dx12);
if (!have11) {
std::printf("SKIP no Direct3D 11 device here\n");
return 77;
}
static NV_LATENCY_RESULT_PARAMS report;
NV_GET_SLEEP_STATUS_PARAMS sleep{};
// 3. Sixty-four reports, read as the header lays them out, with the device handed through untouched.
setMode(0u);
Check(fl::reflex::ReadLatency(api, dx11.device, report) == NVAPI_OK, "D3D11: the report is read");
fl::reflex::Digest d = fl::reflex::Summarise(report);
Check(d.valid == 64u && d.newestFrameId == 5063u, "sixty-four frames, the newest last");
Check(d.newestSimToPresentEnd == 2200u && d.newestSimToGpuEnd == 7500u && d.newestGpuActiveUs == 3500u,
"the spans are the ones the stub wrote");
Check(lastDevice() == dx11.device, "the driver was handed the device, and only the device");
if (have12) {
Check(fl::reflex::ReadLatency(api, dx12.device, report) == NVAPI_OK && lastDevice() == dx12.device,
"D3D12: the same call with the ID3D12Device the Overlay already holds");
} else {
std::printf("NOTE no Direct3D 12 device here; that half is not run\n");
}
Check(fl::reflex::ReadSleepStatus(api, dx11.device, sleep) == NVAPI_OK && sleep.bLowLatencyMode != 0 &&
sleep.sleepIntervalUs == 4166u && sleep.fgMultiplier == 2,
"the sleep status is read");
// 4. A game that set no marker (nvapi.h: every frame comes back zero), and a driver that says no.
setMode(1u);
Check(fl::reflex::ReadLatency(api, dx11.device, report) == NVAPI_OK && fl::reflex::Summarise(report).valid == 0u,
"a report of nothing is zero frames, not sixty-four");
setMode(2u);
Check(fl::reflex::ReadLatency(api, dx11.device, report) == NVAPI_ERROR, "an error is returned as the error");
Check(fl::reflex::ReadSleepStatus(api, dx11.device, sleep) == NVAPI_ERROR, "for the sleep status as well");
Check(fl::reflex::ReadLatency(api, nullptr, report) == NVAPI_INVALID_ARGUMENT &&
latencyCalls() == (have12 ? 4u : 3u),
"no device, no call: the driver was not entered");
setMode(0u);
// 5. A call that does not come back for a while. On a thread of its own, nothing else waits for it...
setBlock(1500u);
Ticker ticker{};
ticker.api = api;
ticker.device = dx11.device;
HANDLE tick = CreateThread(nullptr, 0, &TickerThread, &ticker, 0, nullptr);
Sleep(300);
BlockedCall blocked{api, dx11.device, NVAPI_ERROR};
const std::uint32_t before = ticker.ticks.load();
const double began = QpcSeconds();
HANDLE caller = CreateThread(nullptr, 0, &BlockedCallThread, &blocked, 0, nullptr);
Sleep(1000);
const std::uint32_t during = ticker.ticks.load() - before;
Check(during >= 10u, "a call blocked on its own thread: the ticking thread went on (>= 10 ticks in the second)");
WaitForSingleObject(caller, 5000);
const double took = QpcSeconds() - began;
Check(blocked.status == NVAPI_OK && took >= 1.4, "and the blocked call came back with its report");
std::printf("NOTE the blocked call took %.2f s; the other thread ticked %u times in its first second\n", took,
during);
CloseHandle(caller);
// ...and made BY the ticking thread, that thread stands still for as long as the driver keeps it.
const std::uint32_t before2 = ticker.ticks.load();
ticker.callNow.store(1u);
Sleep(1000);
const std::uint32_t during2 = ticker.ticks.load() - before2;
Check(during2 <= 3u, "the same call made by the ticking thread: it stopped ticking while the driver held it");
std::printf("NOTE made by the ticking thread itself, it ticked %u times in that second\n", during2);
Sleep(1000);
ticker.quit.store(1u);
WaitForSingleObject(tick, 3000);
CloseHandle(tick);
setBlock(0u);
FreeDx12(dx12);
FreeDx11(dx11);
ReleaseIf(adapter);
ReleaseIf(factory);
std::printf("%s: %d failure(s)\n", g_failures == 0 ? "STUB OK" : "STUB FAILED", g_failures);
return g_failures == 0 ? 0 : 1;
}
// ---------------------------------------------------------------------------------------------------------------------
// --real: the installed driver. The probe is the "game" here: it loads NVAPI, initialises it and sets markers.
// ---------------------------------------------------------------------------------------------------------------------
constexpr unsigned int kIdInitialize = 0x0150e828u; // nvapi_interface.h: NvAPI_Initialize
constexpr unsigned int kIdUnload = 0xd22bdd7eu; // NvAPI_Unload
constexpr unsigned int kIdSetLatencyMarker = 0xd9984c05u; // NvAPI_D3D_SetLatencyMarker -- the game's call
using PlainFn = NvAPI_Status(__cdecl*)();
using SetMarkerFn = NvAPI_Status(__cdecl*)(IUnknown*, NV_LATENCY_MARKER_PARAMS*);
struct Game {
SetMarkerFn setMarker = nullptr;
IUnknown* markerDevice = nullptr;
std::uint64_t frame = 0;
std::uint32_t markerErrors = 0;
NvAPI_Status lastMarkerStatus = NVAPI_OK;
};
void Mark(Game& g, NV_LATENCY_MARKER_TYPE type) noexcept {
NV_LATENCY_MARKER_PARAMS p{};
p.version = NV_LATENCY_MARKER_PARAMS_VER1;
p.frameID = g.frame;
p.markerType = type;
const NvAPI_Status s = g.setMarker(g.markerDevice, &p);
if (s != NVAPI_OK) {
++g.markerErrors;
g.lastMarkerStatus = s;
}
}
void Frame11(Game& g, Dx11& dx, bool markers) noexcept {
++g.frame;
if (markers) {
Mark(g, SIMULATION_START);
Mark(g, SIMULATION_END);
Mark(g, RENDERSUBMIT_START);
}
const float colour[4] = {static_cast<float>(g.frame % 255u) / 255.0f, 0.2f, 0.4f, 1.0f};
dx.context->OMSetRenderTargets(1, &dx.target, nullptr);
dx.context->ClearRenderTargetView(dx.target, colour);
if (markers) {
Mark(g, RENDERSUBMIT_END);
Mark(g, PRESENT_START);
}
dx.chain->Present(0, 0);
if (markers) {
Mark(g, PRESENT_END);
}
}
void Frame12(Game& g, Dx12& dx) noexcept {
++g.frame;
Mark(g, SIMULATION_START);
Mark(g, SIMULATION_END);
Mark(g, RENDERSUBMIT_START);
Mark(g, RENDERSUBMIT_END);
Mark(g, PRESENT_START);
dx.chain->Present(0, 0);
Mark(g, PRESENT_END);
}
void PrintDigest(const char* label, NvAPI_Status status, const NV_LATENCY_RESULT_PARAMS& report) noexcept {
const fl::reflex::Digest d = fl::reflex::Summarise(report);
std::printf("%-46s status %d, frames with anything %u, newest id %llu, sim->presentEnd %llu, sim->gpuEnd %llu, "
"gpuActive %u us\n",
label, static_cast<int>(status), d.valid, static_cast<unsigned long long>(d.newestFrameId),
static_cast<unsigned long long>(d.newestSimToPresentEnd),
static_cast<unsigned long long>(d.newestSimToGpuEnd), d.newestGpuActiveUs);
}
struct Poller {
fl::reflex::Api api;
IUnknown* device = nullptr;
std::atomic<std::uint32_t> quit{0};
std::atomic<std::uint32_t> paused{0};
std::atomic<std::uint32_t> intervalMs{250}; // 0: one read after another, as fast as the driver answers
std::uint32_t calls = 0;
std::uint32_t notOk = 0;
std::uint32_t faults = 0;
double worstSeconds = 0.0;
std::uint32_t emptyReports = 0;
};
DWORD WINAPI PollerThread(LPVOID p) noexcept {
auto* poll = static_cast<Poller*>(p);
static NV_LATENCY_RESULT_PARAMS report;
NV_GET_SLEEP_STATUS_PARAMS sleep{};
while (poll->quit.load(std::memory_order_acquire) == 0u) {
if (poll->paused.load(std::memory_order_acquire) != 0u) {
Sleep(50);
continue;
}
const double t0 = QpcSeconds();
const NvAPI_Status a = fl::reflex::ReadLatency(poll->api, poll->device, report);
const NvAPI_Status b = fl::reflex::ReadSleepStatus(poll->api, poll->device, sleep);
const double took = QpcSeconds() - t0;
++poll->calls;
poll->notOk += (a != NVAPI_OK || b != NVAPI_OK) ? 1u : 0u;
poll->faults += (a == fl::reflex::kFaulted || b == fl::reflex::kFaulted) ? 1u : 0u;
poll->emptyReports += (a == NVAPI_OK && fl::reflex::Summarise(report).valid == 0u) ? 1u : 0u;
if (took > poll->worstSeconds) {
poll->worstSeconds = took;
}
const std::uint32_t interval = poll->intervalMs.load(std::memory_order_relaxed);
if (interval != 0u) {
Sleep(interval);
}
}
return 0;
}
// Microseconds a call, over `n` calls: the mean, the median and the worst.
struct Cost {
double mean = 0.0;
double median = 0.0;
double worst = 0.0;
};
template <class Call>
Cost Measure(int n, const Call& call) noexcept {
static double samples[4096];
if (n <= 0) {
return Cost{};
}
if (n > 4096) {
n = 4096;
}
double sum = 0.0;
for (int i = 0; i < n; ++i) {
const double t0 = QpcSeconds();
call();
samples[i] = (QpcSeconds() - t0) * 1e6;
sum += samples[i];
}
for (int i = 1; i < n; ++i) { // insertion sort: a few thousand doubles, once
const double v = samples[i];
int j = i - 1;
while (j >= 0 && samples[j] > v) {
samples[j + 1] = samples[j];
--j;
}
samples[j + 1] = v;
}
return Cost{sum / n, samples[n / 2], samples[n - 1]};
}
double FramesPerSecond11(Game& g, Dx11& dx, double seconds) noexcept {
const double t0 = QpcSeconds();
std::uint32_t frames = 0;
while (QpcSeconds() - t0 < seconds) {
Frame11(g, dx, true);
++frames;
}
return static_cast<double>(frames) / (QpcSeconds() - t0);
}
int RunReal(int pollSeconds) noexcept {
IDXGIFactory4* factory = nullptr;
if (FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory)))) {
std::printf("SKIP no DXGI factory\n");
return 77;
}
IDXGIAdapter1* adapter = FindAdapter(factory, true);
if (adapter == nullptr) {
std::printf("SKIP no NVIDIA adapter on this PC\n");
return 77;
}
DXGI_ADAPTER_DESC1 desc{};
adapter->GetDesc1(&desc);
std::printf("adapter: %ls\n", desc.Description);
// THE GAME'S PART: nvapi64.dll from the system directory, by full path, and NvAPI_Initialize.
wchar_t path[MAX_PATH]{};
const UINT n = GetSystemDirectoryW(path, MAX_PATH);
if (n == 0 || n + 16 > MAX_PATH) {
return 77;
}
wcscat_s(path, L"\\nvapi64.dll");
fl::reflex::Api api{};
std::printf("before the game loaded it: Resolve = %u (1 = NoModule)\n",
static_cast<unsigned>(fl::reflex::Resolve(api)));
HMODULE nvapi = LoadLibraryExW(path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (nvapi == nullptr) {
std::printf("SKIP %ls did not load (%lu)\n", path, GetLastError());
return 77;
}
const auto query = reinterpret_cast<fl::reflex::QueryInterfaceFn>(GetProcAddress(nvapi, "nvapi_QueryInterface"));
const auto initialize = query != nullptr ? reinterpret_cast<PlainFn>(query(kIdInitialize)) : nullptr;
const auto unload = query != nullptr ? reinterpret_cast<PlainFn>(query(kIdUnload)) : nullptr;
Game game{};
game.setMarker = query != nullptr ? reinterpret_cast<SetMarkerFn>(query(kIdSetLatencyMarker)) : nullptr;
if (initialize == nullptr || game.setMarker == nullptr) {
std::printf("SKIP this nvapi64.dll does not answer the ids\n");
return 77;
}
Dx11 dx11{};
if (!MakeDx11(factory, adapter, dx11)) {
std::printf("SKIP no Direct3D 11 device on the NVIDIA adapter\n");
return 77;
}
static NV_LATENCY_RESULT_PARAMS report;
NV_GET_SLEEP_STATUS_PARAMS sleep{};
// 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);
std::printf("NvAPI_Initialize: %d\n", static_cast<int>(initialize()));
// R1. Initialised, no marker ever set: what a game that does not use Reflex gives.
for (int i = 0; i < 120; ++i) {
Frame11(game, dx11, false);
}
PrintDigest("R1 D3D11, 120 frames, no marker:", fl::reflex::ReadLatency(api, dx11.device, report), report);
const NvAPI_Status s1 = fl::reflex::ReadSleepStatus(api, dx11.device, sleep);
std::printf(" sleep status %d: lowLatency %u, fsVrr %u, cplVsync %u, interval %u us, gameSleep %u, iFlip %u, "
"fgMultiplier %u\n",
static_cast<int>(s1), static_cast<unsigned>(sleep.bLowLatencyMode), static_cast<unsigned>(sleep.bFsVrr),
static_cast<unsigned>(sleep.bCplVsyncOn), static_cast<unsigned>(sleep.sleepIntervalUs),
static_cast<unsigned>(sleep.bUseGameSleep), static_cast<unsigned>(sleep.bFullscreenIFlip),
static_cast<unsigned>(sleep.fgMultiplier));
// R2. The game sets markers: 300 frames.
game.markerDevice = dx11.device;
const double began = QpcSeconds();
for (int i = 0; i < 300; ++i) {
Frame11(game, dx11, true);
}
const double frameSeconds = (QpcSeconds() - began) / 300.0;
std::printf("markers: %u error(s), last status %d; a frame took %.1f us by this probe's clock\n", game.markerErrors,
static_cast<int>(game.lastMarkerStatus), frameSeconds * 1e6);
PrintDigest("R2 D3D11, 300 frames with markers:", fl::reflex::ReadLatency(api, dx11.device, report), report);
{
// The unit of the report's times: the gap between two neighbouring frames' simStartTime against the probe's
// own measured frame time.
const auto& a = report.frameReport[62];
const auto& b = report.frameReport[63];
std::printf(" frames 62,63: id %llu,%llu simStart %llu,%llu (gap %llu) gpuFrameTimeUs %u\n",
static_cast<unsigned long long>(a.frameID), static_cast<unsigned long long>(b.frameID),
static_cast<unsigned long long>(a.simStartTime), static_cast<unsigned long long>(b.simStartTime),
static_cast<unsigned long long>(b.simStartTime - a.simStartTime),
static_cast<unsigned>(b.gpuFrameTimeUs));
// Every time of the last four frames, as its distance from that frame's simStartTime ("-" where the driver
// left the field zero): which fields a report fills in, and when a frame's report is complete.
for (int i = 60; i < 64; ++i) {
const auto& r = report.frameReport[i];
const std::uint64_t fields[] = {r.inputSampleTime, r.simEndTime, r.renderSubmitStartTime,
r.renderSubmitEndTime, r.presentStartTime, r.presentEndTime,
r.driverStartTime, r.driverEndTime, r.osRenderQueueStartTime,
r.osRenderQueueEndTime, r.gpuRenderStartTime, r.gpuRenderEndTime};
static const char* const names[] = {"input", "simEnd", "subStart", "subEnd", "presStart", "presEnd",
"drvStart", "drvEnd", "osqStart", "osqEnd", "gpuStart", "gpuEnd"};
std::printf(" frame %d id %llu:", i, static_cast<unsigned long long>(r.frameID));
for (int f = 0; f < 12; ++f) {
if (fields[f] == 0u) {
std::printf(" %s -", names[f]);
} else {
std::printf(" %s %lld", names[f],
static_cast<long long>(fields[f]) - static_cast<long long>(r.simStartTime));
}
}
std::printf(" | gpuActive %u gpuFrame %u\n", static_cast<unsigned>(r.gpuActiveRenderTimeUs),
static_cast<unsigned>(r.gpuFrameTimeUs));
}
}
// R3. What a call costs, on the thread that presents, between two frames.
const Cost latency = Measure(2000, [&]() noexcept { fl::reflex::ReadLatency(api, dx11.device, report); });
const Cost status = Measure(2000, [&]() noexcept { fl::reflex::ReadSleepStatus(api, dx11.device, sleep); });
std::printf("R3 GetLatency us a call: mean %.2f, median %.2f, worst %.2f (2000 calls)\n", latency.mean,
latency.median, latency.worst);
std::printf("R3 GetSleepStatus us a call: mean %.2f, median %.2f, worst %.2f (2000 calls)\n", status.mean,
status.median, status.worst);
// R4. The getters on ANOTHER thread, four times a second, while this one presents and sets markers.
// LEGS OF TEN SECONDS, ALTERNATING -- alone, beside the poller, alone, ... -- because one long leg against one
// short one measures the drift of an uncapped loop over a minute, not the poller (the first run of this probe
// compared 5 s alone with 60 s beside and read 1.3 % apart).
Poller poll{};
poll.api = api;
poll.device = dx11.device;
poll.paused.store(1u);
HANDLE thread = CreateThread(nullptr, 0, &PollerThread, &poll, 0, nullptr);
double aloneSum = 0.0;
double besideSum = 0.0;
const int legs = pollSeconds / 10 > 0 ? pollSeconds / 10 : 1;
for (int leg = 0; leg < legs; ++leg) {
poll.paused.store(1u);
const double alone = FramesPerSecond11(game, dx11, 10.0);
poll.paused.store(0u);
const double beside = FramesPerSecond11(game, dx11, 10.0);
aloneSum += alone;
besideSum += beside;
std::printf("R4 leg %d: frames a second %.0f alone, %.0f beside the poller (%+.2f %%)\n", leg + 1, alone,
beside, (beside - alone) * 100.0 / alone);
}
const std::uint32_t slowCalls = poll.calls;
const std::uint32_t slowNotOk = poll.notOk;
const double slowWorst = poll.worstSeconds;
// THE SAME WITH THE POLLER READING WITHOUT A PAUSE -- hundreds of thousands of reads a second where route D would
// make four. The legs above cannot tell half a percent from the loop's own drift; a dose this large can be seen,
// and what four reads a second cost is that, scaled down by the ratio of the two rates.
poll.intervalMs.store(0u);
double aloneFast = 0.0;
double besideFast = 0.0;
std::uint32_t fastCallsBefore = poll.calls;
for (int leg = 0; leg < 3; ++leg) {
poll.paused.store(1u);
const double alone = FramesPerSecond11(game, dx11, 10.0);
poll.paused.store(0u);
const double beside = FramesPerSecond11(game, dx11, 10.0);
aloneFast += alone;
besideFast += beside;
std::printf("R4b leg %d: frames a second %.0f alone, %.0f beside a poller that never pauses (%+.2f %%)\n",
leg + 1, alone, beside, (beside - alone) * 100.0 / alone);
}
poll.quit.store(1u);
WaitForSingleObject(thread, 5000);
CloseHandle(thread);
std::printf("R4b 30 s beside a poller that never pauses: %u reads (%.0f a second), %u not OK, %u faulted, worst "
"read %.1f us; frames a second %.0f alone, %.0f beside it (%+.2f %%); marker errors %u\n",
poll.calls - fastCallsBefore, static_cast<double>(poll.calls - fastCallsBefore) / 30.0,
poll.notOk - slowNotOk, poll.faults, poll.worstSeconds * 1e6, aloneFast / 3.0, besideFast / 3.0,
(besideFast - aloneFast) * 100.0 / aloneFast, game.markerErrors);
poll.calls = slowCalls;
poll.notOk = slowNotOk;
poll.worstSeconds = slowWorst;
std::printf("R4 %d s beside a poller in %d legs: %u reads, %u not OK, %u faulted, %u empty, worst read %.1f us; "
"frames a second %.0f alone, %.0f beside it (%+.2f %%); marker errors %u\n",
legs * 10, legs, poll.calls, poll.notOk, poll.faults, poll.emptyReports, poll.worstSeconds * 1e6,
aloneSum / legs, besideSum / legs, (besideSum - aloneSum) * 100.0 / aloneSum, game.markerErrors);
// R5. Direct3D 12: which object the driver wants -- the device (what the Overlay holds) or the queue.
Dx12 dx12{};
if (MakeDx12(factory, adapter, dx12)) {
Game game12{};
game12.setMarker = game.setMarker;
game12.markerDevice = dx12.device;
game12.frame = 100000;
for (int i = 0; i < 300; ++i) {
Frame12(game12, dx12);
}
std::printf("R5 D3D12, markers on the DEVICE: %u error(s), last status %d\n", game12.markerErrors,
static_cast<int>(game12.lastMarkerStatus));
PrintDigest("R5 D3D12, read with the device:", fl::reflex::ReadLatency(api, dx12.device, report), report);
PrintDigest("R5 D3D12, read with the queue:", fl::reflex::ReadLatency(api, dx12.queue, report), report);
const NvAPI_Status s12 = fl::reflex::ReadSleepStatus(api, dx12.device, sleep);
std::printf(" sleep status with the device %d, with the queue %d\n", static_cast<int>(s12),
static_cast<int>(fl::reflex::ReadSleepStatus(api, dx12.queue, sleep)));
Game queue12{};
queue12.setMarker = game.setMarker;
queue12.markerDevice = dx12.queue;
queue12.frame = 200000;
for (int i = 0; i < 300; ++i) {
Frame12(queue12, dx12);
}
std::printf("R5 D3D12, markers on the QUEUE: %u error(s), last status %d\n", queue12.markerErrors,
static_cast<int>(queue12.lastMarkerStatus));
PrintDigest("R5 D3D12, read with the device after that:", fl::reflex::ReadLatency(api, dx12.device, report),
report);
FreeDx12(dx12);
} else {
std::printf("R5 no Direct3D 12 device on the NVIDIA adapter\n");
}
FreeDx11(dx11);
if (unload != nullptr) {
std::printf("NvAPI_Unload: %d\n", static_cast<int>(unload()));
}
ReleaseIf(adapter);
ReleaseIf(factory);
return 0;
}
} // namespace
int wmain(int argc, wchar_t** argv) {
if (argc >= 3 && wcscmp(argv[1], L"--stub") == 0) {
return RunStub(argv[2]);
}
if (argc >= 2 && wcscmp(argv[1], L"--real") == 0) {
return RunReal(argc >= 3 ? _wtoi(argv[2]) : 60);
}
std::printf("usage: fl-probe-reflex --stub <path to the stub nvapi64.dll> | --real [seconds beside a poller]\n");
return 2;
}
@@ -84,3 +84,20 @@ fl_add_vendor_stub(fl_stub_ffx_loader "amd_fidelityfx_loader_dx12" stub_amd_fide
# is therefore hookinventory-check Pass C's SECOND positive control for the export
# parser, beside the ffx-api leaf.
fl_add_vendor_stub(fl_stub_ffx_fsr3_host "ffx_fsr3_x64" stub_ffx_fsr3_x64.cpp)
# --- NVIDIA NVAPI, for the spike of Reflex route D (docs/spike-notes §31, owner decision D132) ---
#
# A stand-in for nvapi64.dll: the real module's one way in (nvapi_QueryInterface) answering the two getters route D
# would call, with knobs for what a driver cannot be made to do on demand -- a missing getter, a report of nothing,
# an error, a call that does not return for seconds. Used by fl-probe-reflex only; the Overlay is not involved and
# no inventory row names it, so it takes the vendored NVAPI headers (the include directory alone -- nvapi64.lib is
# not linked) and nothing of the hook inventory.
#
# ITS OWN SUBDIRECTORY for its outputs: a file called nvapi64.lib beside the other stubs' import libraries would be
# one careless link line away from being taken for the vendored one.
fl_add_vendor_stub(fl_stub_nvapi64 "nvapi64" stub_nvapi64.cpp)
target_include_directories(fl_stub_nvapi64 SYSTEM PRIVATE "${CMAKE_SOURCE_DIR}/third_party/nvapi")
set_target_properties(fl_stub_nvapi64 PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/nvapi"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/nvapi"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/nvapi")
@@ -0,0 +1,151 @@
// 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).
//
// 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_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.
//
// 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.
#include <windows.h>
#include <d3d11.h>
#include <atomic>
#include <cstdint>
#include <cstring>
#include <nvapi.h>
namespace {
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};
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);
g_lastDevice.store(device, std::memory_order_relaxed);
if (out == nullptr) {
return NVAPI_INVALID_ARGUMENT;
}
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);
if (block != 0u) {
Sleep(block);
}
const std::uint32_t mode = g_mode.load(std::memory_order_relaxed);
if (mode == 2u) {
return NVAPI_ERROR;
}
if (mode == 1u) {
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").
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;
r.inputSampleTime = t;
r.simStartTime = t + 100u;
r.simEndTime = t + 900u;
r.renderSubmitStartTime = t + 950u;
r.renderSubmitEndTime = t + 2100u;
r.presentStartTime = t + 2150u;
r.presentEndTime = t + 2300u;
r.driverStartTime = t + 2300u;
r.driverEndTime = t + 2700u;
r.osRenderQueueStartTime = t + 2700u;
r.osRenderQueueEndTime = t + 3900u;
r.gpuRenderStartTime = t + 3900u;
r.gpuRenderEndTime = t + 7600u;
r.gpuActiveRenderTimeUs = 3500u;
r.gpuFrameTimeUs = 4200u;
}
return NVAPI_OK;
}
NvAPI_Status __cdecl StubGetSleepStatus(IUnknown* device, NV_GET_SLEEP_STATUS_PARAMS* out) {
g_sleepStatusCalls.fetch_add(1u, std::memory_order_relaxed);
g_lastDevice.store(device, std::memory_order_relaxed);
if (out == nullptr) {
return NVAPI_INVALID_ARGUMENT;
}
if (out->version != NV_GET_SLEEP_STATUS_PARAMS_VER1) {
return NVAPI_INCOMPATIBLE_STRUCT_VERSION;
}
if (g_mode.load(std::memory_order_relaxed) == 2u) {
return NVAPI_ERROR;
}
out->bLowLatencyMode = 1;
out->sleepIntervalUs = 4166u;
out->bUseGameSleep = 1;
out->fgMultiplier = 2;
return NVAPI_OK;
}
} // namespace
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);
if (id == kIdInitialize) {
return reinterpret_cast<void*>(&StubInitialize);
}
if (g_hideGetters.load(std::memory_order_relaxed) != 0u) {
return nullptr;
}
if (id == kIdGetLatency) {
return reinterpret_cast<void*>(&StubGetLatency);
}
if (id == kIdGetSleepStatus) {
return reinterpret_cast<void*>(&StubGetSleepStatus);
}
return nullptr;
}
// 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);
}
__declspec(dllexport) void __cdecl FlStubNvSetBlockMs(std::uint32_t milliseconds) {
g_blockMs.store(milliseconds, std::memory_order_relaxed);
}
__declspec(dllexport) void __cdecl FlStubNvHideGetters(std::uint32_t hide) {
g_hideGetters.store(hide, std::memory_order_relaxed);
}
__declspec(dllexport) std::uint32_t __cdecl FlStubNvQueries() {
return g_queries.load(std::memory_order_relaxed);
}
__declspec(dllexport) std::uint32_t __cdecl FlStubNvLatencyCalls() {
return g_latencyCalls.load(std::memory_order_relaxed);
}
__declspec(dllexport) std::uint32_t __cdecl FlStubNvSleepStatusCalls() {
return g_sleepStatusCalls.load(std::memory_order_relaxed);
}
__declspec(dllexport) void* __cdecl FlStubNvLastDevice() {
return g_lastDevice.load(std::memory_order_relaxed);
}
} // extern "C"