Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5 c8e711da0c measure(gl): the ICD-rewrite hypothesis is WRONG, and the prologue says why it looked right
--hold-presenting-gl 0 measures what the WIP OpenGL hook needed: does something
rewrite opengl32!wglSwapBuffers across its first call, leaving a prologue patch
patching code that no longer runs?

No. Measured on this machine (GL 4.6.0 NVIDIA 610.88):

  ICD loaded before first call: yes
  before  00007FFCCEF87F80: E9 7B 80 FF BF EC 58 48 8B 05 1A BD 0D 00 33 FF
  after   00007FFCCEF87F80: E9 7B 80 FF BF EC 58 48 8B 05 1A BD 0D 00 33 FF
  GetProcAddress again: same address

Bytes identical, address identical, and the vendor ICD was already mapped BEFORE
the first call -- so there is no lazy resolve to race. My hypothesis is refuted
and the next investigator does not have to spend the day on it.

What the bytes hand over instead: the entry point is E9 <rel32>, i.e. it ALREADY
BEGINS WITH AN UNCONDITIONAL JUMP into the ICD. opengl32!wglSwapBuffers is a
thunk, not the implementation. That is the fact worth carrying into the next
attempt -- MinHook's behaviour when a target's first instruction is itself a jmp
is where to look, not the fault policy and not MayObserve, both of which the ring
already exonerated (faults=0, status READY).

Recorded as a measurement rather than a fix, and it is not merged: the OpenGL
hook is still red. The point of this commit is that the WRONG explanation is now
closed off with evidence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 09:58:13 +07:00
poli0981andClaude Opus 5 c64d0ecce2 wip(overlay): OpenGL harness mode works; the wglSwapBuffers hook fires exactly once
NOT FOR MERGE. The test is red and the cause is not yet understood.

What works: hook-harness --hold-presenting-gl creates a hidden-window OpenGL
context and presents through wglSwapBuffers. Measured on this machine: GL_VERSION
4.6.0 NVIDIA 610.88, 128 presents in 2 seconds. It exits 3 when OpenGL is
unavailable so a caller can tell that from a broken hook, and the test SKIPs with
that reason rather than passing.

What does not: the Overlay's MinHook patch on wglSwapBuffers records exactly ONE
frame and then never fires again. Measured from the ring, after ~1,100 further
presents:

  status=1 (READY)  faults=0  writeIndex=1  apiMask=16 (OPENGL only)

So the hook installed, fired, recorded correctly, and stopped -- with no fault, no
self-disable, no unhook, and no supervision expiry. MayObserve cannot explain it
and neither can the fault policy.

The hypothesis worth testing first, unverified: opengl32!wglSwapBuffers is a
dispatcher into the vendor ICD (nvoglv64.dll here), and the first call resolves or
swaps that dispatch, so a prologue patch on the opengl32 export is bypassed from
the second call onward. If that holds, this is the same SHAPE as the Streamline
interposer question -- the symbol we can hook is not the code that runs -- and it
needs a measurement, not another attempt at the patch.

Committed so the harness mode and the diagnostics are not lost. The D3D11/D3D12
paths on main are unaffected; nothing here is merged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 09:54:24 +07:00
3 changed files with 379 additions and 7 deletions

No files matched your search

