feat(telemetry): the NVAPI bridge -- FrameLedger.NvapiBridge.dll, L3 NvapiTelemetrySource, and the NGX probe in-process (P2 PR-E2) (#149)

A new native target, src/native/FrameLedger.NvapiBridge/, is the C ABI the
managed side reaches NVAPI through: refcounted FlNvInit/FlNvShutdown,
FlNvReadSample into a fixed struct with a present bit per field, FlNvNgxState
for one pid, FlNvDriverVersion, and size / ABI-version / build-id queries so a
drifted mirror is refused (FL_NV_BAD_SIZE) rather than read. It is the only
shipped binary that links nvapi64.lib, read-only by construction, loaded by the
Agent into its own process by absolute path (FrameLedger.NvapiBridge.targets)
and never into a game.

Infrastructure.Telemetry: NativeNvapiBridge (the second P/Invoke facade after
the guard's, same absolute-path rule), NvapiTelemetrySource (L3: a clear bit is
null, never 0; an Init that does not answer 0 disables the layer with zero
faults; two throws disable it for the session; VRAM is not read because the
vendored nvapi.h declares no non-deprecated memory-info call, so L1's PDH
counter keeps it), and NvapiNgxStateProbe, the INgxDriverProbe in-process.
The capture host composes L1 + L2 + L3 under the composite and no longer
spawns fl-probe-nvapi.exe; the probe is no longer staged beside it.

Infrastructure.Native.BesideThisAssembly is the assembly's one DllImport
resolver. The runtime allows one per assembly and the guard's static
constructor already set it, which the first real-hardware run of the mirror
test found (TypeInitializationException: a resolver is already set). The
guard claims its name as required (absent throws); the bridge as optional
(absent is a missing layer that reports itself).

Tests: ctest fl_nvapi_bridge (every export, BRANCH: line required);
NvapiBridgeMirrorTests (both mirrors' sizes against the DLL's answers, fails
rather than skips when the DLL is not staged); NvapiTelemetrySourceTests and
NvapiNgxStateProbeTests over a scripted bridge. versioninfo-check.ps1
requires the new DLL's version block.

Measured on the dev box (RTX 5080, 616.64 r616_41), written into
18_GPU_VENDOR_APIS §L3: core 35 °C, GPU domain 0 %, 2670 / 15001 MHz,
throttle mask 0, PCIe x16; memory-temperature and fan bits clear at an idle
desktop.

Docs: 18_GPU_VENDOR_APIS (§Abstraction, §L3 built note, function table,
measured matrix), 12_BUILD (§Targets, the .targets list), 03_METRICS and
20_OPEN_QUESTIONS §H5 (probe in-process), CLAUDE.md (pinned stack, the two
facades), legal/THIRD_PARTY_NOTICES (NVAPI row), CHANGELOG.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Fable 5.1 authored and GitHub committed 2026-09-10 08:18:23 +07:00
1 parent b881ed2297
commit 222dd10083
36 files changed
+1635 -168

No files matched your search

+23
View File
@@ -19,6 +19,29 @@ GitHub release body, so a missing section will mean an empty release note.
### Added
- **P2 PR-E2 — the NVAPI bridge: `FrameLedger.NvapiBridge.dll`, L3 `NvapiTelemetrySource`, and the NGX probe
in-process (2026-09-10).** A new native target, `src/native/FrameLedger.NvapiBridge/` — a C ABI
(`fl_nvapi_bridge.h`: refcounted `FlNvInit`/`FlNvShutdown`, `FlNvReadSample` into a fixed struct with a
`present` bit per field, `FlNvNgxState` for one pid, `FlNvDriverVersion`, and size / ABI-version / build-id
queries so a drifted mirror is refused rather than read) — is the **only shipped binary that links
`nvapi64.lib`**, read-only by construction, loaded by the Agent into its own process by absolute path
(`/FrameLedger.NvapiBridge.targets`, imported by the Agent, the capture host and `Infrastructure.Tests`)
and **never into a game**. `Infrastructure.Telemetry`: `NativeNvapiBridge` (the second P/Invoke facade after
the guard's, same absolute-path rule), `NvapiTelemetrySource` (L3 — a clear bit is `null`, never 0; an `Init`
that does not answer 0 disables the layer with zero faults, two throws disable it for the session; VRAM is
**not** read, because the vendored `nvapi.h` declares neither a non-deprecated memory-info call — L1's PDH
counter keeps it), and `NvapiNgxStateProbe`, the `INgxDriverProbe` in-process. The capture host composes
L1 + L2 + L3 under the composite (`telemetry_source` can now read `l1+lhm+nvapi`) and **no longer spawns
`fl-probe-nvapi.exe`**; the probe is no longer staged beside it. `Infrastructure.Native.BesideThisAssembly`
is the assembly's one `DllImport` resolver — the runtime allows one per assembly, and the guard's static
constructor already set it, which the first real-hardware test run found. ctest `fl_nvapi_bridge`
(`src/native/tests/nvapi_bridge_test.cpp`) exercises every export and requires the `BRANCH:` line;
`NvapiBridgeMirrorTests` checks both mirrors' sizes against the DLL's answers and **fails rather than skips**
when the DLL is not staged; `NvapiTelemetrySourceTests` and `NvapiNgxStateProbeTests` script the bridge.
`tools/versioninfo-check.ps1` requires the new DLL's version block. Measured on the dev box (RTX 5080,
driver 616.64 r616_41) and written into `18_GPU_VENDOR_APIS` §L3: core 35 °C, GPU domain 0 %, 2670 / 15001
MHz, throttle mask 0, PCIe ×16, memory-temperature and fan bits clear at an idle desktop.
- **P2 PR-D — the session recorder: `.partial`, five-step finalize, exit classification, crash auto-disable,
recovery; the first hooked session stored in SQLite (2026-09-10).** `Application.Recording`:
`SessionRecorder` owns a session end to end — identity and QPC time base, the `games` and
+2 -2
View File
@@ -39,7 +39,7 @@ A C++ DLL (`FrameLedger.Overlay.dll`) is injected into games the user explicitly
| UI | WPF + WPF UI (`WPF-UI` pinned = 4.3.0) + CommunityToolkit.Mvvm — `docs/16_WPFUI_SYNTAX.md` |
| App composition | .NET Generic Host + DI in `FrameLedger.App` |
| Charts | ScottPlot 5 |
| GPU telemetry | Layered: DXGI + PDH counters (all vendors) → LibreHardwareMonitorLib (MPL-2.0, all vendors) → **NVAPI (MIT, headers + `amd64/nvapi64.lib` vendored 2026-08-05** at `src/native/third_party/nvapi/`, consumed via the `fl_nvapi` target; NVIDIA extras + Reflex). **No AMD/Intel vendor SDK** — `docs/18_GPU_VENDOR_APIS.md`. ~~**No telemetry source exists in code yet**~~ **`LhmTelemetrySource` (L2) exists since 2026-09-03 (`20_OPEN_QUESTIONS` §M5 row R1, eight GPU fields unelevated); L1 (`BaselineTelemetrySource`: DXGI identity + the PDH adapter-memory counter, the first CsWin32 consumer), `CompositeTelemetrySource` and the 1 Hz `TelemetryPoller` since 2026-09-09; L3 is P2's PR-E2** — `ctest fl_nvapi_probe` is still the only NVAPI consumer, and it exists so the vendoring is verified rather than asserted. This row said no source existed for six days after one did, recorded 2026-09-09 rather than repaired quietly. This row previously claimed the vendoring in the present tense while `third_party/` held only `vulkan-headers`; `legal/` had already caught the identical claim about itself and gained a bidirectional gate, which is what made the real vendoring a red-then-green |
| GPU telemetry | Layered: DXGI + PDH counters (all vendors) → LibreHardwareMonitorLib (MPL-2.0, all vendors) → **NVAPI (MIT, headers + `amd64/nvapi64.lib` vendored 2026-08-05** at `src/native/third_party/nvapi/`, consumed via the `fl_nvapi` target; NVIDIA extras + Reflex). **No AMD/Intel vendor SDK** — `docs/18_GPU_VENDOR_APIS.md`. ~~**No telemetry source exists in code yet**~~ **`LhmTelemetrySource` (L2) exists since 2026-09-03 (`20_OPEN_QUESTIONS` §M5 row R1, eight GPU fields unelevated); L1 (`BaselineTelemetrySource`: DXGI identity + the PDH adapter-memory counter, the first CsWin32 consumer), `CompositeTelemetrySource` and the 1 Hz `TelemetryPoller` since 2026-09-09; L3 (`NvapiTelemetrySource` over the native `FrameLedger.NvapiBridge.dll` — the only shipped binary linking `nvapi64.lib`, loaded by the Agent into its own process and never into a game) since 2026-09-10 (PR-E2)** — `ctest fl_nvapi_probe` was the only NVAPI consumer until then, and it exists so the vendoring is verified rather than asserted. This row said no source existed for six days after one did, recorded 2026-09-09 rather than repaired quietly. This row previously claimed the vendoring in the present tense while `third_party/` held only `vulkan-headers`; `legal/` had already caught the identical claim about itself and gained a bidirectional gate, which is what made the real vendoring a red-then-green |
| CPU/board sensors | LibreHardwareMonitorLib ≥ 0.9.6 (PawnIO) — **optional**, elevated only |
| Tier-2 fallback | **There is none, and Tier 2 is not a measurement.** Owner decision 2026-08-28: the ladder is two rungs — hooked, or duration + sensors + the reason. ~~ETW-based, no injection~~; ~~Intel PresentMon console binary~~ dropped 2026-08-27 after §S31 retired it. Whether a shipped build ever regains a no-injection measurement is `docs/20_OPEN_QUESTIONS.md` §G |
| Storage | SQLite via Microsoft.Data.Sqlite + Dapper (no EF) |
@@ -111,7 +111,7 @@ rules/detection-rules.json # engine/platform/capability + anticheat blocklis
docs/ legal/ legal/licenses/
```
Dependency direction: `App/Agent → Application → Domain`; **`Application → Shared` since 2026-09-09** (P2 PR-A, decision D1 — `Application.Metrics.FrameSampleMapper` is where `FlFrameRecord` becomes Domain's `FrameSample`, and `Application.Capture.CaptureSession`, hosted there since PR-C the same day, is written over the record; `DrainResult` moved to Shared with it); `Infrastructure` implements `Application` ports; Domain references nothing. **The native layer is reachable only through `Infrastructure`** — no P/Invoke anywhere else.
Dependency direction: `App/Agent → Application → Domain`; **`Application → Shared` since 2026-09-09** (P2 PR-A, decision D1 — `Application.Metrics.FrameSampleMapper` is where `FlFrameRecord` becomes Domain's `FrameSample`, and `Application.Capture.CaptureSession`, hosted there since PR-C the same day, is written over the record; `DrainResult` moved to Shared with it); `Infrastructure` implements `Application` ports; Domain references nothing. **The native layer is reachable only through `Infrastructure`** — no P/Invoke anywhere else. **Two facades since 2026-09-10:** `NativeAntiCheatGuard` (required — absent throws) and `NativeNvapiBridge` (optional — absent is a missing telemetry layer that reports itself), both by absolute path beside the assembly through its one `DllImport` resolver, `Infrastructure.Native.BesideThisAssembly`; the runtime allows one resolver per assembly, which is why a third facade claims a name there rather than setting its own.
## Coding conventions
+40
View File
@@ -0,0 +1,40 @@
<Project>
<!--
Ships FrameLedger.NvapiBridge.dll beside the importing project's output (P2 PR-E2).
The second P/Invoke facade after the guard's (docs/18_GPU_VENDOR_APIS.md §L3):
NativeNvapiBridge loads it BY ABSOLUTE PATH from AppContext.BaseDirectory and
never falls back to a search, so it has to actually be there. Read-only, and
NEVER loaded into a game — the Agent (and the unshipped capture host) load it
into their own process for the 1 Hz telemetry read and the NGX per-process word.
Imported by exactly three projects, for the same reasons the guard's is:
- FrameLedger.Agent — the host of the telemetry stack.
- FrameLedger.CaptureHost — the unshipped driver, same stack, own ledger.
- FrameLedger.Infrastructure.Tests — NvapiBridgeLayoutTests and the real-hardware
case P/Invoke into the real DLL.
Warn rather than fail when absent: build.ps1 runs the native build first, so by
the time this evaluates the DLL exists; a hard error would fail `dotnet build`
on a fresh clone for a reason that has nothing to do with the managed code.
Unlike the guard, an absent bridge is NOT a safety hole — L3 disables cleanly
and the session records `telemetry_source` without `nvapi`.
-->
<PropertyGroup>
<FlNvapiBridgeOutDir>$(MSBuildThisFileDirectory)build\native\x64-release\FrameLedger.NvapiBridge\</FlNvapiBridgeOutDir>
</PropertyGroup>
<ItemGroup>
<None Include="$(FlNvapiBridgeOutDir)FrameLedger.NvapiBridge.dll" Condition="Exists('$(FlNvapiBridgeOutDir)FrameLedger.NvapiBridge.dll')">
<Link>FrameLedger.NvapiBridge.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Target Name="FlWarnOnMissingNvapiBridge" AfterTargets="Build"
Condition="!Exists('$(FlNvapiBridgeOutDir)FrameLedger.NvapiBridge.dll')">
<Warning Text="FrameLedger.NvapiBridge.dll was not found at $(FlNvapiBridgeOutDir). Run build.ps1 native first; L3 telemetry will report itself unavailable." />
</Target>
</Project>
+2 -1
View File
@@ -491,7 +491,8 @@ Tier 2 has none of this: `upscaler = unknown`, ratio `N/A`.
> `18_GPU_VENDOR_APIS` L3) returns a feedback word per feature — and **measured 2026-09-06 (driver
> 616.64) its `CREATED | EVALUATE` bits are set for a process with NO NVIDIA-app override** on both
> no-override titles (`20_OPEN_QUESTIONS` §H5). So the capture host probes it out of process beside
> each module snapshot (`fl-probe-nvapi --ngx-state <pid>`, no injection, no consent), and the
> each module snapshot (in-process through `FrameLedger.NvapiBridge.dll` since 2026-09-10, P2 PR-E2;
> `fl-probe-nvapi --ngx-state <pid>` spawned before that — no injection, no consent either way), and the
> `upscaler:` line has a rung between the hooks and `N/A`:
>
> ```
+3 -2
View File
@@ -23,6 +23,7 @@ Targets:
- `FrameLedger.Overlay` → `FrameLedger.Overlay.dll`
- `FrameLedger.VkLayer` → `FrameLedger.VkLayer.dll` + `VkLayer_FRAMELEDGER_overlay.json`
- `FrameLedger.Injector` → **static lib only.** There is no `FrameLedger.Injector.exe` and none ships (`20_OPEN_QUESTIONS` §S9, decided 2026-08-02). A standalone `LoadLibraryW` injector that users can run is a path into a game process that the guard does not stand in front of — a bypass, and a bad look for a project whose position is "we refuse where we are not welcome". The Agent links the static lib; the guard owns the chokepoint inside it (§S13(b)), so there is no callable entry point that skips the gate. Manual testing uses `hook-harness`, never a real game (§Debugging).
- `FrameLedger.NvapiBridge` → `FrameLedger.NvapiBridge.dll` (**2026-09-10, P2 PR-E2**): the C ABI the Agent reaches NVAPI through (`18_GPU_VENDOR_APIS` §L3) and the **only shipped binary that links `nvapi64.lib`**. Read-only by construction, loaded by the Agent into **its own process** by absolute path through `/FrameLedger.NvapiBridge.targets`, and **never into a game** — its name carries none of the words the guard's §S18 heuristic scans for. `fl_native_flags` only, not the hostile-environment set. `versioninfo-check.ps1` requires its version block like the other three shipped natives. ctest `fl_nvapi_bridge` (`src/native/tests/nvapi_bridge_test.cpp`) exercises every export and requires `BRANCH: AVAILABLE` or `BRANCH: DEGRADED` in the output, so a bridge gutted to `return 0` is red on a runner without the driver too.
- `FrameLedger.Overlay.Tests` → Catch2 unit tests (ring buffer, record layout, fault filter, seqlock) **and the guard's fail-closed matrix** (`14_TESTING` §Safety-guard tests) — the guard is native, so its tests are too
- `hook-harness` → the dummy **D3D11 + D3D12** app, WARP + composition swapchain so it runs headless on CI (`17_HOOK_ENGINE` §Test harness). D3D12 is device → command queue → swapchain, which is the acquisition asymmetry a D3D11-only fixture cannot exercise. ~~Vulkan and OpenGL modes to follow as those hooks land.~~ **`--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)
@@ -36,7 +37,7 @@ Compiler/linker flags (enforced in CMake, not per-target ad hoc): `/std:c++20 /M
**MinHook** is fetched by CMake `FetchContent` and built from source, pinned to the **commit** behind tag `v1.3.4` (`c3fcafdc`) rather than to the tag name — a tag can be moved, a commit cannot. FetchContent over a submodule so a fresh clone needs no extra step and CI has nothing to remember. Upstream warnings are not subjected to our `/W4 /WX`: warnings in third-party code are upstream's to fix, and failing our build on them would only tempt someone to patch the fetched copy, which drags it out of "consumed unmodified". The BSD-2-Clause notice ships in `legal/licenses/`, and `tools/license-check.ps1` fails the build if it goes missing while the FetchContent declaration is still present.
**NVAPI SDK** (MIT) **is vendored** at `src/native/third_party/nvapi/` — headers, `amd64/nvapi64.lib`, `License.txt`, consumed through `fl_nvapi` and proven by ctest `fl_nvapi_probe`. `legal/licenses/nvapi-MIT.txt` carries the notice and `license-check.ps1` binds the two bidirectionally.
**NVAPI SDK** (MIT) **is vendored** at `src/native/third_party/nvapi/` — headers, `amd64/nvapi64.lib`, `License.txt`, consumed through `fl_nvapi`, proven by ctest `fl_nvapi_probe`, and **linked by a shipped binary since 2026-09-10** (`FrameLedger.NvapiBridge`, above). `legal/licenses/nvapi-MIT.txt` carries the notice and `license-check.ps1` binds the two bidirectionally.
> **This paragraph said "is not vendored yet" until 2026-08-09**, in the present tense, and added that `src/native/third_party/` *"contains `CMakeLists.txt` and `vulkan-headers` only"*. Both were false from #55 (2026-08-05) onward. The sentence was itself a correction — of an earlier claim that NVAPI *was* vendored when it was not — so this file has now been wrong in both directions about the same fact, which is worth more than the fix: **CLAUDE.md's pinned stack and `18_GPU_VENDOR_APIS` §L3 were updated when the vendoring landed and this one was not.** `legal/` is gated bidirectionally and caught its own version; `docs/` is not gated, and this is what that costs. Link it normally; do **not** resolve NVAPI by ordinal (that was a workaround for a licensing constraint that no longer exists, and it breaks across driver versions). Still guard `NvAPI_Initialize` failure as a normal path — plenty of users have no NVIDIA GPU.
@@ -54,7 +55,7 @@ Compiler/linker flags (enforced in CMake, not per-target ad hoc): `/std:c++20 /M
> **`RuntimeIdentifier` is NOT set here, and this bullet claimed it was until 2026-08-06.** The props file's own comment explains why: forcing a RID onto class libraries pulls RID-specific assets into their restore for no benefit, so each executable sets it — `FrameLedger.App`, `FrameLedger.Agent` and now `FrameLedger.CaptureHost`, plus its test project, which needs the same RID to reference a RID'd exe. A new project copying this document rather than the props file would have inherited nothing.
- Nullable enable, ImplicitUsings enable, `TreatWarningsAsErrors=true`, `AnalysisLevel=latest-all`, deterministic, `ContinuousIntegrationBuild` on CI.
- `Directory.Packages.props`: central package management, all versions pinned (including `WPF-UI` = 4.3.0 exactly — `16_WPFUI_SYNTAX` §Version hygiene).
- **Native output reaches the managed side through `.targets` files imported by `FrameLedger.Agent`**, not through `FrameLedger.Infrastructure`: `/FrameLedger.Guard.targets` (the guard DLL), `/FrameLedger.Overlay.targets` (the payload, §S22) and `/FrameLedger.Rules.targets` (the blocklist seed). Ordering comes from `build.ps1`, which runs the native build first — **not** from the solution: `FrameLedger.slnx` contains no native project.
- **Native output reaches the managed side through `.targets` files imported by `FrameLedger.Agent`**, not through `FrameLedger.Infrastructure`: `/FrameLedger.Guard.targets` (the guard DLL), `/FrameLedger.Overlay.targets` (the payload, §S22), `/FrameLedger.Rules.targets` (the blocklist seed) and, since 2026-09-10, `/FrameLedger.NvapiBridge.targets` (the L3 bridge; it **warns rather than fails** when the DLL is absent, because a missing telemetry layer reports itself where a missing guard would be a safety hole). Ordering comes from `build.ps1`, which runs the native build first — **not** from the solution: `FrameLedger.slnx` contains no native project.
> **This bullet was wrong in four ways and is corrected 2026-08-04.** It named a copy of `FrameLedger.Injector.exe`, which §S9 closed and which line 25 above says does not exist, 24 lines earlier in the same document. It attributed the copying to a build target in `FrameLedger.Infrastructure.csproj`, which contains no `<Target>` at all. It said the copies happen there, when the guard DLL was deliberately moved out to a `.targets` file so it would stop flowing to every referencing project (§S18 blocker 3). And it credited the solution with an ordering the solution cannot express.
- **Struct mirror check — ✅ built 2026-08-05.** `ShmLayoutMirrorTests` runs `tools/fl-layout-dump`, reads its JSON, and asserts size plus every field offset against the C# `[StructLayout]` mirrors in `FrameLedger.Shared` — in **both directions**, so a field on either side alone fails. It also asserts blittability, which offsets cannot see. The `struct-mirror` gate reads the run's `.trx` and fails when that test class did not execute, so deleting the test is red as well as breaking it. Struct drift between the two layers is the most dangerous silent bug in this architecture; the build now genuinely catches it.
+47 -16
View File
@@ -34,7 +34,7 @@ Implementations compose rather than compete:
- `BaselineTelemetrySource` (L1) — always constructed.
- `LhmTelemetrySource` (L2) — constructed when LHM initialises.
- `NvapiTelemetrySource` (L3) — constructed only on NVIDIA hardware.
- `NvapiTelemetrySource` (L3) — ~~constructed only on NVIDIA hardware~~ **always constructed since 2026-09-10 (P2 PR-E2)** and disables itself when the bridge DLL or the NVIDIA driver is absent, so the composite's descriptor simply omits `nvapi` and no caller has to know the vendor before composing.
- `CompositeTelemetrySource` merges them with a fixed precedence per field (**L3 > L2 > L1**) and records which layer supplied each value.
`GpuSample`: `takenAt`, `layer`, `adapterName`, `tempCoreC`, `tempHotspotC`, `tempMemoryC`, `loadPct`, `vramAdapterMB`, `coreClockMhz`, `memClockMhz`, `powerW`, `fanRpm`, `throttleReasons`, `pcieGen/Width`. Every field nullable — `Capabilities` says what to trust, and the UI shows `N/A` rather than zero.
@@ -122,16 +122,41 @@ CPU and motherboard sensors remain LHM-only, elevated-only, PawnIO-dependent, an
Still resolve **entry points defensively at runtime**: `nvapi64.dll` may be absent (no NVIDIA GPU) or older than our headers. `NvAPI_Initialize` failing is a normal condition that must disable L3 cleanly, not throw.
> **Built 2026-09-10 (P2 PR-E2).** NVAPI is a C API behind a static import library, so the managed
> side reaches it through a native DLL of our own: **`FrameLedger.NvapiBridge.dll`**
> (`src/native/FrameLedger.NvapiBridge/`, C ABI in `include/fl_nvapi_bridge.h`) — the **only shipped
> binary that links `nvapi64.lib`**, read-only by construction (every export is a query), loaded by the
> Agent into **its own process** by absolute path and **never into a game**. Its name carries none of
> the words the guard's §S18 heuristic scans a launcher's ancestors for. The ABI is a fixed struct with
> a `present` bitmask per field (`FlNvReadSample`), a refcounted `FlNvInit` / `FlNvShutdown`, the driver
> version, the per-pid NGX words (`FlNvNgxState`), and size / ABI-version / build-id queries so a mirror
> that drifts is refused (`FL_NV_BAD_SIZE`) rather than read. On the managed side, all in
> `Infrastructure.Telemetry`: `NativeNvapiBridge` (the second P/Invoke facade after the guard's — same
> absolute-path rule, through the assembly's one `DllImport` resolver, `Infrastructure.Native.BesideThisAssembly`,
> because the runtime allows exactly one per assembly and two static constructors setting one is an
> exception in whichever runs second), `NvapiTelemetrySource` (a clear bit is `null`, never 0; an
> `Init` that does not answer 0 disables the layer with **zero faults**, because a machine without the
> driver is a normal condition; two throws disable it for the session), and `NvapiNgxStateProbe`
> (`INgxDriverProbe` in-process — the capture host **no longer spawns `fl-probe-nvapi.exe`**, and the
> probe target is no longer staged beside it). Verified by ctest `fl_nvapi_bridge`
> (`src/native/tests/nvapi_bridge_test.cpp`, `BRANCH: AVAILABLE|DEGRADED` required the way
> `fl_nvapi_probe` requires it) and by `NvapiBridgeMirrorTests`, which compares `Marshal.SizeOf` of both
> mirrors against the DLL's own answers and **fails rather than skips** when the DLL is not staged.
>
> **Not in this build, stated so nobody infers it from the table below:** VRAM (`FlNvSample.vram` is
> reserved and its bit is never set — see the Memory row), power, hotspot temperature, per-domain
> utilisation beyond the GPU domain, and anything Reflex (§M8: a hook fact, not a poller field).
| Purpose | Function |
|---|---|
| Init / enumerate | `NvAPI_Initialize`, `NvAPI_EnumPhysicalGPUs`, `NvAPI_GPU_GetFullName` |
| Temperatures | `NvAPI_GPU_GetThermalSettings` (+ extended thermal query for hotspot/memory where available) |
| Utilisation | `NvAPI_GPU_GetDynamicPstatesInfoEx` (GPU / FB / VID / BUS domains) |
| Clocks | `NvAPI_GPU_GetAllClockFrequencies` |
| Memory | `NvAPI_GPU_GetMemoryInfoEx` — **not `NvAPI_GPU_GetMemoryInfo`**, which this table named until 2026-08-05. The vendored headers mark it `__nvapi_deprecated_function` ("deprecated in release 520"), so under `/W4 /WX` a call to it fails the native build |
| **Throttle reasons** | `NvAPI_GPU_GetPerfDecreaseInfo` — not available from L1 or L2 |
| Driver version | `NvAPI_SYS_GetDriverAndBranchVersion` |
| **NGX per-process state** | `NvAPI_NGX_GetNGXOverrideState` (R570+) — the driver's feedback word per DLSS feature for a PID, read OUT OF PROCESS by `fl-probe-nvapi --ngx-state` and, since 2026-09-06, by the capture host beside each module snapshot. Measured: the SR word's `CREATED \| EVALUATE` is set without an NVIDIA-app override; the FG word follows DLSS-G once created (`CREATED \| EVALUATE` at ×4, corrected the same day — the first reading was blind because it was early), the multiplier bits stay clear; `scalingRatio` is 0 even under an override. Identity only, SR and FG (`03_METRICS` §Upscaling) |
| Temperatures | `NvAPI_GPU_GetThermalSettings` (+ extended thermal query for hotspot/memory where available). **Bridge (2026-09-10):** the public enumeration only — core is the `GPU` target; memory is the `MEMORY` target when the driver lists one, and on the RTX 5080 it does not (bit clear → `null`); hotspot is not read |
| Utilisation | `NvAPI_GPU_GetDynamicPstatesInfoEx` (GPU / FB / VID / BUS domains). **Bridge (2026-09-10):** the GPU domain only, as `loadPct` |
| Clocks | `NvAPI_GPU_GetAllClockFrequencies` — **bridge (2026-09-10):** current graphics and memory clocks |
| Memory | `NvAPI_GPU_GetMemoryInfoEx` — **not `NvAPI_GPU_GetMemoryInfo`**, which this table named until 2026-08-05. The vendored headers mark it `__nvapi_deprecated_function` ("deprecated in release 520"), so under `/W4 /WX` a call to it fails the native build. **Neither is called (2026-09-10):** the vendored `nvapi.h` (`cd6918f6`) does not declare `GetMemoryInfoEx` at all — the deprecation message names a function the same header set does not ship — so the bridge's `vram` field is **reserved**, its bit is never set, and VRAM stays L1's PDH adapter counter. Taking a newer header set is the way to change that, not a call to the deprecated one |
| **Throttle reasons** | `NvAPI_GPU_GetPerfDecreaseInfo` — not available from L1 or L2. **Bridge (2026-09-10):** the raw reason mask, and 0 is a measurement (no reason), not a clear bit |
| Driver version | `NvAPI_SYS_GetDriverAndBranchVersion` — **bridge (2026-09-10):** `FlNvDriverVersion`, surfaced as `616.64 (r616_41)` |
| **NGX per-process state** | `NvAPI_NGX_GetNGXOverrideState` (R570+) — the driver's feedback word per DLSS feature for a PID, read OUT OF PROCESS by `fl-probe-nvapi --ngx-state` and, since 2026-09-06, by the capture host beside each module snapshot — **in-process through the bridge since 2026-09-10** (`NvapiNgxStateProbe`; the spawn is retired and the words, the merge and the printed block are unchanged). Measured: the SR word's `CREATED \| EVALUATE` is set without an NVIDIA-app override; the FG word follows DLSS-G once created (`CREATED \| EVALUATE` at ×4, corrected the same day — the first reading was blind because it was early), the multiplier bits stay clear; `scalingRatio` is 0 even under an override. Identity only, SR and FG (`03_METRICS` §Upscaling) |
| **Reflex / PC latency** | `NvAPI_D3D_GetLatency` → per-frame sim/render/present/driver/GPU timestamps; hooking `NvAPI_D3D_SetSleepMode` / `SetLatencyMarker` in the Overlay tells us the game enabled Reflex (`17_HOOK_ENGINE`) |
Reflex latency is the single strongest reason L3 exists — it is genuinely unavailable anywhere else.
@@ -311,19 +336,24 @@ answer; the `untested` cells are exactly as untested as before.
| Field | NVIDIA | AMD | Intel |
|---|---|---|---|
| **Initialises at all** | ✓ **measured 2026-08-05** | `arch` | `arch` |
| **Driver version** | ✓ **measured** — `610.88`, branch `r610_85` | `arch` | `arch` |
| **Driver version** | ✓ **measured** — `610.88`, branch `r610_85`; **through the bridge 2026-09-10:** `616.64`, `r616_41` | `arch` | `arch` |
| **GPU enumeration + name** | ✓ **measured** — 1 GPU, "NVIDIA GeForce RTX 5080" | `arch` | `arch` |
| **Degrades cleanly when absent** | ✓ **measured** — see below | `arch` | `arch` |
| Core / hotspot / memory temp | ? | `arch` | `arch` |
| Per-domain utilisation | ? | `arch` | `arch` |
| Clocks, Power | ? | `arch` | `arch` |
| Throttle reasons | ? | `arch` | `arch` |
| Reflex / PC latency | ? | `arch` | `arch` |
| Core / hotspot / memory temp | **core ✓ measured 2026-09-10** — 35 °C at an idle desktop; **memory: bit clear** on this GPU (no `MEMORY` thermal target enumerated → `null`, not 0); hotspot not read | `arch` | `arch` |
| Per-domain utilisation | **GPU domain ✓ measured 2026-09-10** — 0 % at an idle desktop, present bit set (a measured zero); FB / VID / BUS not read | `arch` | `arch` |
| Clocks, Power | **clocks ✓ measured 2026-09-10** — 2670 MHz graphics, 15001 MHz memory; power not read | `arch` | `arch` |
| Throttle reasons | ✓ **measured 2026-09-10** — mask 0 at an idle desktop, present bit set | `arch` | `arch` |
| Fan | **bit clear at an idle desktop 2026-09-10** — the tach reading is refused while the fans are stopped, and the bridge reports that as absent rather than 0 RPM; a reading under load is the owner's to take | `arch` | `arch` |
| PCIe width | ✓ **measured 2026-09-10** — ×16; generation not read | `arch` | `arch` |
| Reflex / PC latency | not a poller field (§M8) | `arch` | `arch` |
The four measured rows come from `ctest fl_nvapi_probe` (`src/native/tools/fl-probe-nvapi`),
which exists because vendoring added 2.4 MB of headers and an import library that **nothing
else compiles against yet** — an unconsumed vendored dependency is one whose header closure
could be short by a file with every gate still green.
could be short by a file with every gate still green. **The 2026-09-10 rows** come from one
`FlNvReadSample` through `FrameLedger.NvapiBridge.dll` on the dev box (RTX 5080, driver 616.64),
read from the staged DLL by hand after `NvapiBridgeMirrorTests` had passed against it; the
bridge is the second consumer of the vendored material and the first that ships.
**"Degrades cleanly when absent" — what is observed, and what is inferred.** `nvapi64.lib`
is a *static* library of stubs that reach `nvapi64.dll` through `nvapi_QueryInterface` at
@@ -378,6 +408,7 @@ alone could never catch.
> (`LhmTelemetrySource`, `SensorMap`, the port in `FrameLedger.Application.Telemetry`);
> ~~L1 and L3 are still unwritten~~ **L1 and the composite exist as of 2026-09-09**
> (`BaselineTelemetrySource`, `DxgiAdapters`, `PdhAdapterMemoryCounter`,
> `CompositeTelemetrySource`, `TelemetryPoller`); L3 is P2's PR-E2. §M5 in particular (do LHM GPU
> `CompositeTelemetrySource`, `TelemetryPoller`); ~~L3 is P2's PR-E2~~ **L3 exists as of 2026-09-10**
> (`NvapiTelemetrySource` over `FrameLedger.NvapiBridge.dll`, §L3). §M5 in particular (do LHM GPU
> sensors work unelevated, without PawnIO?) decided whether the default unelevated
> Agent has temperatures at all — **it does, on NVIDIA; row R1 above.**
+6
View File
@@ -3589,6 +3589,12 @@ probe never showed a deadlock.
> beside each module snapshot (out of process, no consent needed) or, if it goes in-process, through
> `Infrastructure` only (CLAUDE.md: no P/Invoke elsewhere).
>
> **In-process since 2026-09-10 (P2 PR-E2):** the same words through `FrameLedger.NvapiBridge.dll`
> (`Infrastructure.Telemetry.NvapiNgxStateProbe`, the `INgxDriverProbe` the Agent will take from DI);
> the spawn below is retired and `fl-probe-nvapi.exe` is no longer staged beside the host. The readings,
> the merge and the printed block are unchanged, and `NvapiNgxStateProbeTests` maps the bridge's three
> answers to the three outcomes the machine line used to carry.
>
> **BUILT 2026-09-06, on the owner's decision ("nối probe để bắt đầu").** The capture host spawns
> `fl-probe-nvapi --ngx-state <pid>` beside every module snapshot (the probe prints one machine line,
> `NGXSTATE status=… sr=0x… …`, and is staged beside the host by the project file), merges the readings
+1 -1
View File
@@ -51,7 +51,7 @@ Telemetry is layered so no proprietary vendor licence is ever required (`docs/18
| Component | How we use it | Licence | Bundled? |
|---|---|---|---|
| **NVIDIA NVAPI SDK** (headers, interface definitions, `nvapi64.lib`) | Planned: NVIDIA-only telemetry, throttle reasons, Reflex/PC latency. **No code links it yet** — the `fl_nvapi` target exists and nothing consumes it | **MIT** — <https://github.com/NVIDIA/nvapi> @ `cd6918f6` (2026-06-24) | **Vendored 2026-08-05** at `src/native/third_party/nvapi/`: nine headers (`nvapi.h` and its include closure, plus `nvapi_interface.h`), `License.txt`, and `amd64/nvapi64.lib` — **x64 only**, `x86/nvapi.lib` deliberately not taken. **Verified 2026-08-02 and re-verified on the vendored copy:** `License.txt` opens "nvapi.lib and nvapi64.lib are licensed under the following terms" + `SPDX-License-Identifier: MIT`, so the grant names the import libraries explicitly and the binary is covered rather than only the headers. Every vendored header retains its own SPDX MIT block, which `license-check.ps1` asserts file by file |
| **NVIDIA NVAPI SDK** (headers, interface definitions, `nvapi64.lib`) | NVIDIA-only telemetry — temperatures, GPU-domain utilisation, clocks, fan, throttle reasons, PCIe width, driver version, and the driver's per-process NGX words. ~~**No code links it yet** — the `fl_nvapi` target exists and nothing consumes it~~ **Linked by `FrameLedger.NvapiBridge.dll` since 2026-09-10** (P2 PR-E2): the only shipped binary that links `nvapi64.lib`, loaded by the Agent into its own process and never into a game; the unshipped `fl-probe-nvapi` links it too. Reflex/PC latency is a hook fact, not an NVAPI query (`docs/20_OPEN_QUESTIONS` §M8) | **MIT** — <https://github.com/NVIDIA/nvapi> @ `cd6918f6` (2026-06-24) | **Vendored 2026-08-05** at `src/native/third_party/nvapi/`: nine headers (`nvapi.h` and its include closure, plus `nvapi_interface.h`), `License.txt`, and `amd64/nvapi64.lib` — **x64 only**, `x86/nvapi.lib` deliberately not taken. **Verified 2026-08-02 and re-verified on the vendored copy:** `License.txt` opens "nvapi.lib and nvapi64.lib are licensed under the following terms" + `SPDX-License-Identifier: MIT`, so the grant names the import libraries explicitly and the binary is covered rather than only the headers. Every vendored header retains its own SPDX MIT block, which `license-check.ps1` asserts file by file |
| `nvapi64.dll` (runtime implementation) | Loaded at runtime from the user's system | Part of the NVIDIA graphics driver | No — never redistributed by us |
| **LibreHardwareMonitorLib** | GPU sensors for **all vendors** (AMD, Intel, NVIDIA) + CPU/board sensors when elevated | **MPL-2.0** | Yes, as an unmodified NuGet package |
| **DXGI + Windows performance counters (PDH)** | Vendor-neutral baseline: utilisation, VRAM, adapter identity | Windows OS APIs | n/a |
@@ -35,6 +35,7 @@
not import this.
-->
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Guard.targets" />
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.NvapiBridge.targets" />
<!-- The seed the Agent installs to the product location on first run (§S20). -->
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
@@ -28,9 +28,9 @@ internal static class HostRecorder
public static string PartialDirectory => Path.Combine(AppContext.BaseDirectory, "tmp");
public static SessionRecorder Build(LedgerDatabase db, IGameConsentStore store, int seconds, IProcessLauncher? launcher = null) =>
public static SessionRecorder Build(LedgerDatabase db, HostSessionFactory sessions) =>
new(
new HostSessionFactory(store, seconds, launcher),
sessions,
new SqliteGameRepository(db),
new SqliteHardwareSnapshotRepository(db),
new HardwareSnapshotSource(new DxgiAdapters()),
@@ -45,7 +45,7 @@ internal static class HostRecorder
public static PartialRecovery Recovery(LedgerDatabase db) => new(new PartialSessionStore(PartialDirectory), Finalizer(db), HostMinimumSessionLength);
/// <summary>L1 + L2 under the composite, one poller per session; the poller owns and disposes the layers.</summary>
/// <summary>L1 + L2 + L3 under the composite, one poller per session; the poller owns and disposes the layers.</summary>
private static TelemetryPoller Poller()
{
// Ownership walks up one step at a time and each local is nulled at its hand-off, so a throw
@@ -53,6 +53,7 @@ internal static class HostRecorder
PdhAdapterMemoryCounter? pdh = null;
BaselineTelemetrySource? l1 = null;
LhmTelemetrySource? l2 = null;
NvapiTelemetrySource? l3 = null;
CompositeTelemetrySource? composite = null;
try
{
@@ -60,11 +61,14 @@ internal static class HostRecorder
l1 = new BaselineTelemetrySource(new DxgiAdapters(), pdh, TimeProvider.System);
pdh = null;
l2 = new LhmTelemetrySource(new LhmComputerAdapter(enableCpuAndMemory: false), new LhmTelemetryOptions(), TimeProvider.System);
l3 = new NvapiTelemetrySource(TimeProvider.System);
l1.Start();
l2.Start();
composite = new CompositeTelemetrySource([l1, l2]);
l3.Start();
composite = new CompositeTelemetrySource([l1, l2, l3]);
l1 = null;
l2 = null;
l3 = null;
var poller = new TelemetryPoller(composite, new TelemetryPollerOptions(), TimeProvider.System, ownsSource: true);
composite = null;
return poller;
@@ -74,6 +78,7 @@ internal static class HostRecorder
pdh?.Dispose();
l1?.Dispose();
l2?.Dispose();
l3?.Dispose();
composite?.Dispose();
}
}
@@ -4,12 +4,21 @@ using FrameLedger.Application.Consent;
using FrameLedger.Application.Recording;
using FrameLedger.Infrastructure.AntiCheat;
using FrameLedger.Infrastructure.Capture;
using FrameLedger.Infrastructure.Telemetry;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>The session and its collaborators, wired the only way this host allows; the recorder supplies the observer.</summary>
internal sealed class HostSessionFactory(IGameConsentStore store, int seconds, IProcessLauncher? launcher = null) : ICaptureSessionFactory
/// <summary>
/// The session and its collaborators, wired the only way this host allows; the recorder supplies the observer.
/// Owns the one NGX probe (P2 PR-E2: in-process through the bridge, where <c>fl-probe-nvapi.exe</c> used to be
/// spawned) for as long as the verb runs: one <c>NvAPI_Initialize</c> per host, not per session.
/// </summary>
internal sealed class HostSessionFactory(IGameConsentStore store, int seconds, IProcessLauncher? launcher = null) : ICaptureSessionFactory, IDisposable
{
private readonly NvapiNgxStateProbe _ngx = new();
public void Dispose() => _ngx.Dispose();
public CaptureSession Create(ICaptureObserver observer)
{
var guard = new NativeAntiCheatGuard();
@@ -30,7 +39,7 @@ internal sealed class HostSessionFactory(IGameConsentStore store, int seconds, I
MaxDuration = seconds > 0 ? TimeSpan.FromSeconds(seconds) : TimeSpan.Zero,
},
new RuntimeModuleSnapshot(CensusNames.ModuleFileNames),
new NgxDriverProbe(),
_ngx,
launcher ?? new ProcessLauncher(),
observer);
}
@@ -1,69 +0,0 @@
using System.ComponentModel;
using System.Diagnostics;
using FrameLedger.Application.Capture;
namespace FrameLedger.CaptureHost.Capture;
/// <summary>
/// Runs <c>fl-probe-nvapi --ngx-state &lt;pid&gt;</c> beside this host and parses its machine line.
/// </summary>
/// <remarks>
/// <para>
/// <b>Out of process, on purpose.</b> The probe links <c>nvapi64.lib</c> (MIT, vendored) and asks the driver about
/// a pid; nothing is injected, nothing in the target is touched, no consent is involved. Spawning the tool this
/// repo already builds keeps the native layer reachable only through what is already there (CLAUDE.md: no
/// P/Invoke outside <c>Infrastructure</c>) — the day the shipped Agent wants this fact, it goes through
/// <c>Infrastructure</c> as a native call, not through a child process.
/// </para>
/// <para>
/// The probe is staged beside the host by the project file the way the Overlay payload is; a missing binary is
/// an outcome the report prints, never an exception the loop sees.
/// </para>
/// </remarks>
internal sealed class NgxDriverProbe : INgxDriverProbe
{
private const string _probeFileName = "fl-probe-nvapi.exe";
private static readonly TimeSpan _budget = TimeSpan.FromSeconds(5);
public static string ProbePath => Path.Combine(AppContext.BaseDirectory, _probeFileName);
/// <inheritdoc />
NgxDriverState INgxDriverProbe.Run(int pid) => Run(pid);
public static NgxDriverState Run(int pid) => Run(pid, ProbePath);
public static NgxDriverState Run(int pid, string probePath)
{
if (!File.Exists(probePath))
{
return NgxDriverState.Of(NgxProbeOutcome.ProbeMissing, probePath);
}
try
{
using var probe = new Process();
probe.StartInfo = new ProcessStartInfo(probePath)
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
};
probe.StartInfo.ArgumentList.Add("--ngx-state");
probe.StartInfo.ArgumentList.Add(pid.ToString(System.Globalization.CultureInfo.InvariantCulture));
probe.Start();
string output = probe.StandardOutput.ReadToEnd();
if (!probe.WaitForExit((int)_budget.TotalMilliseconds))
{
probe.Kill();
return NgxDriverState.Of(NgxProbeOutcome.ProbeFailed, "the probe did not exit within " + _budget.TotalSeconds + " s");
}
return NgxDriverState.Parse(output);
}
catch (Exception e) when (e is Win32Exception or InvalidOperationException or IOException)
{
return NgxDriverState.Of(NgxProbeOutcome.ProbeFailed, e.Message);
}
}
}
@@ -82,26 +82,10 @@
staging it beside a host binary is how a host acquires a target of its own.
-->
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Guard.targets" />
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.NvapiBridge.targets" />
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Overlay.targets" />
<!--
fl-probe-nvapi.exe beside the host, the way the Overlay is: NgxDriverProbe spawns it
by absolute path from AppContext.BaseDirectory and reports ProbeMissing rather than
searching. Warn-not-fail for the same reason the Overlay targets do: build.ps1 runs
the native build first. UNSHIPPED with this host; the Agent would call NVAPI through
Infrastructure, not a child process.
-->
<PropertyGroup>
<FlNativeProbeDir>$(MSBuildThisFileDirectory)..\..\build\native\x64-release\tools\fl-probe-nvapi\</FlNativeProbeDir>
</PropertyGroup>
<ItemGroup>
<None Include="$(FlNativeProbeDir)fl-probe-nvapi.exe" Condition="Exists('$(FlNativeProbeDir)fl-probe-nvapi.exe')">
<Link>fl-probe-nvapi.exe</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<!--
The Vulkan implicit layer beside the host (P1 item 3). `launch` writes a manifest pointing at THIS
copy and hands the launched process VK_ADD_IMPLICIT_LAYER_PATH, so the layer is discoverable only by
+4 -2
View File
@@ -177,7 +177,8 @@ internal static class Program
string normalised = ExecutableIdentity.Normalise(exePath);
ExecutableFingerprint? observed = ExecutableIdentity.Read(exePath);
RecordedSession recorded = await HostRecorder.Build(db, store, seconds).RecordAsync(new RecordRequest
using var sessions = new HostSessionFactory(store, seconds);
RecordedSession recorded = await HostRecorder.Build(db, sessions).RecordAsync(new RecordRequest
{
NormalisedExePath = normalised,
Observed = observed,
@@ -208,7 +209,8 @@ internal static class Program
: $"vulkan layer: {vulkan.ManifestPath} (via {VkLayerLaunchEnvironment.ImplicitLayerPathVariable}; " +
$"enable-list entry '{vulkan.ImageName}' for this session)");
RecordedSession recorded = await HostRecorder.Build(db, store, seconds, new ProcessLauncher(vulkan.Variables)).RecordAsync(new RecordRequest
using var sessions = new HostSessionFactory(store, seconds, new ProcessLauncher(vulkan.Variables));
RecordedSession recorded = await HostRecorder.Build(db, sessions).RecordAsync(new RecordRequest
{
NormalisedExePath = normalised,
Observed = observed,
@@ -1,6 +1,7 @@
using System.Runtime.InteropServices;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Domain.AntiCheat;
using FrameLedger.Infrastructure.Native;
namespace FrameLedger.Infrastructure.AntiCheat;
@@ -49,7 +50,9 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard
// THE ENTIRE ANTI-CHEAT GATE with whatever the attacker wants it to say.
// That is a worse outcome than any other DLL-hijack in this application, so
// the search path is not merely restricted — it is never consulted. The
// resolver below loads exactly one file, beside this assembly, by full path.
// assembly's one resolver (Native/BesideThisAssembly) loads exactly one file
// for this name, beside this assembly, by full path, and throws when it is
// absent: `required: true` below is that policy.
//
// The DefaultDllImportSearchPaths attributes are the belt to that braces:
// System32 is the most restrictive value the analyzers accept, and if the
@@ -95,22 +98,11 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard
static NativeAntiCheatGuard()
{
NativeLibrary.SetDllImportResolver(typeof(NativeAntiCheatGuard).Assembly, Resolve);
}
private static IntPtr Resolve(string libraryName, System.Reflection.Assembly assembly, DllImportSearchPath? path)
{
if (!string.Equals(libraryName, _guardDll, StringComparison.Ordinal))
{
return IntPtr.Zero;
}
// AppContext.BaseDirectory, not the current directory and not the PATH.
// If it is not there, FAIL — falling back to a search would reintroduce
// exactly the hijack this exists to prevent, and a missing guard must
// never degrade into "carry on without one".
string full = Path.Combine(AppContext.BaseDirectory, _guardDll);
return NativeLibrary.Load(full);
BesideThisAssembly.Claim(_guardDll, required: true);
}
/// <inheritdoc />
@@ -0,0 +1,63 @@
using System.Collections.Concurrent;
using System.Reflection;
using System.Runtime.InteropServices;
namespace FrameLedger.Infrastructure.Native;
/// <summary>
/// The one <c>DllImport</c> resolver this assembly may have — the runtime allows exactly one per assembly, and
/// the second native facade (P2 PR-E2, <c>NativeNvapiBridge</c> after <c>NativeAntiCheatGuard</c>) found that out:
/// two static constructors each calling <c>SetDllImportResolver</c> is a <see cref="InvalidOperationException"/>
/// in whichever runs second. Every facade claims its library name here, with the one policy that differs.
/// </summary>
/// <remarks>
/// <para>
/// <b>Absolute path, never a search.</b> <c>AppContext.BaseDirectory</c> joined with the library name: not the
/// current directory, not the PATH, not the application directory through the loader's own probing. The reason
/// is written on the guard, whose replacement on the probe order would replace the whole anti-cheat gate; the
/// bridge inherits the rule because one facade with a looser rule is the precedent the next one cites.
/// </para>
/// <para>
/// <b>Required or optional</b> is the only policy a facade chooses. The guard is required: absent means
/// <see cref="NativeLibrary.Load(string)"/> throws, and a missing guard never degrades into "carry on without one".
/// The bridge is optional: absent answers <see cref="IntPtr.Zero"/>, the P/Invoke raises
/// <see cref="DllNotFoundException"/> under its System32-only default search, and L3 reports itself unavailable.
/// </para>
/// </remarks>
internal static class BesideThisAssembly
{
private static readonly ConcurrentDictionary<string, bool> _required = new(StringComparer.Ordinal);
static BesideThisAssembly()
{
NativeLibrary.SetDllImportResolver(typeof(BesideThisAssembly).Assembly, Resolve);
}
/// <summary>Claims a library name for this resolver; a facade calls it from its static constructor.</summary>
/// <param name="libraryName">The file name exactly as the <c>DllImport</c> attributes spell it.</param>
/// <param name="required">Whether absence is a throw (the guard) or a zero handle (the bridge).</param>
public static void Claim(string libraryName, bool required)
{
ArgumentException.ThrowIfNullOrEmpty(libraryName);
_required[libraryName] = required;
}
/// <summary>The full path a claimed library is loaded from, for the facades' own presence checks.</summary>
public static string PathOf(string libraryName) => Path.Combine(AppContext.BaseDirectory, libraryName);
private static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
if (!_required.TryGetValue(libraryName, out bool required))
{
return IntPtr.Zero;
}
string full = PathOf(libraryName);
if (required)
{
return NativeLibrary.Load(full);
}
return NativeLibrary.TryLoad(full, out IntPtr handle) ? handle : IntPtr.Zero;
}
}
@@ -0,0 +1,24 @@
namespace FrameLedger.Infrastructure.Telemetry;
/// <summary>
/// The bridge's C ABI as the managed sources see it, so <see cref="NvapiTelemetrySource"/> and
/// <see cref="NvapiNgxStateProbe"/> are tested on a machine with no NVIDIA driver. <see cref="NativeNvapiBridge"/>
/// is the real one.
/// </summary>
public interface INvapiBridge : IDisposable
{
/// <summary><c>FlNvInit</c>: 0, <c>FL_NV_NO_GPU</c>, or the <c>NvAPI_Status</c> that refused — a normal condition.</summary>
int Init();
/// <summary><c>FlNvReadSample</c>: 0 with the sample filled, or a status.</summary>
int ReadSample(out NvapiSample sample);
/// <summary><c>FlNvNgxState</c>: 0 with the words filled (their <c>Status</c> says which branch), or a status.</summary>
int NgxState(uint pid, out NvapiNgxWords words);
/// <summary><c>FlNvDriverVersion</c>: 0 with the version (e.g. 61664) and branch, or a status.</summary>
int DriverVersion(out uint version, out string branch);
/// <summary><c>FlNvShutdown</c>.</summary>
void Shutdown();
}
@@ -0,0 +1,175 @@
using System.Runtime.InteropServices;
using System.Text;
using FrameLedger.Infrastructure.Native;
namespace FrameLedger.Infrastructure.Telemetry;
/// <summary>
/// <c>FrameLedger.NvapiBridge.dll</c> behind <see cref="INvapiBridge"/>: the second P/Invoke facade after
/// <c>NativeAntiCheatGuard</c>, and it follows the same rule — loaded by absolute path from beside this
/// assembly, never from a search path (<c>18_GPU_VENDOR_APIS</c> §L3; P2 PR-E2).
/// </summary>
/// <remarks>
/// <para>
/// <b>Absent is not a fault.</b> A build without the native tree (or a fresh clone before <c>build.ps1
/// native</c>) has no DLL beside the binary; <see cref="Init"/> answers <see cref="Unavailable"/> and L3
/// disables itself the way a machine without an NVIDIA driver does. The guard's absence is a safety hole
/// and throws; the bridge's absence is a missing telemetry layer and reports itself.
/// </para>
/// <para>
/// <b>Never loaded into a game.</b> The Agent loads it into its own process; the name carries none of the
/// words the guard's §S18 heuristic scans a launcher's ancestors for.
/// </para>
/// </remarks>
public sealed class NativeNvapiBridge : INvapiBridge
{
/// <summary>What <see cref="Init"/> answers when the DLL is not beside this assembly at all.</summary>
public const int Unavailable = -1999;
/// <summary><c>FL_NV_NO_GPU</c>: the driver initialised and enumerated no GPU. NGX words are still queryable.</summary>
public const int NoGpu = -1002;
private const string _dll = "FrameLedger.NvapiBridge.dll";
private bool _disposed;
/// <summary>
/// References this instance holds on the DLL's refcounted <c>FlNvInit</c>. Two owners in one process
/// (the L3 source and the NGX probe) each hold their own instance, so one instance's <see cref="Dispose"/>
/// releases exactly what it took and never the other's.
/// </summary>
private int _live;
static NativeNvapiBridge()
{
// Optional where the guard is required: absent is a zero handle, a DllNotFoundException under the
// System32-only default search, and Unavailable from Init -- never a search of anything else.
BesideThisAssembly.Claim(_dll, required: false);
}
/// <summary>Whether the DLL is beside this assembly, without loading it.</summary>
public static bool IsPresent => File.Exists(BesideThisAssembly.PathOf(_dll));
public int Init()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!IsPresent)
{
return Unavailable;
}
try
{
int status = FlNvInit();
if (status is 0 or NoGpu)
{
// Both take a reference on the native side (NGX words need no GPU handle).
_live++;
}
return status;
}
catch (DllNotFoundException)
{
return Unavailable;
}
}
public int ReadSample(out NvapiSample sample)
{
sample = new NvapiSample { Size = (uint)Marshal.SizeOf<NvapiSample>() };
return FlNvReadSample(ref sample);
}
public int NgxState(uint pid, out NvapiNgxWords words)
{
words = new NvapiNgxWords { Size = (uint)Marshal.SizeOf<NvapiNgxWords>() };
return FlNvNgxState(pid, ref words);
}
public int DriverVersion(out uint version, out string branch)
{
var buffer = new byte[64];
int status = FlNvDriverVersion(out version, buffer, (uint)buffer.Length);
int end = Array.IndexOf(buffer, (byte)0);
branch = Encoding.ASCII.GetString(buffer, 0, end < 0 ? buffer.Length : end);
return status;
}
public void Shutdown()
{
if (_live > 0)
{
_live--;
FlNvShutdown();
}
}
/// <summary>The DLL's own build id, for the mirror test; null when it is absent.</summary>
public static string? BuildId()
{
if (!IsPresent)
{
return null;
}
IntPtr p = FlNvBuildId();
return p == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(p);
}
public static uint SampleSize() => FlNvSampleSize();
public static uint NgxStateSize() => FlNvNgxStateSize();
public static uint AbiVersion() => FlNvAbiVersion();
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
while (_live > 0)
{
Shutdown();
}
}
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern int FlNvInit();
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern void FlNvShutdown();
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern int FlNvReadSample(ref NvapiSample sample);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern int FlNvNgxState(uint pid, ref NvapiNgxWords words);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern int FlNvDriverVersion(out uint version, [Out] byte[] branch, uint capacity);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern uint FlNvAbiVersion();
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern uint FlNvSampleSize();
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern uint FlNvNgxStateSize();
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr FlNvBuildId();
}
@@ -0,0 +1,18 @@
namespace FrameLedger.Infrastructure.Telemetry;
/// <summary>The <c>FL_NV_FIELD_*</c> bits of <c>FlNvSample.present</c>: a clear bit is N/A, never 0.</summary>
[Flags]
public enum NvapiField
{
None = 0,
TempCore = 0x001,
TempMemory = 0x002,
Load = 0x004,
Vram = 0x008,
CoreClock = 0x010,
MemClock = 0x020,
Fan = 0x040,
Throttle = 0x080,
PcieWidth = 0x100,
Name = 0x200,
}
@@ -0,0 +1,94 @@
using System.Globalization;
using FrameLedger.Application.Capture;
namespace FrameLedger.Infrastructure.Telemetry;
/// <summary>
/// <c>NvAPI_NGX_GetNGXOverrideState</c> for one pid, in-process through the bridge (P2 PR-E2) — what the
/// capture host used to spawn <c>fl-probe-nvapi.exe</c> for. The words are the same; the outcomes map to
/// <see cref="NgxProbeOutcome"/> as the probe's machine line did, so <see cref="NgxDriverState"/> and every
/// consumer of it are untouched.
/// </summary>
/// <remarks>
/// Out of process, by pid, from the driver's own bookkeeping: no game memory, no hook, nothing loaded
/// into the target. Owns one bridge reference for its lifetime; a machine without an NVIDIA driver
/// answers <see cref="NgxProbeOutcome.Degraded"/> on every call and never throws.
/// </remarks>
public sealed class NvapiNgxStateProbe : INgxDriverProbe, IDisposable
{
private readonly INvapiBridge _bridge;
private readonly Lock _lock = new();
private bool _started;
private bool _usable;
private string? _refusal;
private bool _disposed;
public NvapiNgxStateProbe(INvapiBridge bridge)
{
_bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));
}
/// <summary>Over the real DLL: the bridge is born owned here, so there is no hand-off to reason about.</summary>
public NvapiNgxStateProbe()
{
_bridge = new NativeNvapiBridge();
}
public NgxDriverState Run(int pid)
{
ObjectDisposedException.ThrowIf(_disposed, this);
lock (_lock)
{
if (!_started)
{
_started = true;
int init = _bridge.Init();
// NGX words are per driver, not per GPU handle: a driver that enumerated no GPU still answers.
_usable = init is 0 or NativeNvapiBridge.NoGpu;
_refusal = init == NativeNvapiBridge.Unavailable
? "the bridge DLL is not beside this binary"
: "NvAPI_Initialize " + init.ToString(CultureInfo.InvariantCulture);
}
if (!_usable)
{
return NgxDriverState.Of(NgxProbeOutcome.Degraded, _refusal);
}
int status = _bridge.NgxState(checked((uint)pid), out NvapiNgxWords w);
if (status != 0)
{
return NgxDriverState.Of(NgxProbeOutcome.ProbeFailed, "FlNvNgxState " + status.ToString(CultureInfo.InvariantCulture));
}
return w.Status switch
{
NvapiNgxWords.Answered => new NgxDriverState(NgxProbeOutcome.Answered, w.Sr, w.Rr, w.Fg, w.ScalingRatio,
w.PerformanceMode, w.RenderPreset, w.FrameGenerationCount, w.FrameGenerationPreset, w.FrameGenerationMode,
w.Driver, 1, 1, false, null),
NvapiNgxWords.Unanswered => NgxDriverState.Of(NgxProbeOutcome.Unanswered, "NvAPI " + w.NvapiStatus.ToString(CultureInfo.InvariantCulture)),
_ => NgxDriverState.Of(NgxProbeOutcome.Degraded, "NvAPI_Initialize " + w.NvapiStatus.ToString(CultureInfo.InvariantCulture)),
};
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
lock (_lock)
{
if (_usable)
{
_bridge.Shutdown();
_usable = false;
}
}
_bridge.Dispose();
}
}
@@ -0,0 +1,47 @@
using System.Runtime.InteropServices;
namespace FrameLedger.Infrastructure.Telemetry;
/// <summary>Mirror of <c>FlNvNgxState</c> (<c>fl_nvapi_bridge.h</c>): the driver's NGX words for one process.</summary>
// CA1815 is the same call FrameLedger.Shared makes for its ring mirrors: this is a window onto a native struct, not
// a value anyone compares, and an Equals over it would be ceremony that hides the layout the file exists to state.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1815:Override equals and operator equals on value types", Justification = "P/Invoke mirror of a native struct; never compared.")]
[StructLayout(LayoutKind.Sequential)]
public struct NvapiNgxWords
{
public const int Answered = 0;
public const int Unanswered = 1;
public const int Degraded = 2;
public uint Size;
public int Status;
public int NvapiStatus;
public uint Driver;
public ulong Sr;
public ulong Rr;
public ulong Fg;
public float ScalingRatio;
public uint PerformanceMode;
public uint RenderPreset;
public uint FrameGenerationCount;
public uint FrameGenerationPreset;
public uint FrameGenerationMode;
public uint Reserved0;
public uint Reserved1;
}
@@ -0,0 +1,50 @@
using System.Runtime.InteropServices;
namespace FrameLedger.Infrastructure.Telemetry;
/// <summary>
/// Mirror of <c>FlNvSample</c> (<c>fl_nvapi_bridge.h</c>). <see cref="Size"/> is set by the caller and checked
/// by the bridge, so a drift between the two is refused (<c>FL_NV_BAD_SIZE</c>) rather than read; <c>NvapiBridgeLayoutTests</c>
/// compares <c>Marshal.SizeOf</c> against <c>FlNvSampleSize()</c> as well.
/// </summary>
// CA1815 is the same call FrameLedger.Shared makes for its ring mirrors: this is a window onto a native struct, not
// a value anyone compares, and an Equals over it would be ceremony that hides the layout the file exists to state.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1815:Override equals and operator equals on value types", Justification = "P/Invoke mirror of a native struct; never compared.")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct NvapiSample
{
public uint Size;
public uint Present;
public float TempCoreC;
public float TempMemoryC;
public float LoadPct;
public float VramUsedMb;
public float CoreClockMhz;
public float MemClockMhz;
public float FanRpm;
public uint ThrottleReasons;
public uint PcieWidth;
public uint Reserved0;
public uint Reserved1;
public uint Reserved2;
public uint Reserved3;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string Name;
public readonly bool Has(NvapiField field) => (Present & (uint)field) != 0;
}
@@ -0,0 +1,208 @@
using System.Diagnostics.CodeAnalysis;
using FrameLedger.Application.Telemetry;
namespace FrameLedger.Infrastructure.Telemetry;
/// <summary>
/// L3 — NVIDIA extras through the bridge (<c>docs/18_GPU_VENDOR_APIS.md</c> §L3): throttle reasons,
/// vendor-reported load, clocks, temperatures, fan, adapter memory, PCIe width, the driver version.
/// </summary>
/// <remarks>
/// <para>
/// <b>Reads on the caller's thread, like L1</b>: a bridge read is a handful of NVAPI queries in
/// microseconds, so the poller thread calls <see cref="TryRead"/>. <b>Unavailable is not zero and not a
/// fault</b>: a machine with no NVIDIA driver, or a build without the DLL, disables the layer at
/// <see cref="Start"/> with <see cref="GpuCapabilities.None"/>, and the composite's descriptor drops
/// <c>nvapi</c>. A bridge that THROWS twice is disabled by the port's rule; an NVAPI call the driver
/// refuses only leaves its bit clear.
/// </para>
/// <para>
/// <b>Not latency.</b> Reflex / PC latency is per frame and in the ring (<c>20_OPEN_QUESTIONS</c> §M8);
/// this source never calls <c>NvAPI_D3D_GetLatency</c>.
/// </para>
/// </remarks>
public sealed class NvapiTelemetrySource : IGpuTelemetrySource
{
/// <summary>Faults tolerated before the layer is disabled. The second one disables.</summary>
public const int MaxFaults = 2;
private readonly INvapiBridge _bridge;
private readonly TimeProvider _clock;
private readonly Lock _lock = new();
private bool _started;
private bool _initialised;
private bool _disposed;
private int _capabilities;
private int _faults;
private int _disabled;
private string? _lastFault;
private string? _driverVersion;
public NvapiTelemetrySource(INvapiBridge bridge, TimeProvider clock)
{
_bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
/// <summary>Over the real DLL: the bridge is born owned here, so there is no hand-off to reason about.</summary>
public NvapiTelemetrySource(TimeProvider clock)
{
_bridge = new NativeNvapiBridge();
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
public TelemetryLayer Layer => TelemetryLayer.Nvapi;
public GpuCapabilities Capabilities => (GpuCapabilities)Volatile.Read(ref _capabilities);
public bool IsDisabled => Volatile.Read(ref _disabled) != 0;
public int Faults => Volatile.Read(ref _faults);
public string? LastFault => Volatile.Read(ref _lastFault);
/// <summary>The driver's marketing version (<c>616.64</c>), once started on an NVIDIA machine; null otherwise.</summary>
public string? DriverVersion => Volatile.Read(ref _driverVersion);
/// <summary>Initialise NVAPI through the bridge. Idempotent; a refusal disables the layer for the session.</summary>
public void Start()
{
ObjectDisposedException.ThrowIf(_disposed, this);
lock (_lock)
{
if (_started || IsDisabled)
{
return;
}
_started = true;
int status;
try
{
status = _bridge.Init();
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
RecordFault($"Init: {ex.GetType().Name}: {ex.Message}");
Disable();
return;
}
if (status != 0)
{
Volatile.Write(ref _lastFault, status == NativeNvapiBridge.Unavailable
? "the bridge DLL is not beside this binary"
: $"NvAPI_Initialize / enumeration answered {status}");
Disable();
return;
}
_initialised = true;
if (_bridge.DriverVersion(out uint version, out string branch) == 0)
{
Volatile.Write(ref _driverVersion, $"{version / 100}.{version % 100:00} ({branch})");
}
}
}
public bool TryRead([NotNullWhen(true)] out GpuSample? sample)
{
sample = null;
if (IsDisabled)
{
return false;
}
Start();
lock (_lock)
{
if (IsDisabled || !_initialised)
{
return false;
}
NvapiSample raw;
try
{
if (_bridge.ReadSample(out raw) != 0)
{
return false;
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
RecordFault($"ReadSample: {ex.GetType().Name}: {ex.Message}");
return false;
}
sample = Map(raw, _clock.GetUtcNow());
}
MergeCapabilities(sample.PresentFields);
return true;
}
private static GpuSample Map(NvapiSample r, DateTimeOffset takenAt) => new()
{
TakenAt = takenAt,
Layer = TelemetryLayer.Nvapi,
AdapterName = r.Has(NvapiField.Name) ? r.Name : null,
TempCoreC = r.Has(NvapiField.TempCore) ? r.TempCoreC : null,
TempMemoryC = r.Has(NvapiField.TempMemory) ? r.TempMemoryC : null,
LoadPct = r.Has(NvapiField.Load) ? r.LoadPct : null,
VramAdapterMb = r.Has(NvapiField.Vram) ? r.VramUsedMb : null,
CoreClockMhz = r.Has(NvapiField.CoreClock) ? r.CoreClockMhz : null,
MemClockMhz = r.Has(NvapiField.MemClock) ? r.MemClockMhz : null,
FanRpm = r.Has(NvapiField.Fan) ? r.FanRpm : null,
ThrottleReasons = r.Has(NvapiField.Throttle) ? r.ThrottleReasons : null,
PcieWidth = r.Has(NvapiField.PcieWidth) ? (int)r.PcieWidth : null,
};
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
lock (_lock)
{
if (_initialised)
{
_bridge.Shutdown();
_initialised = false;
}
}
_bridge.Dispose();
}
private void MergeCapabilities(GpuCapabilities present)
{
int seen;
int merged;
do
{
seen = Volatile.Read(ref _capabilities);
merged = seen | (int)present;
}
while (Interlocked.CompareExchange(ref _capabilities, merged, seen) != seen);
}
private void RecordFault(string what)
{
Volatile.Write(ref _lastFault, what);
if (Interlocked.Increment(ref _faults) >= MaxFaults)
{
Disable();
}
}
private void Disable()
{
Volatile.Write(ref _disabled, 1);
Volatile.Write(ref _capabilities, (int)GpuCapabilities.None);
}
}
+1
View File
@@ -181,6 +181,7 @@ add_subdirectory(third_party)
add_subdirectory(FrameLedger.Shm)
add_subdirectory(FrameLedger.Overlay)
add_subdirectory(FrameLedger.Injector)
add_subdirectory(FrameLedger.NvapiBridge)
add_subdirectory(FrameLedger.VkLayer)
# enable_testing() must be called from the TOP-LEVEL CMakeLists, not from a
@@ -0,0 +1,22 @@
# FrameLedger.NvapiBridge — the C ABI the managed Agent reaches NVAPI through
# (docs/18_GPU_VENDOR_APIS.md §L3; P2 PR-E2).
#
# A SHARED library, because P/Invoke needs one and CLAUDE.md puts the native
# boundary in Infrastructure: the second facade after the guard's, and the ONLY
# shipped binary that links nvapi64.lib. Read-only by construction — every call
# in fl_nvapi_bridge.cpp is a query (§Runtime policy: never a setter).
#
# NEVER LOADED INTO A GAME. The Agent loads it beside its own binary by absolute
# path; nothing injects it, and its name carries none of the words the guard's
# §S18 heuristic scans a launcher's ancestors for (guard / hook / inject / cheat).
#
# fl_native_flags only, NOT fl_hostile_env_flags: this runs in our own process.
# It ships, so tools/versioninfo-check.ps1 covers it: a binary that can appear on
# a machine must say what it is (docs/19_SAFETY).
add_library(FrameLedger.NvapiBridge SHARED
src/fl_nvapi_bridge.cpp
)
target_include_directories(FrameLedger.NvapiBridge PUBLIC include)
target_link_libraries(FrameLedger.NvapiBridge PRIVATE FrameLedger.Shm fl_native_flags fl_nvapi)
target_compile_definitions(FrameLedger.NvapiBridge PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
fl_add_version_resource(FrameLedger.NvapiBridge "FrameLedger NVAPI telemetry bridge (read-only; loaded by the Agent, never into a game)")
@@ -0,0 +1,118 @@
// fl_nvapi_bridge.h — the C ABI the managed Agent reaches NVAPI through (docs/18_GPU_VENDOR_APIS.md §L3).
//
// WHAT THIS IS. NVAPI is a C API behind a vendored import library, and CLAUDE.md puts the native
// boundary in FrameLedger.Infrastructure: this DLL is the second P/Invoke facade after the guard's,
// and it is READ-ONLY by construction — nothing here calls a setter, and nothing here is reachable
// from a game process. It is loaded by the Agent (and the unshipped capture host) BESIDE the
// binary, by absolute path, never into a target: the name deliberately carries none of the words
// the guard's own §S18 heuristic scans a launcher's ancestors for.
//
// WHAT IT IS NOT. Not Reflex latency: NvAPI_D3D_GetLatency is per frame and per device, and the
// Overlay's in-process hook is where that fact lives (20_OPEN_QUESTIONS §M8). Not a poller: the
// managed TelemetryPoller asks FlNvReadSample at 1 Hz; this answers what the driver says now.
//
// VERSIONED STRUCTS. Every out-struct carries its own size as the first field, set by the caller and
// checked here, so a managed mirror that drifts from this header is refused (FL_NV_BAD_SIZE) rather
// than read as garbage — the same rule fl_shm.h applies with its static_asserts, one step later.
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifdef FL_NV_BUILDING
#define FL_NV_API __declspec(dllexport)
#else
#define FL_NV_API __declspec(dllimport)
#endif
#define FL_NV_ABI_VERSION 1u
// Status codes. Zero is success; negatives are ours; an NvAPI_Status is passed through where the
// caller can act on it (it is negative too, and never one of ours).
#define FL_NV_OK 0
#define FL_NV_NOT_INITIALISED (-1000)
#define FL_NV_BAD_SIZE (-1001)
#define FL_NV_NO_GPU (-1002)
#define FL_NV_BAD_ARGUMENT (-1003)
// Which fields of FlNvSample carry a value. A clear bit is N/A, never 0 (03_METRICS §Sensor aggregates).
#define FL_NV_FIELD_TEMP_CORE 0x001u
#define FL_NV_FIELD_TEMP_MEMORY 0x002u
#define FL_NV_FIELD_LOAD 0x004u
#define FL_NV_FIELD_VRAM \
0x008u // reserved: the vendored headers carry no memory-info entry point (L1 PDH and L2 own it)
#define FL_NV_FIELD_CORE_CLOCK 0x010u
#define FL_NV_FIELD_MEM_CLOCK 0x020u
#define FL_NV_FIELD_FAN 0x040u
#define FL_NV_FIELD_THROTTLE 0x080u
#define FL_NV_FIELD_PCIE_WIDTH 0x100u
#define FL_NV_FIELD_NAME 0x200u
typedef struct FlNvSample {
uint32_t size; // sizeof(FlNvSample), set by the caller
uint32_t present; // FL_NV_FIELD_* bits
float tempCoreC;
float tempMemoryC;
float loadPct; // NVAPI_GPU_UTILIZATION_DOMAIN_GPU, last 1 s
float vramUsedMb; // reserved (FL_NV_FIELD_VRAM is never set by this build)
float coreClockMhz;
float memClockMhz;
float fanRpm;
uint32_t throttleReasons; // NV_GPU_PERF_DECREASE_REASON_* bits, raw
uint32_t pcieWidth;
uint32_t reserved[4];
char name[64]; // NvAPI_ShortString, NUL-terminated
} FlNvSample;
// NvAPI_NGX_GetNGXOverrideState for one process (R570+): the driver's own per-process NGX words.
#define FL_NV_NGX_ANSWERED 0
#define FL_NV_NGX_UNANSWERED 1 // NvAPI answered but not for this pid
#define FL_NV_NGX_DEGRADED 2 // no usable NVIDIA driver
typedef struct FlNvNgxWords {
uint32_t size; // sizeof(FlNvNgxWords), set by the caller
int32_t status; // FL_NV_NGX_*
int32_t nvapiStatus; // the NvAPI_Status behind status, verbatim
uint32_t driver; // NvAPI_SYS_GetDriverAndBranchVersion, e.g. 61664
uint64_t sr; // feedbackMaskSR
uint64_t rr; // feedbackMaskRR
uint64_t fg; // feedbackMaskFG
float scalingRatio;
uint32_t performanceMode;
uint32_t renderPreset;
uint32_t frameGenerationCount;
uint32_t frameGenerationPreset;
uint32_t frameGenerationMode;
uint32_t reserved[2];
} FlNvNgxWords;
// Reference-counted: every FlNvInit is matched by an FlNvShutdown, and NvAPI_Unload runs at zero.
// Returns FL_NV_OK, or the NvAPI_Status NvAPI_Initialize answered (a normal condition on a machine
// with no NVIDIA driver — L3 disables cleanly, never throws). A machine whose driver initialises
// but enumerates no GPU answers FL_NV_NO_GPU.
FL_NV_API int32_t FlNvInit(void);
FL_NV_API void FlNvShutdown(void);
// One reading of the first physical GPU. Each field is independent: a call the driver refuses
// leaves its bit clear and the others intact. FL_NV_NOT_INITIALISED / FL_NV_BAD_SIZE otherwise.
FL_NV_API int32_t FlNvReadSample(FlNvSample* out);
// The driver's NGX words for `pid`. Never fails for a reason the caller cannot read: `status` says
// which branch was taken, and `nvapiStatus` says why.
FL_NV_API int32_t FlNvNgxState(uint32_t pid, FlNvNgxWords* out);
// Driver version (e.g. 61664) and branch string; FL_NV_NOT_INITIALISED before FlNvInit.
FL_NV_API int32_t FlNvDriverVersion(uint32_t* version, char* branch, uint32_t branchCapacity);
// What the managed mirror tests compare against, and what a build id check reads.
FL_NV_API uint32_t FlNvAbiVersion(void);
FL_NV_API uint32_t FlNvSampleSize(void);
FL_NV_API uint32_t FlNvNgxStateSize(void);
FL_NV_API const char* FlNvBuildId(void);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,266 @@
// fl_nvapi_bridge.cpp — see fl_nvapi_bridge.h.
//
// EVERY NVAPI CALL HERE IS A READ. 18_GPU_VENDOR_APIS §Runtime policy: the libraries behind the
// layers can also set clocks, fan curves and power limits; FrameLedger never calls a setter, and
// this translation unit is the whole of what links nvapi64.lib into a shipped binary, so the claim
// is checkable by reading one file.
#define FL_NV_BUILDING
#include "fl_nvapi_bridge.h"
#include <windows.h>
#include <atomic>
#include <cstring>
#include "nvapi.h"
namespace {
// Initialise/shutdown are serialised; reads are independent NVAPI calls on a handle that is set
// once and never changes while the count is above zero.
CRITICAL_SECTION g_lock;
bool g_lockInit = false;
int g_refs = 0;
NvPhysicalGpuHandle g_gpu = nullptr;
bool g_haveGpu = false;
std::atomic<bool> g_ready{false};
void EnsureLock() {
// DllMain is not used (no work under the loader lock); the first caller creates the section.
// A race between two first callers is not a shape the managed side produces — the facade is
// constructed once — and the section is never deleted, so a second init would only leak one.
if (!g_lockInit) {
InitializeCriticalSection(&g_lock);
g_lockInit = true;
}
}
struct Locked {
Locked() {
EnsureLock();
EnterCriticalSection(&g_lock);
}
~Locked() { LeaveCriticalSection(&g_lock); }
Locked(const Locked&) = delete;
Locked& operator=(const Locked&) = delete;
};
void ReadThermal(FlNvSample& s) {
NV_GPU_THERMAL_SETTINGS t{};
t.version = NV_GPU_THERMAL_SETTINGS_VER;
if (NvAPI_GPU_GetThermalSettings(g_gpu, NVAPI_THERMAL_TARGET_ALL, &t) != NVAPI_OK) {
return;
}
for (NvU32 i = 0; i < t.count && i < NVAPI_MAX_THERMAL_SENSORS_PER_GPU; ++i) {
if (t.sensor[i].target == NVAPI_THERMAL_TARGET_GPU && (s.present & FL_NV_FIELD_TEMP_CORE) == 0u) {
s.tempCoreC = static_cast<float>(t.sensor[i].currentTemp);
s.present |= FL_NV_FIELD_TEMP_CORE;
} else if (t.sensor[i].target == NVAPI_THERMAL_TARGET_MEMORY && (s.present & FL_NV_FIELD_TEMP_MEMORY) == 0u) {
s.tempMemoryC = static_cast<float>(t.sensor[i].currentTemp);
s.present |= FL_NV_FIELD_TEMP_MEMORY;
}
}
}
void ReadLoad(FlNvSample& s) {
NV_GPU_DYNAMIC_PSTATES_INFO_EX p{};
p.version = NV_GPU_DYNAMIC_PSTATES_INFO_EX_VER;
if (NvAPI_GPU_GetDynamicPstatesInfoEx(g_gpu, &p) != NVAPI_OK) {
return;
}
// Index 0 is the GPU domain: nvapi.h documents utilization[NVAPI_GPU_UTILIZATION_DOMAIN_GPU] and
// defines no such constant in this vintage of the header, so the documented index is spelled out.
constexpr NvU32 kGpuDomain = 0;
if (p.utilization[kGpuDomain].bIsPresent != 0u) {
s.loadPct = static_cast<float>(p.utilization[kGpuDomain].percentage);
s.present |= FL_NV_FIELD_LOAD;
}
}
void ReadClocks(FlNvSample& s) {
NV_GPU_CLOCK_FREQUENCIES c{};
c.version = NV_GPU_CLOCK_FREQUENCIES_VER;
c.ClockType = NV_GPU_CLOCK_FREQUENCIES_CURRENT_FREQ;
if (NvAPI_GPU_GetAllClockFrequencies(g_gpu, &c) != NVAPI_OK) {
return;
}
if (c.domain[NVAPI_GPU_PUBLIC_CLOCK_GRAPHICS].bIsPresent != 0u) {
s.coreClockMhz = static_cast<float>(c.domain[NVAPI_GPU_PUBLIC_CLOCK_GRAPHICS].frequency) / 1000.0f;
s.present |= FL_NV_FIELD_CORE_CLOCK;
}
if (c.domain[NVAPI_GPU_PUBLIC_CLOCK_MEMORY].bIsPresent != 0u) {
s.memClockMhz = static_cast<float>(c.domain[NVAPI_GPU_PUBLIC_CLOCK_MEMORY].frequency) / 1000.0f;
s.present |= FL_NV_FIELD_MEM_CLOCK;
}
}
void ReadExtras(FlNvSample& s) {
NvU32 v = 0;
if (NvAPI_GPU_GetTachReading(g_gpu, &v) == NVAPI_OK) {
s.fanRpm = static_cast<float>(v);
s.present |= FL_NV_FIELD_FAN;
}
v = 0;
if (NvAPI_GPU_GetPerfDecreaseInfo(g_gpu, &v) == NVAPI_OK) {
s.throttleReasons = v;
s.present |= FL_NV_FIELD_THROTTLE;
}
v = 0;
if (NvAPI_GPU_GetCurrentPCIEDownstreamWidth(g_gpu, &v) == NVAPI_OK && v != 0u) {
s.pcieWidth = v;
s.present |= FL_NV_FIELD_PCIE_WIDTH;
}
NvAPI_ShortString name{};
if (NvAPI_GPU_GetFullName(g_gpu, name) == NVAPI_OK) {
std::memcpy(s.name, name, sizeof(s.name) - 1);
s.name[sizeof(s.name) - 1] = '\0';
s.present |= FL_NV_FIELD_NAME;
}
}
} // namespace
extern "C" {
FL_NV_API int32_t FlNvInit(void) {
Locked lock;
if (g_refs > 0) {
++g_refs;
return g_haveGpu ? FL_NV_OK : FL_NV_NO_GPU;
}
const NvAPI_Status init = NvAPI_Initialize();
if (init != NVAPI_OK) {
return static_cast<int32_t>(init);
}
NvPhysicalGpuHandle handles[NVAPI_MAX_PHYSICAL_GPUS]{};
NvU32 count = 0;
g_haveGpu = NvAPI_EnumPhysicalGPUs(handles, &count) == NVAPI_OK && count > 0u;
g_gpu = g_haveGpu ? handles[0] : nullptr;
g_refs = 1;
g_ready.store(true, std::memory_order_release);
return g_haveGpu ? FL_NV_OK : FL_NV_NO_GPU;
}
FL_NV_API void FlNvShutdown(void) {
Locked lock;
if (g_refs == 0) {
return;
}
if (--g_refs == 0) {
g_ready.store(false, std::memory_order_release);
g_gpu = nullptr;
g_haveGpu = false;
NvAPI_Unload();
}
}
FL_NV_API int32_t FlNvReadSample(FlNvSample* out) {
if (out == nullptr) {
return FL_NV_BAD_ARGUMENT;
}
if (out->size != sizeof(FlNvSample)) {
return FL_NV_BAD_SIZE;
}
if (!g_ready.load(std::memory_order_acquire)) {
return FL_NV_NOT_INITIALISED;
}
Locked lock;
if (!g_haveGpu) {
return FL_NV_NO_GPU;
}
FlNvSample s{};
s.size = sizeof(FlNvSample);
ReadThermal(s);
ReadLoad(s);
ReadClocks(s);
ReadExtras(s);
*out = s;
return FL_NV_OK;
}
FL_NV_API int32_t FlNvNgxState(uint32_t pid, FlNvNgxWords* out) {
if (out == nullptr) {
return FL_NV_BAD_ARGUMENT;
}
if (out->size != sizeof(FlNvNgxWords)) {
return FL_NV_BAD_SIZE;
}
FlNvNgxWords r{};
r.size = sizeof(FlNvNgxWords);
if (!g_ready.load(std::memory_order_acquire)) {
r.status = FL_NV_NGX_DEGRADED;
r.nvapiStatus = FL_NV_NOT_INITIALISED;
*out = r;
return FL_NV_OK;
}
Locked lock;
NvU32 driver = 0;
NvAPI_ShortString branch{};
if (NvAPI_SYS_GetDriverAndBranchVersion(&driver, branch) == NVAPI_OK) {
r.driver = driver;
}
NV_NGX_DLSS_OVERRIDE_GET_STATE_PARAMS params{};
params.version = NV_NGX_DLSS_OVERRIDE_GET_STATE_PARAMS_VER;
params.processIdentifier = static_cast<NvU32>(pid);
const NvAPI_Status status = NvAPI_NGX_GetNGXOverrideState(&params);
r.nvapiStatus = static_cast<int32_t>(status);
if (status != NVAPI_OK) {
r.status = FL_NV_NGX_UNANSWERED;
*out = r;
return FL_NV_OK;
}
r.status = FL_NV_NGX_ANSWERED;
r.sr = params.feedbackMaskSR;
r.rr = params.feedbackMaskRR;
r.fg = params.feedbackMaskFG;
r.scalingRatio = params.scalingRatio;
r.performanceMode = params.performanceMode;
r.renderPreset = params.renderPreset;
r.frameGenerationCount = params.frameGenerationCount;
r.frameGenerationPreset = params.frameGenerationPreset;
r.frameGenerationMode = params.frameGenerationMode;
*out = r;
return FL_NV_OK;
}
FL_NV_API int32_t FlNvDriverVersion(uint32_t* version, char* branch, uint32_t branchCapacity) {
if (version == nullptr) {
return FL_NV_BAD_ARGUMENT;
}
if (!g_ready.load(std::memory_order_acquire)) {
return FL_NV_NOT_INITIALISED;
}
Locked lock;
NvU32 v = 0;
NvAPI_ShortString b{};
const NvAPI_Status status = NvAPI_SYS_GetDriverAndBranchVersion(&v, b);
if (status != NVAPI_OK) {
return static_cast<int32_t>(status);
}
*version = v;
if (branch != nullptr && branchCapacity > 0u) {
const size_t n = std::strlen(b);
const size_t copy = n < branchCapacity - 1u ? n : branchCapacity - 1u;
std::memcpy(branch, b, copy);
branch[copy] = '\0';
}
return FL_NV_OK;
}
FL_NV_API uint32_t FlNvAbiVersion(void) {
return FL_NV_ABI_VERSION;
}
FL_NV_API uint32_t FlNvSampleSize(void) {
return sizeof(FlNvSample);
}
FL_NV_API uint32_t FlNvNgxStateSize(void) {
return sizeof(FlNvNgxWords);
}
FL_NV_API const char* FlNvBuildId(void) {
return FL_BUILD_ID;
}
} // extern "C"
+13
View File
@@ -9,6 +9,19 @@ add_executable(fl_shm_layout_test layout_test.cpp)
target_link_libraries(fl_shm_layout_test PRIVATE FrameLedger.Shm fl_native_flags)
add_test(NAME fl_shm_layout COMMAND fl_shm_layout_test)
# The NVAPI bridge's C ABI (P2 PR-E2). Links the SHIPPED DLL rather than compiling its source in,
# because what the managed side loads is that DLL's export table; the DLL is copied beside the test
# so the loader finds it the way the Agent's directory will. Green on both kinds of machine and it
# says which (the same alternation fl_nvapi_probe pins, for the same reason).
add_executable(fl_nvapi_bridge_test nvapi_bridge_test.cpp)
target_link_libraries(fl_nvapi_bridge_test PRIVATE FrameLedger.NvapiBridge fl_native_flags Catch2::Catch2WithMain)
target_compile_options(fl_nvapi_bridge_test PRIVATE /EHsc)
add_custom_command(TARGET fl_nvapi_bridge_test POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
$<TARGET_FILE:FrameLedger.NvapiBridge> $<TARGET_FILE_DIR:fl_nvapi_bridge_test>)
add_test(NAME fl_nvapi_bridge COMMAND fl_nvapi_bridge_test)
set_tests_properties(fl_nvapi_bridge PROPERTIES PASS_REGULAR_EXPRESSION "BRANCH: (AVAILABLE|DEGRADED)")
# The safety-guard matrix. 20_OPEN_QUESTIONS §S13(a) put the guard in C++, which
# made Catch2 a PREREQUISITE of the guard rather than a later nicety: 14_TESTING
# requires forcing EnumProcessModulesEx failures, partial module lists and
+101
View File
@@ -0,0 +1,101 @@
// nvapi_bridge_test.cpp — the bridge's C ABI, green on both kinds of machine and saying which.
//
// A hosted runner has no NVIDIA driver: FlNvInit answers an NvAPI_Status and every read answers
// FL_NV_NOT_INITIALISED; the NGX query answers DEGRADED. The dev box takes the other branch. Both
// are the contract (18_GPU_VENDOR_APIS §L3: unavailability is a normal condition, never a throw),
// and the sizes the managed mirror compares against are the same on both.
#include <windows.h>
#include <catch2/catch_test_macros.hpp>
#include <cstdio>
#include <cstring>
#include "fl_nvapi_bridge.h"
TEST_CASE("the bridge's sizes and version are what the managed mirror will compare against", "[nvapi][abi]") {
CHECK(FlNvAbiVersion() == FL_NV_ABI_VERSION);
CHECK(FlNvSampleSize() == sizeof(FlNvSample));
CHECK(FlNvNgxStateSize() == sizeof(FlNvNgxWords));
CHECK(std::strlen(FlNvBuildId()) > 0u);
CHECK(std::strlen(FlNvBuildId()) < 32u);
}
TEST_CASE("a wrong struct size is refused before anything is read", "[nvapi][abi]") {
FlNvSample s{};
s.size = sizeof(FlNvSample) - 4u;
CHECK(FlNvReadSample(&s) == FL_NV_BAD_SIZE);
CHECK(FlNvReadSample(nullptr) == FL_NV_BAD_ARGUMENT);
FlNvNgxWords n{};
n.size = 1u;
CHECK(FlNvNgxState(0u, &n) == FL_NV_BAD_SIZE);
}
TEST_CASE("before FlNvInit every read says so, and the NGX query answers DEGRADED rather than failing",
"[nvapi][abi]") {
FlNvSample s{};
s.size = sizeof(FlNvSample);
CHECK(FlNvReadSample(&s) == FL_NV_NOT_INITIALISED);
uint32_t v = 0;
CHECK(FlNvDriverVersion(&v, nullptr, 0u) == FL_NV_NOT_INITIALISED);
FlNvNgxWords n{};
n.size = sizeof(FlNvNgxWords);
REQUIRE(FlNvNgxState(GetCurrentProcessId(), &n) == FL_NV_OK);
CHECK(n.status == FL_NV_NGX_DEGRADED);
}
TEST_CASE("FlNvInit takes one of two branches and says which; a sample never claims a field it did not read",
"[nvapi][abi]") {
const int32_t init = FlNvInit();
if (init != FL_NV_OK && init != FL_NV_NO_GPU) {
std::printf("BRANCH: DEGRADED (NvAPI_Initialize %d)\n", init);
FlNvSample s{};
s.size = sizeof(FlNvSample);
CHECK(FlNvReadSample(&s) == FL_NV_NOT_INITIALISED);
return;
}
std::printf("BRANCH: AVAILABLE (%s)\n", init == FL_NV_OK ? "a GPU" : "no GPU enumerated");
FlNvSample s{};
s.size = sizeof(FlNvSample);
const int32_t read = FlNvReadSample(&s);
if (init == FL_NV_NO_GPU) {
CHECK(read == FL_NV_NO_GPU);
} else {
REQUIRE(read == FL_NV_OK);
// A bit set is a value read; a bit clear is N/A. Both directions are pinned here on
// the only fields whose absence has a stable meaning: a name always reads, and a load
// percentage is within range when it does.
CHECK((s.present & FL_NV_FIELD_NAME) != 0u);
CHECK(std::strlen(s.name) > 0u);
if ((s.present & FL_NV_FIELD_LOAD) != 0u) {
CHECK(s.loadPct >= 0.0f);
CHECK(s.loadPct <= 100.0f);
}
if ((s.present & FL_NV_FIELD_TEMP_CORE) != 0u) {
CHECK(s.tempCoreC > -50.0f);
CHECK(s.tempCoreC < 150.0f);
}
std::printf(" present=0x%X name=%s temp=%.0f load=%.0f vram=%.0f MB core=%.0f MHz mem=%.0f MHz fan=%.0f "
"throttle=0x%X pcie=x%u\n",
s.present, s.name, s.tempCoreC, s.loadPct, s.vramUsedMb, s.coreClockMhz, s.memClockMhz, s.fanRpm,
s.throttleReasons, s.pcieWidth);
uint32_t version = 0;
char branch[64]{};
CHECK(FlNvDriverVersion(&version, branch, sizeof(branch)) == FL_NV_OK);
CHECK(version > 0u);
std::printf(" driver %u.%02u (%s)\n", version / 100u, version % 100u, branch);
}
// This process renders nothing through NGX, so the only honest NGX answers are the two that say so.
FlNvNgxWords n{};
n.size = sizeof(FlNvNgxWords);
REQUIRE(FlNvNgxState(GetCurrentProcessId(), &n) == FL_NV_OK);
CHECK((n.status == FL_NV_NGX_UNANSWERED || n.status == FL_NV_NGX_DEGRADED));
// Reference counting: a second init is a second reference, and the reads survive the first shutdown.
const int32_t again = FlNvInit();
CHECK((again == FL_NV_OK || again == FL_NV_NO_GPU));
FlNvShutdown();
FlNvShutdown();
const int32_t afterOne = FlNvReadSample(&s);
CHECK((afterOne == FL_NV_OK || afterOne == FL_NV_NO_GPU));
FlNvShutdown();
CHECK(FlNvReadSample(&s) == FL_NV_NOT_INITIALISED);
}
@@ -1,37 +0,0 @@
using FluentAssertions;
using FrameLedger.Application.Capture;
using FrameLedger.CaptureHost.Capture;
using FrameLedger.CaptureHost.Consume;
namespace FrameLedger.CaptureHost.Tests.Capture;
/// <summary>
/// The out-of-process probe as the loop calls it: every way it can fail is an outcome on the result, never a throw.
/// </summary>
public sealed class NgxDriverProbeTests
{
[Fact]
public void AMissingProbeIsAnOutcomeThatNamesThePath()
{
NgxDriverState s = NgxDriverProbe.Run(Environment.ProcessId, @"C:\nowhere\fl-probe-nvapi.exe");
s.Outcome.Should().Be(NgxProbeOutcome.ProbeMissing);
s.Detail.Should().Contain("fl-probe-nvapi.exe");
s.SrCreatedAndEvaluated.Should().BeFalse();
}
[Fact]
public void RunAgainstThisTestProcessNeverThrowsAndNeverClaimsAFeature()
{
// The real binary is staged beside the host by the project file when the native build ran
// first (CI does; a fresh clone may not). Whichever it is, this process renders nothing
// through NGX, so the only honest outcomes are the ones that say so.
NgxDriverState s = NgxDriverProbe.Run(Environment.ProcessId);
s.Outcome.Should().BeOneOf(NgxProbeOutcome.Unanswered, NgxProbeOutcome.Degraded, NgxProbeOutcome.ProbeMissing,
NgxProbeOutcome.ProbeFailed);
s.SrCreatedAndEvaluated.Should().BeFalse();
s.Readings.Should().Be(1);
s.Describe().Should().StartWith(" NVIDIA driver NGX state");
}
}
@@ -34,6 +34,7 @@
AppContext.BaseDirectory — so it has to sit beside the test binary.
-->
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Guard.targets" />
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.NvapiBridge.targets" />
<!--
The packaged seed, so the seeder tests run against the artifact that ships
@@ -0,0 +1,66 @@
using FrameLedger.Infrastructure.Telemetry;
namespace FrameLedger.Infrastructure.Tests.Telemetry;
/// <summary>A scripted <see cref="INvapiBridge"/>: what Init answers, what each read answers.</summary>
internal sealed class FakeNvapiBridge : INvapiBridge
{
public int InitResult { get; set; }
public Func<NvapiSample>? Sample { get; set; }
public Func<int, NvapiNgxWords>? Ngx { get; set; }
public uint Driver { get; set; } = 61664;
public int Inits { get; private set; }
public int Shutdowns { get; private set; }
public int Reads { get; private set; }
public bool Disposed { get; private set; }
public int Init()
{
Inits++;
return InitResult;
}
public int ReadSample(out NvapiSample sample)
{
Reads++;
sample = Sample is null ? default : Sample();
return Sample is null ? -1 : 0;
}
public int NgxState(uint pid, out NvapiNgxWords words)
{
words = Ngx is null ? new NvapiNgxWords { Status = NvapiNgxWords.Unanswered, NvapiStatus = -121 } : Ngx((int)pid);
return 0;
}
public int DriverVersion(out uint version, out string branch)
{
version = Driver;
branch = "r616_00";
return 0;
}
public void Shutdown() => Shutdowns++;
public void Dispose() => Disposed = true;
public static NvapiSample Full() => new()
{
Present = (uint)(NvapiField.TempCore | NvapiField.Load | NvapiField.CoreClock | NvapiField.MemClock | NvapiField.Fan | NvapiField.Throttle | NvapiField.PcieWidth | NvapiField.Name),
TempCoreC = 62,
LoadPct = 57,
CoreClockMhz = 2610,
MemClockMhz = 15001,
FanRpm = 1200,
ThrottleReasons = 0x2,
PcieWidth = 16,
Name = "NVIDIA GeForce RTX 5080",
};
}
@@ -0,0 +1,50 @@
using System.Runtime.InteropServices;
using FluentAssertions;
using FrameLedger.Infrastructure.Telemetry;
namespace FrameLedger.Infrastructure.Tests.Telemetry;
/// <summary>
/// The managed mirrors of <c>FlNvSample</c> and <c>FlNvNgxState</c> against the DLL's own sizes, and the DLL's
/// build id against the guard's — the same mirror discipline <c>ShmLayoutMirrorTests</c> applies, one binary later.
/// Fails rather than skips when the bridge is not staged: a mirror test that quietly does nothing is a gate that cannot fail.
/// </summary>
public sealed class NvapiBridgeMirrorTests
{
[Fact]
public void TheMirrorsAreTheSizesTheBridgeAnswersAndTheAbiVersionIsTheOneWeWroteAgainst()
{
NativeNvapiBridge.IsPresent.Should().BeTrue("FrameLedger.NvapiBridge.dll must be staged beside the test binary (FrameLedger.NvapiBridge.targets)");
NativeNvapiBridge.AbiVersion().Should().Be(1u);
((uint)Marshal.SizeOf<NvapiSample>()).Should().Be(NativeNvapiBridge.SampleSize());
((uint)Marshal.SizeOf<NvapiNgxWords>()).Should().Be(NativeNvapiBridge.NgxStateSize());
NativeNvapiBridge.BuildId().Should().NotBeNullOrEmpty();
}
[Fact]
public void TheRealBridgeEitherInitialisesOrSaysWhyAndNeverClaimsAFieldItDidNotRead()
{
using var bridge = new NativeNvapiBridge();
using var source = new NvapiTelemetrySource(bridge, TimeProvider.System);
source.Start();
if (source.IsDisabled)
{
// A runner without an NVIDIA driver, or no GPU: the normal branch on CI.
source.Faults.Should().Be(0);
source.LastFault.Should().NotBeNull();
return;
}
source.DriverVersion.Should().MatchRegex(@"^\d+\.\d{2} \(.+\)$");
source.TryRead(out Application.Telemetry.GpuSample? s).Should().BeTrue();
s!.AdapterName.Should().NotBeNullOrWhiteSpace();
(s.PresentFields & ~source.Capabilities).Should().Be(Application.Telemetry.GpuCapabilities.None);
if (s.LoadPct is { } load)
{
load.Should().BeInRange(0, 100);
}
}
}
@@ -0,0 +1,62 @@
using FluentAssertions;
using FrameLedger.Application.Capture;
using FrameLedger.Infrastructure.Telemetry;
namespace FrameLedger.Infrastructure.Tests.Telemetry;
/// <summary>The in-process probe maps the bridge's three branches to the outcomes the spawned probe used to print.</summary>
public sealed class NvapiNgxStateProbeTests
{
[Fact]
public void AnAnsweredWordIsTheDriverStateVerbatim()
{
using var bridge = new FakeNvapiBridge
{
Ngx = _ => new NvapiNgxWords { Status = NvapiNgxWords.Answered, Sr = 0x600, Rr = 0x1, Fg = 0x605, Driver = 61664, FrameGenerationCount = 0, ScalingRatio = 0 },
};
using var probe = new NvapiNgxStateProbe(bridge);
NgxDriverState s = probe.Run(4242);
s.Outcome.Should().Be(NgxProbeOutcome.Answered);
s.SrCreatedAndEvaluated.Should().BeTrue();
s.FgCreatedAndEvaluated.Should().BeTrue();
s.Driver.Should().Be(61664u);
s.Readings.Should().Be(1);
s.Answered.Should().Be(1);
}
[Fact]
public void UnansweredAndDegradedAreOutcomesNotThrows()
{
using var b1 = new FakeNvapiBridge();
using var b2 = new FakeNvapiBridge { InitResult = -6 };
using var b3 = new FakeNvapiBridge { InitResult = NativeNvapiBridge.Unavailable };
using var b4 = new FakeNvapiBridge { InitResult = NativeNvapiBridge.NoGpu };
using var unanswered = new NvapiNgxStateProbe(b1);
using var noDriver = new NvapiNgxStateProbe(b2);
using var noDll = new NvapiNgxStateProbe(b3);
using var noGpu = new NvapiNgxStateProbe(b4);
unanswered.Run(1).Outcome.Should().Be(NgxProbeOutcome.Unanswered);
unanswered.Run(1).Detail.Should().Contain("-121");
noDriver.Run(1).Outcome.Should().Be(NgxProbeOutcome.Degraded);
noDll.Run(1).Detail.Should().Contain("not beside this binary");
noGpu.Run(1).Outcome.Should().Be(NgxProbeOutcome.Unanswered, "NGX words are per driver; no GPU handle is needed");
}
[Fact]
public void TheBridgeIsInitialisedOnceAndShutDownOnDispose()
{
using var bridge = new FakeNvapiBridge();
var probe = new NvapiNgxStateProbe(bridge);
probe.Run(1);
probe.Run(2);
probe.Dispose();
bridge.Inits.Should().Be(1);
bridge.Shutdowns.Should().Be(1);
bridge.Disposed.Should().BeTrue();
}
}
@@ -0,0 +1,99 @@
using FluentAssertions;
using FrameLedger.Application.Telemetry;
using FrameLedger.Infrastructure.Telemetry;
namespace FrameLedger.Infrastructure.Tests.Telemetry;
/// <summary>L3's contract through a scripted bridge: unavailable is not zero, a clear bit is null, two throws disable.</summary>
public sealed class NvapiTelemetrySourceTests
{
private sealed class ManualTimeProvider : TimeProvider
{
public override DateTimeOffset GetUtcNow() => new(2026, 9, 10, 12, 0, 0, TimeSpan.Zero);
}
[Fact]
public void AFullSampleMapsEveryFieldAndTheLayerIsNvapi()
{
using var bridge = new FakeNvapiBridge { Sample = FakeNvapiBridge.Full };
using var source = new NvapiTelemetrySource(bridge, new ManualTimeProvider());
source.TryRead(out GpuSample? s).Should().BeTrue();
s!.Layer.Should().Be(TelemetryLayer.Nvapi);
s.AdapterName.Should().Be("NVIDIA GeForce RTX 5080");
s.TempCoreC.Should().Be(62);
s.TempMemoryC.Should().BeNull("the bit was clear");
s.LoadPct.Should().Be(57);
s.VramAdapterMb.Should().BeNull("this build reads no memory info");
s.CoreClockMhz.Should().Be(2610);
s.MemClockMhz.Should().Be(15001);
s.FanRpm.Should().Be(1200);
s.ThrottleReasons.Should().Be(0x2u);
s.PcieWidth.Should().Be(16);
s.PcieGen.Should().BeNull();
source.Capabilities.Should().Be(GpuCapabilities.TempCore | GpuCapabilities.Load | GpuCapabilities.CoreClock
| GpuCapabilities.MemClock | GpuCapabilities.Fan | GpuCapabilities.ThrottleReasons | GpuCapabilities.Pcie);
source.DriverVersion.Should().Be("616.64 (r616_00)");
bridge.Inits.Should().Be(1);
}
[Theory]
[InlineData(NativeNvapiBridge.Unavailable)]
[InlineData(-6)]
[InlineData(NativeNvapiBridge.NoGpu)]
public void AnInitThatDoesNotAnswerZeroDisablesTheLayerWithoutAFault(int init)
{
using var bridge = new FakeNvapiBridge { InitResult = init, Sample = FakeNvapiBridge.Full };
using var source = new NvapiTelemetrySource(bridge, new ManualTimeProvider());
source.Start();
source.IsDisabled.Should().BeTrue();
source.Capabilities.Should().Be(GpuCapabilities.None, "unavailable is N/A, never zero");
source.Faults.Should().Be(0, "a machine without the driver is a normal condition");
source.LastFault.Should().NotBeNull();
source.TryRead(out _).Should().BeFalse();
bridge.Reads.Should().Be(0);
}
[Fact]
public void ABridgeThatThrowsTwiceIsDisabledAndAReadTheDriverRefusesIsNot()
{
int calls = 0;
using var bridge = new FakeNvapiBridge
{
Sample = () => ++calls is 2 or 4 ? throw new InvalidOperationException("driver went away") : FakeNvapiBridge.Full(),
};
using var source = new NvapiTelemetrySource(bridge, new ManualTimeProvider());
source.TryRead(out _).Should().BeTrue();
source.TryRead(out _).Should().BeFalse();
source.Faults.Should().Be(1);
source.IsDisabled.Should().BeFalse();
source.TryRead(out _).Should().BeTrue();
source.TryRead(out _).Should().BeFalse();
source.IsDisabled.Should().BeTrue();
source.Capabilities.Should().Be(GpuCapabilities.None);
source.TryRead(out _).Should().BeFalse("never retried");
}
[Fact]
public void DisposeShutsTheBridgeDownOnceAndOnlyIfItWasInitialised()
{
using var live = new FakeNvapiBridge { Sample = FakeNvapiBridge.Full };
var source = new NvapiTelemetrySource(live, new ManualTimeProvider());
source.Start();
source.Dispose();
source.Dispose();
live.Shutdowns.Should().Be(1);
live.Disposed.Should().BeTrue();
using var dead = new FakeNvapiBridge { InitResult = -6 };
var disabled = new NvapiTelemetrySource(dead, new ManualTimeProvider());
disabled.Start();
disabled.Dispose();
dead.Shutdowns.Should().Be(0, "nothing was initialised");
dead.Disposed.Should().BeTrue();
}
}
+1 -1
View File
@@ -29,7 +29,7 @@ Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Every binary that can end up inside a process we do not own.
$required = @('FrameLedger.Overlay.dll', 'FrameLedger.VkLayer.dll', 'FrameLedger.Guard.dll')
$required = @('FrameLedger.Overlay.dll', 'FrameLedger.VkLayer.dll', 'FrameLedger.Guard.dll', 'FrameLedger.NvapiBridge.dll')
if (-not (Test-Path $BuildDir)) {
Write-Host "VERSIONINFO CHECK FAILED: no native build at $BuildDir" -ForegroundColor Red