Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5.5 ad3dead20c feat(overlay): shared-memory region 4 - the presenting swap chain's exclusive state, window and back buffer, polled twice a second (layout 4, beta.10)
The owner asked for the game's window size and display mode (exclusive fullscreen / borderless / windowed) and the share of
a session each took. Two of the facts that decide it only the process knows: whether the swap chain is in exclusive
fullscreen, and which window it presents to. This change publishes them; the Agent's window geometry, the classification,
the storage and the App follow in the next PR of the train.

- fl_shm.h layout 4: FlDisplayState, a 64-byte region at 0xC0 (the ring moved to 0x100; FlWriterState had no slack left).
  A seqlock the writer never waits on: a presenting thread that finds it taken skips the sample. DXGI_SWAP_EFFECT is
  stored plus one (DISCARD is 0, the vendor-zero trap).
- Overlay: the present hook asks GetFullscreenState(&fs, nullptr) and GetDesc at most every 500 ms per chain - getters
  on the chain the title passed, the same object FindOrAdd already described (CLAUDE.md rule 4); the chain with the
  largest back buffer is described, and one silent for 2 s gives way. SetFullscreenState stays unhooked on purpose: DXGI
  leaves exclusive fullscreen by itself (focus loss, Alt+Enter) without the title calling it. The periodic GetDesc also
  refreshes every record's output size, closing the unhooked ResizeBuffers1 hole on D3D12. OpenGL publishes the window
  and client size it already read, with no exclusive bits.
- Managed: ShmLayout mirror + FlDisplayFlags; ShmRingReader.DisplayState takes a consistent copy (eight attempts, a full
  fence between copy and re-check); ICaptureSink/ShmCaptureSink expose it. Nothing consumes it yet.
- Tests: hook-harness --hold-presenting-hwnd (the first DXGI fixture with a window); fl_guard "[display]" checks the region
  names the harness's own window, its back buffer, windowed and a second sample; the OpenGL case checks its region; the
  mirror test covers the region and now fails a struct the dump emits but nothing mirrors.
- Overhead (hook-harness --probe-frames, 3 runs, WARP): GetFullscreenState 12.6-13.1 ns/call, GetDesc 13.6-14.5 ns/call,
  paid at most twice a second per chain - under 1 ns per present at 60 fps, plus one QPC comparison per present.
- Docs: 07_IPC (layout 4 + region 4; the FlWriterState block showed reserved[5] where the header had none), 17_HOOK_ENGINE
  (SetFullscreenState row: polled, not hooked), 15_ROADMAP, 11_UPDATER (pre-1.0 practice for the MAJOR rule).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 22:20:28 +07:00
19 changed files with 701 additions and 23 deletions

No files matched your search