+118 -7
View File
@@ -12,12 +12,18 @@
// both, and `api` is resolved per swapchain by asking the swapchain which device
// created it -- FL_API_UNKNOWN when it will not say, never a guess.
//
// NOT HERE: OpenGL (wglSwapBuffers is a flat export in opengl32.dll and needs no
// vtable, but hook-harness has no OpenGL mode, and shipping an untested hook into
// a game process is not something this project does), Vulkan (the layer, P1), and
// the upscaler / FG / RT feature hooks. The record's measuredMask says so on
// every frame rather than letting the zero-defaults assert a measurement nobody
// made.
// OPENGL TOO, via a flat MinHook patch on wglSwapBuffers -- no vtable, no dummy
// object. Installed only if opengl32.dll is ALREADY mapped, and resolved with
// GetModuleHandleW rather than LoadLibraryW: loading GL into a process that did
// not ask for it would change the host's module list for our convenience, which
// is not something an observer does. The Overlay does not import opengl32
// either, for the same reason.
//
// NOT HERE: Vulkan (the layer, P1), a title that loads opengl32 AFTER we inject
// (that is the deferred LoadLibrary hook §H2 leaves open, and it is why "we hook
// OpenGL" must not be read as covering lazy loaders), and the upscaler / FG / RT
// feature hooks. The record's measuredMask says so on every frame rather than
// letting the zero-defaults assert a measurement nobody made.
//
// docs/17_HOOK_ENGINE.md is the specification. The constraints that shape every
// line:
@@ -298,6 +304,38 @@ uint8_t ResolveApi(IDXGISwapChain* sc) noexcept {
SwapChainSlot g_chains[kMaxSwapChains]{};
uint32_t g_nextChainId = 1;
// Identity lookup keyed on an opaque pointer, so the DXGI path (IDXGISwapChain*)
// and the GL path (HDC) share ONE table and one id space. Two tables would be two
// id spaces, and the Agent segments on swapchainId.
SwapChainSlot* FindOrAddRaw(void* key, uint8_t api) noexcept {
for (auto& s : g_chains) {
if (s.ptr == key) {
return &s;
}
}
for (auto& s : g_chains) {
if (s.ptr == nullptr) {
s.ptr = key;
s.id = g_nextChainId++;
s.api = api;
if (api == FL_API_OPENGL) {
HWND wnd = WindowFromDC(static_cast<HDC>(key));
RECT r{};
if (wnd != nullptr && GetClientRect(wnd, &r)) {
s.outW = static_cast<uint16_t>(r.right - r.left);
s.outH = static_cast<uint16_t>(r.bottom - r.top);
}
}
if (api != FL_API_UNKNOWN && g_state != nullptr) {
std::atomic_ref<uint32_t> mask{g_state->apiMask};
mask.fetch_or(1u << api, std::memory_order_relaxed);
}
return &s;
}
}
return nullptr;
}
SwapChainSlot* FindOrAdd(IDXGISwapChain* sc) noexcept {
for (auto& s : g_chains) {
if (s.ptr == sc) {
@@ -523,6 +561,71 @@ HRESULT STDMETHODCALLTYPE Hook_ResizeBuffers(IDXGISwapChain* sc, UINT count, UIN
return hr;
}
// ---------------------------------------------------------------------------
// OpenGL. A flat C export, so there is no vtable and no dummy object -- MinHook
// patches wglSwapBuffers directly (17_HOOK_ENGINE §Hook inventory names this
// entry point, not the GDI SwapBuffers).
//
// Installed ONLY if opengl32.dll is already mapped. A title that loads it later
// is missed, and that is the LoadLibrary-hook case §H2 defers -- recorded here
// rather than papered over, because "we hooked OpenGL" would otherwise read as
// covering lazy loaders.
// ---------------------------------------------------------------------------
using PFN_wglSwapBuffers = BOOL(WINAPI*)(HDC);
PFN_wglSwapBuffers g_origWglSwapBuffers = nullptr;
// The HDC is the stream identity for GL, the way the swapchain pointer is for
// DXGI: one hook sees every context in the process.
void RecordGlPresent(HDC hdc) noexcept {
if (!MayObserve()) {
return;
}
LARGE_INTEGER qpc{};
QueryPerformanceCounter(&qpc);
SwapChainSlot* slot = FindOrAddRaw(hdc, FL_API_OPENGL);
FlFrameRecord rec{};
rec.qpc = static_cast<uint64_t>(qpc.QuadPart);
rec.frameIndex = g_frameIndex++;
rec.api = FL_API_OPENGL;
rec.swapchainId = slot != nullptr ? slot->id : 0u;
if (slot != nullptr) {
rec.outputW = slot->outW;
rec.outputH = slot->outH;
}
// Same honesty rule as the DXGI path: a present-only writer may claim the
// output size and nothing else.
rec.measuredMask = FL_MEASURED_OUTPUT_RES;
rec.rtFlags = FL_RT_NOT_MEASURED;
g_writer.Publish(rec);
}
BOOL WINAPI Hook_wglSwapBuffers(HDC hdc) {
FL_HOOK_GUARD({ RecordGlPresent(hdc); })
return g_origWglSwapBuffers(hdc);
}
bool InstallOpenGlHook() noexcept {
// GetModuleHandleW, never LoadLibrary: loading opengl32 into a process that
// did not ask for it would change the host's module list for our
// convenience, which is not something an observer does.
HMODULE gl = GetModuleHandleW(L"opengl32.dll");
if (gl == nullptr) {
return false;
}
void* target = reinterpret_cast<void*>(GetProcAddress(gl, "wglSwapBuffers"));
if (target == nullptr) {
return false;
}
if (MH_CreateHook(target, reinterpret_cast<void*>(&Hook_wglSwapBuffers),
reinterpret_cast<void**>(&g_origWglSwapBuffers)) != MH_OK) {
return false;
}
return MH_EnableHook(target) == MH_OK;
}
// A throwaway WARP swapchain, purely to read the shared class vtable. Released
// immediately: 17_HOOK_ENGINE §Getting vtable addresses. Never hardcode the
// pointer, never keep the object.
@@ -607,7 +710,15 @@ DWORD WINAPI InitThread(LPVOID) noexcept {
std::atomic_ref<uint32_t> status{g_state->status};
if (MH_Initialize() != MH_OK || !InstallPresentHooks()) {
if (MH_Initialize() != MH_OK) {
status.store(FL_STATUS_INIT, std::memory_order_release);
return 1;
}
// OpenGL is opportunistic and its absence is normal -- most titles are DXGI.
// The DXGI hooks are what READY depends on.
const bool gl = InstallOpenGlHook();
(void)gl;
if (!InstallPresentHooks()) {
// Hooking failed, so nothing will ever be recorded. Staying at INIT says
// exactly that; READY would be a claim about a capture side that does not
// exist, and the Agent's degradation path is what should run instead.
+86
View File
@@ -1236,6 +1236,92 @@ TEST_CASE("the injected Overlay publishes a handshake the Agent can validate", "
CloseHandle(mapping);
}
TEST_CASE("an OpenGL title is recorded through wglSwapBuffers", "[guard][inject][shm][gl]") {
// OpenGL has no vtable and no swapchain: wglSwapBuffers is a flat export, so
// MinHook patches it directly and the HDC is the stream identity.
//
// This is the one case with a real environment dependency. wglCreateContext
// needs an HDC with a pixel format, which needs an HWND, which needs a window
// station -- there is no WARP-equivalent to force. The harness exits 3 when
// that is unavailable, and this SKIPS with the reason rather than passing:
// "OpenGL is absent here" and "the hook is broken" must not produce the same
// green.
Child child;
std::wstring cmd = std::wstring(L"\"") + FL_HARNESS_EXE + L"\" --real --hold-presenting-gl 10";
STARTUPINFOW si{};
si.cb = sizeof(si);
REQUIRE(CreateProcessW(FL_HARNESS_EXE, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
&child.pi));
Sleep(800);
DWORD early = STILL_ACTIVE;
GetExitCodeProcess(child.pi.hProcess, &early);
if (early == 3) {
SKIP("OpenGL is not available in this environment (no window station or no GL ICD); "
"the harness reported it rather than the hook being exercised");
}
REQUIRE(WaitForSingleObject(child.pi.hProcess, 0) == WAIT_TIMEOUT);
ResetFake();
g.modules = {"kernel32.dll"};
g.scanSet = {child.pi.dwProcessId};
REQUIRE(GuardedInjectWithSources(child.pi.dwProcessId, FL_OVERLAY_DLL, FakeSources()).Allowed());
wchar_t name[128]{};
REQUIRE(_snwprintf_s(name, _TRUNCATE, L"Local\\FrameLedger.Ring.%lu", child.pi.dwProcessId) > 0);
HANDLE mapping = nullptr;
for (int i = 0; i < 100 && mapping == nullptr; ++i) {
mapping = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, name);
if (mapping == nullptr) {
Sleep(50);
}
}
REQUIRE(mapping != nullptr);
void* base = MapViewOfFile(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
REQUIRE(base != nullptr);
auto* st = reinterpret_cast<fl::FlWriterState*>(static_cast<unsigned char*>(base) + FL_SHM_WRITER_OFFSET);
auto* ctl = reinterpret_cast<fl::FlControlBlock*>(static_cast<unsigned char*>(base) + FL_SHM_CONTROL_OFFSET);
for (int i = 0; i < 100 && st->status != fl::FL_STATUS_READY; ++i) {
Sleep(50);
}
REQUIRE(st->status == fl::FL_STATUS_READY);
fl::RingReader rd;
REQUIRE(rd.Init(base, FL_SHM_DEFAULT_CAPACITY));
std::vector<fl::FlFrameRecord> all;
for (int i = 0; i < 50 && all.size() < 30; ++i) {
++ctl->guardTicks;
fl::FlFrameRecord buf[256]{};
const auto r = rd.Drain(buf, 256);
for (std::uint32_t k = 0; k < r.copied; ++k) {
all.push_back(buf[k]);
}
Sleep(100);
}
INFO("status=" << st->status << " faults=" << st->faultCount << " writeIndex=" << st->writeIndex
<< " apiMask=" << st->apiMask << " drained=" << all.size());
REQUIRE(all.size() > 10);
bool allGl = true;
for (const auto& rec : all) {
if (rec.api != fl::FL_API_OPENGL || rec.swapchainId == 0 ||
rec.measuredMask != fl::FL_MEASURED_OUTPUT_RES || (rec.rtFlags & fl::FL_RT_NOT_MEASURED) == 0) {
allGl = false;
}
}
CHECK(allGl);
CHECK((st->apiMask & (1u << fl::FL_API_OPENGL)) != 0);
// No DXGI swapchain was ever presented through, so neither D3D bit may be set
// -- the GL and DXGI paths share one identity table and one id space, and
// this is what catches them bleeding into each other.
CHECK((st->apiMask & (1u << fl::FL_API_D3D11)) == 0);
CHECK((st->apiMask & (1u << fl::FL_API_D3D12)) == 0);
UnmapViewOfFile(base);
CloseHandle(mapping);
}
TEST_CASE("a D3D12 title is recorded as D3D12, not as the D3D11 we used to assume", "[guard][inject][shm]") {
// One hook on the SHARED dxgi.dll class vtable catches D3D11 and D3D12 alike,
// so the present call itself cannot tell them apart -- and `api` was
+175
View File
@@ -36,6 +36,7 @@
#include <d3d11.h>
#include <d3d12.h>
#include <dxgi1_4.h>
#include <gl/GL.h>
#include <algorithm>
#include <atomic>
@@ -48,6 +49,7 @@
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3d12.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "opengl32.lib")
namespace {
@@ -686,6 +688,165 @@ bool ProbeFrameIdentity(Gfx& g) {
} // namespace
// Why does a prologue patch on opengl32!wglSwapBuffers stop firing after ONE
// call? (WIP c64d0ec: the Overlay's hook recorded exactly one frame, with no
// fault, no self-disable and no unhook.)
//
// The hypothesis this measures: opengl32!wglSwapBuffers is a dispatcher into the
// vendor ICD, and the first call resolves or rewrites that dispatch, so the
// patched bytes are no longer the code that runs. If true it is the same shape as
// the Streamline interposer question -- the symbol we can hook is not the code
// that executes -- and the fix is a different hook target, not a better patch.
//
// Deliberately reads rather than patches: this answers whether the BYTES change
// and whether the ICD arrives, which is enough to decide, and it leaves the
// process's own GL stack untouched.
void ProbeGlDispatch(HDC hdc) {
HMODULE gl = GetModuleHandleW(L"opengl32.dll");
auto* fn = reinterpret_cast<unsigned char*>(GetProcAddress(gl, "wglSwapBuffers"));
if (fn == nullptr) {
Check(false, "opengl32 exports wglSwapBuffers");
return;
}
auto dump = [](const char* when, const unsigned char* p) {
std::printf(" %-14s %p:", when, static_cast<const void*>(p));
for (int i = 0; i < 16; ++i) {
std::printf(" %02X", p[i]);
}
std::printf("\n");
};
auto icdLoaded = []() {
// Any vendor GL implementation, not just NVIDIA's.
return GetModuleHandleW(L"nvoglv64.dll") != nullptr || GetModuleHandleW(L"atioglxx.dll") != nullptr ||
GetModuleHandleW(L"ig9icd64.dll") != nullptr;
};
unsigned char before[16]{};
std::memcpy(before, fn, sizeof(before));
std::printf(" ICD loaded before first call: %s\n", icdLoaded() ? "yes" : "no");
dump("before", fn);
using PFN = BOOL(WINAPI*)(HDC);
auto swap = reinterpret_cast<PFN>(reinterpret_cast<void*>(fn));
swap(hdc);
unsigned char after[16]{};
std::memcpy(after, fn, sizeof(after));
std::printf(" ICD loaded after first call: %s\n", icdLoaded() ? "yes" : "no");
dump("after", fn);
// Resolving again: a changed ADDRESS would mean the export itself moved.
auto* fn2 = reinterpret_cast<unsigned char*>(GetProcAddress(gl, "wglSwapBuffers"));
std::printf(" GetProcAddress again: %p (%s)\n", static_cast<void*>(fn2), fn2 == fn ? "same" : "DIFFERENT");
const bool bytesChanged = std::memcmp(before, after, sizeof(before)) != 0;
std::printf("\n ==> prologue bytes %s across the first call\n", bytesChanged ? "CHANGED" : "did NOT change");
if (bytesChanged) {
std::printf(" The hypothesis holds: something rewrites the entry point, so a\n"
" prologue patch survives exactly one call. Hook the ICD's own export\n"
" or the dispatch table instead.\n");
} else {
std::printf(" The hypothesis is WRONG. The bytes are stable, so a prologue patch\n"
" should keep firing -- the single-record behaviour has another cause\n"
" and this measurement has ruled out the obvious one.\n");
}
swap(hdc);
swap(hdc);
}
// OpenGL hold. Returns false only for a real failure; a missing GL stack exits
// the process with 3 so a caller can tell "not available" from "broken".
bool RunGlHold(int seconds, bool real) {
std::printf("\n[gl] hidden-window OpenGL context\n");
WNDCLASSEXW wc{};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = DefWindowProcW;
wc.hInstance = GetModuleHandleW(nullptr);
wc.lpszClassName = L"FlHarnessGL";
RegisterClassExW(&wc);
// WS_POPUP with no WS_VISIBLE: created, never shown. It still needs a window
// station, which is the part that can be absent on a hosted runner.
HWND hwnd = CreateWindowExW(0, wc.lpszClassName, L"", WS_POPUP, 0, 0, 64, 64, nullptr, nullptr, wc.hInstance,
nullptr);
if (hwnd == nullptr) {
std::printf(" OpenGL UNAVAILABLE: CreateWindowExW failed (%lu)\n", GetLastError());
std::exit(3);
}
HDC hdc = GetDC(hwnd);
if (hdc == nullptr) {
std::printf(" OpenGL UNAVAILABLE: GetDC failed\n");
std::exit(3);
}
PIXELFORMATDESCRIPTOR pfd{};
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
const int fmt = ChoosePixelFormat(hdc, &pfd);
if (fmt == 0 || !SetPixelFormat(hdc, fmt, &pfd)) {
std::printf(" OpenGL UNAVAILABLE: no usable pixel format (%lu)\n", GetLastError());
std::exit(3);
}
HGLRC rc = wglCreateContext(hdc);
if (rc == nullptr || !wglMakeCurrent(hdc, rc)) {
std::printf(" OpenGL UNAVAILABLE: wglCreateContext/MakeCurrent failed (%lu)\n", GetLastError());
std::exit(3);
}
std::printf(" GL_VERSION = %s\n", reinterpret_cast<const char*>(glGetString(GL_VERSION)));
if (seconds == 0) {
// --hold-presenting-gl 0 is the dispatch measurement, not a hold.
ProbeGlDispatch(hdc);
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(rc);
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
return true;
}
// wglSwapBuffers, NOT the GDI SwapBuffers. 17_HOOK_ENGINE §Hook inventory
// names the wgl entry point, and that is what the Overlay hooks; presenting
// through the GDI one would exercise a different symbol and the count would
// be a lie about what we intercept.
std::printf(" presenting GL for %d second(s) [%s]\n", seconds, real ? "REAL" : "no-op");
std::fflush(stdout);
const ULONGLONG until = GetTickCount64() + static_cast<ULONGLONG>(seconds) * 1000ULL;
long long presented = 0;
// Resolved by name rather than by import: wglSwapBuffers is declared behind
// header guards that WIN32_LEAN_AND_MEAN-style builds do not always expose,
// and going through GetProcAddress is exactly what the Overlay does to hook
// it -- so the harness and the hook are talking about the same symbol by
// construction rather than by assumption.
using PFN_wglSwapBuffers = BOOL(WINAPI*)(HDC);
auto swap = reinterpret_cast<PFN_wglSwapBuffers>(
reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"opengl32.dll"), "wglSwapBuffers")));
if (swap == nullptr) {
std::printf(" OpenGL UNAVAILABLE: opengl32 exports no wglSwapBuffers\n");
std::exit(3);
}
while (GetTickCount64() < until) {
glClear(GL_COLOR_BUFFER_BIT);
swap(hdc);
++presented;
Sleep(8);
}
std::printf(" presented=%lld\n", presented);
std::fflush(stdout);
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(rc);
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
return true;
}
int main(int argc, char** argv) {
std::printf("FrameLedger hook-harness (WARP, headless — no GPU or window required)\n");
@@ -747,6 +908,20 @@ int main(int argc, char** argv) {
std::fflush(stdout);
Sleep(static_cast<DWORD>(std::atoi(argv[++i])) * 1000);
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-gl") == 0 && i + 1 < argc) {
// OpenGL cannot use the two tricks that make the D3D modes headless.
// There is no WARP equivalent to force, and wglCreateContext needs a
// real HDC with a pixel format, which means a real HWND. So this
// creates a HIDDEN window: no WS_VISIBLE, never shown, 64x64.
//
// That is a genuine environment dependency, and it is reported rather
// than hidden: exit code 3 means "OpenGL is not available here",
// which is a different fact from "the hook is broken". A test that
// could not tell those apart would pass on a machine with no GL at
// all, which is the shape this repository keeps finding.
const int seconds = std::atoi(argv[++i]);
ok = RunGlHold(seconds, real) && ok;
ranSomething = true;
} else if (std::strcmp(argv[i], "--hold-presenting-d3d12") == 0 && i + 1 < argc) {
// The same shape as --hold-presenting, but the swapchain is created
// from a D3D12 COMMAND QUEUE rather than a D3D11 device.