Compare commits

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

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

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

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

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

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 19:25:45 +07:00
32 changed files with 2158 additions and 165 deletions

No files matched your search

+15
View File
@@ -19,6 +19,21 @@ GitHub release body, so a missing section will mean an empty release note.
### Added
- **P1 item 3 — the Vulkan layer intercepts `vkQueuePresentKHR` (2026-09-06; `20_OPEN_QUESTIONS` §S2 ✅).**
In a process both gates admitted, the layer creates the same ring the Overlay would (`fl_shm_host.h`,
now the one home of the DACL / name / handshake for both capture sides; one ring per process, first
creator owns it) at the first `vkCreateDevice`, writes one record per present (`api` = Vulkan, output
size from `vkCreateSwapchainKHR`'s `imageExtent`, no `PRESENT_ARGS` because the call has none), and
forwards everything — including when the ring is not its own, which the first fixture run proved
necessary. §S2 part three lands with it: `unhookRequested` and the 07_IPC tick deadline both stop the
layer on the present path (passthrough with the reason on the mapping), proven by a fake loader chain
(ctest `fl_vklayer`) and a 1.5 s test-only flavour of the DLL (`fl_vklayer_supervision`). The harness
gains `--vulkan --hold-presenting N` (real loader via `LoadLibraryW`, hidden window, exit 77 = cannot
run here) and ctest `fl_vklayer_real` drives it through the real loader with `VK_ADD_IMPLICIT_LAYER_PATH`
— measured honoured by loader 1.4.357 with no registry — skipping on CI. Launch mode classifies a
Vulkan-only target as the layer's (`TargetIsVulkanLayered` = 26: full guard, nothing injected, attach to
the layer's ring) and the CaptureHost hands the launched process the layer's environment
(`VkLayerLaunchEnvironment`: manifest, enable variable, enable-list line for the session).
- **P1 item 2 — launch mode, built as "inject late" (2026-09-06; `20_OPEN_QUESTIONS` §S1 ◐, §S13(c) ✅).**
The guard gains `FlGuardedInjectWhenReady(pid, dll, timeoutMs)`: it polls the launched target through
the module seam — matching no blocklist — until a presentation runtime is mapped, then runs every
+4 -2
View File
@@ -11,7 +11,9 @@
> charts, no library import, no UI and no installer yet.
>
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles. The Vulkan layer and OpenGL/D3D9 intercept nothing yet.
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
@@ -66,7 +68,7 @@ FrameLedger is built to keep that risk small and to be honest about it:
| Safeguard | |
|---|---|
| **Off by default** | Injection is disabled for every game until you enable it individually, after a consent prompt |
| **Hard refusal** | Known anti-cheat/anti-tamper components are detected before injection and every 30 s during a session. Detected ⇒ FrameLedger refuses, or stops capturing at the next scan — so up to 30 s can pass before it reacts to anti-cheat that loads mid-session. For Direct3D/OpenGL that means hooks are removed; for Vulkan it means the layer goes passthrough, because a layer cannot leave the loader chain of a running game. **There is no override — not in settings, not in a config file, not on the command line**<br><br>⚠ **Half of this is built.** The *pre-injection* refusal is real and runs every documented check. The **in-session re-scan does not run at all**: the component inside the game removes its hooks within one frame of being told to, and within 65 s if it stops hearing from the scanner — but nothing yet drives the scanner during a session, so nothing ever tells it. `legal/DISCLAIMER.md` §2 states this in full. The Vulkan layer additionally intercepts nothing yet, so there is no Vulkan capture to stop. |
| **Hard refusal** | Known anti-cheat/anti-tamper components are detected before injection and every 30 s during a session. Detected ⇒ FrameLedger refuses, or stops capturing at the next scan — so up to 30 s can pass before it reacts to anti-cheat that loads mid-session. For Direct3D/OpenGL that means hooks are removed; for Vulkan it means the layer goes passthrough, because a layer cannot leave the loader chain of a running game. **There is no override — not in settings, not in a config file, not on the command line**<br><br>⚠ **Half of this is built.** The *pre-injection* refusal is real and runs every documented check. The **in-session re-scan does not run at all**: the component inside the game removes its hooks within one frame of being told to, and within 65 s if it stops hearing from the scanner — but nothing yet drives the scanner during a session, so nothing ever tells it. `legal/DISCLAIMER.md` §2 states this in full. For a Vulkan title the stop is the layer's own: it checks the scanner's counter on every present and goes passthrough within one present of the stop flag, or after 65 s without a scan — a title that has stopped presenting is not stopped by that deadline, and presents nothing to be observed either. |
| **No evasion, ever** | FrameLedger does not hide, rename, obfuscate, or disguise itself. It keeps its real name, real exports, and version info. It is meant to be plainly visible to any security software that looks. This is an architectural rule, not a setting |
| **Read-only** | It never reads or writes game memory, never modifies game behavior, never touches saves or input, and never changes GPU clocks, fans, or power limits |
| **Always a way out** | FrameLedger refuses rather than pushes through. When the guard finds anti-cheat, or the hook fails, or you have not enabled a game, it **stops** — and records the session anyway: start, end, duration, whatever hardware sensors your machine provides, and the reason there is nothing else. Every measured value reads `N/A`; it never estimates one.<br><br>**The way out is that it does not inject, not that it measures another way.** An earlier version of this row promised a no-injection measurement mode. It was designed around Intel PresentMon, that was dropped on 2026-08-27 after measurement, and no replacement was chosen — so **frame times require hooking**. Said in this row rather than a footnote because the row is in the SAFETY table, and a reader deciding whether to enable a game needs the real alternative, not a comfortable one |
+10 -1
View File
@@ -205,7 +205,16 @@ Idle → Detected(pid) → Guarded → Injecting → Capturing → Finalizing
**Vulkan sessions do not pass through `Injecting`.** The layer is loaded by the
Vulkan loader when the Agent launches an opted-in game, so the path is
`Detected(pid) → Guarded → Capturing`, skipping injection entirely. This is
`Detected(pid) → Guarded → Capturing`, skipping injection entirely.
> **Built 2026-09-06 (P1 item 3), through launch mode.** The guard's waiting entry classifies the
> launched target by what it mapped: `vulkan-1.dll` with no D3D or OpenGL runtime runs the **full** guard
> and, on a pass, injects nothing — `TargetIsVulkanLayered`, which the loop reads as "attach to the
> layer's ring" with launch mode's budget (the ring appears at the title's first `vkCreateDevice`). The
> CaptureHost's `launch` gives the process the layer's environment (`VkLayerLaunchEnvironment`:
> `VK_ADD_IMPLICIT_LAYER_PATH`, the enable variable, the enable-list line for the session); a D3D title
> ignores all of it. One ring per process, the first creator owns it (`fl_shm_host.h`). Attach mode on a
> running Vulkan title stays Tier 2: only a launch can set the loader's environment. This is
stated because the state machine above, read literally, meant the 30 s guard
re-scan — which `19_SAFETY` calls the most important runtime behaviour in the
capture layer — was not specified to run for Vulkan at all. It runs for **every
+1 -1
View File
@@ -24,7 +24,7 @@ Targets:
- `FrameLedger.VkLayer` → `FrameLedger.VkLayer.dll` + `VkLayer_FRAMELEDGER_overlay.json`
- `FrameLedger.Injector` → **static lib only.** There is no `FrameLedger.Injector.exe` and none ships (`20_OPEN_QUESTIONS` §S9, decided 2026-08-02). A standalone `LoadLibraryW` injector that users can run is a path into a game process that the guard does not stand in front of — a bypass, and a bad look for a project whose position is "we refuse where we are not welcome". The Agent links the static lib; the guard owns the chokepoint inside it (§S13(b)), so there is no callable entry point that skips the gate. Manual testing uses `hook-harness`, never a real game (§Debugging).
- `FrameLedger.Overlay.Tests` → Catch2 unit tests (ring buffer, record layout, fault filter, seqlock) **and the guard's fail-closed matrix** (`14_TESTING` §Safety-guard tests) — the guard is native, so its tests are too
- `hook-harness` → the dummy **D3D11 + D3D12** app, WARP + composition swapchain so it runs headless on CI (`17_HOOK_ENGINE` §Test harness). D3D12 is device → command queue → swapchain, which is the acquisition asymmetry a D3D11-only fixture cannot exercise. Vulkan and OpenGL modes to follow as those hooks land.
- `hook-harness` → the dummy **D3D11 + D3D12** app, WARP + composition swapchain so it runs headless on CI (`17_HOOK_ENGINE` §Test harness). D3D12 is device → command queue → swapchain, which is the acquisition asymmetry a D3D11-only fixture cannot exercise. ~~Vulkan and OpenGL modes to follow as those hooks land.~~ **`--vulkan --hold-presenting N` since 2026-09-06 (P1 item 3):** a real swapchain on a hidden window through the real loader, reached by `LoadLibraryW("vulkan-1.dll")` so only the vendored headers are needed and CI (no loader) still builds it; exit 77 = cannot run here, which the ctest reads as SKIP. OpenGL to follow.
- `fl-probe-hookprofile` → build-profile probes for `/guard:cf` and `-D_HAS_EXCEPTIONS=0` (`20_OPEN_QUESTIONS` §H1/§H3)
- `fl-probe-guard` → measures the Windows APIs the guard is built on, unelevated (`spike-notes.md` §1). Not the guard, and takes no injection rights.
- `fl_stub_sl_interposer` → `sl.interposer.dll`, and `fl_stub_sl_common` → `sl.common.dll` (`src/native/tools/vendor-stubs/`). **Fixtures, never shipped**, built under `FL_BUILD_TOOLS`; nothing `12_BUILD` publishes references them. They export the **measured** vendor names from `docs/vendor-exports.json` so the Overlay's symbol resolution is observable, and the second is a **decoy** exporting the same name from a different module — without it, "we resolve module-scoped" is a property no test can falsify. Their **output filenames are the vendor's and their version blocks are ours**: `fl_add_version_resource` takes the real filename so a file called `sl.interposer.dll` in our build tree still says plainly that it is FrameLedger's, which `19_SAFETY` requires of everything we build.
+4 -2
View File
@@ -290,8 +290,10 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
> launch mode (§S13(c), §S1's deferred input) — **landed 2026-09-06 as "inject late"**
> (`FlGuardedInjectWhenReady`, the CaptureHost `launch` verb, `dxgiPresentsBeforeHook` as the cost meter;
> `04_CAPTURE` §Launch mode); **3** the Vulkan layer to `vkQueuePresentKHR` with §S2's
> in-layer supervision and a harness Vulkan mode (reopens §S29(d)'s CI leg); **4** the unhook path,
> native logging, D3D9 / OpenGL.
> in-layer supervision and a harness Vulkan mode — **landed 2026-09-06** (`layer.cpp` capture side,
> `fl_shm_host.h` shared with the Overlay, `hook-harness --vulkan`, ctest `fl_vklayer*`, launch mode's
> `TargetIsVulkanLayered` branch; §S2 ✅, §S29(d)'s assertion now a ctest that skips on CI); **4** the
> unhook path, native logging, D3D9 / OpenGL.
> **The guard already shipped, in P0.** This line used to read "the guard,
> complete and fully tested — it ships before the first real injection, not
+7 -1
View File
@@ -172,7 +172,7 @@ Every hook must be listed here with a purpose. Anything not on this list is not
| ⏳ `IDXGISwapChain3::SetColorSpace1` | HDR output detection. **`IDXGISwapChain3`, not 4** — 4 adds only `SetHDRMetaData` (`20_OPEN_QUESTIONS` §H9). Unbuilt, which is why `colorSpace` reads `NOT_REPORTED` and `FL_MEASURED_HDR` stays clear. **When it is built, the writer must initialise `colorSpace = FL_COLOR_SPACE_SDR` at swapchain identification** — an SDR title never calls `SetColorSpace1`, so "hook live, no call" would otherwise sit at `NOT_REPORTED` forever and HDR's definite `No` would be unreachable. DXGI documents G22/Rec.709 as the default, which makes SDR a *measured* default rather than an affirmative negative |
| ⏳ `IDXGIFactory::CreateSwapChain*` | Capture swapchain desc (format, buffer count, swap effect, flags) at creation. Unbuilt — the swapchain description is currently read on demand in the present hook via `GetDesc` |
| ⏳ `wglSwapBuffers` | OpenGL titles. Unbuilt, and deliberately not attempted before `hook-harness` has an OpenGL mode: the hook is small (a flat export, no vtable) but shipping an unexercised hook into a game process is not something this project does. Measured 2026-08-05: `opengl32!wglSwapBuffers` is a `jmp` thunk (`E9 <rel32>`) into the vendor ICD, which is already mapped before the first call |
| ⏳ Vulkan `vkQueuePresentKHR` | via layer, not hook (below). Unbuilt — P1, and §S2's in-layer supervision check lands with it. The layer today loads, gates and self-scans, and intercepts nothing |
| ✅ Vulkan `vkQueuePresentKHR` (2026-09-06, P1 item 3) | via layer, not hook (below). Frame boundary and QPC, one record per present; `vkCreateSwapchainKHR` / `vkDestroySwapchainKHR` intercepted beside it for the output size (`imageExtent`, the API's own argument — rule 4). **No `FL_MEASURED_PRESENT_ARGS`**: `vkQueuePresentKHR` carries no sync interval and no flags, which is why that bit exists. §S2's in-layer supervision check landed with it, on the present path. Measured under the real loader on the harness's `--vulkan` mode: 241 records in 4 s, status READY, `apiMask` = Vulkan (ctest `fl_vklayer_real`) |
### Upscaling / frame generation (the accuracy problem this rewrite exists to solve)
| Hook | Yields |
@@ -383,6 +383,12 @@ is not something this loader supports.
> admin. Registering under HKCU (below) is the less common choice and the better
> one: no elevation, and per-user scope.
- Intercepts `vkQueuePresentKHR`, `vkCreateSwapchainKHR`, `vkCmdTraceRaysKHR`, `vkCmdBuildAccelerationStructuresKHR`, `vkCreateGraphicsPipelines`.
> **Built 2026-09-06 (P1 item 3): the first two, plus `vkDestroySwapchainKHR`; the three feature entries are still ⏳.** How the capture side works, stated once:
> - **The ring is the same ring.** `fl_shm_host.h` (header-only, in `FrameLedger.Shm`) now holds the user-only DACL, the `Local\FrameLedger.Ring.<pid>` name, the mapping and the handshake for **both** capture sides; the Overlay calls it too. **One ring per process: whichever side creates the mapping first owns it, the other sees `ERROR_ALREADY_EXISTS` and stays inert** — and stays *forwarding*: the layer registers every device's next pointers before it tries the ring, because a hook with nothing to forward to failed the application's present (measured, `VK_ERROR_DEVICE_LOST` on the harness, the first time the Overlay got there first). That is also why the launch-mode guard **does not inject a presenter that mapped `vulkan-1.dll`** (`Reason::kTargetIsVulkanLayered`, `fl_guard.cpp`) — with or without a D3D runtime beside it, because **an NVIDIA Vulkan ICD maps `dxgi.dll` + `d3d12.dll` itself and presents the Vulkan swapchain through a DXGI flip chain** (measured on the harness's `--vulkan` mode: classified as D3D, the injected Overlay recorded 295 DXGI presents of a Vulkan swapchain and the layer forwarded into nothing). The layer is the capture side for anything that maps the Vulkan loader; a D3D title that happens to is the rarer shape and the one this rule gets wrong.
> - **It comes up at the first admitted `vkCreateDevice`**, never at load and never at `vkCreateInstance`, so a process either gate refused never has a mapping with its pid on it. Init is not a hook path; the present hook is, and it follows the Overlay's rules — SEH-guarded, allocation-free, lock-free, three faults → `SELF_DISABLED`.
> - **§S2 part three, the in-layer supervision, runs on the present path**, because the layer may not own a thread (the loader owns its mapping). `guardTicks` not advancing for `FL_GUARD_TICK_DEADLINE_MS` → `FL_STATUS_UNHOOKED`; `unhookRequested` → the same within one present; `pauseRequested` → no record, still forwarded. "Stops" means **passthrough forever with the reason on the mapping** — a layer cannot leave a running game's loader chain. A title that stops presenting is not stopped by the deadline, and has nothing to be observed either. Proven with a test-only flavour of the DLL whose deadline is 1.5 s (`fl_vklayer_shortdeadline`, never shipped; ctest `fl_vklayer_supervision`).
> - **No registry for the operator host.** Loader 1.4.357 honours `VK_ADD_IMPLICIT_LAYER_PATH` (measured 2026-09-06, `spike-notes` §2): the CaptureHost's `launch` writes a manifest under `%LOCALAPPDATA%\FrameLedger\vklayer`, points the launched process at it, sets the enable variable and adds the image name to the enable-list for the session — discoverable by that process alone, gone when it ends. The Agent's HKCU registration (`12_BUILD`) is unchanged and remains P2's.
- The layer respects the same guard, in two steps at init: it checks the enable-list, and it scans **its own process** against the anti-cheat blocklist. Either one saying no means fully passthrough. **A layer is machine-wide by nature — these checks are mandatory, not optional.**
- The self-scan uses the **same matcher and the same rules file as the injection guard** (`fl_ac_rules.h`, compiled into both targets). Not a copy: a layer with its own blocklist would be a second matcher that can disagree with the first. Every uncertainty — rules unreadable, malformed, enumeration failed, a truncated list — resolves to passthrough, which is the opposite polarity from the injection guard and the same principle: leave the host alone.
- Registered only while at least one Vulkan game has hooking enabled; unregistered on uninstall (Velopack hook) and when the last such game is disabled. **Never at install time** — `12_BUILD` §The Vulkan layer is not registered at install time.
+25 -4
View File
@@ -79,7 +79,7 @@ or it becomes the next stale status claim this file exists to record.
| **S14** | 🅓 **exe half wired 2026-08-05; store-id half deferred to P4, rationale written 2026-09-06** | The store-id half's only in-policy route is P4's platform metadata extractors feeding a guard-side resolver; a resolver with no extractor would refuse every title. No title is blocked by store id today because none is listed |
| **S23-1** | ✅ **resolved 2026-08-05** | `FlGuardBuildId` gives the Agent a build id of its own, and `ShmHandshakeValidator` performs the comparison `07_IPC` and `04_CAPTURE` both specify. Every refusal path is driven, including **both ids empty** — the shape the feature shipped in, where `"" == ""` reported `Ok` for every process on the machine |
| **S23-4** | ✅ **resolved 2026-08-05** | `19_SAFETY` §During a session said "the module scan and the driver scan"; `EvaluateImpl` runs four. Reworded to "every pre-injection check" so it cannot go stale when a check is added, with the two omissions named — `services` is the only tier measured firing on real anti-cheat, and the pre-scan is the only one touching the filesystem |
| **S2 part three** | 🅓 **deferred to P1, rationale written 2026-09-06** | In-layer supervision lands with `vkQueuePresentKHR` (P1). Building it sooner would be a predicate whose wrong answer changes nothing observable; the layer intercepts nothing, so nothing a user sees waits on it |
| **S2 part three** | ✅ **built 2026-09-06 (P1 item 3)** | In-layer supervision on the present path, landed with `vkQueuePresentKHR`; `unhookRequested` and the tick deadline both stop the layer (passthrough with the reason on the mapping), proven by a fake loader chain and a 1.5 s test-only flavour of the DLL |
| **S4 signing** | 🅓 **deferred to P4, rationale written 2026-09-06** | Signing is a property of the feed and there is no feed (§S20); every rules file today shipped inside a release whose checksum attests it. The P4 decision (compiled-in key, detached signature, fail-closed) is written in the entry |
| **S6** | ✅ **built 2026-09-06 (P1 item 1)** | The detour on `kernelbase!LoadLibraryExW` stops the Overlay from inside on an exact-floor MODULE match, within one present or one watchdog iteration, and wakes the lazy installers within milliseconds for an inventoried module; measured against the real Overlay in ctest `fl_guard` `[loader]`/`[S6]`. Exact names only — fragment and signer stay the host's 30 s scan, so the disclosure does not change |
| **S19(a)** | ✅ **resolved 2026-08-05** | `gameguard` could never fire — `guard` subsumed it. Removed; `rules-validate` now fails when any fragment contains another, so the class cannot return. Zero coverage lost: nProtect has its own named module family |
@@ -431,6 +431,14 @@ would matter.
> S29 as an S-item; the count below is written for the absent row and corrected if the
> census says otherwise.
>
> **2026-09-06 (P1 item 3): the assertion now lives in a ctest, and it no longer needs the registry.**
> `fl_vklayer_real` starts the harness's `--vulkan` mode with `VK_ADD_IMPLICIT_LAYER_PATH` pointed at the
> build tree's manifest and the enable variable set, and asserts the loader mapped the layer and the layer
> recorded the presents — on every dev-box build, with no HKCU write and nothing left behind. It SKIPS
> where there is no loader or no presentable device, which is CI's row; the census still decides (d)'s
> CI leg. `vklayer-blastradius.ps1` remains the hand-run check of the *unset-variable* case (it was run
> before this PR, green), and the loader-upgrade reminder is now the ctest rather than a HANDOFF trap.
>
> **Read 2026-09-06 off the sweep PR's run (`windows-latest`): `vulkan-1.dll` PRESENT in
> System32, `vulkaninfo.exe` absent (not in System32, not on PATH), no ICD registry key.** The
> absent row: **🅓 deferred on that measurement.** The loader is there but nothing to drive it
@@ -1340,7 +1348,7 @@ still lacks.
> `opengl32` or `vulkan-1` lazily rather than at startup. The owner supplies real
> fixtures on request; this one has not been found on this machine.
### S2 ◐ · The Vulkan layer has no guard — **both halves done; mid-session unhook still open**
### S2 ✅ · The Vulkan layer has no guard — **both halves done; part three built 2026-09-06 (P1 item 3)**
An implicit layer is machine-wide and loads **before** anything of ours runs, so
the injection guard cannot cover it: no module scan, no driver scan, no
@@ -1398,6 +1406,18 @@ ctest that always skips is a gate that cannot fail.
### ◐ Part three: mid-session guard inside a layered process — decided, half built
> #### ✅ Built 2026-09-06 (P1 item 3), in the PR that added the present hook — as the deferral below said it would be
>
> The layer intercepts `vkQueuePresentKHR` (+ `vkCreateSwapchainKHR` / `vkDestroySwapchainKHR`), owns the
> same ring the Overlay would (`fl_shm_host.h`, one per process) and runs the in-layer check **on the
> present path**: `unhookRequested` → `UNHOOKED` within one present; `guardTicks` not advancing for the
> 07_IPC deadline → `UNHOOKED`; `pauseRequested` → no record, still forwarded. "Stops" is passthrough forever
> with the reason on the mapping. Driven end to end by a fake loader chain (ctest `fl_vklayer`), the deadline
> proven with a 1.5 s test-only flavour of the DLL (`fl_vklayer_supervision`: ticks every 600 ms keep it
> alive past the deadline, 1.8 s without one stops it), and the real loader + the harness's `--vulkan` mode
> on the dev box (`fl_vklayer_real`, 241 records in 4 s; skips on CI, which has no loader). `17_HOOK_ENGINE`
> §Vulkan carries the shape. **The residual below is unchanged** and the Disclaimer's wording with it.
>
> #### 🅓 Deferred to P1, rationale written 2026-09-06
>
> The decision is taken (below: supervision is the Agent's job; a layer that cannot confirm
@@ -1459,12 +1479,13 @@ process in the §S16 scan set — and the capture side would then keep observing
"the Overlay keeps writing (harmless)" on heartbeat loss described an
unsupervised hooked process as harmless.
**◐ The in-layer half is deliberately NOT built yet, and this stays open.**
**~~◐ The in-layer half is deliberately NOT built yet, and this stays open.~~ ✅ Built 2026-09-06, see the top of this part.**
The layer intercepts nothing — `vkQueuePresentKHR` is P1 — so a `ShouldObserve()`
today would be a predicate whose wrong answer *in either direction* changes
nothing observable. That is a gate on something that does not exist, which is the
defect class this file keeps recording. It lands in the PR that adds the present
hook, where a fake loader chain can drive it end to end.
hook, where a fake loader chain can drive it end to end. *(It did: `MayObserve()` in
`layer.cpp`, ctest `fl_vklayer` / `fl_vklayer_supervision`.)*
**Residual, to state rather than discover:** even once built, the mid-session
*driver* case is invisible from inside a layered process, and a layer cannot
+3 -1
View File
@@ -40,7 +40,9 @@ and lazily loaded runtimes both hang on, unhook path, native logging; the Inject
launch mode (§S13(c), §S1's deferred input); the Vulkan layer to `vkQueuePresentKHR`
with §S2's in-layer supervision. **P1 item 1 — the `LoadLibrary` detour — landed 2026-09-06
(§S6 ✅); item 2, launch mode, landed the same day as "inject late" (§S1 ◐, §S13(c) ✅ —
`04_CAPTURE` §Launch mode); next is item 3, the Vulkan layer to `vkQueuePresentKHR`.** The ~~three~~ two P1-deferred S-items (~~S6~~, S2 part three, and
`04_CAPTURE` §Launch mode); item 3, the Vulkan layer to `vkQueuePresentKHR` with §S2's in-layer
supervision, landed the same day (§S2 ✅; `17_HOOK_ENGINE` §Vulkan); next is item 4 — the unhook
path, native logging, D3D9 / OpenGL.** The ~~three~~ ~~two~~ one P1-deferred S-item (~~S6~~, ~~S2 part three~~, and
the hand-run blast-radius script behind S29(d)) are the reminders. The text below is
P0's history and stays as it stood.
+25
View File
@@ -443,6 +443,31 @@ the same shape as defects found elsewhere in this project:
The unambiguous signal is the loader printing `Insert instance layer` /
`Inserted device layer` with our name and DLL path.
### ✅ `VK_ADD_IMPLICIT_LAYER_PATH` is honoured, and it needs no registry (2026-09-06, P1 item 3)
Measured against the same loader 1.4.357 with `vulkaninfo --summary` and `VK_LOADER_DEBUG=layer`: with
`VK_ADD_IMPLICIT_LAYER_PATH` pointed at the build tree's `FrameLedger.VkLayer` directory and
`FRAMELEDGER_ENABLE_VK_LAYER=1`, the loader prints `Insert instance layer "VK_LAYER_FRAMELEDGER_overlay"
(…\FrameLedger.VkLayer.dll)` and `Inserted device layer …` — the unambiguous signal above — with nothing
under `HKCU` or `HKLM`, and `vulkaninfo` exits 0 with the layer inert (no enable-list entry for it). The
first run's `grep … | head` cut the log before the `Insert` lines and read as "found, not inserted"; the
lines are at the instance-creation point, ~850 lines in. So the operator host launches Vulkan titles with
no registration at all, and the real-loader ctest (`fl_vklayer_real`) does the same: the harness's
`--vulkan` mode presented 241 frames in 4 s on a hidden 240-wide window and the layer recorded every one.
### ✅ On NVIDIA a Vulkan swapchain presents through DXGI — and the DXGI hook sees it (2026-09-06)
Found by the first end-to-end run of `launch` on the harness's `--vulkan` mode: the guard's poll saw
`dxgi.dll` + `d3d12.dll` (the fixture imports d3d11/dxgi; but the NVIDIA Vulkan ICD `nvoglv64` maps them
too) and injected the Overlay, whose `Present` hook then recorded **295 DXGI presents in 5 s with
`apiMask = D3D12` and DXGI's counter agreeing (248 samples, 0 unseen)** — the Vulkan swapchain's own
presents, made by the driver on an internal DXGI flip-model chain. So on this driver the injected Overlay
*can* measure a Vulkan title's presents; that is a driver property, not a portable one (AMD's and Intel's
WSI need not do it), which is why the layer stays the capture side. Two consequences landed: the
launch-mode guard now classifies **any** process that mapped `vulkan-1.dll` as the layer's, and the
harness's `--vulkan` mode maps the loader before anything else so the fixture looks like a real Vulkan
title to the first poll.
### ✅ The in-layer blocklist scan — §S2's second half
The layer scans its own process at init and goes fully passthrough on any hit,
+3 -1
View File
@@ -17,7 +17,9 @@
> charts, no library import, no UI and no installer yet.
>
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles. The Vulkan layer and OpenGL/D3D9 intercept nothing yet.
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
+4 -2
View File
@@ -18,7 +18,7 @@
>
> - ~~§1's *"what it observes: … presentation, upscaling, ray tracing, pipeline creation"* and §4's *"upscaling, frame-generation and ray-tracing state are read from the parameters the game passes to those APIs"* — **only the presentation path is intercepted.** There is no upscaler hook, no frame-generation hook, no ray-tracing hook and no pipeline hook anywhere in the software.~~ **FALSE SINCE #64, corrected 2026-08-14 — the fourth drift, and this one is the block's own subject.** An **upscaler hook exists**: one detour on `sl.interposer.dll!slEvaluateFeature`, module-scoped, reading one argument. It measures **which upscaler is running** (DLSS, NIS, or `unknown` — never "none") and, for Streamline titles, **whether Ray Reconstruction is active**, which is a `Yes`/`No` the software now publishes. What still does not exist: quality preset, render resolution, frame generation, ray tracing, pipeline. The capture side states all of that in its own data on every frame rather than defaulting to "none", so nothing false is *recorded*; what over-promised was this document, in the direction of under-claiming rather than over-claiming — which is the safer direction and is still wrong. Both sentences are qualified where they sit.
> - §2's *"and every 30 seconds afterwards … it stops at the next scan"* — the pre-injection guard is real and refuses. The **receiving half is implemented**: an injected D3D title removes its hooks within one frame of the stop flag being set. The **sending half is still missing, and the missing part is narrower than this block used to say.** Both the write path (`ShmRingReader.PublishGuardResult`, which maps the shared memory and advances the field) and the read path exist in shipped code and are tested; what does not exist is a production caller that runs the loop between them. A missing loop, not a missing subsystem — and the user-facing consequence is identical: **no re-scan runs and no stop is ever sent.**
> - §2's *"waits **65 seconds** before concluding that contact is lost"* — **the deadline now has a reader, and since 2026-08-05 it runs whether or not the game is presenting.** For one day it was evaluated only on a present, so a title that had hung or been alt-tabbed never reached it — the exact case the mechanism was specified for. A watchdog inside the injected component now checks once a second regardless. Two qualifications remain: it covers **injected Direct3D titles only**, because the Vulkan layer intercepts nothing yet, and **the 65-second value itself is not covered by a test** — the stop is proven to fire, but a suite that runs on every build cannot wait 65 seconds, so what is verified is the mechanism, not the number.
> - §2's *"waits **65 seconds** before concluding that contact is lost"* — **the deadline now has a reader, and since 2026-08-05 it runs whether or not the game is presenting.** For one day it was evaluated only on a present, so a title that had hung or been alt-tabbed never reached it — the exact case the mechanism was specified for. A watchdog inside the injected component now checks once a second regardless. Two qualifications remain: for **Vulkan titles the check runs on each present rather than once a second** — the layer may not own a thread, so a Vulkan title that has stopped presenting is not stopped by the deadline (and presents nothing to be observed) — and **the 65-second value itself is not covered by a test** — the stop is proven to fire, but a suite that runs on every build cannot wait 65 seconds, so what is verified is the mechanism, not the number.
> - §3's *"automatically stops injecting into a game that crashes shortly after injection twice"* — the only trace of this anywhere is a `hook_crash_count` column in a schema for which no `.sql` file exists. There is no design for it.
> - §1's *"Only FrameLedger's own component is ever loaded"* — **narrower than it sounds, and the qualification is now in §1 itself.** The check is a directory test: the payload must resolve into FrameLedger's own install directory. It does not compare a filename, a version or any content, deliberately — a name check would be defeated by any DLL that borrowed the name. A published self-contained build puts several hundred files in that directory.
>
@@ -98,7 +98,9 @@ Frame timing is derived from high-resolution timestamps taken at the moment the
> charts, no library import, no UI and no installer yet.
>
> - **Frame times and output resolution:** measured, from the present hook, for injected D3D11/12
> titles. The Vulkan layer and OpenGL/D3D9 intercept nothing yet.
> titles, and for Vulkan titles **launched through FrameLedger** (the layer intercepts
> `vkQueuePresentKHR` since 2026-09-06; a Vulkan title already running when FrameLedger attaches is
> not observed). OpenGL/D3D9 intercept nothing yet.
> - **Which upscaler is running:** measured from the API the game calls — DLSS (with Ray
> Reconstruction Yes/No) through NVIDIA Streamline; FSR 2/3.x/4 through AMD's shipped DLLs; DLSS on
> titles that bypass Streamline is reported from the NVIDIA driver's own per-process record,
@@ -158,12 +158,18 @@ internal sealed class CaptureLoop(
HookRequest request = HookRequest.FromConsent(record, observed, pid, payloadPath, waitMs);
AntiCheatVerdict verdict = await gate.StartAsync(request, ct).ConfigureAwait(false);
TimeSpan? launchWait = started?.Elapsed;
if (!verdict.IsAllowed)
// THE ONE VERDICT THAT IS NEITHER: the guard passed and injected nothing because the target
// presents through Vulkan, where the implicit layer is the capture side (P1 item 3). The ring
// to attach to is the layer's, and it appears at the title's first vkCreateDevice -- which is
// why the attach budget is launch mode's, not the 5 s an already-injected Overlay gets.
bool layered = verdict.Reason == AntiCheatRefusalReason.TargetIsVulkanLayered;
if (!verdict.IsAllowed && !layered)
{
return new CaptureResult { Reason = RefusalOf(verdict.Reason), Verdict = verdict, LaunchWait = launchWait };
}
(ICaptureSink? sink, ShmAttachRefusal refusal) = await AttachAsync(pid, ct).ConfigureAwait(false);
TimeSpan attachBudget = layered ? options.LaunchWaitBudget : options.AttachBudget;
(ICaptureSink? sink, ShmAttachRefusal refusal) = await AttachAsync(pid, attachBudget, ct).ConfigureAwait(false);
if (sink is null)
{
return new CaptureResult
@@ -202,10 +208,11 @@ internal sealed class CaptureLoop(
/// middle one is transient. Every other refusal is terminal, and retrying one
/// would turn a clear answer into a timeout.
/// </remarks>
private async Task<(ICaptureSink? Sink, ShmAttachRefusal Refusal)> AttachAsync(int pid, CancellationToken ct)
private async Task<(ICaptureSink? Sink, ShmAttachRefusal Refusal)> AttachAsync(int pid, TimeSpan budget,
CancellationToken ct)
{
ShmAttachRefusal refusal = ShmAttachRefusal.NotEvaluated;
DateTimeOffset deadline = DateTimeOffset.UtcNow + options.AttachBudget;
DateTimeOffset deadline = DateTimeOffset.UtcNow + budget;
while (DateTimeOffset.UtcNow < deadline)
{
(ICaptureSink? sink, refusal) = attach(pid);
@@ -32,7 +32,14 @@ internal static class ProcessLauncher
public const string VulkanLayerEnableVariable = "FRAMELEDGER_ENABLE_VK_LAYER";
/// <summary>Start <paramref name="exePath"/> with <paramref name="arguments"/>; null when it could not be started or pinned.</summary>
public static (int Pid, ITargetLiveness Alive)? Start(string exePath, string arguments)
/// <param name="exePath">The consented executable.</param>
/// <param name="arguments">Its own command line, verbatim.</param>
/// <param name="environment">
/// Variables added to the child's environment — the Vulkan layer's, from
/// <c>VkLayerLaunchEnvironment</c>, when the layer is staged beside this host (P1 item 3).
/// </param>
public static (int Pid, ITargetLiveness Alive)? Start(string exePath, string arguments,
IReadOnlyDictionary<string, string>? environment = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(exePath);
@@ -42,6 +49,10 @@ internal static class ProcessLauncher
WorkingDirectory = Path.GetDirectoryName(exePath) ?? string.Empty,
};
psi.Environment[VulkanLayerEnableVariable] = "1";
foreach ((string name, string value) in environment ?? new Dictionary<string, string>(StringComparer.Ordinal))
{
psi.Environment[name] = value;
}
Process? process;
try
@@ -100,4 +100,20 @@
</None>
</ItemGroup>
<!--
The Vulkan implicit layer beside the host (P1 item 3). `launch` writes a manifest pointing at THIS
copy and hands the launched process VK_ADD_IMPLICIT_LAYER_PATH, so the layer is discoverable only by
that process: no registry, nothing machine-wide (VkLayerLaunchEnvironment). Warn-not-fail like the
others: build.ps1 runs the native build first, and a missing DLL is reported by `launch` itself.
-->
<PropertyGroup>
<FlVkLayerDir>$(MSBuildThisFileDirectory)..\..\build\native\x64-release\FrameLedger.VkLayer\</FlVkLayerDir>
</PropertyGroup>
<ItemGroup>
<None Include="$(FlVkLayerDir)FrameLedger.VkLayer.dll" Condition="Exists('$(FlVkLayerDir)FrameLedger.VkLayer.dll')">
<Link>FrameLedger.VkLayer.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+24 -4
View File
@@ -23,6 +23,7 @@ using FrameLedger.Infrastructure.AntiCheat;
using FrameLedger.Infrastructure.Io;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Rules;
using FrameLedger.Infrastructure.Vulkan;
using FrameLedger.Shared;
namespace FrameLedger.CaptureHost;
@@ -148,13 +149,26 @@ internal static class Program
}
/// <summary>Launch mode: the same loop, entered by starting the executable rather than finding it.</summary>
/// <remarks>
/// The Vulkan layer rides on the launch (P1 item 3): the process gets <c>VK_ADD_IMPLICIT_LAYER_PATH</c> and
/// the enable variable, and its image name goes on the layer's enable-list for the session -- no registry,
/// nothing machine-wide, removed when the session ends. A D3D title ignores all of it; a Vulkan title is
/// observed by the layer and the guard injects nothing (<c>TargetIsVulkanLayered</c>).
/// </remarks>
private static async Task<int> LaunchAsync(FileGameConsentStore store, string exePath, string arguments,
int seconds)
{
string normalised = ExecutableIdentity.Normalise(exePath);
ExecutableFingerprint? observed = ExecutableIdentity.Read(exePath);
CaptureResult result = await BuildLoop(store, seconds)
using var vulkan = VkLayerLaunchEnvironment.Prepare(normalised,
Path.Combine(AppContext.BaseDirectory, "FrameLedger.VkLayer.dll"));
HostConsole.Line(vulkan.ManifestPath is null
? "vulkan layer: NOT staged beside this host - a Vulkan title will present unobserved"
: $"vulkan layer: {vulkan.ManifestPath} (via {VkLayerLaunchEnvironment.ImplicitLayerPathVariable}; " +
$"enable-list entry '{vulkan.ImageName}' for this session)");
CaptureResult result = await BuildLoop(store, seconds, (exe, args) => ProcessLauncher.Start(exe, args, vulkan.Variables))
.RunLaunchedAsync(normalised, observed, Payload, arguments).ConfigureAwait(false);
return await ConcludeAsync(store, normalised, observed, result).ConfigureAwait(false);
@@ -164,7 +178,12 @@ internal static class Program
ExecutableFingerprint? observed, CaptureResult result)
{
HostConsole.Line($"session: {result.Reason}");
if (result.Verdict.Reason != Domain.AntiCheat.AntiCheatRefusalReason.Allow)
if (result.Verdict.Reason == Domain.AntiCheat.AntiCheatRefusalReason.TargetIsVulkanLayered)
{
HostConsole.Line(" capture side: the Vulkan implicit layer - the guard passed and nothing was injected " +
"(one ring per process; 17_HOOK_ENGINE §Vulkan)");
}
else if (result.Verdict.Reason != Domain.AntiCheat.AntiCheatRefusalReason.Allow)
{
HostConsole.Line($" verdict: {result.Verdict.Reason} {result.Verdict.Family} {result.Verdict.Signal}");
}
@@ -326,7 +345,8 @@ internal static class Program
}
/// <summary>The loop and its four collaborators, wired the only way this host allows.</summary>
private static CaptureLoop BuildLoop(FileGameConsentStore store, int seconds)
private static CaptureLoop BuildLoop(FileGameConsentStore store, int seconds,
Func<string, string, (int Pid, ITargetLiveness Alive)?>? launcher = null)
{
var guard = new NativeAntiCheatGuard();
return new CaptureLoop(
@@ -356,7 +376,7 @@ internal static class Program
},
pid => RuntimeModuleSnapshot.Take(pid, CensusNames.ModuleFileNames),
NgxDriverProbe.Run,
ProcessLauncher.Start);
launcher ?? ((exe, args) => ProcessLauncher.Start(exe, args)));
}
/// <summary>
@@ -186,4 +186,15 @@ public enum AntiCheatRefusalReason
/// or a launcher still sitting on its window. Nothing was injected.
/// </summary>
LaunchNoPresentationRuntime = 25,
/// <summary>
/// Launch mode, the Vulkan branch (P1 item 3): the target mapped <c>vulkan-1.dll</c> and no D3D or OpenGL
/// runtime, the FULL guard passed, and nothing was injected on purpose — a Vulkan title is captured by the
/// implicit layer, and one process carries one ring (<c>fl_shm_host.h</c>).
/// </summary>
/// <remarks>
/// Not an allow — the Overlay is not in the target — and not a refusal either: the host reads it as
/// "attach to the layer's ring". <c>CaptureLoop</c> is the one place that distinction is made.
/// </remarks>
TargetIsVulkanLayered = 26,
}
@@ -0,0 +1,187 @@
using System.Text;
using System.Text.Json;
namespace FrameLedger.Infrastructure.Vulkan;
/// <summary>
/// What a launched process needs for the Vulkan implicit layer to observe it, and nothing else on the machine to:
/// the loader's <c>VK_ADD_IMPLICIT_LAYER_PATH</c> pointed at a directory holding our manifest, the manifest's
/// <c>enable_environment</c> variable set, and the process image name on the layer's enable-list.
/// </summary>
/// <remarks>
/// <para>
/// <b>No registry.</b> <c>12_BUILD</c> §The Vulkan layer is not registered at install time makes registration a
/// deliberate, later act of the Agent, kept only while a Vulkan game has hooking enabled. The unshipped host
/// does not need it at all: loader 1.4.357 honours <c>VK_ADD_IMPLICIT_LAYER_PATH</c> (measured 2026-09-06,
/// <c>spike-notes</c> §2), so the layer is discoverable ONLY by the process this host starts — a smaller blast
/// radius than an HKCU registration, and gone when the variable is. The Agent's registration path (P2) is
/// unchanged by this.
/// </para>
/// <para>
/// <b>The enable-list is written here because this host stands in for the Agent</b>, which
/// <c>17_HOOK_ENGINE</c> §The enable-list names as its sole writer. One line, the lowercased image name, added
/// only when absent and removed on dispose only when this object added it. An entry somebody else wrote is
/// left exactly as found.
/// </para>
/// <para>
/// <b>Without a staged layer DLL nothing is written and no variable is set</b>: a manifest pointing at a file
/// that is not there would make the loader log an error into the game for no benefit.
/// </para>
/// </remarks>
public sealed class VkLayerLaunchEnvironment : IDisposable
{
/// <summary>The manifest's <c>enable_environment</c> variable (<c>17_HOOK_ENGINE</c> §Vulkan).</summary>
public const string EnableVariable = "FRAMELEDGER_ENABLE_VK_LAYER";
/// <summary>The loader's additional implicit-layer search path, honoured without any registration.</summary>
public const string ImplicitLayerPathVariable = "VK_ADD_IMPLICIT_LAYER_PATH";
/// <summary>The layer's name, as the manifest and the loader log carry it.</summary>
public const string LayerName = "VK_LAYER_FRAMELEDGER_overlay";
private const string _manifestFileName = "VkLayer_FRAMELEDGER_overlay.json";
private static readonly JsonSerializerOptions _manifestOptions = new() { WriteIndented = true };
private readonly bool _addedEnableListEntry;
private readonly string? _writtenManifest;
private bool _disposed;
private VkLayerLaunchEnvironment(string directory, string imageName, string enableListPath, string? manifest,
bool addedEntry, IReadOnlyDictionary<string, string> variables)
{
Directory = directory;
ImageName = imageName;
EnableListPath = enableListPath;
_writtenManifest = manifest;
_addedEnableListEntry = addedEntry;
Variables = variables;
}
/// <summary>The product's per-user layer directory: <c>%LOCALAPPDATA%\FrameLedger\vklayer</c>.</summary>
public static string DefaultDirectory => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FrameLedger", "vklayer");
/// <summary>The directory the loader is pointed at, which also holds the enable-list.</summary>
public string Directory { get; }
/// <summary>The lowercased process image name written to the enable-list.</summary>
public string ImageName { get; }
/// <summary>The enable-list this object wrote to (or would have).</summary>
public string EnableListPath { get; }
/// <summary>The manifest written for this launch, or null when the layer DLL was not staged.</summary>
public string? ManifestPath => _writtenManifest;
/// <summary>Variables to add to the launched process's environment; empty when the layer is not staged.</summary>
public IReadOnlyDictionary<string, string> Variables { get; }
/// <summary>
/// Prepare the environment for launching <paramref name="exePath"/> with the layer at
/// <paramref name="layerDllPath"/>; <paramref name="directory"/> defaults to <see cref="DefaultDirectory"/>.
/// </summary>
public static VkLayerLaunchEnvironment Prepare(string exePath, string layerDllPath, string? directory = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(exePath);
ArgumentException.ThrowIfNullOrWhiteSpace(layerDllPath);
string dir = directory ?? DefaultDirectory;
#pragma warning disable CA1308 // the enable-list's format is LOWERCASED image names (17_HOOK_ENGINE §The enable-list)
string image = Path.GetFileName(exePath).ToLowerInvariant();
#pragma warning restore CA1308
string enableList = Path.Combine(dir, "enabled.txt");
if (!File.Exists(layerDllPath))
{
return new VkLayerLaunchEnvironment(dir, image, enableList, manifest: null, addedEntry: false,
new Dictionary<string, string>(StringComparer.Ordinal));
}
System.IO.Directory.CreateDirectory(dir);
bool added = AddEnableListEntry(enableList, image);
string manifest = Path.Combine(dir, _manifestFileName);
File.WriteAllText(manifest, ManifestJson(Path.GetFullPath(layerDllPath)), new UTF8Encoding(false));
var variables = new Dictionary<string, string>(StringComparer.Ordinal)
{
[EnableVariable] = "1",
[ImplicitLayerPathVariable] = dir,
};
return new VkLayerLaunchEnvironment(dir, image, enableList, manifest, added, variables);
}
/// <summary>The manifest, with the DLL's absolute path — the shape <c>VkLayer_FRAMELEDGER_overlay.json.in</c> generates.</summary>
internal static string ManifestJson(string libraryPath)
{
var doc = new
{
file_format_version = "1.2.0",
layer = new
{
name = LayerName,
type = "GLOBAL",
library_path = libraryPath,
api_version = "1.4.357",
implementation_version = "1",
description = "FrameLedger performance capture (opt-in per game; passthrough otherwise)",
enable_environment = new Dictionary<string, string>(StringComparer.Ordinal) { [EnableVariable] = "1" },
disable_environment = new Dictionary<string, string>(StringComparer.Ordinal) { ["DISABLE_FRAMELEDGER_VK_LAYER"] = "1" },
},
};
return JsonSerializer.Serialize(doc, _manifestOptions);
}
/// <summary>True when the entry was added; false when it was already there.</summary>
private static bool AddEnableListEntry(string enableList, string image)
{
List<string> lines = File.Exists(enableList) ? [.. File.ReadAllLines(enableList)] : [];
if (lines.Any(l => string.Equals(l.Trim(), image, StringComparison.OrdinalIgnoreCase)))
{
return false;
}
lines.Add(image);
File.WriteAllText(enableList, string.Join('\n', lines) + '\n', new UTF8Encoding(false));
return true;
}
/// <summary>Remove exactly what <see cref="Prepare"/> added.</summary>
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
try
{
if (_addedEnableListEntry && File.Exists(EnableListPath))
{
List<string> kept = [.. File.ReadAllLines(EnableListPath)
.Where(l => !string.Equals(l.Trim(), ImageName, StringComparison.OrdinalIgnoreCase))];
if (kept.Count == 0)
{
File.Delete(EnableListPath);
}
else
{
File.WriteAllText(EnableListPath, string.Join('\n', kept) + '\n', new UTF8Encoding(false));
}
}
if (_writtenManifest is not null && File.Exists(_writtenManifest))
{
File.Delete(_writtenManifest);
}
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
// Leaving a line or a manifest behind grants nothing: the layer still gates on the enable
// variable, which only a launch sets. Stated rather than thrown from a Dispose.
}
}
}
@@ -165,6 +165,18 @@ enum class Reason : std::uint8_t {
kLaunchTargetExited,
kLaunchNoPresentationRuntime,
// LAUNCH MODE, the Vulkan branch (P1 item 3). The launched target mapped
// vulkan-1.dll (with or without a D3D runtime beside it -- an NVIDIA Vulkan
// ICD maps dxgi + d3d12 itself, measured), the full guard PASSED, and
// nothing was injected on purpose: a Vulkan title is captured by the implicit
// layer the loader mapped into it (17_HOOK_ENGINE §Vulkan), and one process
// carries ONE ring -- an Overlay injected beside the layer would find the
// mapping already there and stay inert, or win the race and leave the layer
// inert with nothing to hook (fl_shm_host.h). Allowed() is false because the
// DLL is NOT loaded in the target; the host reads this as "attach to the
// layer's ring", not as a refusal.
kTargetIsVulkanLayered,
// NOT A REASON. The count, so appending above it updates the exported
// FlGuardReasonCount by construction.
//
@@ -522,6 +522,8 @@ const char* ReasonName(Reason r) noexcept {
return "LaunchTargetExited";
case Reason::kLaunchNoPresentationRuntime:
return "LaunchNoPresentationRuntime";
case Reason::kTargetIsVulkanLayered:
return "TargetIsVulkanLayered";
case Reason::kCount:
break; // not a reason; falls through to the guard below
}
@@ -729,15 +731,29 @@ bool RuntimeSinkFn(void* ctx, const char* name, const wchar_t*) noexcept {
return true;
}
bool HasPresentationRuntime(const Sources& s, std::uint32_t pid) noexcept {
// What the target presents through, as far as the loader can say. kVulkan is the
// branch the guard must NOT inject (Reason::kTargetIsVulkanLayered), and IT WINS
// over a D3D runtime mapped beside it. Measured 2026-09-06 on the harness's
// Vulkan mode under an NVIDIA driver: the Vulkan ICD itself maps dxgi.dll and
// d3d12.dll and presents the Vulkan swapchain through a DXGI chain, so "vulkan-1
// beside d3d12" is what EVERY Vulkan title looks like there -- treating it as D3D
// injected the Overlay, which owned the ring, and left the layer forwarding into
// nothing. A process does not map vulkan-1.dll unless it uses Vulkan; a D3D title
// that happens to is the rarer shape and the one this rule gets wrong.
enum class PresentationRuntime : std::uint8_t { kNone, kD3dOrOpenGl, kVulkan };
PresentationRuntime FindPresentationRuntime(const Sources& s, std::uint32_t pid) noexcept {
if (s.EnumerateModules == nullptr) {
return false;
return PresentationRuntime::kNone;
}
RuntimeProbe p;
if (s.EnumerateModules(pid, &RuntimeSinkFn, &p) == Collected::kFailed) {
return false; // still in its loader, or unreadable -- the full scan is what refuses the latter
return PresentationRuntime::kNone; // still in its loader, or unreadable -- the full scan refuses the latter
}
return (p.dxgi && p.d3d) || p.gl || p.vk;
if (p.vk) {
return PresentationRuntime::kVulkan;
}
return ((p.dxgi && p.d3d) || p.gl) ? PresentationRuntime::kD3dOrOpenGl : PresentationRuntime::kNone;
}
Verdict GuardedInjectWhenReadyImpl(std::uint32_t targetPid, const wchar_t* dllPath, std::uint32_t timeoutMs,
@@ -756,10 +772,22 @@ Verdict GuardedInjectWhenReadyImpl(std::uint32_t targetPid, const wchar_t* dllPa
"the target exited before it mapped a presentation runtime; nothing was injected");
break;
}
if (HasPresentationRuntime(sources, targetPid)) {
const PresentationRuntime runtime = FindPresentationRuntime(sources, targetPid);
if (runtime == PresentationRuntime::kD3dOrOpenGl) {
v = GuardedInjectImpl(targetPid, dllPath, sources);
break;
}
if (runtime == PresentationRuntime::kVulkan) {
// The FULL guard still runs -- a Vulkan title with anti-cheat is refused
// by name exactly as a D3D one is -- and on a pass nothing is injected.
v = EvaluateImpl(targetPid, sources);
if (v.Allowed()) {
v = Refuse(Reason::kTargetIsVulkanLayered, nullptr,
"the guard passed; the target presents through Vulkan, where the implicit layer is the "
"capture side, so nothing was injected");
}
break;
}
if (GetTickCount64() - start >= timeoutMs) {
v = Refuse(Reason::kLaunchNoPresentationRuntime, nullptr,
"no presentation runtime was mapped within the launch budget; nothing was injected");
+6 -125
View File
@@ -49,10 +49,10 @@
#include <fl_ring.h>
#include <fl_rt_accum.h>
#include <fl_shm.h>
#include <fl_shm_host.h>
#include <fl_sl_inputs.h>
#include <fl_sl_seen.h>
#include <MinHook.h>
#include <sddl.h>
// Its own block, below the sorted one, because it needs Family/Group/MatchKind
// from fl_ac_rules.h and clang-format sorts each block independently. Types plus
@@ -101,134 +101,15 @@ void* g_base = nullptr;
fl::RingWriter g_writer;
HANDLE g_initThread = nullptr;
// The mapping is created with a DACL granting ONLY the current user's SID, and
// lives in the session-scoped Local\ namespace (docs/07_IPC.md §Security). No
// Global\ object: it would need admin and would be visible across sessions for
// no benefit.
//
// Returns false rather than falling back to a default DACL. A mapping the whole
// machine can write is not a degraded version of this one -- the Agent's control
// block is in it, and unhookRequested is the safety stop.
bool BuildUserOnlySecurity(SECURITY_ATTRIBUTES& sa, PSECURITY_DESCRIPTOR& sd) noexcept {
sd = nullptr;
HANDLE token = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
return false;
}
unsigned char buffer[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE]{};
DWORD got = 0;
const BOOL ok = GetTokenInformation(token, TokenUser, buffer, sizeof(buffer), &got);
CloseHandle(token);
if (!ok) {
return false;
}
LPWSTR sidText = nullptr;
const auto* user = reinterpret_cast<const TOKEN_USER*>(buffer);
if (!ConvertSidToStringSidW(user->User.Sid, &sidText)) {
return false;
}
// D:P = a protected DACL, so nothing is inherited in. One ACE, generic all,
// for us alone.
wchar_t sddl[256]{};
const int n = _snwprintf_s(sddl, _TRUNCATE, L"D:P(A;;GA;;;%ls)", sidText);
LocalFree(sidText);
if (n < 0) {
return false;
}
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &sd, nullptr)) {
return false;
}
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
return true;
}
// Local\FrameLedger.Ring.<pid>. Deliberately plain and identifiable: 19_SAFETY
// forbids obfuscated object names, because being visible to anti-cheat is the
// whole design posture.
bool MakeRingName(wchar_t* out, size_t cap, DWORD pid) noexcept {
return _snwprintf_s(out, cap, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid) >= 0;
}
// The ring host half -- the user-only DACL, the Local\FrameLedger.Ring.<pid> name,
// the mapping and the handshake -- lives in fl_shm_host.h since P1 item 3, SHARED
// with the Vulkan layer: one contract, one copy, for both capture sides.
bool CreateRing() noexcept {
SECURITY_ATTRIBUTES sa{};
PSECURITY_DESCRIPTOR sd = nullptr;
if (!BuildUserOnlySecurity(sa, sd)) {
return false;
}
wchar_t name[128]{};
if (!MakeRingName(name, 128, GetCurrentProcessId())) {
LocalFree(sd);
return false;
}
const size_t bytes = fl::FlShmSizeForCapacity(FL_SHM_DEFAULT_CAPACITY);
g_mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, static_cast<DWORD>(bytes >> 32),
static_cast<DWORD>(bytes & 0xFFFFFFFFu), name);
const DWORD err = GetLastError();
LocalFree(sd);
if (g_mapping == nullptr) {
return false;
}
// A pre-existing mapping under our own pid is not a mapping we understand:
// either a stale object or another writer. Refuse rather than share a ring
// with an unknown producer.
if (err == ERROR_ALREADY_EXISTS) {
CloseHandle(g_mapping);
g_mapping = nullptr;
return false;
}
g_base = MapViewOfFile(g_mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, bytes);
if (g_base == nullptr) {
CloseHandle(g_mapping);
g_mapping = nullptr;
return false;
}
return true;
return fl::shmhost::CreateRingMapping(g_mapping, g_base);
}
// Write-once at init, per docs/07_IPC.md §A + B. adapterLuid is deliberately
// left 0 = "not yet known": this runs two steps before any graphics module is
// resolved, and our own dummy device's adapter is not the game's (#36). It is
// published at first present, with the hook.
void PublishHandshake() noexcept {
auto* h = reinterpret_cast<FlShmHandshake*>(static_cast<unsigned char*>(g_base) + FL_SHM_HANDSHAKE_OFFSET);
h->recordSize = sizeof(FlFrameRecord);
h->capacity = FL_SHM_DEFAULT_CAPACITY;
h->pid = GetCurrentProcessId();
// FL_BUILD_ID comes from git describe at configure time (FrameLedger.Shm's
// CMakeLists). It had no producer at all until #36; without one the Agent's
// refuse-to-attach-on-mismatch compares "" with "" forever.
const char* build = FL_BUILD_ID;
size_t i = 0;
for (; i + 1 < sizeof(h->buildId) && build[i] != '\0'; ++i) {
h->buildId[i] = build[i];
}
h->buildId[i] = '\0';
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
h->qpcEpoch = static_cast<uint64_t>(qpc.QuadPart);
h->adapterLuid = 0;
// layoutVersion LAST, with a release fence in front of it. It is the field a
// reader validates first, so it must not become visible before the fields it
// vouches for. A reader that saw the version while capacity was still zero
// would compute a ring of no slots and read garbage.
std::atomic_thread_fence(std::memory_order_release);
std::atomic_ref<uint32_t> version{h->layoutVersion};
version.store(FL_SHM_LAYOUT_VERSION, std::memory_order_release);
fl::shmhost::PublishHandshake(g_base);
}
// ---------------------------------------------------------------------------
@@ -0,0 +1,180 @@
// The capture side's HOST half of the shared-memory contract: create the one
// ring a process may carry, and publish the handshake a reader validates first.
//
// Header-only and shared by the two capture sides -- the injected Overlay and
// the Vulkan layer -- because 07_IPC says ONE ring per process, named
// Local\FrameLedger.Ring.<pid>, with ONE layout, ONE build id and ONE security
// descriptor, and two copies of that are two places for it to drift. It lived in
// FrameLedger.Overlay/src/dllmain.cpp until 2026-09-06 (P1 item 3), when the
// layer gained vkQueuePresentKHR and needed exactly the same thing.
//
// Not a hook path: this runs once, at init, on whichever thread creates the
// ring. It may allocate (LocalAlloc inside the SDDL conversion) and it may fail
// -- and every failure returns false, so the caller stays inert rather than
// sharing a ring it does not own.
//
// WHO OWNS THE RING WHEN BOTH SIDES ARE IN ONE PROCESS. A Vulkan title launched
// through the host has the layer mapped by the loader and could also receive the
// Overlay if the guard injected it; whichever creates the mapping FIRST owns it,
// and the other sees ERROR_ALREADY_EXISTS here and stays inert. That is the same
// rule the Overlay always had for a pre-existing mapping under its own pid --
// "either a stale object or another writer: refuse rather than share" -- and it
// is why the guard does not inject a Vulkan-only presenter at all
// (fl_guard.cpp, Reason::kTargetIsVulkanLayered).
#ifndef FRAMELEDGER_FL_SHM_HOST_H
#define FRAMELEDGER_FL_SHM_HOST_H
#include <windows.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <sddl.h>
#include "fl_shm.h"
#ifndef FL_BUILD_ID
#error "FL_BUILD_ID must be defined (FrameLedger.Shm's INTERFACE compile definition)"
#endif
namespace fl::shmhost {
// The mapping is created with a DACL granting ONLY the current user's SID, and
// lives in the session-scoped Local\ namespace (docs/07_IPC.md §Security). No
// Global\ object: it would need admin and would be visible across sessions for
// no benefit.
//
// Returns false rather than falling back to a default DACL. A mapping the whole
// machine can write is not a degraded version of this one -- the Agent's control
// block is in it, and unhookRequested is the safety stop.
inline bool BuildUserOnlySecurity(SECURITY_ATTRIBUTES& sa, PSECURITY_DESCRIPTOR& sd) noexcept {
sd = nullptr;
HANDLE token = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
return false;
}
unsigned char buffer[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE]{};
DWORD got = 0;
const BOOL ok = GetTokenInformation(token, TokenUser, buffer, sizeof(buffer), &got);
CloseHandle(token);
if (!ok) {
return false;
}
LPWSTR sidText = nullptr;
const auto* user = reinterpret_cast<const TOKEN_USER*>(buffer);
if (!ConvertSidToStringSidW(user->User.Sid, &sidText)) {
return false;
}
// D:P = a protected DACL, so nothing is inherited in. One ACE, generic all,
// for us alone.
wchar_t sddl[256]{};
const int n = _snwprintf_s(sddl, _TRUNCATE, L"D:P(A;;GA;;;%ls)", sidText);
LocalFree(sidText);
if (n < 0) {
return false;
}
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &sd, nullptr)) {
return false;
}
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
return true;
}
// Local\FrameLedger.Ring.<pid>. Deliberately plain and identifiable: 19_SAFETY
// forbids obfuscated object names, because being visible to anti-cheat is the
// whole design posture.
inline bool MakeRingName(wchar_t* out, std::size_t cap, DWORD pid) noexcept {
return _snwprintf_s(out, cap, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid) >= 0;
}
// Create and map this process's ring. On success `mapping` and `base` are set;
// on any failure both stay null and nothing is left open.
inline bool CreateRingMapping(HANDLE& mapping, void*& base) noexcept {
mapping = nullptr;
base = nullptr;
SECURITY_ATTRIBUTES sa{};
PSECURITY_DESCRIPTOR sd = nullptr;
if (!BuildUserOnlySecurity(sa, sd)) {
return false;
}
wchar_t name[128]{};
if (!MakeRingName(name, 128, GetCurrentProcessId())) {
LocalFree(sd);
return false;
}
const std::size_t bytes = fl::FlShmSizeForCapacity(FL_SHM_DEFAULT_CAPACITY);
HANDLE h = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, static_cast<DWORD>(bytes >> 32),
static_cast<DWORD>(bytes & 0xFFFFFFFFu), name);
const DWORD err = GetLastError();
LocalFree(sd);
if (h == nullptr) {
return false;
}
// A pre-existing mapping under our own pid is not a mapping we understand:
// either a stale object or another writer. Refuse rather than share a ring
// with an unknown producer (see the file header for the two-capture-sides case).
if (err == ERROR_ALREADY_EXISTS) {
CloseHandle(h);
return false;
}
void* view = MapViewOfFile(h, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, bytes);
if (view == nullptr) {
CloseHandle(h);
return false;
}
mapping = h;
base = view;
return true;
}
// Write-once at init, per docs/07_IPC.md §A + B. adapterLuid is deliberately
// left 0 = "not yet known": on the Overlay this runs two steps before any
// graphics module is resolved, and our own dummy device's adapter is not the
// game's (#36); on the layer there is no adapter LUID to publish at all.
inline void PublishHandshake(void* base) noexcept {
auto* h = reinterpret_cast<FlShmHandshake*>(static_cast<unsigned char*>(base) + FL_SHM_HANDSHAKE_OFFSET);
h->recordSize = sizeof(FlFrameRecord);
h->capacity = FL_SHM_DEFAULT_CAPACITY;
h->pid = GetCurrentProcessId();
// FL_BUILD_ID comes from git describe at configure time (FrameLedger.Shm's
// CMakeLists). It had no producer at all until #36; without one the Agent's
// refuse-to-attach-on-mismatch compares "" with "" forever.
const char* build = FL_BUILD_ID;
std::size_t i = 0;
for (; i + 1 < sizeof(h->buildId) && build[i] != '\0'; ++i) {
h->buildId[i] = build[i];
}
h->buildId[i] = '\0';
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
h->qpcEpoch = static_cast<std::uint64_t>(qpc.QuadPart);
h->adapterLuid = 0;
// layoutVersion LAST, with a release fence in front of it. It is the field a
// reader validates first, so it must not become visible before the fields it
// vouches for. A reader that saw the version while capacity was still zero
// would compute a ring of no slots and read garbage.
std::atomic_thread_fence(std::memory_order_release);
std::atomic_ref<std::uint32_t> version{h->layoutVersion};
version.store(FL_SHM_LAYOUT_VERSION, std::memory_order_release);
}
} // namespace fl::shmhost
#endif // FRAMELEDGER_FL_SHM_HOST_H
@@ -30,6 +30,24 @@ target_link_libraries(FrameLedger.VkLayer PRIVATE
add_dependencies(FrameLedger.VkLayer fl_ac_floor_gen)
set_target_properties(FrameLedger.VkLayer PROPERTIES OUTPUT_NAME "FrameLedger.VkLayer")
# TEST-ONLY flavour: the same sources with the supervision deadline shortened
# from 65 s to 1.5 s, so ctest fl_vklayer can prove §S2 part three -- the
# in-layer stop when guardTicks stops advancing -- in seconds rather than
# minutes. Never shipped: no version resource, no manifest, a different file
# name, and 12_BUILD publishes only what the App/Agent projects stage. The
# shipped DLL keeps FL_GUARD_TICK_DEADLINE_MS, the one number 07_IPC pins.
add_library(fl_vklayer_shortdeadline SHARED
src/layer.cpp
../FrameLedger.Injector/src/fl_ac_rules.cpp
FrameLedger.VkLayer.def
)
target_include_directories(fl_vklayer_shortdeadline PRIVATE ../FrameLedger.Injector/include)
target_link_libraries(fl_vklayer_shortdeadline PRIVATE
FrameLedger.Shm fl_native_flags fl_hostile_env_flags fl_vulkan_headers fl_jsmn Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_vklayer_shortdeadline fl_ac_floor_gen)
target_compile_definitions(fl_vklayer_shortdeadline PRIVATE FL_VKLAYER_TICK_DEADLINE_MS=1500u)
set_target_properties(fl_vklayer_shortdeadline PROPERTIES OUTPUT_NAME "FrameLedger.VkLayer.shortdeadline")
# Same requirement as the Overlay, and arguably sharper here: an implicit layer
# is machine-wide, so it can appear inside processes the user never associated
# with FrameLedger. It had better say who it is (docs/19_SAFETY).
+376 -4
View File
@@ -46,11 +46,14 @@
#include <vulkan/vk_layer.h>
#include <vulkan/vulkan.h>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_ring.h>
#include <fl_shm.h>
#include <fl_shm_host.h>
#include <psapi.h>
namespace fl::vklayer {
@@ -256,7 +259,356 @@ bool MustStayInert() noexcept {
}
// ---------------------------------------------------------------------------
// Loader interface. Everything forwards; nothing is observed.
// The capture side (P1 item 3): the ring, the present record, the stop.
//
// Created at the first vkCreateDevice of an ADMITTED process -- not at load, not
// at vkCreateInstance -- so a process the gates refused never has a mapping
// with its pid on it. Init is not a hook path; the present hook is, and it
// follows the Overlay's rules: SEH-guarded, allocation-free, lock-free, no
// logging, one record, forward.
// ---------------------------------------------------------------------------
bool ThisProcessIsEnabledCached();
// The supervision deadline. FL_VKLAYER_TICK_DEADLINE_MS exists so a TEST-ONLY
// flavour of this DLL (fl_vklayer_shortdeadline, never shipped) can prove the
// stop within seconds; the shipped layer uses the one number 07_IPC pins, the
// same the Overlay uses.
#ifndef FL_VKLAYER_TICK_DEADLINE_MS
#define FL_VKLAYER_TICK_DEADLINE_MS FL_GUARD_TICK_DEADLINE_MS
#endif
constexpr ULONGLONG kTickDeadlineMs = FL_VKLAYER_TICK_DEADLINE_MS;
HANDLE g_mapping = nullptr;
void* g_base = nullptr;
FlWriterState* g_state = nullptr;
FlControlBlock* g_control = nullptr;
fl::RingWriter g_writer;
std::atomic<uint32_t> g_observing{0};
std::atomic<uint32_t> g_captureState{0}; // 0 = not tried, 1 = live, 2 = failed (inert for good)
std::atomic<uint32_t> g_frameIndex{0};
std::atomic<uint32_t> g_lastTicks{0};
std::atomic<ULONGLONG> g_lastTickAt{0};
// Which device a queue belongs to is answered by the dispatch key: the loader
// gives a VkDevice and every VkQueue created from it the SAME first-pointer
// (the dispatch table), which is how every layer keys its per-device state.
inline void* DispatchKey(const void* dispatchable) noexcept {
return *reinterpret_cast<void* const*>(dispatchable);
}
struct DeviceSlot {
void* key = nullptr;
PFN_vkQueuePresentKHR present = nullptr;
PFN_vkCreateSwapchainKHR createSwapchain = nullptr;
PFN_vkDestroySwapchainKHR destroySwapchain = nullptr;
};
constexpr size_t kMaxDevices = 8;
DeviceSlot g_devices[kMaxDevices];
std::atomic<uint32_t> g_deviceCount{0};
bool HasDevice(void* key) noexcept {
const uint32_t n = g_deviceCount.load(std::memory_order_acquire);
for (uint32_t i = 0; i < n && i < kMaxDevices; ++i) {
if (g_devices[i].key == key) {
return true;
}
}
return false;
}
const DeviceSlot* FindDevice(void* key) noexcept {
const uint32_t n = g_deviceCount.load(std::memory_order_acquire);
for (uint32_t i = 0; i < n && i < kMaxDevices; ++i) {
if (g_devices[i].key == key) {
return &g_devices[i];
}
}
// A queue whose device we never registered (more than kMaxDevices, or a
// device created before the gates admitted us): forward through the first
// device's next pointer rather than through nothing.
return n != 0 ? &g_devices[0] : nullptr;
}
// Per-swapchain output size, keyed by the non-dispatchable handle; id 0 stays
// "unidentified" (fl_shm.h), exactly as the Overlay's table does.
struct SwapchainSlot {
std::atomic<uint64_t> handle{0};
uint32_t id = 0;
uint16_t w = 0;
uint16_t h = 0;
};
constexpr size_t kMaxSwapchains = 16;
SwapchainSlot g_swapchains[kMaxSwapchains];
std::atomic<uint32_t> g_nextSwapchainId{1};
const SwapchainSlot* FindSwapchain(VkSwapchainKHR sc) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
if (g_swapchains[i].handle.load(std::memory_order_acquire) == key) {
return &g_swapchains[i];
}
}
return nullptr;
}
void RememberSwapchain(VkSwapchainKHR sc, VkExtent2D extent) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
uint64_t none = 0;
if (g_swapchains[i].handle.compare_exchange_strong(none, ~0ull, std::memory_order_acq_rel)) {
g_swapchains[i].id = g_nextSwapchainId.fetch_add(1u, std::memory_order_relaxed);
g_swapchains[i].w = static_cast<uint16_t>(extent.width > 0xFFFFu ? 0u : extent.width);
g_swapchains[i].h = static_cast<uint16_t>(extent.height > 0xFFFFu ? 0u : extent.height);
g_swapchains[i].handle.store(key, std::memory_order_release); // visible LAST
return;
}
}
// Full: the present will carry id 0 = unidentified, never a wrong id.
}
void ForgetSwapchain(VkSwapchainKHR sc) noexcept {
const uint64_t key = reinterpret_cast<uint64_t>(sc);
for (size_t i = 0; i < kMaxSwapchains; ++i) {
uint64_t have = key;
if (g_swapchains[i].handle.compare_exchange_strong(have, 0ull, std::memory_order_acq_rel)) {
return;
}
}
}
// "Stops" = passthrough forever, with the reason on the mapping. There is no
// unhook: the loader owns the chain, and the Overlay's MH_DisableHook has no
// equivalent here. First reason wins, exactly as in the Overlay.
void StopObserving(uint32_t reason) noexcept {
uint32_t live = 1;
if (!g_observing.compare_exchange_strong(live, 0u, std::memory_order_acq_rel)) {
return;
}
if (g_state != nullptr) {
std::atomic_ref<uint32_t> status{g_state->status};
status.store(reason, std::memory_order_release);
}
}
LONG FlFilter(DWORD code) noexcept {
if (code == EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP) {
return EXCEPTION_CONTINUE_SEARCH;
}
return EXCEPTION_EXECUTE_HANDLER;
}
void NoteFault() noexcept {
if (g_state == nullptr) {
return;
}
std::atomic_ref<uint32_t> faults{g_state->faultCount};
if (faults.fetch_add(1, std::memory_order_acq_rel) + 1 >= 3) {
StopObserving(fl::FL_STATUS_SELF_DISABLED); // 17_HOOK_ENGINE §Fault policy: three faults, dormant
}
}
// The present-path decision. Same order and same polarity as the Overlay's
// MayObserve, minus the LoadLibrary detour it has no equivalent of -- plus the
// supervision check that the Overlay runs on its watchdog and this layer cannot
// (§S2 part three). guardTicks counts COMPLETED guard evaluations, not seconds;
// "never advanced" and "stopped advancing" are the same state, and the clock
// starts when the mapping is published.
bool MayObserve() noexcept {
if (g_observing.load(std::memory_order_acquire) == 0u) {
return false;
}
if (g_control == nullptr) {
return true;
}
std::atomic_ref<uint32_t> unhook{g_control->unhookRequested};
if (unhook.load(std::memory_order_acquire) != 0u) {
StopObserving(fl::FL_STATUS_UNHOOKED);
return false;
}
std::atomic_ref<uint32_t> ticks{g_control->guardTicks};
const uint32_t now = ticks.load(std::memory_order_acquire);
const ULONGLONG t = GetTickCount64();
if (now != g_lastTicks.load(std::memory_order_relaxed)) {
g_lastTicks.store(now, std::memory_order_relaxed);
g_lastTickAt.store(t, std::memory_order_relaxed);
} else if (t - g_lastTickAt.load(std::memory_order_relaxed) >= kTickDeadlineMs) {
StopObserving(fl::FL_STATUS_UNHOOKED);
return false;
}
std::atomic_ref<uint32_t> paused{g_control->pauseRequested};
return paused.load(std::memory_order_relaxed) == 0u;
}
// Once, on the first admitted vkCreateDevice. Failure -- most likely the ring
// already existing because an Overlay got there first -- is final: the layer
// forwards and observes nothing, which is what an un-owned ring requires.
bool EnsureCapture() noexcept {
uint32_t expected = 0;
if (!g_captureState.compare_exchange_strong(expected, 3u, std::memory_order_acq_rel)) {
// 3 = in progress on another thread; treat as not yet live.
return g_captureState.load(std::memory_order_acquire) == 1u;
}
if (!fl::shmhost::CreateRingMapping(g_mapping, g_base)) {
g_captureState.store(2u, std::memory_order_release);
return false;
}
fl::shmhost::PublishHandshake(g_base);
g_state = reinterpret_cast<FlWriterState*>(static_cast<unsigned char*>(g_base) + FL_SHM_WRITER_OFFSET);
g_control = reinterpret_cast<FlControlBlock*>(static_cast<unsigned char*>(g_base) + FL_SHM_CONTROL_OFFSET);
if (!g_writer.Init(g_base, FL_SHM_DEFAULT_CAPACITY)) {
g_captureState.store(2u, std::memory_order_release);
return false;
}
g_lastTicks.store(0, std::memory_order_relaxed);
g_lastTickAt.store(GetTickCount64(), std::memory_order_relaxed);
{
std::atomic_ref<uint32_t> api{g_state->apiMask};
api.fetch_or(1u << fl::FL_API_VULKAN, std::memory_order_relaxed);
std::atomic_ref<uint32_t> hooks{g_state->hooksInstalledMask};
hooks.fetch_or(static_cast<uint32_t>(fl::FL_HOOK_PRESENT), std::memory_order_relaxed);
// No DXGI counter exists on this path; the word stays "not read".
std::atomic_ref<uint32_t> before{g_state->dxgiPresentsBeforeHook};
before.store(0xFFFFFFFFu, std::memory_order_relaxed);
std::atomic_ref<uint32_t> status{g_state->status};
status.store(fl::FL_STATUS_READY, std::memory_order_release);
}
g_observing.store(1u, std::memory_order_release);
g_captureState.store(1u, std::memory_order_release);
return true;
}
// RULE 4: `pPresentInfo` is the argument of the API we intercept, and the only
// thing read from it is which swapchain(s) it names -- to look up an output size
// WE recorded at creation. Nothing of the game's is dereferenced beyond that.
void RecordPresent(const VkPresentInfoKHR* info) noexcept {
if (!MayObserve()) {
return;
}
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
const SwapchainSlot* slot = nullptr;
if (info != nullptr && info->swapchainCount > 0u && info->pSwapchains != nullptr) {
slot = FindSwapchain(info->pSwapchains[0]);
}
FlFrameRecord rec{};
rec.qpc = static_cast<uint64_t>(qpc.QuadPart);
rec.frameIndex = g_frameIndex.fetch_add(1u, std::memory_order_relaxed);
rec.api = static_cast<uint8_t>(fl::FL_API_VULKAN);
if (slot != nullptr) {
rec.swapchainId = slot->id;
rec.outputW = slot->w;
rec.outputH = slot->h;
}
// vkQueuePresentKHR carries no sync interval and no present flags, which is
// exactly why FL_MEASURED_PRESENT_ARGS exists rather than being assumed
// (fl_shm.h); only the output size may be claimed, and only when there is one.
rec.measuredMask = (rec.outputW != 0u && rec.outputH != 0u) ? fl::FL_MEASURED_OUTPUT_RES : 0u;
g_writer.Publish(rec);
}
// SEH around OUR code only, never around the forward (the Overlay's rule: a
// game's fault inside the next layer must not be counted as ours). A separate
// function because __try cannot share a frame with objects that need unwinding.
void RecordPresentGuarded(const VkPresentInfoKHR* info) noexcept {
__try {
RecordPresent(info);
} __except (FlFilter(GetExceptionCode())) {
NoteFault();
}
}
VKAPI_ATTR VkResult VKAPI_CALL QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) {
const DeviceSlot* d = (queue != nullptr) ? FindDevice(DispatchKey(queue)) : nullptr;
RecordPresentGuarded(pPresentInfo);
if (d == nullptr || d->present == nullptr) {
return VK_ERROR_DEVICE_LOST; // unreachable by construction: we only hand out this hook for registered
// devices
}
return d->present(queue, pPresentInfo);
}
VKAPI_ATTR VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) {
const DeviceSlot* d = (device != nullptr) ? FindDevice(DispatchKey(device)) : nullptr;
if (d == nullptr || d->createSwapchain == nullptr) {
return VK_ERROR_DEVICE_LOST;
}
const VkResult r = d->createSwapchain(device, pCreateInfo, pAllocator, pSwapchain);
if (r == VK_SUCCESS && pCreateInfo != nullptr && pSwapchain != nullptr && *pSwapchain != VK_NULL_HANDLE) {
RememberSwapchain(*pSwapchain, pCreateInfo->imageExtent); // rule 4: the API's own argument
}
return r;
}
VKAPI_ATTR void VKAPI_CALL DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
const VkAllocationCallbacks* pAllocator) {
if (swapchain != VK_NULL_HANDLE) {
ForgetSwapchain(swapchain);
}
const DeviceSlot* d = (device != nullptr) ? FindDevice(DispatchKey(device)) : nullptr;
if (d != nullptr && d->destroySwapchain != nullptr) {
d->destroySwapchain(device, swapchain, pAllocator);
}
}
// After the next layer's vkCreateDevice succeeded in an admitted process: the
// ring (once) and this device's next-pointers, resolved through the chain's own
// GetDeviceProcAddr so we call whatever sits below us and never the loader's
// trampoline for ourselves.
void RegisterDevice(VkDevice device) noexcept {
if (device == nullptr || g_nextGetDeviceProcAddr == nullptr || HasDevice(DispatchKey(device))) {
return;
}
// THE NEXT POINTERS FIRST, UNCONDITIONALLY. Once GetDeviceProcAddr has handed
// out our hooks, every present on this device passes through them, and a hook
// with nothing to forward to would fail the application's present -- measured
// 2026-09-06 as VK_ERROR_DEVICE_LOST on the harness when an injected Overlay
// owned the ring and the layer had registered nothing. The ring failing to
// come up must only ever mean "observe nothing", never "forward nothing".
const uint32_t i = g_deviceCount.load(std::memory_order_acquire);
if (i >= kMaxDevices) {
return;
}
DeviceSlot& d = g_devices[i];
d.key = DispatchKey(device);
d.present = reinterpret_cast<PFN_vkQueuePresentKHR>(g_nextGetDeviceProcAddr(device, "vkQueuePresentKHR"));
d.createSwapchain =
reinterpret_cast<PFN_vkCreateSwapchainKHR>(g_nextGetDeviceProcAddr(device, "vkCreateSwapchainKHR"));
d.destroySwapchain =
reinterpret_cast<PFN_vkDestroySwapchainKHR>(g_nextGetDeviceProcAddr(device, "vkDestroySwapchainKHR"));
g_deviceCount.store(i + 1u, std::memory_order_release); // visible LAST
// Then the capture side, whose failure (an Overlay already owning the ring,
// most likely) leaves the hooks in place as pure forwarders.
EnsureCapture();
}
bool Active() noexcept {
return ThisProcessIsEnabledCached() && !MustStayInert();
}
// The three names we answer for, in an admitted process, from either proc-addr
// entry: applications and layers above us may fetch device functions through
// vkGetInstanceProcAddr as well.
PFN_vkVoidFunction OurDeviceFunction(const char* pName) noexcept {
if (std::strcmp(pName, "vkQueuePresentKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&QueuePresentKHR);
}
if (std::strcmp(pName, "vkCreateSwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&CreateSwapchainKHR);
}
if (std::strcmp(pName, "vkDestroySwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&DestroySwapchainKHR);
}
return nullptr;
}
// ---------------------------------------------------------------------------
// Loader interface. Everything forwards; an admitted process is also observed.
// ---------------------------------------------------------------------------
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance, const char* pName);
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice device, const char* pName);
@@ -309,7 +661,13 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physicalDevice, con
}
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
return createDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
const VkResult r = createDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
// The capture side comes up HERE and only here: after the next layer built the
// device, and only in a process both gates admitted (P1 item 3).
if (r == VK_SUCCESS && pDevice != nullptr && Active()) {
RegisterDevice(*pDevice);
}
return r;
}
// Evaluated once, on first use. The enable-list decides what we INTERCEPT, not
@@ -339,8 +697,7 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance
return (g_nextGetInstanceProcAddr != nullptr) ? g_nextGetInstanceProcAddr(instance, pName) : nullptr;
}
// Exactly the entry points needed to stay in the chain and forward.
// vkQueuePresentKHR is deliberately absent — see the file header.
// The entry points needed to stay in the chain and forward, then ours.
if (std::strcmp(pName, "vkGetInstanceProcAddr") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&GetInstanceProcAddr);
}
@@ -350,6 +707,10 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance
if (std::strcmp(pName, "vkCreateDevice") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&CreateDevice);
}
// Past the gate: an admitted process gets our present / swapchain entries.
if (PFN_vkVoidFunction ours = OurDeviceFunction(pName); ours != nullptr) {
return ours;
}
if (g_nextGetInstanceProcAddr == nullptr) {
return nullptr;
}
@@ -363,6 +724,17 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice device, cons
if (std::strcmp(pName, "vkGetDeviceProcAddr") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&GetDeviceProcAddr);
}
if (Active()) {
if (PFN_vkVoidFunction ours = OurDeviceFunction(pName); ours != nullptr) {
// A device that reached us here without passing through CreateDevice
// (created before the gates were consulted, or beyond the table) is
// registered now, so the hook we hand out always has a next pointer.
if (device != nullptr) {
RegisterDevice(device);
}
return ours;
}
}
if (g_nextGetDeviceProcAddr == nullptr) {
return nullptr;
}
+28
View File
@@ -110,6 +110,34 @@ add_dependencies(fl_guard_test hook-harness FrameLedger.Overlay fl_stage_overlay
add_test(NAME fl_guard COMMAND fl_guard_test)
# The Vulkan layer's capture side (P1 item 3), driven by a FAKE loader chain --
# no registry, no loader, no GPU -- so it is merge-gated. Three ctests, three
# processes, because one process carries one ring and each DLL flavour makes one.
# fl_ac_rules.cpp is compiled in for LocalAppDataDir / RulesFilePath, the same
# functions the layer reads through, so the files the test writes land exactly
# where the layer looks.
add_executable(fl_vklayer_test vklayer_test.cpp "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/src/fl_ac_rules.cpp")
target_include_directories(fl_vklayer_test PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Injector/include")
target_link_libraries(fl_vklayer_test PRIVATE FrameLedger.Shm fl_native_flags fl_jsmn fl_vulkan_headers
Catch2::Catch2WithMain Shell32 Ole32 fl_ac_floor)
add_dependencies(fl_vklayer_test fl_ac_floor_gen FrameLedger.VkLayer fl_vklayer_shortdeadline hook-harness)
target_compile_options(fl_vklayer_test PRIVATE /EHsc)
target_compile_definitions(fl_vklayer_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
FL_VKLAYER_DLL=L"$<TARGET_FILE:FrameLedger.VkLayer>"
FL_VKLAYER_SHORTDEADLINE_DLL=L"$<TARGET_FILE:fl_vklayer_shortdeadline>"
# The directory the loader is pointed at through VK_ADD_IMPLICIT_LAYER_PATH:
# it holds the generated manifest beside the DLL.
FL_VKLAYER_MANIFEST_DIR=L"$<TARGET_FILE_DIR:FrameLedger.VkLayer>"
FL_HARNESS_EXE=L"$<TARGET_FILE:hook-harness>"
FL_REPO_RULES=L"${CMAKE_SOURCE_DIR}/../../rules/detection-rules.json"
)
add_test(NAME fl_vklayer COMMAND fl_vklayer_test "[vklayer]")
add_test(NAME fl_vklayer_supervision COMMAND fl_vklayer_test "[vklayer-deadline]")
# The real-loader leg SKIPS (Catch2 exit 4) where there is no Vulkan loader or no
# presentable device -- CI, per the §S29(d) census -- and runs on a dev box.
add_test(NAME fl_vklayer_real COMMAND fl_vklayer_test "[vklayer-real]")
set_tests_properties(fl_vklayer_real PROPERTIES SKIP_RETURN_CODE 4)
# Check 4's fail-closed matrix, as its own ctest name so a regression in the
# static pre-scan is legible in the ctest summary rather than buried in
# fl_guard's total. Same binary, selected by tag — duplicating the evidence
+38
View File
@@ -2125,6 +2125,44 @@ TEST_CASE("launch mode: the poll matches no blocklist, so anti-cheat mapped besi
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("launch mode: a Vulkan-only presenter passes the FULL guard and is NOT injected -- the layer is the capture "
"side",
"[guard][inject][launch][vulkan]") {
Child child;
REQUIRE(StartHarness(child));
ResetFake();
g.modules = {"kernel32.dll"};
g.modulesLate = {"kernel32.dll", "vulkan-1.dll"}; // no dxgi, no d3d, no opengl32
g.moduleCallsBeforeLate = 2;
g.scanSet = {child.pi.dwProcessId};
const Verdict v = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
INFO("reason " << ReasonName(v.reason) << " signal=" << v.signal);
CHECK(v.reason == Reason::kTargetIsVulkanLayered);
CHECK_FALSE(v.Allowed());
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
// ...and the full guard really ran: anti-cheat beside vulkan-1 is refused by name.
ResetFake();
g.modules = {"kernel32.dll", "vulkan-1.dll", "BEClient_x64.dll"};
g.scanSet = {child.pi.dwProcessId};
const Verdict blocked =
GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
CHECK(blocked.reason == Reason::kBlockedModule);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
// A title that maps vulkan-1 BESIDE a D3D runtime is STILL the layer's: an NVIDIA
// Vulkan ICD maps dxgi + d3d12 itself (measured on the harness's --vulkan mode),
// so this is what every Vulkan title looks like there.
ResetFake();
g.modules = {"kernel32.dll", "vulkan-1.dll", "dxgi.dll", "d3d12.dll"};
g.scanSet = {child.pi.dwProcessId};
const Verdict both = GuardedInjectWhenReadyWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, 10000, FakeSources());
CHECK(both.reason == Reason::kTargetIsVulkanLayered);
CHECK_FALSE(TargetHasModule(child.pi.dwProcessId, L"FrameLedger.Overlay.dll"));
}
TEST_CASE("launch mode against the real harness through the real module seam: injected once dxgi maps, and the "
"writer says how many presents ran unhooked",
"[guard][inject][shm][launch]") {
+559
View File
@@ -0,0 +1,559 @@
// The Vulkan layer's capture side (P1 item 3): vkQueuePresentKHR intercepted,
// the ring written, the in-layer supervision stop (§S2 part three) -- driven
// end to end by a FAKE loader chain, exactly as 20_OPEN_QUESTIONS §S2 said it
// would land: "in the PR that adds the present hook, where a fake loader chain
// can drive it end to end".
//
// Three ctests, three processes, because a process carries ONE ring and each
// flavour of the DLL creates one:
// [vklayer] the shipped DLL: records, forwarding, the unhook stop
// [vklayer-deadline] the short-deadline flavour: guardTicks stops -> the layer stops
// [vklayer-real] the REAL loader, the REAL harness (--vulkan), via
// VK_ADD_IMPLICIT_LAYER_PATH -- SKIPPED where there is no
// Vulkan loader or no presentable device (CI, §S29(d))
//
// The layer reads its enable-list and rules from the ONE product location under
// %LOCALAPPDATA% and there is deliberately no override (§S3), so this test writes
// its own image name into that enable-list and, when no rules file is installed,
// the repository seed -- and removes exactly what it added. It never touches an
// existing rules file.
#include <windows.h>
#include <vulkan/vk_layer.h>
#include <vulkan/vulkan.h>
#include <atomic>
#include <catch2/catch_test_macros.hpp>
#include <cstdio>
#include <cstring>
#include <fl_ac_rules.h>
#include <fl_shm.h>
#include <string>
namespace {
// ---------------------------------------------------------------------------
// The product's files: enable-list + rules, added and removed by this test.
// ---------------------------------------------------------------------------
struct ProductFiles {
std::wstring enableList;
std::string enableListBackup; // the previous contents, when there were any
bool hadEnableList = false;
std::wstring rules;
bool installedRules = false;
static std::wstring LocalAppData() {
wchar_t base[fl::guard::kMaxRulesPathLen]{};
REQUIRE(fl::guard::LocalAppDataDir(base, fl::guard::kMaxRulesPathLen));
return base;
}
static void EnsureDir(const std::wstring& dir) {
std::wstring cur;
for (size_t i = 0; i < dir.size(); ++i) {
cur += dir[i];
if ((dir[i] == L'\\' || i + 1 == dir.size()) && cur.size() > 3) {
CreateDirectoryW(cur.c_str(), nullptr);
}
}
}
static bool ReadAll(const std::wstring& path, std::string& out) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return false;
}
char buf[4096];
DWORD n = 0;
out.clear();
while (ReadFile(h, buf, sizeof(buf), &n, nullptr) && n > 0) {
out.append(buf, n);
}
CloseHandle(h);
return true;
}
static bool WriteAll(const std::wstring& path, const std::string& text) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return false;
}
DWORD n = 0;
const BOOL ok = WriteFile(h, text.data(), static_cast<DWORD>(text.size()), &n, nullptr);
CloseHandle(h);
return ok && n == text.size();
}
// Adds `imageName` to the enable-list (creating it if needed) and installs the
// repository seed rules when no rules file exists.
void Install(const char* imageName) {
const std::wstring base = LocalAppData();
const std::wstring dir = base + L"\\FrameLedger\\vklayer";
EnsureDir(dir);
enableList = dir + L"\\enabled.txt";
std::string existing;
hadEnableList = ReadAll(enableList, existing);
if (hadEnableList) {
enableListBackup = existing;
}
std::string text = existing;
if (!text.empty() && text.back() != '\n') {
text += '\n';
}
text += "# added by fl_vklayer_test, removed when it exits\n";
text += imageName;
text += '\n';
REQUIRE(WriteAll(enableList, text));
wchar_t rulesPath[fl::guard::kMaxRulesPathLen]{};
REQUIRE(fl::guard::RulesFilePath(rulesPath, fl::guard::kMaxRulesPathLen));
rules = rulesPath;
if (GetFileAttributesW(rulesPath) == INVALID_FILE_ATTRIBUTES) {
const std::wstring rulesDir = rules.substr(0, rules.find_last_of(L'\\'));
EnsureDir(rulesDir);
REQUIRE(CopyFileW(FL_REPO_RULES, rulesPath, TRUE));
installedRules = true;
}
}
~ProductFiles() {
if (!enableList.empty()) {
if (hadEnableList) {
WriteAll(enableList, enableListBackup);
} else {
DeleteFileW(enableList.c_str());
}
}
if (installedRules) {
DeleteFileW(rules.c_str());
}
}
};
std::string OwnImageName() {
char full[MAX_PATH]{};
REQUIRE(GetModuleFileNameA(nullptr, full, MAX_PATH) != 0);
const char* leaf = std::strrchr(full, '\\');
return leaf != nullptr ? leaf + 1 : full;
}
// ---------------------------------------------------------------------------
// The fake loader chain. Dispatchable handles are objects whose FIRST word is the
// dispatch key, which is what the loader guarantees and what the layer keys on;
// the device and its queue share one key, as they do under a real loader.
// ---------------------------------------------------------------------------
void* g_deviceKey = &g_deviceKey;
void* g_instanceKey = &g_instanceKey;
struct Dispatchable {
void* key;
};
Dispatchable g_instanceObj{g_instanceKey};
Dispatchable g_deviceObj{g_deviceKey};
Dispatchable g_queueObj{g_deviceKey};
std::atomic<int> g_forwardedPresents{0};
std::atomic<int> g_destroyed{0};
VkSwapchainKHR g_lastPresented = VK_NULL_HANDLE;
const VkSwapchainKHR kFakeSwapchain = reinterpret_cast<VkSwapchainKHR>(static_cast<uintptr_t>(0x1234));
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateInstance(const VkInstanceCreateInfo*, const VkAllocationCallbacks*,
VkInstance* pInstance) {
*pInstance = reinterpret_cast<VkInstance>(&g_instanceObj);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateDevice(VkPhysicalDevice, const VkDeviceCreateInfo*,
const VkAllocationCallbacks*, VkDevice* pDevice) {
*pDevice = reinterpret_cast<VkDevice>(&g_deviceObj);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeQueuePresent(VkQueue, const VkPresentInfoKHR* info) {
++g_forwardedPresents;
g_lastPresented = (info != nullptr && info->swapchainCount > 0) ? info->pSwapchains[0] : VK_NULL_HANDLE;
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateSwapchain(VkDevice, const VkSwapchainCreateInfoKHR*,
const VkAllocationCallbacks*, VkSwapchainKHR* out) {
*out = kFakeSwapchain;
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL FakeDestroySwapchain(VkDevice, VkSwapchainKHR, const VkAllocationCallbacks*) {
++g_destroyed;
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL FakeGetDeviceProcAddr(VkDevice, const char* name) {
if (std::strcmp(name, "vkQueuePresentKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeQueuePresent);
}
if (std::strcmp(name, "vkCreateSwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateSwapchain);
}
if (std::strcmp(name, "vkDestroySwapchainKHR") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeDestroySwapchain);
}
return nullptr;
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL FakeGetInstanceProcAddr(VkInstance, const char* name) {
if (std::strcmp(name, "vkCreateInstance") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateInstance);
}
if (std::strcmp(name, "vkCreateDevice") == 0) {
return reinterpret_cast<PFN_vkVoidFunction>(&FakeCreateDevice);
}
return nullptr;
}
// The layer, driven as the loader would drive it: negotiate, create an instance
// through the chain, create a device through the chain, fetch the device entries.
struct DrivenLayer {
HMODULE dll = nullptr;
PFN_vkGetInstanceProcAddr gipa = nullptr;
PFN_vkGetDeviceProcAddr gdpa = nullptr;
VkInstance instance = nullptr;
VkDevice device = nullptr;
PFN_vkQueuePresentKHR present = nullptr;
PFN_vkCreateSwapchainKHR createSwapchain = nullptr;
PFN_vkDestroySwapchainKHR destroySwapchain = nullptr;
void Drive(const wchar_t* path) {
dll = LoadLibraryW(path);
REQUIRE(dll != nullptr);
auto negotiate = reinterpret_cast<PFN_vkNegotiateLoaderLayerInterfaceVersion>(
GetProcAddress(dll, "vkNegotiateLoaderLayerInterfaceVersion"));
REQUIRE(negotiate != nullptr);
VkNegotiateLayerInterface n{};
n.sType = LAYER_NEGOTIATE_INTERFACE_STRUCT;
n.loaderLayerInterfaceVersion = 2;
REQUIRE(negotiate(&n) == VK_SUCCESS);
gipa = n.pfnGetInstanceProcAddr;
gdpa = n.pfnGetDeviceProcAddr;
REQUIRE(gipa != nullptr);
REQUIRE(gdpa != nullptr);
VkLayerInstanceLink ilink{nullptr, &FakeGetInstanceProcAddr, nullptr};
VkLayerInstanceCreateInfo ici{};
ici.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
ici.function = VK_LAYER_LINK_INFO;
ici.u.pLayerInfo = &ilink;
VkInstanceCreateInfo ci{};
ci.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
ci.pNext = &ici;
auto createInstance = reinterpret_cast<PFN_vkCreateInstance>(gipa(nullptr, "vkCreateInstance"));
REQUIRE(createInstance != nullptr);
REQUIRE(createInstance(&ci, nullptr, &instance) == VK_SUCCESS);
REQUIRE(instance == reinterpret_cast<VkInstance>(&g_instanceObj));
VkLayerDeviceLink dlink{nullptr, &FakeGetInstanceProcAddr, &FakeGetDeviceProcAddr};
VkLayerDeviceCreateInfo dci{};
dci.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
dci.function = VK_LAYER_LINK_INFO;
dci.u.pLayerInfo = &dlink;
VkDeviceCreateInfo dc{};
dc.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dc.pNext = &dci;
auto createDevice = reinterpret_cast<PFN_vkCreateDevice>(gipa(instance, "vkCreateDevice"));
REQUIRE(createDevice != nullptr);
REQUIRE(createDevice(nullptr, &dc, nullptr, &device) == VK_SUCCESS);
REQUIRE(device == reinterpret_cast<VkDevice>(&g_deviceObj));
present = reinterpret_cast<PFN_vkQueuePresentKHR>(gdpa(device, "vkQueuePresentKHR"));
createSwapchain = reinterpret_cast<PFN_vkCreateSwapchainKHR>(gdpa(device, "vkCreateSwapchainKHR"));
destroySwapchain = reinterpret_cast<PFN_vkDestroySwapchainKHR>(gdpa(device, "vkDestroySwapchainKHR"));
}
VkResult PresentOnce(VkSwapchainKHR sc) const {
uint32_t index = 0;
VkPresentInfoKHR info{};
info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
info.swapchainCount = 1;
info.pSwapchains = &sc;
info.pImageIndices = &index;
return present(reinterpret_cast<VkQueue>(&g_queueObj), &info);
}
};
struct OwnRing {
HANDLE mapping = nullptr;
void* base = nullptr;
fl::FlShmHandshake* hs = nullptr;
fl::FlWriterState* st = nullptr;
fl::FlControlBlock* ctl = nullptr;
const fl::FlFrameRecord* ring = nullptr;
bool Open() {
wchar_t name[128]{};
_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", GetCurrentProcessId());
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
return false;
}
base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (base == nullptr) {
return false;
}
auto* bytes = static_cast<unsigned char*>(base);
hs = reinterpret_cast<fl::FlShmHandshake*>(bytes + FL_SHM_HANDSHAKE_OFFSET);
st = reinterpret_cast<fl::FlWriterState*>(bytes + FL_SHM_WRITER_OFFSET);
ctl = reinterpret_cast<fl::FlControlBlock*>(bytes + FL_SHM_CONTROL_OFFSET);
ring = reinterpret_cast<const fl::FlFrameRecord*>(bytes + FL_SHM_RING_OFFSET);
return true;
}
~OwnRing() {
if (base != nullptr) {
UnmapViewOfFile(base);
}
if (mapping != nullptr) {
CloseHandle(mapping);
}
}
};
} // namespace
// ===========================================================================
TEST_CASE("the layer, driven by a fake loader chain, owns the ring and records every present it forwards",
"[vklayer]") {
ProductFiles files;
files.Install(OwnImageName().c_str()); // BEFORE the DLL loads: both gates are cached on first use
DrivenLayer layer;
layer.Drive(FL_VKLAYER_DLL);
REQUIRE(layer.present != nullptr);
CHECK(layer.present != &FakeQueuePresent); // ours, not the next layer's
REQUIRE(layer.createSwapchain != nullptr);
REQUIRE(layer.destroySwapchain != nullptr);
// The ring exists under OUR pid, with the handshake a reader validates first.
OwnRing r;
REQUIRE(r.Open());
CHECK(r.hs->layoutVersion == FL_SHM_LAYOUT_VERSION);
CHECK(r.hs->pid == GetCurrentProcessId());
CHECK(r.hs->recordSize == sizeof(fl::FlFrameRecord));
CHECK(r.st->status == fl::FL_STATUS_READY);
CHECK((r.st->apiMask & (1u << fl::FL_API_VULKAN)) != 0u);
CHECK((r.st->hooksInstalledMask & fl::FL_HOOK_PRESENT) != 0u);
CHECK(r.st->dxgiPresentsBeforeHook == 0xFFFFFFFFu); // no DXGI counter on this path: "not read"
// A swapchain created through us is remembered with its extent.
VkSwapchainCreateInfoKHR sci{};
sci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
sci.imageExtent = VkExtent2D{1280u, 720u};
VkSwapchainKHR sc = VK_NULL_HANDLE;
REQUIRE(layer.createSwapchain(layer.device, &sci, nullptr, &sc) == VK_SUCCESS);
REQUIRE(sc == kFakeSwapchain);
// Presents: one record each, forwarded each, the record naming the chain and its size.
for (int i = 0; i < 5; ++i) {
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
}
CHECK(g_forwardedPresents.load() == 5);
CHECK(g_lastPresented == kFakeSwapchain);
CHECK(r.st->writeIndex == 5u);
const fl::FlFrameRecord& rec = r.ring[0];
CHECK(rec.api == static_cast<uint8_t>(fl::FL_API_VULKAN));
CHECK(rec.outputW == 1280u);
CHECK(rec.outputH == 720u);
CHECK(rec.swapchainId != 0u);
CHECK(rec.measuredMask == fl::FL_MEASURED_OUTPUT_RES); // and NOT PRESENT_ARGS: vkQueuePresentKHR has none
CHECK(r.ring[4].frameIndex == rec.frameIndex + 4u);
CHECK(r.ring[4].qpc > rec.qpc);
// A present on a chain we never saw is still recorded, as "unidentified", and forwarded.
const auto unknown = reinterpret_cast<VkSwapchainKHR>(static_cast<uintptr_t>(0x9999));
REQUIRE(layer.PresentOnce(unknown) == VK_SUCCESS);
CHECK(r.st->writeIndex == 6u);
CHECK(r.ring[5].swapchainId == 0u);
CHECK(r.ring[5].measuredMask == 0u);
// Destroyed through us: forgotten, and the next layer told.
layer.destroySwapchain(layer.device, sc, nullptr);
CHECK(g_destroyed.load() == 1);
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.ring[6].swapchainId == 0u);
// Pause is not stop: no record, still forwarded, status untouched.
r.ctl->pauseRequested = 1;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.st->writeIndex == 7u);
CHECK(g_forwardedPresents.load() == 8);
CHECK(r.st->status == fl::FL_STATUS_READY);
r.ctl->pauseRequested = 0;
// THE SAFETY STOP: unhookRequested -> UNHOOKED within one present, writeIndex frozen,
// and every later present still forwarded -- "stops" is passthrough, never a broken app.
r.ctl->unhookRequested = 1;
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_UNHOOKED);
CHECK(r.st->writeIndex == 7u);
for (int i = 0; i < 3; ++i) {
REQUIRE(layer.PresentOnce(sc) == VK_SUCCESS);
}
CHECK(r.st->writeIndex == 7u);
CHECK(g_forwardedPresents.load() == 12);
CHECK(r.st->faultCount == 0u);
}
// ===========================================================================
TEST_CASE("§S2 part three: when guardTicks stops advancing the layer stops itself, and while it advances it does not",
"[vklayer-deadline]") {
// The short-deadline flavour (1.5 s instead of 65 s), same sources. The clock
// starts when the ring is published; ticks that keep coming keep it alive
// past the deadline, and ticks that stop end it -- on the present path, since
// the layer owns no thread (§S2).
ProductFiles files;
files.Install(OwnImageName().c_str());
DrivenLayer layer;
layer.Drive(FL_VKLAYER_SHORTDEADLINE_DLL);
REQUIRE(layer.present != nullptr);
OwnRing r;
REQUIRE(r.Open());
REQUIRE(r.st->status == fl::FL_STATUS_READY);
// Supervised: 2.4 s of presents with a tick every 600 ms -- past the 1.5 s deadline, still READY.
for (int i = 0; i < 4; ++i) {
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
Sleep(600);
}
++r.ctl->guardTicks;
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_READY);
const uint64_t recorded = r.st->writeIndex;
CHECK(recorded == 5u);
// Unsupervised: no tick for 1.8 s -> the next present stops the layer.
Sleep(1800);
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS);
CHECK(r.st->status == fl::FL_STATUS_UNHOOKED);
CHECK(r.st->writeIndex == recorded);
REQUIRE(layer.PresentOnce(kFakeSwapchain) == VK_SUCCESS); // still forwarded
CHECK(g_forwardedPresents.load() == 7);
}
// ===========================================================================
namespace {
struct Child {
PROCESS_INFORMATION pi{};
~Child() {
if (pi.hProcess != nullptr) {
TerminateProcess(pi.hProcess, 0);
WaitForSingleObject(pi.hProcess, 3000);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
}
};
struct ChildRing {
HANDLE mapping = nullptr;
void* base = nullptr;
fl::FlWriterState* st = nullptr;
fl::FlControlBlock* ctl = nullptr;
const fl::FlFrameRecord* ring = nullptr;
~ChildRing() {
if (base != nullptr) {
UnmapViewOfFile(base);
}
if (mapping != nullptr) {
CloseHandle(mapping);
}
}
bool OpenFor(DWORD pid, HANDLE process, int waitMs) {
wchar_t name[128]{};
_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", pid);
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(waitMs);
while (mapping == nullptr && GetTickCount64() < until) {
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
if (WaitForSingleObject(process, 0) != WAIT_TIMEOUT) {
return false; // the child is gone
}
Sleep(50);
}
}
if (mapping == nullptr) {
return false;
}
base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (base == nullptr) {
return false;
}
auto* bytes = static_cast<unsigned char*>(base);
st = reinterpret_cast<fl::FlWriterState*>(bytes + FL_SHM_WRITER_OFFSET);
ctl = reinterpret_cast<fl::FlControlBlock*>(bytes + FL_SHM_CONTROL_OFFSET);
ring = reinterpret_cast<const fl::FlFrameRecord*>(bytes + FL_SHM_RING_OFFSET);
return true;
}
};
} // namespace
TEST_CASE("the REAL loader maps the layer from VK_ADD_IMPLICIT_LAYER_PATH into the harness's Vulkan mode, and every "
"present is recorded",
"[vklayer-real]") {
// No registry: the loader honours VK_ADD_IMPLICIT_LAYER_PATH (measured 2026-09-06
// against 1.4.357, spike-notes §2), so the layer is discoverable ONLY by the
// process this test starts. Skipped honestly where there is no loader or no
// presentable device -- CI has neither (§S29(d)).
if (LoadLibraryW(L"vulkan-1.dll") == nullptr) {
SKIP("no Vulkan loader on this machine");
}
ProductFiles files;
files.Install("hook-harness.exe");
// Environment for the child: inherited from ours, so set, spawn, unset.
REQUIRE(SetEnvironmentVariableW(L"VK_ADD_IMPLICIT_LAYER_PATH", FL_VKLAYER_MANIFEST_DIR));
REQUIRE(SetEnvironmentVariableW(L"FRAMELEDGER_ENABLE_VK_LAYER", L"1"));
Child child;
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --vulkan --hold-presenting 4";
STARTUPINFOW si{};
si.cb = sizeof(si);
const BOOL started = CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr,
nullptr, &si, &child.pi);
SetEnvironmentVariableW(L"VK_ADD_IMPLICIT_LAYER_PATH", nullptr);
SetEnvironmentVariableW(L"FRAMELEDGER_ENABLE_VK_LAYER", nullptr);
REQUIRE(started);
ChildRing r;
const bool ringUp = r.OpenFor(child.pi.dwProcessId, child.pi.hProcess, 15000);
if (!ringUp) {
DWORD code = 0;
WaitForSingleObject(child.pi.hProcess, 5000);
GetExitCodeProcess(child.pi.hProcess, &code);
if (code == 77u) {
SKIP("the harness found no presentable Vulkan device on this machine (exit 77)");
}
FAIL("the layer published no ring for the harness (harness exit " << code << ")");
}
// Keep it supervised while the harness presents, then read what it wrote.
for (int i = 0; i < 50; ++i) {
++r.ctl->guardTicks;
Sleep(100);
if (WaitForSingleObject(child.pi.hProcess, 0) != WAIT_TIMEOUT) {
break;
}
}
WaitForSingleObject(child.pi.hProcess, 10000);
DWORD code = 1;
GetExitCodeProcess(child.pi.hProcess, &code);
INFO("harness exit " << code << ", records " << r.st->writeIndex << ", status " << r.st->status);
CHECK(code == 0u);
CHECK(r.st->status == fl::FL_STATUS_READY);
CHECK(r.st->writeIndex >= 20u); // ~4 s at ~120/s minus device creation; a loose floor, not a rate claim
CHECK((r.st->apiMask & (1u << fl::FL_API_VULKAN)) != 0u);
CHECK(r.ring[0].api == static_cast<uint8_t>(fl::FL_API_VULKAN));
CHECK(r.ring[0].outputW != 0u);
CHECK((r.ring[0].measuredMask & fl::FL_MEASURED_OUTPUT_RES) != 0u);
CHECK(r.st->faultCount == 0u);
}
+5 -2
View File
@@ -4,14 +4,17 @@
# Deliberately NOT built with fl_hostile_env_flags. This is our own process, not
# an injected DLL: it has no reason to give up exceptions, and the COM proxy in
# proxy_swapchain.h is ordinary C++ that benefits from them.
add_executable(hook-harness main.cpp proxy_swapchain.h)
# vk_hold.cpp is the Vulkan mode (P1 item 3): the loader is reached through
# LoadLibraryW at run time, so only the vendored Khronos HEADERS are needed and
# the harness still builds and runs on a machine with no Vulkan at all.
add_executable(hook-harness main.cpp vk_hold.cpp proxy_swapchain.h)
# fl_dxgi_vtable, not a local copy of the slot numbers: this harness proves the
# indices by behaviour, and it must prove the SHIPPED ones (§S29(b)). The same
# reasoning brings in fl_hook_inventory.h from the Overlay's include directory:
# --probe-upscaler-resolve calls the OVERLAY'S resolver, not a copy of it, or it
# would prove a fact about GetProcAddress.
target_link_libraries(hook-harness PRIVATE FrameLedger.Shm fl_dxgi_vtable fl_native_flags fl_streamline_headers
fl_fidelityfx_headers fl_fsr3_host_headers)
fl_fidelityfx_headers fl_fsr3_host_headers fl_vulkan_headers)
target_include_directories(hook-harness PRIVATE "${CMAKE_SOURCE_DIR}/FrameLedger.Overlay/include")
target_compile_definitions(hook-harness PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
+42 -5
View File
@@ -45,6 +45,12 @@
// LoadLibrary detour (17_HOOK_ENGINE §DLL entry, §S6): a
// vendor module that appears LATE, or an anti-cheat-named
// one, is what the detour must react to. Up to 4
// --vulkan with --hold-presenting N: a REAL Vulkan swapchain on a hidden
// window instead of the D3D11 one, presented every few ms, so
// the implicit layer's vkQueuePresentKHR is exercised under the
// real loader (P1 item 3). Exit 77 = this machine cannot run it
// (no loader / no presentable device), which the test that
// spawns it reads as SKIP, never as failure. vk_hold.cpp.
// --hold-presenting-overflow N
// fill the Overlay's fixed 16-slot swapchain table, then
// present for N seconds on one that cannot get a slot. The
@@ -2778,11 +2784,31 @@ bool ProbeFrameIdentity(Gfx& g) {
} // namespace
// vk_hold.cpp -- the Vulkan mode (P1 item 3).
int HoldPresentingVulkan(int seconds, int presentIntervalMs);
int main(int argc, char** argv) {
std::printf("FrameLedger hook-harness (WARP, headless — no GPU or window required)\n");
// --vulkan skips the D3D11 device entirely: a Vulkan fixture that also mapped
// dxgi + d3d11 would be classified as a D3D target by the launch-mode guard
// (fl_guard.cpp FindPresentationRuntime) and get the Overlay instead of the
// layer -- the Overlay owning the ring and the layer observing nothing.
bool vulkanMode = false;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--vulkan") == 0) {
vulkanMode = true;
}
}
if (vulkanMode) {
// A real Vulkan title imports vulkan-1.dll, so it is mapped before its
// first instruction; this fixture imports d3d11/dxgi instead. Map the
// loader NOW so the launch-mode guard's first poll sees what it would see
// on a real title, rather than a D3D process that turns Vulkan later.
LoadLibraryW(L"vulkan-1.dll");
}
Gfx g;
if (!CreateGfx(g)) {
if (!vulkanMode && !CreateGfx(g)) {
std::printf("FAILED: could not create the graphics objects\n");
return 2;
}
@@ -2796,6 +2822,7 @@ int main(int argc, char** argv) {
bool ranSomething = false;
// --real applies to --present and --hold, wherever it appears on the line.
bool real = false;
bool vulkan = false;
int plusUi = 0;
// MILLISECONDS BETWEEN PRESENTS in the --hold-presenting modes. 8 is ~120/s and is the default for
@@ -2830,6 +2857,8 @@ int main(int argc, char** argv) {
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--real") == 0) {
real = true;
} else if (std::strcmp(argv[i], "--vulkan") == 0) {
vulkan = true;
} else if (std::strcmp(argv[i], "--plus-ui") == 0 && i + 1 < argc) {
plusUi = std::atoi(argv[++i]);
} else if (std::strcmp(argv[i], "--present-interval-ms") == 0 && i + 1 < argc) {
@@ -2892,10 +2921,11 @@ int main(int argc, char** argv) {
}
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--real") == 0 || std::strcmp(argv[i], "--plus-ui") == 0 ||
std::strcmp(argv[i], "--present-interval-ms") == 0 || std::strcmp(argv[i], "--presents-per-eval") == 0 ||
std::strcmp(argv[i], "--ffx-topology") == 0 || std::strcmp(argv[i], "--ffx-no-prepare") == 0 ||
std::strcmp(argv[i], "--sl-tag-for-frame") == 0 || std::strcmp(argv[i], "--sl-tag-whole-resource") == 0 ||
if (std::strcmp(argv[i], "--real") == 0 || std::strcmp(argv[i], "--vulkan") == 0 ||
std::strcmp(argv[i], "--plus-ui") == 0 || std::strcmp(argv[i], "--present-interval-ms") == 0 ||
std::strcmp(argv[i], "--presents-per-eval") == 0 || std::strcmp(argv[i], "--ffx-topology") == 0 ||
std::strcmp(argv[i], "--ffx-no-prepare") == 0 || std::strcmp(argv[i], "--sl-tag-for-frame") == 0 ||
std::strcmp(argv[i], "--sl-tag-whole-resource") == 0 ||
std::strcmp(argv[i], "--sl-tag-dlssg-inputs") == 0 || std::strcmp(argv[i], "--load") == 0 ||
std::strcmp(argv[i], "--load-after-ms") == 0) {
if (std::strcmp(argv[i], "--plus-ui") == 0 || std::strcmp(argv[i], "--present-interval-ms") == 0 ||
@@ -3058,6 +3088,13 @@ int main(int argc, char** argv) {
f->Release();
}
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting") == 0 && i + 1 < argc && vulkan) {
// The Vulkan mode: its own file, its own exit codes (77 = cannot run here).
const int code = HoldPresentingVulkan(std::atoi(argv[++i]), presentIntervalMs);
if (code != 0) {
return code;
}
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting") == 0 && i + 1 < argc) {
// WHAT --hold CANNOT DO, and why the injection tests needed this.
//
+328
View File
@@ -0,0 +1,328 @@
// hook-harness --vulkan --hold-presenting N: a REAL Vulkan swapchain on a hidden
// window, presented every few milliseconds for N seconds, so the layer's
// vkQueuePresentKHR can be exercised under the real loader (12_BUILD §Targets:
// "Vulkan and OpenGL modes to follow as those hooks land" -- this is the Vulkan
// one, P1 item 3).
//
// The loader is reached through LoadLibraryW("vulkan-1.dll") and
// vkGetInstanceProcAddr, never a link-time import: the repository vendors the
// Khronos HEADERS only, and CI has no loader at all. Exit codes:
// 0 presented for the whole hold
// 77 this machine cannot run the fixture (no loader, no device, no surface
// support) -- a SKIP for the test that spawns it, never a failure
// 2 the fixture is broken (an API that should have worked did not)
#define VK_USE_PLATFORM_WIN32_KHR
#include <windows.h>
#include <vulkan/vulkan.h>
#include <cstdio>
#include <cstdlib>
#include <vector>
namespace {
PFN_vkGetInstanceProcAddr g_gipa = nullptr;
template <typename T>
T Instance(VkInstance instance, const char* name) {
return reinterpret_cast<T>(g_gipa(instance, name));
}
LRESULT CALLBACK HiddenWndProc(HWND h, UINT m, WPARAM w, LPARAM l) {
return DefWindowProcW(h, m, w, l);
}
HWND CreateHiddenWindow() {
WNDCLASSW wc{};
wc.lpfnWndProc = &HiddenWndProc;
wc.hInstance = GetModuleHandleW(nullptr);
wc.lpszClassName = L"FrameLedgerHookHarnessVulkan";
RegisterClassW(&wc);
// Never shown: a surface needs an HWND, not a visible one.
return CreateWindowExW(0, wc.lpszClassName, L"FrameLedger hook-harness (Vulkan)", WS_OVERLAPPEDWINDOW, 0, 0, 256,
256, nullptr, nullptr, wc.hInstance, nullptr);
}
int Skip(const char* why) {
std::printf(" [SKIP] %s\n", why);
std::fflush(stdout);
return 77;
}
int Broken(const char* what, VkResult r) {
std::printf(" [FAIL] %s (VkResult %d)\n", what, static_cast<int>(r));
std::fflush(stdout);
return 2;
}
} // namespace
int HoldPresentingVulkan(int seconds, int presentIntervalMs) {
std::printf("\n[vulkan-hold] a real swapchain on a hidden window, presenting for %d second(s) every %d ms\n",
seconds, presentIntervalMs);
std::fflush(stdout);
const HMODULE loader = LoadLibraryW(L"vulkan-1.dll");
if (loader == nullptr) {
return Skip("no vulkan-1.dll on this machine");
}
g_gipa = reinterpret_cast<PFN_vkGetInstanceProcAddr>(GetProcAddress(loader, "vkGetInstanceProcAddr"));
if (g_gipa == nullptr) {
return Skip("vulkan-1.dll exports no vkGetInstanceProcAddr");
}
// --- instance ---------------------------------------------------------
auto createInstance = Instance<PFN_vkCreateInstance>(nullptr, "vkCreateInstance");
VkApplicationInfo app{};
app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app.pApplicationName = "FrameLedger hook-harness";
app.apiVersion = VK_API_VERSION_1_1;
const char* instanceExts[] = {"VK_KHR_surface", "VK_KHR_win32_surface"};
VkInstanceCreateInfo ici{};
ici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
ici.pApplicationInfo = &app;
ici.enabledExtensionCount = 2;
ici.ppEnabledExtensionNames = instanceExts;
VkInstance instance = nullptr;
if (createInstance == nullptr || createInstance(&ici, nullptr, &instance) != VK_SUCCESS) {
return Skip("vkCreateInstance failed (no ICD, or no surface extensions)");
}
auto enumPhys = Instance<PFN_vkEnumeratePhysicalDevices>(instance, "vkEnumeratePhysicalDevices");
auto queueProps =
Instance<PFN_vkGetPhysicalDeviceQueueFamilyProperties>(instance, "vkGetPhysicalDeviceQueueFamilyProperties");
auto surfaceSupport =
Instance<PFN_vkGetPhysicalDeviceSurfaceSupportKHR>(instance, "vkGetPhysicalDeviceSurfaceSupportKHR");
auto createSurface = Instance<PFN_vkCreateWin32SurfaceKHR>(instance, "vkCreateWin32SurfaceKHR");
auto surfaceCaps =
Instance<PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR>(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
auto surfaceFormats =
Instance<PFN_vkGetPhysicalDeviceSurfaceFormatsKHR>(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR");
auto createDevice = Instance<PFN_vkCreateDevice>(instance, "vkCreateDevice");
auto gdpa = Instance<PFN_vkGetDeviceProcAddr>(instance, "vkGetDeviceProcAddr");
if (enumPhys == nullptr || queueProps == nullptr || surfaceSupport == nullptr || createSurface == nullptr ||
surfaceCaps == nullptr || surfaceFormats == nullptr || createDevice == nullptr || gdpa == nullptr) {
return Skip("the instance lacks the surface / device entry points this fixture needs");
}
// --- surface ----------------------------------------------------------
const HWND hwnd = CreateHiddenWindow();
if (hwnd == nullptr) {
return Skip("no window could be created (no interactive window station?)");
}
VkWin32SurfaceCreateInfoKHR sci{};
sci.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
sci.hinstance = GetModuleHandleW(nullptr);
sci.hwnd = hwnd;
VkSurfaceKHR surface = VK_NULL_HANDLE;
if (createSurface(instance, &sci, nullptr, &surface) != VK_SUCCESS) {
return Skip("vkCreateWin32SurfaceKHR failed");
}
// --- a physical device with a queue that can draw AND present ---------
uint32_t physCount = 0;
enumPhys(instance, &physCount, nullptr);
std::vector<VkPhysicalDevice> phys(physCount);
enumPhys(instance, &physCount, phys.data());
VkPhysicalDevice chosen = nullptr;
uint32_t family = 0;
for (VkPhysicalDevice p : phys) {
uint32_t n = 0;
queueProps(p, &n, nullptr);
std::vector<VkQueueFamilyProperties> props(n);
queueProps(p, &n, props.data());
for (uint32_t i = 0; i < n && chosen == nullptr; ++i) {
VkBool32 present = VK_FALSE;
if ((props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0u &&
surfaceSupport(p, i, surface, &present) == VK_SUCCESS && present == VK_TRUE) {
chosen = p;
family = i;
}
}
if (chosen != nullptr) {
break;
}
}
if (chosen == nullptr) {
return Skip("no physical device with a graphics queue that can present to a Win32 surface");
}
// --- device -----------------------------------------------------------
const float priority = 1.0f;
VkDeviceQueueCreateInfo qci{};
qci.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
qci.queueFamilyIndex = family;
qci.queueCount = 1;
qci.pQueuePriorities = &priority;
const char* deviceExts[] = {"VK_KHR_swapchain"};
VkDeviceCreateInfo dci{};
dci.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dci.queueCreateInfoCount = 1;
dci.pQueueCreateInfos = &qci;
dci.enabledExtensionCount = 1;
dci.ppEnabledExtensionNames = deviceExts;
VkDevice device = nullptr;
if (VkResult r = createDevice(chosen, &dci, nullptr, &device); r != VK_SUCCESS) {
return Broken("vkCreateDevice", r);
}
#define FL_DEV(name) auto name = reinterpret_cast<PFN_##name>(gdpa(device, #name))
FL_DEV(vkGetDeviceQueue);
FL_DEV(vkCreateSwapchainKHR);
FL_DEV(vkGetSwapchainImagesKHR);
FL_DEV(vkAcquireNextImageKHR);
FL_DEV(vkQueuePresentKHR);
FL_DEV(vkQueueSubmit);
FL_DEV(vkQueueWaitIdle);
FL_DEV(vkCreateSemaphore);
FL_DEV(vkCreateCommandPool);
FL_DEV(vkAllocateCommandBuffers);
FL_DEV(vkBeginCommandBuffer);
FL_DEV(vkEndCommandBuffer);
FL_DEV(vkCmdPipelineBarrier);
FL_DEV(vkDeviceWaitIdle);
#undef FL_DEV
if (vkGetDeviceQueue == nullptr || vkCreateSwapchainKHR == nullptr || vkGetSwapchainImagesKHR == nullptr ||
vkAcquireNextImageKHR == nullptr || vkQueuePresentKHR == nullptr || vkQueueSubmit == nullptr ||
vkQueueWaitIdle == nullptr || vkCreateSemaphore == nullptr || vkCreateCommandPool == nullptr ||
vkAllocateCommandBuffers == nullptr || vkBeginCommandBuffer == nullptr || vkEndCommandBuffer == nullptr ||
vkCmdPipelineBarrier == nullptr || vkDeviceWaitIdle == nullptr) {
return Broken("a device entry point was missing", VK_ERROR_INITIALIZATION_FAILED);
}
VkQueue queue = nullptr;
vkGetDeviceQueue(device, family, 0, &queue);
// --- swapchain --------------------------------------------------------
VkSurfaceCapabilitiesKHR caps{};
surfaceCaps(chosen, surface, &caps);
uint32_t formatCount = 0;
surfaceFormats(chosen, surface, &formatCount, nullptr);
std::vector<VkSurfaceFormatKHR> formats(formatCount);
surfaceFormats(chosen, surface, &formatCount, formats.data());
if (formats.empty()) {
return Skip("the surface reports no formats");
}
VkExtent2D extent = caps.currentExtent;
if (extent.width == 0xFFFFFFFFu || extent.width == 0u || extent.height == 0u) {
extent = VkExtent2D{256u, 256u};
}
VkSwapchainCreateInfoKHR sc{};
sc.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
sc.surface = surface;
sc.minImageCount = caps.minImageCount < 2u ? 2u : caps.minImageCount;
if (caps.maxImageCount != 0u && sc.minImageCount > caps.maxImageCount) {
sc.minImageCount = caps.maxImageCount;
}
sc.imageFormat = formats[0].format;
sc.imageColorSpace = formats[0].colorSpace;
sc.imageExtent = extent;
sc.imageArrayLayers = 1;
sc.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
sc.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
sc.preTransform = caps.currentTransform;
sc.compositeAlpha = (caps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) != 0u
? VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR
: VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
sc.presentMode = VK_PRESENT_MODE_FIFO_KHR;
sc.clipped = VK_TRUE;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
if (VkResult r = vkCreateSwapchainKHR(device, &sc, nullptr, &swapchain); r != VK_SUCCESS) {
return Broken("vkCreateSwapchainKHR", r);
}
uint32_t imageCount = 0;
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr);
std::vector<VkImage> images(imageCount);
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, images.data());
// --- one command buffer per image: UNDEFINED -> PRESENT_SRC, nothing drawn -
VkCommandPoolCreateInfo pci{};
pci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pci.queueFamilyIndex = family;
VkCommandPool pool = VK_NULL_HANDLE;
if (VkResult r = vkCreateCommandPool(device, &pci, nullptr, &pool); r != VK_SUCCESS) {
return Broken("vkCreateCommandPool", r);
}
VkCommandBufferAllocateInfo cai{};
cai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cai.commandPool = pool;
cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cai.commandBufferCount = imageCount;
std::vector<VkCommandBuffer> cmds(imageCount);
if (VkResult r = vkAllocateCommandBuffers(device, &cai, cmds.data()); r != VK_SUCCESS) {
return Broken("vkAllocateCommandBuffers", r);
}
for (uint32_t i = 0; i < imageCount; ++i) {
VkCommandBufferBeginInfo bi{};
bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vkBeginCommandBuffer(cmds[i], &bi);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = images[i];
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.layerCount = 1;
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
vkCmdPipelineBarrier(cmds[i], VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0,
nullptr, 0, nullptr, 1, &barrier);
vkEndCommandBuffer(cmds[i]);
}
VkSemaphoreCreateInfo semi{};
semi.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore acquired = VK_NULL_HANDLE;
VkSemaphore ready = VK_NULL_HANDLE;
vkCreateSemaphore(device, &semi, nullptr, &acquired);
vkCreateSemaphore(device, &semi, nullptr, &ready);
// --- the hold ---------------------------------------------------------
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(seconds) * 1000ULL;
long long presented = 0;
while (GetTickCount64() < until) {
uint32_t index = 0;
VkResult r = vkAcquireNextImageKHR(device, swapchain, 1000000000ull, acquired, VK_NULL_HANDLE, &index);
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) {
return Broken("vkAcquireNextImageKHR", r);
}
const VkPipelineStageFlags wait = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkSubmitInfo si{};
si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
si.waitSemaphoreCount = 1;
si.pWaitSemaphores = &acquired;
si.pWaitDstStageMask = &wait;
si.commandBufferCount = 1;
si.pCommandBuffers = &cmds[index];
si.signalSemaphoreCount = 1;
si.pSignalSemaphores = &ready;
if (r = vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE); r != VK_SUCCESS) {
return Broken("vkQueueSubmit", r);
}
VkPresentInfoKHR pi{};
pi.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
pi.waitSemaphoreCount = 1;
pi.pWaitSemaphores = &ready;
pi.swapchainCount = 1;
pi.pSwapchains = &swapchain;
pi.pImageIndices = &index;
r = vkQueuePresentKHR(queue, &pi);
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) {
return Broken("vkQueuePresentKHR", r);
}
++presented;
vkQueueWaitIdle(queue); // simplest correct pacing: no fences to juggle in a fixture
if (presentIntervalMs > 0) {
Sleep(static_cast<DWORD>(presentIntervalMs));
}
}
vkDeviceWaitIdle(device);
// The count goes to stdout so a test can compare it against records drained
// from the ring rather than asserting "more than zero".
std::printf(" presented=%lld\n", presented);
std::fflush(stdout);
// Objects are left for process exit: this is a fixture that ends here, and a
// teardown that itself could fail would only add exit codes to a test.
return 0;
}
@@ -199,6 +199,42 @@ public sealed class CaptureLoopLaunchTests : IDisposable
}
}
[Fact]
public async Task AVulkanLayeredVerdictIsNeitherAllowNorRefusalAndTheLoopAttachesToTheLayersRing()
{
// P1 item 3: the guard passed, injected nothing, and the ring is the layer's -- so the loop goes
// on to attach exactly as it would after an injection, carrying the verdict for the report.
var guard = new WaitingGuard
{
Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.TargetIsVulkanLayered, string.Empty, "vulkan-1 only"),
};
int attachCalls = 0;
var loop = new CaptureLoop(await StoreAsync(consented: true), new HookedCaptureGate(guard), guard,
new NeverResolves(), _ => new NoLiveness(),
_ =>
{
attachCalls++;
return (null, ShmAttachRefusal.BuildIdMismatch);
},
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromMilliseconds(20),
MaxDuration = TimeSpan.FromMilliseconds(50),
LaunchWaitBudget = TimeSpan.FromSeconds(42),
},
launcher: (_, _) => (_pid, new NoLiveness()));
CaptureResult r = await loop.RunLaunchedAsync(_exe, Fingerprint, "payload.dll", string.Empty,
TestContext.Current.CancellationToken);
attachCalls.Should().BeGreaterThan(0, "a layered target is attached to, not refused");
r.Reason.Should().Be(SessionEndReason.AttachRefused, "this fixture has no ring");
r.Verdict.Reason.Should().Be(AntiCheatRefusalReason.TargetIsVulkanLayered);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task ALoopBuiltWithoutALauncherCannotLaunch()
{
@@ -274,6 +274,47 @@ public sealed class CaptureHostEndToEndTests : IDisposable
host.ExitCode.Should().Be(0, stdout);
}
[Fact]
public async Task LaunchModeOnAVulkanTargetAttachesToTheLayersRingAndInjectsNothing()
{
// P1 item 3, from OUTSIDE the process: the host launches the harness in its Vulkan mode with the
// layer's environment, the guard passes and injects nothing (TargetIsVulkanLayered), and the
// records come from the layer's ring. Skipped honestly where there is no Vulkan loader or no
// presentable device -- the harness says so with exit 77, which the session reports as
// LaunchTargetExited before any ring existed.
if (!File.Exists(Path.Combine(Environment.SystemDirectory, "vulkan-1.dll")))
{
Assert.Skip("no Vulkan loader on this machine");
}
var store = new FileGameConsentStore(HostConsentFile);
ExecutableFingerprint fingerprint = FrameLedger.Infrastructure.Io.ExecutableIdentity.Read(ConsentedExecutable)!.Value;
(await store.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
{
Fingerprint = fingerprint,
DisclosureVersion = OperatorDisclosure.Version,
AcknowledgedAt = DateTimeOffset.UtcNow,
}, TestContext.Current.CancellationToken)).Should().Be(ConsentWriteOutcome.Written);
using Process host = StartHost("launch", "--exe", ConsentedExecutable, "--args", "--vulkan --hold-presenting 8",
"--seconds", "5");
Task<string> stderrTask = host.StandardError.ReadToEndAsync(TestContext.Current.CancellationToken);
string stdout = await host.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
await host.WaitForExitAsync(TestContext.Current.CancellationToken);
stdout += "\n---- stderr ----\n" + await stderrTask + $"\n---- exit {host.ExitCode} ----\n";
if (stdout.Contains(nameof(SessionEndReason.LaunchTargetExited), StringComparison.Ordinal))
{
Assert.Skip("the harness found no presentable Vulkan device on this machine: " + stdout);
}
stdout.Should().Contain("vulkan layer: ", "the launch names the manifest it wrote and the enable-list entry");
stdout.Should().Contain("capture side: the Vulkan implicit layer", stdout);
stdout.Should().Contain("apiMask=0x8", "FL_API_VULKAN is bit 3; the ring is the layer's, not an Overlay's");
stdout.Should().NotContain("records: 0 ", stdout);
host.ExitCode.Should().Be(0, stdout);
}
[Fact]
public async Task WhenTheTargetExitsTheHostStopsAndSaysWhy()
{
@@ -0,0 +1,94 @@
using System.Text.Json;
using FluentAssertions;
using FrameLedger.Infrastructure.Vulkan;
namespace FrameLedger.Infrastructure.Tests.Vulkan;
public sealed class VkLayerLaunchEnvironmentTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-vklayer-" + Guid.NewGuid().ToString("N"));
private readonly string _dll;
public VkLayerLaunchEnvironmentTests()
{
Directory.CreateDirectory(_dir);
_dll = Path.Combine(_dir, "FrameLedger.VkLayer.dll");
File.WriteAllBytes(_dll, [0x4D, 0x5A]);
}
public void Dispose()
{
try
{
Directory.Delete(_dir, recursive: true);
}
catch (IOException)
{
}
}
private string LayerDir => Path.Combine(_dir, "vklayer");
[Fact]
public void PrepareWritesTheManifestTheEnableListEntryAndTheTwoVariables()
{
using var env = VkLayerLaunchEnvironment.Prepare(@"D:\Games\Title\Game.exe", _dll, LayerDir);
env.ImageName.Should().Be("game.exe", "the enable-list holds lowercased image names");
env.Variables.Should().Contain(VkLayerLaunchEnvironment.EnableVariable, "1");
env.Variables.Should().Contain(VkLayerLaunchEnvironment.ImplicitLayerPathVariable, LayerDir);
File.ReadAllText(env.EnableListPath).Should().Contain("game.exe");
env.ManifestPath.Should().NotBeNull();
using JsonDocument manifest = JsonDocument.Parse(File.ReadAllText(env.ManifestPath!));
JsonElement layer = manifest.RootElement.GetProperty("layer");
layer.GetProperty("name").GetString().Should().Be(VkLayerLaunchEnvironment.LayerName);
layer.GetProperty("library_path").GetString().Should().Be(Path.GetFullPath(_dll));
layer.GetProperty("enable_environment").GetProperty(VkLayerLaunchEnvironment.EnableVariable).GetString()
.Should().Be("1", "the loader compares the VALUE, so the manifest must say what the host sets");
}
[Fact]
public void DisposeRemovesExactlyWhatPrepareAddedAndNothingElse()
{
Directory.CreateDirectory(LayerDir);
string enableList = Path.Combine(LayerDir, "enabled.txt");
File.WriteAllText(enableList, "# somebody's list\nother.exe\n");
string manifest;
using (var env = VkLayerLaunchEnvironment.Prepare(@"D:\Games\Title\Game.exe", _dll, LayerDir))
{
manifest = env.ManifestPath!;
File.ReadAllLines(enableList).Should().Contain("game.exe").And.Contain("other.exe");
}
File.ReadAllLines(enableList).Should().NotContain("game.exe").And.Contain("other.exe").And.Contain("# somebody's list");
File.Exists(manifest).Should().BeFalse();
}
[Fact]
public void AnEntrySomebodyElseWroteIsNeitherDuplicatedNorRemoved()
{
Directory.CreateDirectory(LayerDir);
string enableList = Path.Combine(LayerDir, "enabled.txt");
File.WriteAllText(enableList, "GAME.EXE\n");
using (VkLayerLaunchEnvironment.Prepare(@"D:\Games\Title\Game.exe", _dll, LayerDir))
{
File.ReadAllLines(enableList).Should().ContainSingle("the existing entry matches case-insensitively");
}
File.ReadAllLines(enableList).Should().ContainSingle().Which.Should().Be("GAME.EXE");
}
[Fact]
public void WithoutAStagedLayerNothingIsWrittenAndNoVariableIsSet()
{
using var env = VkLayerLaunchEnvironment.Prepare(@"D:\Games\Title\Game.exe", Path.Combine(_dir, "missing.dll"), LayerDir);
env.Variables.Should().BeEmpty("a manifest pointing at nothing would only make the loader log an error into the game");
env.ManifestPath.Should().BeNull();
Directory.Exists(LayerDir).Should().BeFalse();
}
}