+13
View File
@@ -38,6 +38,16 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
whole, once per version of the file (up to 7.5 s on a USB drive for Black Myth: Wukong), and the scan stops if the Agent
is asked to. Rules `2026.09.6`: every game is re-detected once. Schema 0015 adds `games.engine_version_source`.
### Changed
- **Groundwork for the display mode (beta.10): the injected component reports how the game presents** — whether its swap
chain is in exclusive fullscreen, which window it presents to, its back buffer and swap effect — at most twice a second,
from two getters on the swap chain the game passed (measured at 13–15 ns each on the test fixture: nothing a frame rate
can see). The shared-memory layout moves to version 4 (a new region; the frame ring moved behind it): **a game that is
running while FrameLedger is updated must be restarted before it can be measured**, which the app already says when it
meets an old layout. Nothing is shown yet — the window's size, the mode and its share of a session arrive in the next
change of this train.
### Fixed
- **An Unreal game's engine version was a bare "4" or "5"** — and for most titles nothing at all. The rule's pattern had two
@@ -45,6 +55,9 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
Schema 0015 removes the digits the old rule wrote (only where detection wrote them — a version you typed stays), and the
rules validator now refuses any version pattern that does not compile or that captures anything but exactly one group.
- **A Direct3D 12 game that resized through `ResizeBuffers1` kept its old output size in every later frame.** That call is
not hooked; the swap chain's size is now re-read twice a second, so a resize by either route is seen.
## [0.1.0-beta.9] - 2026-09-26
**The ninth pre-release: one narrow exception you can make yourself for a game whose only anti-cheat runs in user
+45 -4
View File
@@ -12,13 +12,15 @@ Three channels, each chosen for its constraints:
Created by the Overlay on init, opened by the Agent. Name is deliberately plain and identifiable (`19_SAFETY` — no obfuscated object names).
Layout — **four regions, each exactly one 64-byte cache line before the ring**:
Layout — **~~four~~ five regions, each exactly one 64-byte cache line before the ring** (layout 4 since
2026-09-27, beta.10: region 4 is new and the ring moved from `0xC0` to `0x100`):
```
[0x0000] FlShmHandshake 64 B write-once by the Overlay at init
[0x0040] FlWriterState 64 B Overlay-written (writeIndex touched every present)
[0x0080] FlControlBlock 64 B Agent-written
[0x00C0] FlFrameRecord[capacity] (64 B each, power-of-two capacity)
[0x00C0] FlDisplayState 64 B Overlay-written, at most every 500 ms per chain (layout 4)
[0x0100] FlFrameRecord[capacity] (64 B each, power-of-two capacity)
```
The header is split in two on purpose. The immutable handshake and the
@@ -49,9 +51,19 @@ struct alignas(64) FlWriterState { // Overlay-written
uint32_t rtStateObjectsCreated; // @32 session count, published at 1 Hz
uint32_t rasterPsoCreated; // @36 session count, published at 1 Hz
uint32_t runtimeCensus; // @40 FlRuntimeCensus bits; watchdog-published, OR-only (2026-09-03, took reserved[0])
uint32_t reserved[5]; // @44..63 must be zero; reserved for additive fields
uint32_t slTagCensus; // @44 FlSlTagType bits per route (2026-09-05)
uint32_t dxgiPresentsUnseen; // @48 presents DXGI counted beyond the hooked ones (2026-09-05, saturating)
uint32_t dxgiPresentSamples; // @52 hooked presents on which that counter was read
uint16_t loaderSignals; // @56 the LoadLibrary detour's installed bit + wake count (2026-09-06)
uint16_t earlyStopFamily; // @58 1-based floor family index of an early stop; 0 = none (2026-09-06)
uint32_t dxgiPresentsBeforeHook; // @60 presents before the first hooked one (2026-09-06) -- the LAST word:
// no slack left, so layout 4 added a region rather than a field
};
> **This block showed `reserved[5]` at @44 until 2026-09-27** — five words the header had spent by 2026-09-06
> (`slTagCensus`, the two DXGI counters, the loader words, `dxgiPresentsBeforeHook`). `fl_shm.h` is normative and the
> mirror test reads the header, so nothing broke; a reader of this page was told there was room where there was none.
struct alignas(64) FlControlBlock { // Agent-written
uint32_t pauseRequested; // @0
uint32_t unhookRequested; // @4 19_SAFETY: set when the guard fires mid-session
@@ -61,12 +73,41 @@ struct alignas(64) FlControlBlock { // Agent-written
uint32_t reserved[11]; // @20..63 must be zero
};
struct alignas(64) FlDisplayState { // Overlay-written (layout 4, 2026-09-27, beta.10)
uint32_t seq; // @0 seqlock: odd while a writer is inside; the writer CASes and SKIPS if taken
uint32_t flags; // @4 FlDisplayFlags: SAMPLED | EXCLUSIVE_KNOWN | EXCLUSIVE | OPENGL
uint64_t hwnd; // @8 OutputWindow (DXGI) or WindowFromDC (OpenGL); 0 = a composition chain
uint32_t bufferWidth; // @16 the back buffer (DXGI) / client area (OpenGL)
uint32_t bufferHeight; // @20
uint32_t swapEffect; // @24 DXGI_SWAP_EFFECT + 1 (DISCARD is 0); 0 = not read
uint32_t swapFlags; // @28 DXGI_SWAP_CHAIN_DESC.Flags
uint32_t chainId; // @32 the FlFrameRecord.swapchainId described
uint32_t samples; // @36 samples published (wraps)
uint64_t sampleQpc; // @40 QPC of the last sample
uint32_t reserved[4]; // @48..63 must be zero
};
static_assert(sizeof(FlShmHandshake) == 64);
static_assert(sizeof(FlWriterState) == 64);
static_assert(sizeof(FlControlBlock) == 64);
static_assert(FL_SHM_RING_OFFSET == 0xC0 && FL_SHM_RING_OFFSET % 64 == 0);
static_assert(sizeof(FlDisplayState) == 64);
static_assert(FL_SHM_DISPLAY_OFFSET == 0xC0 && FL_SHM_RING_OFFSET == 0x100 && FL_SHM_RING_OFFSET % 64 == 0);
```
**Region 4 — the presenting swap chain's display facts (layout 4, 2026-09-27, beta.10).** The owner asked for the game's
window size and display mode (exclusive fullscreen / borderless / windowed) and the share of a session each took. The two
facts only the process knows — whether the chain is in exclusive fullscreen, and which window it presents to — are
getters on the chain the title passed to the hooked Present (`GetFullscreenState`, `GetDesc`), asked at most every 500 ms
per chain; everything else — the window's rectangle and style, its monitor, the classification — is the Agent's, read
out of process with user32 at the drain tick, exactly as the foreground sample is (`03_METRICS` §Display mode). The
region describes ONE chain: the largest back buffer, and a chain silent for 2 s gives way; `chainId` names it. It is a
seqlock the writer never waits on — a writer that finds `seq` odd (another presenting thread inside) skips the sample and
the next present retries — and `ShmRingReader.DisplayState` takes a copy between two reads of an even, unchanged `seq`
(eight attempts, then null for that tick). The Vulkan layer never writes it (all zeros: nothing sampled); an OpenGL stream
writes the window and client size with no exclusive bits, which a reader treats as *unknown*, never as *windowed*. A
minimised game presents only `DXGI_PRESENT_TEST`, which the hook drops before sampling, so a `sampleQpc` older than 2 s
leaves the exclusive bits unknown.
The cross-process fields are declared as plain integers and accessed through
`std::atomic_ref` rather than as `std::atomic<T>` members. `std::atomic<T>` has
no guaranteed layout, cannot be memcpy'd, and cannot be mirrored by a C#
+5
View File
@@ -36,6 +36,11 @@ Binaries are not code-signed (project policy). Consequences and mitigations, doc
SemVer `MAJOR.MINOR.PATCH`. Tag `vX.Y.Z` triggers the release workflow (13_CI_CD). `MAJOR` bumps for DB schema or IPC protocol breaks; migrations must cover every released `MAJOR-1` version.
> **Under `0.x` this rule is not applied, and every pre-release says so by shipping one anyway** (SemVer §4: a major version
> zero is initial development). Schemas 0008–0015 and the shared-memory layout 4 (2026-09-27, beta.10) each shipped in a
> `0.1.0-beta.N`. What protects a user is not the number: the ledger migrates in place (`06_DATA_MODEL` §Migrations), and a
> layout mismatch is refused at attach with "restart the game" (`07_IPC` §Protocol rules). The rule applies from `1.0.0`.
## Built 2026-09-14 (P4 PR-5) — what exists, and where it deviates from the above
`src/FrameLedger.App/Update/`. Velopack 1.2.0 (`Directory.Packages.props`, pinned since P0, referenced since
+1 -1
View File
@@ -298,7 +298,7 @@ Findings written to `docs/spike-notes.md`. Nothing in P1 starts until the exit c
> `logs\overlay-<pid>-*.log` (init / Agent request / stop), `opengl32!wglSwapBuffers` with the harness's
> `--opengl` mode. **D3D9 is not built and will not be**: `20_OPEN_QUESTIONS` §Scope decisions rules it out
> of v1 (the Overlay is x64-only and those titles are 32-bit); listing it here was the roadmap's, not the
> scope's. What P1 still leaves ⏳ in `17_HOOK_ENGINE` §Hook inventory: `SetFullscreenState`,
> scope's. What P1 still leaves ⏳ in `17_HOOK_ENGINE` §Hook inventory: ~~`SetFullscreenState`~~ (polled instead, 2026-09-27),
> `SetColorSpace1`, `CreateSwapChain*`, `ID3D12Device5::CreateStateObject`, the Vulkan RT / pipeline entries,
> §Pipeline and §Memory/latency — feature rows, each with its own measurement question, not P1's core. P2
> (the Agent, the recorder, SQLite) is next per this file.
+2 -2
View File
@@ -143,7 +143,7 @@ Every hook must be listed here with a purpose. Anything not on this list is not
> Reset is load-bearing — and no vendor symbol is resolved by name, so `FL_HOOK_INVENTORY`
> and `hookinventory-check` do not cover them at all.
> **Every other row below is unwritten**, including
> `SetFullscreenState`, `SetColorSpace1`, `CreateSwapChain*`, ~~`wglSwapBuffers`~~ (built 2026-09-06, #141, its row below),
> ~~`SetFullscreenState`~~ (polled instead since 2026-09-27, its row below), `SetColorSpace1`, `CreateSwapChain*`, ~~`wglSwapBuffers`~~ (built 2026-09-06, #141, its row below),
> `ID3D12Device5::CreateStateObject`, §Pipeline and §Memory/latency.
>
> Stated here because the distinction is invisible from the table. What a writer may then
@@ -179,7 +179,7 @@ Every hook must be listed here with a purpose. Anything not on this list is not
|---|---|
| ✅ `IDXGISwapChain::Present`, `Present1` | Frame boundary, QPC, sync interval, present flags. **`DXGI_PRESENT_TEST` calls are dropped without a record** — the occlusion probe submits nothing, and a minimised game emits a stream of them (`07_IPC` §Protocol rules). **Since 2026-09-05 the hook also reads `IDXGISwapChain::GetLastPresentCount` on the chain it just saw** (rule 4: the same COM object `FindOrAdd` already calls `GetDesc` on, no new hook) and publishes `dxgiPresentSamples` / `dxgiPresentsUnseen` — DXGI's count of presents on that chain that this hook never saw, the in-process half of `20_OPEN_QUESTIONS` §H5 Leg 1. One virtual call per hooked present, costed by `hook-harness --probe-frames`. **And per record since the same night: `dxgiUnseen` @52 under `FL_MEASURED_DXGI_PRESENTS`**, so the consumer's window counts `Displayed = hooked + unseen` per bucket (`03_METRICS` §Displayed may be DXGI-COUNTED) — measured 2.90 / 2.95 on DL:TB at Streamline 2.8.0, 0 on 2.7.3 and 2.10.3. **And since 2026-09-06 (P1 item 2) the same read, at the FIRST hooked present on the first hooked chain, is published once as `FlWriterState.dxgiPresentsBeforeHook` @60** — DXGI's count of presents that ran before the hook was in, launch mode's cost meter (`20_OPEN_QUESTIONS` §S1); 0xFFFFFFFF until a present is seen, set before the present hooks go in. **Corrected 2026-09-14 (`fl_dxgi_count.h`, ctest `fl_dxgi_count`):** a reading that went *backwards* — a chain released and re-created at the same address inherits the slot's old count — used to wrap `now − previous` to ~4e9, saturate the record byte at 255 (the `DxgiSaturated` refusal) and add the wrap to the session total: the owner's ledger held `dxgi_unseen_total = 4294967243`. A regression is now a reset (no delta claimed, nothing added, the slot re-armed) and the total saturates at `UINT32_MAX` rather than wrapping. Cost: one compare on the same virtual call; measured per `14_TESTING` §Hook overhead in the PR |
| ✅ `IDXGISwapChain::ResizeBuffers` · ⏳ `ResizeTarget` | Output resolution changes mid-session. `ResizeBuffers` re-reads the swapchain description *after* the original returns; `ResizeTarget` is not hooked |
| ⏳ `IDXGISwapChain::SetFullscreenState` | Fullscreen ↔ borderless transitions |
| ~~⏳ `IDXGISwapChain::SetFullscreenState`~~ **not hooked — polled (2026-09-27, beta.10)** | ~~Fullscreen ↔ borderless transitions~~ **Region 4, `FlDisplayState` (`07_IPC`, layout 4).** DXGI leaves exclusive fullscreen by itself — focus lost, Alt+Enter inside its own window hook — without the title calling this method, so a hook would miss exactly the transitions a mode share must count. Instead the present hook asks, **at most every 500 ms per chain**, two getters on the chain the title passed: `GetFullscreenState(&fs, nullptr)` (no `IDXGIOutput` taken) and `GetDesc` (the window, the back buffer, the swap effect). Rule 4: the same object `FindOrAdd` already calls `GetDesc` on and the counter reads — no new hook, no read beyond it; the window's geometry and the classification are the Agent's, out of process. `GetDesc` again also refreshes the size every record carries, which closes `IDXGISwapChain3::ResizeBuffers1` (unhooked: a D3D12 title resizing through it kept its old size until now). Published through a seqlock the writer never waits on (a taken lock skips the sample). OpenGL publishes the window and client size `ReadGlSize` already holds, with no exclusive bits. Cost per `14_TESTING` §Hook overhead in the PR |
| ⏳ `IDXGISwapChain3::SetColorSpace1` | HDR output detection. **`IDXGISwapChain3`, not 4** — 4 adds only `SetHDRMetaData` (`20_OPEN_QUESTIONS` §H9 — *answered and removed with H1/H3/H4 in the P0 spike (`6b1fa83`); this row used to say `IDXGISwapChain4`, and the corrected interface here IS the answer, so the citation points at history rather than at a live entry*). 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` (2026-09-06, P1 item 4) | OpenGL titles: one record per `opengl32!wglSwapBuffers`, `api` = OpenGL, the output size from `GetClientRect` on the window the HDC belongs to (first sighting and every 256th present, so a resize is caught without a second hook), **no `FL_MEASURED_PRESENT_ARGS`** — the call has no sync interval and no flags. A MinHook inline patch on the flat export (measured 2026-08-05: a `jmp` thunk into the vendor ICD, relocated like any first instruction), installed at init when `opengl32.dll` is already mapped and lazily on the watchdog otherwise, with the `LoadLibrary` detour waking it for `opengl32.dll`. Exercised by `hook-harness --opengl --hold-presenting N`, which calls **gdi32's `SwapBuffers`** the way a title does — measured to reach the hook (ctest `fl_guard` `[opengl]`, on Microsoft's generic renderer, so it runs on CI too). The one system-module row below carries the inventory asymmetry |
@@ -20,6 +20,12 @@ public interface ICaptureSink : IDisposable
FlShmHandshake Handshake { get; }
/// <summary>
/// Region 4 (layout 4, beta.10): the presenting swap chain as DXGI describes it, a consistent copy — or null when the
/// Overlay was writing it on every attempt this tick. A Vulkan title's ring (the layer never writes it) reads all zeros.
/// </summary>
FlDisplayState? DisplayState { get; }
long TotalDropped { get; }
long TotalGaps { get; }
@@ -13,6 +13,8 @@ public sealed class ShmCaptureSink(ShmRingReader reader) : ICaptureSink
public FlShmHandshake Handshake => _reader.Handshake;
public FlDisplayState? DisplayState => _reader.DisplayState;
public long TotalDropped => _reader.TotalDropped;
public long TotalGaps => _reader.TotalGaps;
@@ -188,6 +188,40 @@ public sealed unsafe class ShmRingReader : IDisposable
/// <summary>Region 1, read fresh.</summary>
public FlShmHandshake Handshake => *(FlShmHandshake*)(_base + ShmLayout.HandshakeOffset);
/// <summary>How many times <see cref="DisplayState"/> re-reads a region a writer was inside before giving up for this tick.</summary>
public const int DisplayStateAttempts = 8;
/// <summary>
/// Region 4 (layout 4, beta.10), a consistent copy — or null when the Overlay was inside it on every one of
/// <see cref="DisplayStateAttempts"/> reads (the next tick asks again). A copy is taken between two reads of an even,
/// unchanged <see cref="FlDisplayState.Seq"/>; the full fence between the copy and the second read keeps the copy's loads
/// from moving past it, which acquire alone would not.
/// </summary>
public FlDisplayState? DisplayState
{
get
{
var region = (FlDisplayState*)(_base + ShmLayout.DisplayOffset);
for (int attempt = 0; attempt < DisplayStateAttempts; attempt++)
{
uint before = Volatile.Read(ref region->Seq);
if ((before & 1u) != 0u)
{
continue;
}
FlDisplayState copy = *region;
Interlocked.MemoryBarrier();
if (Volatile.Read(ref region->Seq) == before)
{
return copy;
}
}
return null;
}
}
/// <summary>
/// Copies up to <paramref name="into"/>.Length records. <paramref name="gapIndices"/> receives the
/// ring index of each torn slot, so the caller can record a gap rather than a missing frame.
+71 -3
View File
@@ -34,12 +34,16 @@ public static class ShmLayout
/// user to restart the game — the DLL lives inside a running process, so the two sides cannot be
/// assumed to update in lockstep.
/// </summary>
public const uint LayoutVersion = 3u;
public const uint LayoutVersion = 4u;
public const uint HandshakeOffset = 0x00u;
public const uint WriterOffset = 0x40u;
public const uint ControlOffset = 0x80u;
public const uint RingOffset = 0xC0u;
/// <summary>Region 4, <see cref="FlDisplayState"/> (layout 4, beta.10): the ring moved from 0xC0 to make room for it.</summary>
public const uint DisplayOffset = 0xC0u;
public const uint RingOffset = 0x100u;
/// <summary>8192 × 64 B = 512 KiB, ≈16 s at 500 fps.</summary>
public const uint DefaultCapacity = 8192u;
@@ -635,7 +639,71 @@ public unsafe struct FlControlBlock
public fixed uint Reserved[11];
}
/// <summary>Region 4 — the ring. Exactly 64 bytes, no implicit padding.</summary>
/// <summary><see cref="FlDisplayState.Flags"/> bits (layout 4, beta.10). A reader ignores a bit it does not know.</summary>
[Flags]
public enum FlDisplayFlags : uint
{
None = 0,
/// <summary>At least one chain has been described.</summary>
Sampled = 1u << 0,
/// <summary><c>GetFullscreenState</c> answered on the described chain (DXGI only).</summary>
ExclusiveKnown = 1u << 1,
/// <summary>...and said exclusive fullscreen. Meaningless without <see cref="ExclusiveKnown"/>.</summary>
Exclusive = 1u << 2,
/// <summary>Described from <c>wglSwapBuffers</c>' HDC: OpenGL has no exclusive state to ask.</summary>
OpenGl = 1u << 3,
}
/// <summary>
/// Region 4 — Overlay-written, at most every 500 ms per chain (layout 4, 2026-09-27, beta.10): the presenting swap chain as
/// DXGI describes it — whether it is in exclusive fullscreen, the window it presents to, its back buffer and swap effect.
/// The window's geometry and the display mode are the Agent's, read out of process (<c>03_METRICS</c> §Display mode).
/// </summary>
/// <remarks>
/// <b>A seqlock the writer never waits on.</b> <see cref="Seq"/> is odd while a writer is inside; a copy taken between two
/// reads of an even, unchanged value is consistent (<c>ShmRingReader.DisplayState</c>). A stale <see cref="SampleQpc"/> is not
/// "still exclusive": a minimised game issues only <c>DXGI_PRESENT_TEST</c>, which the hook drops before it samples.
/// </remarks>
[StructLayout(LayoutKind.Sequential, Size = 64)]
public unsafe struct FlDisplayState
{
/// <summary>Odd while a writer is inside; +2 per sample.</summary>
public uint Seq;
public FlDisplayFlags Flags;
/// <summary><c>OutputWindow</c> (DXGI) or <c>WindowFromDC</c> (OpenGL); 0 = none (a composition chain).</summary>
public ulong Hwnd;
/// <summary>The back buffer (DXGI) or the client area (OpenGL).</summary>
public uint BufferWidth;
public uint BufferHeight;
/// <summary><c>DXGI_SWAP_EFFECT</c> PLUS ONE — <c>DISCARD</c> is 0, the vendor-zero trap; 0 = not read.</summary>
public uint SwapEffect;
/// <summary><c>DXGI_SWAP_CHAIN_DESC.Flags</c>.</summary>
public uint SwapFlags;
/// <summary>The <see cref="FlFrameRecord.SwapchainId"/> of the chain described.</summary>
public uint ChainId;
/// <summary>Samples published (wraps).</summary>
public uint Samples;
/// <summary>QueryPerformanceCounter at the last sample.</summary>
public ulong SampleQpc;
/// <summary>Must be zero.</summary>
public fixed uint Reserved[4];
}
/// <summary>Region 5 — the ring. Exactly 64 bytes, no implicit padding.</summary>
[StructLayout(LayoutKind.Sequential, Size = 64)]
public unsafe struct FlFrameRecord
{
+136 -4
View File
@@ -406,8 +406,77 @@ struct SwapChainSlot {
bool haveDxgiCount = false;
uint32_t lastDxgiCount = 0;
uint32_t dxgiEpoch = 0; // g_dxgiEpoch when lastDxgiCount was read; a mismatch means presents went by unrecorded
// Layout 4 (beta.10): what region 4 says about this chain, from the same GetDesc as outW/outH.
uint64_t hwnd = 0; // DXGI_SWAP_CHAIN_DESC.OutputWindow; 0 for a composition chain
uint32_t swapEffect = 0; // DXGI_SWAP_EFFECT + 1 (fl_shm.h §Region 4: DISCARD is 0); 0 = not read
uint32_t swapFlags = 0; // DXGI_SWAP_CHAIN_DESC.Flags
uint64_t displayQpc = 0; // the QPC of this chain's last display sample
};
// Region 4 (fl_shm.h, layout 4, beta.10): set in InitThread beside g_state, written only through PublishDisplay.
FlDisplayState* g_display = nullptr;
// Which chain region 4 describes: the largest back buffer, and one silent for 2 s gives way (fl_shm.h §Region 4).
std::atomic<uint32_t> g_displayChain{0};
std::atomic<uint64_t> g_displayArea{0};
std::atomic<uint64_t> g_displayChainQpc{0};
// The seqlock writer (fl_shm.h §Region 4). It takes the lock by compare-exchange from an even `seq` and, when another
// presenting thread holds it, gives up this sample -- the next present retries -- so nothing here ever waits. Every
// field goes through std::atomic_ref, so a reader's torn copy is defined behaviour that the second `seq` read throws
// away.
void PublishDisplay(uint32_t flags, uint64_t hwnd, uint32_t width, uint32_t height, uint32_t swapEffect,
uint32_t swapFlags, uint32_t chainId, uint64_t qpc) noexcept {
if (g_display == nullptr) {
return;
}
std::atomic_ref<uint32_t> seq{g_display->seq};
uint32_t even = seq.load(std::memory_order_relaxed);
if ((even & 1u) != 0u ||
!seq.compare_exchange_strong(even, even + 1u, std::memory_order_acquire, std::memory_order_relaxed)) {
return;
}
std::atomic_ref<uint32_t>{g_display->flags}.store(flags, std::memory_order_relaxed);
std::atomic_ref<uint64_t>{g_display->hwnd}.store(hwnd, std::memory_order_relaxed);
std::atomic_ref<uint32_t>{g_display->bufferWidth}.store(width, std::memory_order_relaxed);
std::atomic_ref<uint32_t>{g_display->bufferHeight}.store(height, std::memory_order_relaxed);
std::atomic_ref<uint32_t>{g_display->swapEffect}.store(swapEffect, std::memory_order_relaxed);
std::atomic_ref<uint32_t>{g_display->swapFlags}.store(swapFlags, std::memory_order_relaxed);
std::atomic_ref<uint32_t>{g_display->chainId}.store(chainId, std::memory_order_relaxed);
std::atomic_ref<uint64_t>{g_display->sampleQpc}.store(qpc, std::memory_order_relaxed);
std::atomic_ref<uint32_t> samples{g_display->samples};
samples.store(samples.load(std::memory_order_relaxed) + 1u, std::memory_order_relaxed);
seq.store(even + 2u, std::memory_order_release);
}
// Whether chain `chainId` is the one region 4 describes, claiming it when it is larger than the current one or the
// current one has not been sampled for 2 s. A race between two presenting threads can flip the claim once; the region
// always names the chain it describes, so a reader is never told one chain's facts under another's id.
bool DescribesDisplay(uint32_t chainId, uint64_t area, uint64_t now) noexcept {
const uint32_t current = g_displayChain.load(std::memory_order_relaxed);
if (current != chainId) {
const uint64_t last = g_displayChainQpc.load(std::memory_order_relaxed);
const uint64_t silence = 2u * g_logQpcFreq;
const bool silent = current == 0u || (now > last && now - last > silence);
if (!silent && area <= g_displayArea.load(std::memory_order_relaxed)) {
return false;
}
g_displayChain.store(chainId, std::memory_order_relaxed);
}
g_displayArea.store(area, std::memory_order_relaxed);
g_displayChainQpc.store(now, std::memory_order_relaxed);
return true;
}
// What FindOrAdd and ForgetChainSize keep from one GetDesc: the size every record carries, and region 4's facts.
void RememberDesc(SwapChainSlot& s, const DXGI_SWAP_CHAIN_DESC& desc) noexcept {
s.outW = static_cast<uint16_t>(desc.BufferDesc.Width);
s.outH = static_cast<uint16_t>(desc.BufferDesc.Height);
s.hwnd = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(desc.OutputWindow));
s.swapEffect = static_cast<uint32_t>(desc.SwapEffect) + 1u;
s.swapFlags = desc.Flags;
}
// Ask the device whether it can ray-trace, once, and publish it as FlRtTier.
//
// NOT A HOOK. This is a capability QUERY on a device DXGI just handed us for a
@@ -557,8 +626,7 @@ SwapChainSlot* FindOrAdd(IDXGISwapChain* sc) noexcept {
s.id = g_nextChainId++;
DXGI_SWAP_CHAIN_DESC desc{};
if (SUCCEEDED(sc->GetDesc(&desc))) {
s.outW = static_cast<uint16_t>(desc.BufferDesc.Width);
s.outH = static_cast<uint16_t>(desc.BufferDesc.Height);
RememberDesc(s, desc);
}
s.api = ResolveApi(sc);
// apiMask records what we have ACTUALLY seen present, not what the
@@ -581,14 +649,51 @@ void ForgetChainSize(IDXGISwapChain* sc) noexcept {
s.outH = 0;
DXGI_SWAP_CHAIN_DESC desc{};
if (SUCCEEDED(sc->GetDesc(&desc))) {
s.outW = static_cast<uint16_t>(desc.BufferDesc.Width);
s.outH = static_cast<uint16_t>(desc.BufferDesc.Height);
RememberDesc(s, desc);
}
return;
}
}
}
// REGION 4 FROM THE PRESENT PATH (fl_shm.h §Region 4, layout 4, beta.10), at most every 500 ms per chain: two getters
// on the swap chain the title just passed to Present -- the same object FindOrAdd calls GetDesc on and the counter
// above reads, CLAUDE.md rule 4 -- and no other read. Amortised, it is two virtual calls a second on a hook that makes
// one QPC comparison per present (costed in the PR per 14_TESTING §Hook overhead).
//
// GetDesc AGAIN, and not only for region 4: it refreshes the size every record carries, which closes the hole the
// unhooked IDXGISwapChain3::ResizeBuffers1 left -- a D3D12 title resizing through it kept its old size until now. The
// output size can therefore change between two records of one chain, which is what a resize IS; SegmentBuilder splits
// there like after any other resize (03_METRICS §Display mode).
//
// GetFullscreenState with a null output: the IDXGIOutput it would hand back is AddRef'd, and we have no use for it.
void SampleDisplay(IDXGISwapChain* sc, SwapChainSlot& slot, uint64_t now) noexcept {
const uint64_t half = g_logQpcFreq / 2u;
if (g_display == nullptr || half == 0u || (slot.displayQpc != 0u && now - slot.displayQpc < half)) {
return;
}
slot.displayQpc = now;
DXGI_SWAP_CHAIN_DESC desc{};
if (SUCCEEDED(sc->GetDesc(&desc))) {
RememberDesc(slot, desc);
}
BOOL fullscreen = FALSE;
const bool known = SUCCEEDED(sc->GetFullscreenState(&fullscreen, nullptr));
if (!DescribesDisplay(slot.id, static_cast<uint64_t>(slot.outW) * slot.outH, now)) {
return;
}
uint32_t flags = FL_DISPLAY_SAMPLED;
if (known) {
flags |= FL_DISPLAY_EXCLUSIVE_KNOWN;
if (fullscreen != FALSE) {
flags |= FL_DISPLAY_EXCLUSIVE;
}
}
PublishDisplay(flags, slot.hwnd, slot.outW, slot.outH, slot.swapEffect, slot.swapFlags, slot.id, now);
}
// adapterLuid is published at FIRST PRESENT, not at init: at init we are two
// steps before any graphics module is resolved and our dummy device's adapter is
// not the game's. 0 means "not yet known" (#36).
@@ -2374,6 +2479,7 @@ DWORD WINAPI WatchdogThread(LPVOID) noexcept {
// The hot path. One QPC read, a few cached-state reads, one 60-byte store in two
// spans, two relaxed atomic stores, two fences. No syscall, no allocation, no
// lock, no logging (NFR-1, target <= 1 us; a bare vtable detour measured 8.4 ns).
// Twice a second per chain, two getters more (SampleDisplay, layout 4, beta.10).
void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
if (!MayObserve()) {
if ((flags & DXGI_PRESENT_TEST) == 0u) {
@@ -2412,6 +2518,9 @@ void RecordPresent(IDXGISwapChain* sc, UINT syncInterval, UINT flags) noexcept {
SwapChainSlot* slot = FindOrAdd(sc);
PublishAdapterOnce(sc);
if (slot != nullptr) {
SampleDisplay(sc, *slot, static_cast<uint64_t>(qpc.QuadPart));
}
// DXGI'S OWN COUNT OF THIS CHAIN'S PRESENTS, read here on the object the title passed
// (the same class of read as GetDesc above), BEFORE this present is forwarded: the
@@ -2946,6 +3055,8 @@ struct GlSlot {
uint16_t w = 0;
uint16_t h = 0;
uint32_t presents = 0;
HWND wnd = nullptr; // the window the HDC belongs to, as ReadGlSize last found it (layout 4, beta.10)
uint64_t displayQpc = 0; // the QPC of this stream's last display sample
};
constexpr size_t kMaxGlSlots = 8;
GlSlot g_gl[kMaxGlSlots]{};
@@ -2953,12 +3064,29 @@ GlSlot g_gl[kMaxGlSlots]{};
void ReadGlSize(GlSlot& s) noexcept {
const HWND wnd = WindowFromDC(s.hdc);
RECT r{};
s.wnd = wnd;
if (wnd != nullptr && GetClientRect(wnd, &r) && r.right > 0 && r.bottom > 0) {
s.w = static_cast<uint16_t>(r.right > 0xFFFF ? 0 : r.right);
s.h = static_cast<uint16_t>(r.bottom > 0xFFFF ? 0 : r.bottom);
}
}
// Region 4 for an OpenGL stream (fl_shm.h §Region 4): the window and client size ReadGlSize already holds, and no
// exclusive bits -- OpenGL has no state to ask, which the Agent reads as "exclusivity unknown", never as "windowed".
// Nothing new is called here: the window came from WindowFromDC on the HDC the title passed.
void SampleGlDisplay(GlSlot& s, uint64_t now) noexcept {
const uint64_t half = g_logQpcFreq / 2u;
if (g_display == nullptr || half == 0u || (s.displayQpc != 0u && now - s.displayQpc < half)) {
return;
}
s.displayQpc = now;
if (!DescribesDisplay(s.id, static_cast<uint64_t>(s.w) * s.h, now)) {
return;
}
PublishDisplay(FL_DISPLAY_SAMPLED | FL_DISPLAY_OPENGL, static_cast<uint64_t>(reinterpret_cast<uintptr_t>(s.wnd)),
s.w, s.h, 0u, 0u, s.id, now);
}
GlSlot* FindOrAddGl(HDC hdc) noexcept {
for (auto& s : g_gl) {
if (s.hdc == hdc) {
@@ -2987,6 +3115,9 @@ void RecordGlPresent(HDC hdc) noexcept {
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
GlSlot* slot = FindOrAddGl(hdc);
if (slot != nullptr) {
SampleGlDisplay(*slot, static_cast<uint64_t>(qpc.QuadPart));
}
FlFrameRecord rec{};
rec.qpc = static_cast<uint64_t>(qpc.QuadPart);
@@ -3122,6 +3253,7 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
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);
g_display = reinterpret_cast<FlDisplayState*>(static_cast<unsigned char*>(g_base) + FL_SHM_DISPLAY_OFFSET);
// The supervision clock starts HERE, when the mapping is published -- not at
// first present. 07_IPC is explicit that a capture side no Agent ever adopts
// is inert from the beginning rather than enjoying a grace window.
+86 -6
View File
@@ -25,11 +25,14 @@
// [0x0000] FlShmHandshake 64 B write-once by the Overlay at init
// [0x0040] FlWriterState 64 B Overlay-written (writeIndex every present)
// [0x0080] FlControlBlock 64 B Agent-written
// [0x00C0] FlFrameRecord[capacity]
// [0x00C0] FlDisplayState 64 B Overlay-written, at most every 500 ms (layout 4, beta.10)
// [0x0100] FlFrameRecord[capacity]
//
// The three header regions are separate cache lines on purpose. The Overlay
// The header regions are separate cache lines on purpose. The Overlay
// writes region 2 every frame while the Agent writes region 3 every second;
// sharing a line would put a cross-process cache-line bounce on the hot path.
// Region 4 is its own line for the same reason: it is rewritten twice a second
// by whichever thread presents, and the Agent reads it at 10 Hz.
//
// A previous revision of the design declared a single 88-byte header while
// mapping the control block to 0x0040. In code, unhookRequested would have
@@ -51,12 +54,18 @@
// Bump whenever ANY struct below changes. The Agent refuses to attach on
// mismatch and tells the user to restart the game — the DLL lives inside a
// running process, so the two sides cannot be assumed to update in lockstep.
#define FL_SHM_LAYOUT_VERSION 3u
//
// 4 (2026-09-27, beta.10): region 4, FlDisplayState, and the ring moved from
// 0xC0 to 0x100 to make room for it. FlWriterState had no slack left
// (dxgiPresentsBeforeHook took its last word), and the display facts are not
// frame facts, so neither the writer state nor the record was the place.
#define FL_SHM_LAYOUT_VERSION 4u
#define FL_SHM_HANDSHAKE_OFFSET 0x00u
#define FL_SHM_WRITER_OFFSET 0x40u
#define FL_SHM_CONTROL_OFFSET 0x80u
#define FL_SHM_RING_OFFSET 0xC0u
#define FL_SHM_DISPLAY_OFFSET 0xC0u
#define FL_SHM_RING_OFFSET 0x100u
#define FL_SHM_DEFAULT_CAPACITY 8192u // 8192 * 64 B = 512 KiB, ~16 s at 500 fps
@@ -785,7 +794,61 @@ struct alignas(64) FlControlBlock {
};
// ---------------------------------------------------------------------------
// Region 4 — the ring. 64 bytes exactly, no implicit padding.
// Region 4 — Overlay-written: the presenting swap chain as DXGI describes it (layout 4, 2026-09-27, beta.10).
// ---------------------------------------------------------------------------
// The owner asked for the game's window size and display mode — exclusive fullscreen, borderless, windowed — and for
// how much of a session each took. Two of the three facts that decide it are only knowable INSIDE the process: whether
// the swap chain is in exclusive fullscreen (IDXGISwapChain::GetFullscreenState) and which window it presents to
// (DXGI_SWAP_CHAIN_DESC.OutputWindow). Both are getters on the object the title passed to the hooked Present -- the
// same class of read as GetDesc in FindOrAdd and GetLastPresentCount (CLAUDE.md rule 4) -- and nothing else is read
// here. The window's geometry, its monitor and the classification are the Agent's, OUT of process, with user32
// (04_CAPTURE §Ring draining), exactly as the foreground sample is.
//
// WHY NOT SetFullscreenState. 17_HOOK_ENGINE had it as a ⏳ row. DXGI leaves exclusive fullscreen on its own -- focus
// lost, Alt+Enter handled inside DXGI's window hook -- without the title calling it, so a hook would miss exactly the
// transitions a mode share has to count. A poll does not: the present hook asks at most every 500 ms per chain (QPC,
// already read there), which amortises to nothing and needs no new hook.
//
// WHICH CHAIN. One title can present several (a launcher window, a video player, a second stream -- the FG ladder's
// multiple_streams). The region describes ONE: the chain with the largest back buffer, and a chain that has not
// presented for 2 s gives way to whoever does. `chainId` says which, in FlFrameRecord.swapchainId's id space.
//
// A SEQLOCK THAT NEVER WAITS. `seq` is odd while a writer is inside. A writer takes it by compare-exchange from an even
// value and, if another presenting thread holds it, SKIPS this sample -- the next present retries -- so nothing on the
// present path ever blocks or spins. A reader takes a copy between two reads of an even, unchanged `seq`, and retries a
// bounded number of times. The fields are written through std::atomic_ref so a torn read is defined behaviour.
//
// A MINIMISED OR FULLY OCCLUDED GAME ISSUES ONLY DXGI_PRESENT_TEST, which RecordPresent drops before it samples
// anything, so a stale `sampleQpc` is not "still exclusive": the Agent treats the exclusive bits as unknown once the
// sample is older than 2 s (03_METRICS §Display mode).
// FlDisplayState.flags. Additive: a reader ignores a bit it does not know.
enum FlDisplayFlags : uint32_t {
FL_DISPLAY_SAMPLED = 1u << 0, // at least one chain has been described
FL_DISPLAY_EXCLUSIVE_KNOWN = 1u << 1, // GetFullscreenState answered on the described chain (DXGI only)
FL_DISPLAY_EXCLUSIVE = 1u << 2, // ...and said exclusive fullscreen. Meaningless without the bit above
FL_DISPLAY_OPENGL = 1u << 3, // described from wglSwapBuffers' HDC: OpenGL has no exclusive state to ask
};
struct alignas(64) FlDisplayState {
uint32_t seq; // @0 seqlock: odd while a writer is inside, +2 per sample
uint32_t flags; // @4 FlDisplayFlags
uint64_t hwnd; // @8 OutputWindow (DXGI) or WindowFromDC (OpenGL); 0 = none (a composition chain)
uint32_t bufferWidth; // @16 the back buffer (DXGI) or the client area (OpenGL)
uint32_t bufferHeight; // @20
// DXGI_SWAP_EFFECT PLUS ONE. DXGI_SWAP_EFFECT_DISCARD is 0, and storing the vendor value verbatim would say
// "discard" about every chain nobody described -- the vendor-zero trap HANDOFF records twice (rtTier,
// upscalerQuality).
uint32_t swapEffect; // @24 0 = not read
uint32_t swapFlags; // @28 DXGI_SWAP_CHAIN_DESC.Flags (ALLOW_TEARING, ...)
uint32_t chainId; // @32 the FlFrameRecord.swapchainId of the chain described
uint32_t samples; // @36 samples published (wraps); a reader tells "no new sample" from "same value"
uint64_t sampleQpc; // @40 QueryPerformanceCounter at the last sample
uint32_t reserved[4]; // @48..63 must be zero
};
// ---------------------------------------------------------------------------
// Region 5 — the ring. 64 bytes exactly, no implicit padding.
// ---------------------------------------------------------------------------
struct alignas(64) FlFrameRecord {
uint64_t qpc; // @0 present entry timestamp
@@ -1014,10 +1077,27 @@ static_assert(offsetof(FlFrameRecord, measuredMask) % 2 == 0);
static_assert(offsetof(FlFrameRecord, vramUsedMb) % 4 == 0);
static_assert(offsetof(FlFrameRecord, seq) % 4 == 0);
// Region 4 (layout 4): 64 bytes, every field where 07_IPC says, each naturally aligned for std::atomic_ref.
static_assert(sizeof(FlDisplayState) == 64);
static_assert(offsetof(FlDisplayState, seq) == 0);
static_assert(offsetof(FlDisplayState, flags) == 4);
static_assert(offsetof(FlDisplayState, hwnd) == 8);
static_assert(offsetof(FlDisplayState, bufferWidth) == 16);
static_assert(offsetof(FlDisplayState, bufferHeight) == 20);
static_assert(offsetof(FlDisplayState, swapEffect) == 24);
static_assert(offsetof(FlDisplayState, swapFlags) == 28);
static_assert(offsetof(FlDisplayState, chainId) == 32);
static_assert(offsetof(FlDisplayState, samples) == 36);
static_assert(offsetof(FlDisplayState, sampleQpc) == 40);
static_assert(offsetof(FlDisplayState, reserved) == 48);
static_assert(offsetof(FlDisplayState, hwnd) % 8 == 0 && offsetof(FlDisplayState, sampleQpc) % 8 == 0);
// The regions must not overlap, and the ring must stay 64-aligned.
static_assert(FL_SHM_HANDSHAKE_OFFSET + sizeof(FlShmHandshake) <= FL_SHM_WRITER_OFFSET);
static_assert(FL_SHM_WRITER_OFFSET + sizeof(FlWriterState) <= FL_SHM_CONTROL_OFFSET);
static_assert(FL_SHM_CONTROL_OFFSET + sizeof(FlControlBlock) <= FL_SHM_RING_OFFSET);
static_assert(FL_SHM_CONTROL_OFFSET + sizeof(FlControlBlock) <= FL_SHM_DISPLAY_OFFSET);
static_assert(FL_SHM_DISPLAY_OFFSET + sizeof(FlDisplayState) <= FL_SHM_RING_OFFSET);
static_assert(FL_SHM_DISPLAY_OFFSET % 64 == 0);
static_assert(FL_SHM_RING_OFFSET % 64 == 0);
constexpr size_t FlShmSizeForCapacity(uint32_t capacity) noexcept {
+101
View File
@@ -1335,6 +1335,8 @@ TEST_CASE(
#include <windows.h>
#include <dxgi.h> // DXGI_SWAP_EFFECT, for region 4's swapEffect (layout 4, beta.10)
#include <psapi.h>
// The shared-memory contract the injected Overlay publishes. Included here rather
@@ -1901,6 +1903,7 @@ struct MappedRing {
void* base = nullptr;
fl::FlWriterState* st = nullptr;
fl::FlControlBlock* ctl = nullptr;
fl::FlDisplayState* display = nullptr; // region 4 (layout 4, beta.10)
~MappedRing() {
if (base != nullptr) {
UnmapViewOfFile(base);
@@ -1931,12 +1934,34 @@ bool OpenRingFor(DWORD pid, MappedRing& r) {
}
r.st = reinterpret_cast<fl::FlWriterState*>(static_cast<unsigned char*>(r.base) + FL_SHM_WRITER_OFFSET);
r.ctl = reinterpret_cast<fl::FlControlBlock*>(static_cast<unsigned char*>(r.base) + FL_SHM_CONTROL_OFFSET);
r.display = reinterpret_cast<fl::FlDisplayState*>(static_cast<unsigned char*>(r.base) + FL_SHM_DISPLAY_OFFSET);
for (int i = 0; i < 100 && r.st->status != fl::FL_STATUS_READY; ++i) {
Sleep(50);
}
return r.st->status == fl::FL_STATUS_READY;
}
// A consistent copy of region 4 (fl_shm.h §Region 4), the way the Agent takes one: between two reads of an even,
// unchanged seq. Waits (bounded) for a sample newer than `afterSamples` -- the present hook samples twice a second, so
// a test that read once would race the writer the same way a test reading writer state once races InitThread.
bool ReadDisplay(const MappedRing& r, fl::FlDisplayState& out, uint32_t afterSamples = 0u) {
for (int i = 0; i < 100; ++i) {
std::atomic_ref<uint32_t> seq{r.display->seq};
const uint32_t before = seq.load(std::memory_order_acquire);
if ((before & 1u) == 0u) {
fl::FlDisplayState copy{};
std::memcpy(&copy, r.display, sizeof(copy));
std::atomic_thread_fence(std::memory_order_seq_cst);
if (seq.load(std::memory_order_acquire) == before && copy.samples > afterSamples) {
out = copy;
return true;
}
}
Sleep(50);
}
return false;
}
bool StartHarness(Child& child, const std::wstring& args) {
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" " + args;
STARTUPINFOW si{};
@@ -2439,6 +2464,82 @@ TEST_CASE("OpenGL: the injected Overlay hooks opengl32!wglSwapBuffers and record
CHECK(ring[5].qpc > ring[0].qpc);
CHECK(r.st->faultCount == 0u);
CHECK(r.st->status == fl::FL_STATUS_READY);
// Region 4 (layout 4, beta.10): the stream's window and client size, and NO exclusive bits -- OpenGL has no state
// to ask, and a reader must see "unknown", never "windowed".
fl::FlDisplayState d{};
REQUIRE(ReadDisplay(r, d));
CHECK((d.flags & fl::FL_DISPLAY_SAMPLED) != 0u);
CHECK((d.flags & fl::FL_DISPLAY_OPENGL) != 0u);
CHECK((d.flags & (fl::FL_DISPLAY_EXCLUSIVE_KNOWN | fl::FL_DISPLAY_EXCLUSIVE)) == 0u);
CHECK(d.hwnd != 0u);
CHECK(d.bufferWidth == ring[0].outputW);
CHECK(d.chainId == ring[0].swapchainId);
CHECK(d.swapEffect == 0u);
}
TEST_CASE("region 4 describes a swap chain on a real window: its window, its back buffer, windowed",
"[guard][inject][shm][display]") {
// Layout 4 (beta.10). Every other DXGI fixture presents to a composition chain, which has no window to describe;
// this one binds a D3D11 chain to a real (hidden, windowed) window. Exclusive fullscreen needs a real output and is
// the owner's measurement on real hardware -- here the claim is the one a runner can check: the swap chain SAID
// windowed.
Child child;
if (!StartHarness(child, L"--hold-presenting-hwnd 8")) {
DWORD code = 0;
GetExitCodeProcess(child.pi.hProcess, &code);
if (code == 77u) {
SKIP("the harness could not make a swap chain for a window on this machine (exit 77)");
}
FAIL("the harness died (exit " << code << ")");
}
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
REQUIRE(GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed());
MappedRing r;
REQUIRE(OpenRingFor(child.pi.dwProcessId, r));
for (int i = 0; i < 80 && r.st->writeIndex < 20; ++i) {
++r.ctl->guardTicks;
Sleep(50);
}
REQUIRE(r.st->writeIndex >= 20u);
const auto* ring =
reinterpret_cast<const fl::FlFrameRecord*>(static_cast<unsigned char*>(r.base) + FL_SHM_RING_OFFSET);
fl::FlDisplayState first{};
REQUIRE(ReadDisplay(r, first));
++r.ctl->guardTicks;
fl::FlDisplayState d{};
REQUIRE(ReadDisplay(r, d, first.samples)); // a SECOND sample: the hook keeps asking, twice a second
INFO("flags 0x" << std::hex << d.flags << std::dec << " hwnd " << d.hwnd << " " << d.bufferWidth << "x"
<< d.bufferHeight << " effect " << d.swapEffect << " samples " << d.samples);
CHECK((d.flags & fl::FL_DISPLAY_SAMPLED) != 0u);
CHECK((d.flags & fl::FL_DISPLAY_EXCLUSIVE_KNOWN) != 0u); // GetFullscreenState answered...
CHECK((d.flags & fl::FL_DISPLAY_EXCLUSIVE) == 0u); // ...and said windowed
CHECK((d.flags & fl::FL_DISPLAY_OPENGL) == 0u);
CHECK(d.sampleQpc > first.sampleQpc);
// The window is the harness's own, which is the Agent's check before it reads any geometry (a HWND is reused).
REQUIRE(d.hwnd != 0u);
const HWND wnd = reinterpret_cast<HWND>(static_cast<uintptr_t>(d.hwnd));
DWORD owner = 0;
CHECK(IsWindow(wnd) != FALSE);
CHECK(GetWindowThreadProcessId(wnd, &owner) != 0u);
CHECK(owner == child.pi.dwProcessId);
// The back buffer is the one every record carries, and the chain is the one the records name.
CHECK(d.bufferWidth != 0u);
CHECK(d.bufferWidth == ring[0].outputW);
CHECK(d.bufferHeight == ring[0].outputH);
CHECK(d.chainId == ring[0].swapchainId);
// DXGI_SWAP_EFFECT + 1: FLIP_DISCARD (4) or, where flip is unavailable, DISCARD (0) -- never the vendor's bare 0.
CHECK((d.swapEffect == static_cast<uint32_t>(DXGI_SWAP_EFFECT_FLIP_DISCARD) + 1u ||
d.swapEffect == static_cast<uint32_t>(DXGI_SWAP_EFFECT_DISCARD) + 1u));
CHECK((d.seq & 1u) == 0u);
CHECK(r.st->faultCount == 0u);
}
TEST_CASE("the native log: written at init, on the Agent's request, and on the stop -- and the stop restores each "
+19 -2
View File
@@ -35,8 +35,10 @@ void Field(const char* name, size_t offset, size_t size, bool last = false) {
int main() {
std::printf("{\n");
std::printf(" \"layoutVersion\": %u,\n", FL_SHM_LAYOUT_VERSION);
std::printf(" \"regions\": { \"handshake\": %u, \"writer\": %u, \"control\": %u, \"ring\": %u },\n",
FL_SHM_HANDSHAKE_OFFSET, FL_SHM_WRITER_OFFSET, FL_SHM_CONTROL_OFFSET, FL_SHM_RING_OFFSET);
std::printf(
" \"regions\": { \"handshake\": %u, \"writer\": %u, \"control\": %u, \"display\": %u, \"ring\": %u },\n",
FL_SHM_HANDSHAKE_OFFSET, FL_SHM_WRITER_OFFSET, FL_SHM_CONTROL_OFFSET, FL_SHM_DISPLAY_OFFSET,
FL_SHM_RING_OFFSET);
// D33: the tolerance mapping (fl_tolerance.h) the Agent writes before an injection under a user-mode exception.
std::printf(" \"tolerance\": { \"magic\": %u, \"version\": %u, \"maxFamilies\": %u, \"nameLen\": %u },\n",
FL_TOLERANCE_MAGIC, FL_TOLERANCE_VERSION, FL_TOLERANCE_MAX_FAMILIES, FL_TOLERANCE_NAME_LEN);
@@ -84,6 +86,21 @@ int main() {
Field("reserved", offsetof(FlControlBlock, reserved), sizeof(uint32_t) * 11, true);
std::printf(" ] },\n");
// Layout 4 (beta.10): region 4, the presenting swap chain's display facts.
std::printf(" \"FlDisplayState\": { \"size\": %zu, \"fields\": [\n", sizeof(FlDisplayState));
Field("seq", offsetof(FlDisplayState, seq), sizeof(uint32_t));
Field("flags", offsetof(FlDisplayState, flags), sizeof(uint32_t));
Field("hwnd", offsetof(FlDisplayState, hwnd), sizeof(uint64_t));
Field("bufferWidth", offsetof(FlDisplayState, bufferWidth), sizeof(uint32_t));
Field("bufferHeight", offsetof(FlDisplayState, bufferHeight), sizeof(uint32_t));
Field("swapEffect", offsetof(FlDisplayState, swapEffect), sizeof(uint32_t));
Field("swapFlags", offsetof(FlDisplayState, swapFlags), sizeof(uint32_t));
Field("chainId", offsetof(FlDisplayState, chainId), sizeof(uint32_t));
Field("samples", offsetof(FlDisplayState, samples), sizeof(uint32_t));
Field("sampleQpc", offsetof(FlDisplayState, sampleQpc), sizeof(uint64_t));
Field("reserved", offsetof(FlDisplayState, reserved), sizeof(uint32_t) * 4, true);
std::printf(" ] },\n");
std::printf(" \"FlFrameRecord\": { \"size\": %zu, \"fields\": [\n", sizeof(FlFrameRecord));
Field("qpc", offsetof(FlFrameRecord, qpc), sizeof(uint64_t));
Field("frameIndex", offsetof(FlFrameRecord, frameIndex), sizeof(uint32_t));
+3 -1
View File
@@ -10,7 +10,9 @@
# gl_hold.cpp is the OpenGL mode (P1 item 4): a real context on a hidden window,
# SwapBuffers'd through gdi32 the way a title does it; Microsoft's generic
# renderer answers everywhere, so this one runs on CI too.
add_executable(hook-harness main.cpp vk_hold.cpp gl_hold.cpp proxy_swapchain.h)
# hwnd_hold.cpp is the one DXGI mode with a WINDOW (layout 4, beta.10): every other mode presents to a
# composition swap chain, which region 4 (the display facts) has nothing to describe about.
add_executable(hook-harness main.cpp vk_hold.cpp gl_hold.cpp hwnd_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:
+114
View File
@@ -0,0 +1,114 @@
// hook-harness --hold-presenting-hwnd N: a D3D11 swap chain bound to a REAL window, presented every few milliseconds
// for N seconds (layout 4, 2026-09-27, beta.10). Every other DXGI mode here presents to a composition swap chain, which
// has no window -- so until this mode no test had a chain whose OutputWindow, exclusive state and back buffer region 4
// (fl_shm.h §Region 4) could describe. The window is never shown and the chain stays windowed: exclusive fullscreen
// needs a real output, which a hosted runner has not got, and is the owner's measurement on real hardware.
//
// WARP, so it runs with no GPU. Flip model first (what a modern title uses), the legacy discard model when flip is not
// available. The window, its client size and the swap effect are printed so a test compares region 4 with what the
// fixture made rather than with a number it assumes. Exit codes:
// 0 presented for the whole hold
// 77 this machine cannot run the fixture (no window, no device, no swap chain)
#include <windows.h>
#include <d3d11.h>
#include <dxgi.h>
#include <cstdint>
#include <cstdio>
namespace {
LRESULT CALLBACK HwndHoldWndProc(HWND h, UINT m, WPARAM w, LPARAM l) {
return DefWindowProcW(h, m, w, l);
}
int Skip(const char* why) {
std::printf(" [SKIP] %s\n", why);
std::fflush(stdout);
return 77;
}
HRESULT MakeChain(HWND hwnd, LONG width, LONG height, DXGI_SWAP_EFFECT effect, UINT buffers, IDXGISwapChain** sc,
ID3D11Device** dev, ID3D11DeviceContext** ctx) {
DXGI_SWAP_CHAIN_DESC desc{};
desc.BufferDesc.Width = static_cast<UINT>(width);
desc.BufferDesc.Height = static_cast<UINT>(height);
desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = buffers;
desc.OutputWindow = hwnd;
desc.Windowed = TRUE;
desc.SwapEffect = effect;
return D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION,
&desc, sc, dev, nullptr, ctx);
}
} // namespace
int HoldPresentingHwnd(int seconds, int presentIntervalMs) {
std::printf("\n[hwnd-hold] a D3D11 swap chain on a real (hidden) window, presenting for %d second(s) every %d ms\n",
seconds, presentIntervalMs);
std::fflush(stdout);
WNDCLASSW wc{};
wc.lpfnWndProc = &HwndHoldWndProc;
wc.hInstance = GetModuleHandleW(nullptr);
wc.lpszClassName = L"FrameLedgerHookHarnessHwnd";
RegisterClassW(&wc);
const HWND hwnd = CreateWindowExW(0, wc.lpszClassName, L"FrameLedger hook-harness (HWND swap chain)",
WS_OVERLAPPEDWINDOW, 0, 0, 320, 200, nullptr, nullptr, wc.hInstance, nullptr);
if (hwnd == nullptr) {
return Skip("no window could be created (no interactive window station?)");
}
RECT client{};
if (!GetClientRect(hwnd, &client) || client.right <= 0 || client.bottom <= 0) {
DestroyWindow(hwnd);
return Skip("the window has no client area");
}
IDXGISwapChain* sc = nullptr;
ID3D11Device* dev = nullptr;
ID3D11DeviceContext* ctx = nullptr;
DXGI_SWAP_EFFECT effect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
HRESULT hr = MakeChain(hwnd, client.right, client.bottom, effect, 2, &sc, &dev, &ctx);
if (FAILED(hr)) {
effect = DXGI_SWAP_EFFECT_DISCARD;
hr = MakeChain(hwnd, client.right, client.bottom, effect, 1, &sc, &dev, &ctx);
}
if (FAILED(hr) || sc == nullptr) {
std::printf(" D3D11CreateDeviceAndSwapChain(WARP, hwnd) failed: 0x%08lX\n", static_cast<unsigned long>(hr));
DestroyWindow(hwnd);
return Skip("no D3D11 swap chain for a window on this machine");
}
std::printf(" hwnd=0x%llx width=%ld height=%ld swapEffect=%d\n",
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(hwnd)), client.right, client.bottom,
static_cast<int>(effect));
std::fflush(stdout);
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(seconds) * 1000ULL;
long long presented = 0;
MSG msg{};
while (GetTickCount64() < until) {
// A window nobody pumps is still a window, but DXGI's own window hook posts to it; drain the queue so the
// fixture behaves like a title's message loop rather than a hung one.
while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
sc->Present(0, 0);
++presented;
Sleep(presentIntervalMs > 0 ? static_cast<DWORD>(presentIntervalMs) : 0u);
}
std::printf(" presented=%lld\n", presented);
std::fflush(stdout);
ctx->Release();
dev->Release();
sc->Release();
DestroyWindow(hwnd);
return 0;
}
+33
View File
@@ -2819,6 +2819,29 @@ bool ProbeFrameIdentity(Gfx& g) {
std::printf(" GetLastPresentCount costs %.1f ns/call (%d calls, WARP; the Overlay pays this once per hooked "
"present)\n",
ns, kCalls);
// Region 4's two getters (layout 4, beta.10). The Overlay asks them at most every 500 ms per chain, so their
// per-present share is (these / presents in 500 ms) plus one QPC comparison on every present -- the figure the
// PR states under 14_TESTING §Hook overhead.
BOOL fs = FALSE;
DXGI_SWAP_CHAIN_DESC desc{};
QueryPerformanceCounter(&t0);
for (int i = 0; i < kCalls; ++i) {
g.swapChain1->GetFullscreenState(&fs, nullptr);
}
QueryPerformanceCounter(&t1);
const double fsNs =
static_cast<double>(t1.QuadPart - t0.QuadPart) * 1e9 / static_cast<double>(f.QuadPart) / kCalls;
QueryPerformanceCounter(&t0);
for (int i = 0; i < kCalls; ++i) {
g.swapChain1->GetDesc(&desc);
}
QueryPerformanceCounter(&t1);
const double descNs =
static_cast<double>(t1.QuadPart - t0.QuadPart) * 1e9 / static_cast<double>(f.QuadPart) / kCalls;
std::printf(" GetFullscreenState costs %.1f ns/call, GetDesc %.1f ns/call (%d calls each, WARP; the Overlay "
"pays both at most twice a second per chain)\n",
fsNs, descNs, kCalls);
}
// The two together are the contract. Separately, each passes against a
@@ -2833,6 +2856,8 @@ bool ProbeFrameIdentity(Gfx& g) {
int HoldPresentingVulkan(int seconds, int presentIntervalMs);
// gl_hold.cpp -- the OpenGL mode (P1 item 4).
int HoldPresentingOpenGl(int seconds, int presentIntervalMs);
// hwnd_hold.cpp -- a D3D11 swap chain on a real window (layout 4, beta.10).
int HoldPresentingHwnd(int seconds, int presentIntervalMs);
int main(int argc, char** argv) {
std::printf("FrameLedger hook-harness (WARP, headless — no GPU or window required)\n");
@@ -3144,6 +3169,14 @@ int main(int argc, char** argv) {
f->Release();
}
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-hwnd") == 0 && i + 1 < argc) {
// Region 4 (layout 4, beta.10): a chain with a real OutputWindow. Its own file and exit codes (77 = cannot
// run here).
const int code = HoldPresentingHwnd(std::atoi(argv[++i]), presentIntervalMs);
if (code != 0) {
return code;
}
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting") == 0 && i + 1 < argc && opengl) {
const int code = HoldPresentingOpenGl(std::atoi(argv[++i]), presentIntervalMs);
if (code != 0) {
@@ -145,6 +145,8 @@ public sealed class CaptureSessionTests : IAsyncDisposable
public FlShmHandshake Handshake => default;
public FlDisplayState? DisplayState => null;
public long TotalDropped { get; set; }
public long TotalGaps { get; set; }
@@ -343,6 +345,8 @@ public sealed class CaptureSessionTests : IAsyncDisposable
public FlShmHandshake Handshake => default;
public FlDisplayState? DisplayState => null;
public long TotalDropped => 0;
public long TotalGaps => 0;
@@ -481,6 +485,8 @@ public sealed class CaptureSessionTests : IAsyncDisposable
public FlShmHandshake Handshake => default;
public FlDisplayState? DisplayState => null;
public long TotalDropped => 0;
public long TotalGaps => 0;
@@ -89,6 +89,8 @@ public sealed class SessionRecorderTests : IAsyncDisposable
public FlShmHandshake Handshake => default;
public FlDisplayState? DisplayState => null;
public long TotalDropped => 0;
public long TotalGaps => 0;
@@ -183,6 +183,7 @@ public sealed class ShmLayoutMirrorTests
regions.GetProperty("handshake").GetUInt32().Should().Be(ShmLayout.HandshakeOffset);
regions.GetProperty("writer").GetUInt32().Should().Be(ShmLayout.WriterOffset);
regions.GetProperty("control").GetUInt32().Should().Be(ShmLayout.ControlOffset);
regions.GetProperty("display").GetUInt32().Should().Be(ShmLayout.DisplayOffset);
regions.GetProperty("ring").GetUInt32().Should().Be(ShmLayout.RingOffset);
}
@@ -195,6 +196,10 @@ public sealed class ShmLayoutMirrorTests
[Fact]
public void TheControlBlockMirrorMatches() => AssertMirror<FlControlBlock>("FlControlBlock");
/// <summary>Layout 4 (beta.10): region 4, the presenting swap chain's display facts.</summary>
[Fact]
public void TheDisplayStateMirrorMatches() => AssertMirror<FlDisplayState>("FlDisplayState");
[Fact]
public void TheFrameRecordMirrorMatches() => AssertMirror<FlFrameRecord>("FlFrameRecord");
@@ -226,6 +231,7 @@ public sealed class ShmLayoutMirrorTests
("FlShmHandshake", typeof(FlShmHandshake)),
("FlWriterState", typeof(FlWriterState)),
("FlControlBlock", typeof(FlControlBlock)),
("FlDisplayState", typeof(FlDisplayState)),
("FlFrameRecord", typeof(FlFrameRecord)),
("FlTolerance", typeof(FlTolerance)),
];
@@ -255,6 +261,22 @@ public sealed class ShmLayoutMirrorTests
}
}
/// <summary>
/// The third direction (beta.10): every struct the dump EMITS has a mirror here. The field walks above start from a
/// list of pairs this file names, so a struct added to <c>fl_shm.h</c> and the dump but never to that list was reported
/// by the native side and checked by nobody — which is how layout 4's region would have gone unchecked had the pair
/// been forgotten.
/// </summary>
[Fact]
public void EveryDumpedStructHasAMirror()
{
string[] mirrored = ["FlShmHandshake", "FlWriterState", "FlControlBlock", "FlDisplayState", "FlFrameRecord", "FlTolerance"];
IEnumerable<string> dumped = _nativeLayout.Value.GetProperty("structs").EnumerateObject().Select(static p => p.Name);
dumped.Should().BeEquivalentTo(mirrored, "a struct fl-layout-dump reports must be asserted, and one it stopped reporting is a check that shrank");
}
[Fact]
public void TheRecordSizeUsedForRingArithmeticMatches()
{