HydraHook
Direct3D and Core Audio hooking library for Windows
Loading...
Searching...
No Matches
Game.cpp
Go to the documentation of this file.
1/*
2MIT License
3
4Copyright (c) 2018-2026 Benjamin Höglinger-Stelzer
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23*/
24
25#define WIN32_LEAN_AND_MEAN
26#include <Windows.h>
27
28#include <Utils/Hook.h>
29
30#include "Game.h"
31#include "Shutdown.h"
32#include "Utils/Global.h"
33#include "Exceptions.hpp"
34#include "CrashHandler.h"
35using namespace HydraHook::Core::Exceptions;
36
37//
38// Hooking helper sub-systems
39//
40#include <Game/Hook/Direct3D9.h>
42#include <Game/Hook/DXGI.h>
43#include <dxgi.h>
44#include <dxgi1_2.h>
45#include <dxgi1_4.h>
46#include <d3d12.h>
47#include <wrl/client.h>
52
53//
54// Public
55//
62
63//
64// Internal
65//
66#include "Engine.h"
67#include "Utils/SrwLock.h"
68
69//
70// STL
71//
72#include <memory>
73#include <atomic>
74#include <cstdint>
75#include <cstring>
76#include <unordered_map>
77#include <vector>
78
79//
80// Logging
81//
82#include <spdlog/spdlog.h>
83
84#ifndef HYDRAHOOK_NO_D3D12
85static SRWLOCK g_d3d12QueueMapLock = SRWLOCK_INIT;
86static std::unordered_map<IDXGISwapChain*, ID3D12CommandQueue*> g_d3d12SwapChainToQueue;
88static std::unordered_map<ID3D12Device*, ID3D12CommandQueue*> g_d3d12DeviceToQueue;
89static std::atomic<ID3D12CommandQueue*> g_lastObservedDirectQueue{nullptr};
90
91enum class DxgiModuleStatus : std::uint32_t
92{
96};
97static std::atomic<std::uint32_t> g_dxgiModuleStatus{static_cast<std::uint32_t>(DxgiModuleStatus::Unknown)};
98static std::atomic<const BYTE*> g_dxgiModuleImage{nullptr};
99
100static void ResetDxgiModuleCache() noexcept
101{
102 g_dxgiModuleStatus.store(static_cast<std::uint32_t>(DxgiModuleStatus::Unknown), std::memory_order_relaxed);
103 g_dxgiModuleImage.store(nullptr, std::memory_order_relaxed);
104}
105
106static void RecordD3D12SwapChainQueue(IDXGISwapChain* chain, ID3D12CommandQueue* queue)
107{
108 ID3D12CommandQueue* displaced = nullptr;
109 {
111 if (const auto it = g_d3d12SwapChainToQueue.find(chain); it != g_d3d12SwapChainToQueue.end())
112 {
113 displaced = it->second;
114 g_d3d12SwapChainToQueue.erase(it);
115 }
116 if (queue)
117 {
118 g_d3d12SwapChainToQueue.emplace(chain, queue);
119 queue->AddRef();
120 }
121 }
122 if (displaced)
123 displaced->Release();
124}
125
127{
128 std::vector<ID3D12CommandQueue*> queues;
129 {
131 queues.reserve(g_d3d12SwapChainToQueue.size() + g_d3d12DeviceToQueue.size());
132 for (auto& kv : g_d3d12SwapChainToQueue)
133 {
134 if (kv.second)
135 queues.push_back(kv.second);
136 }
138 for (auto& kv : g_d3d12DeviceToQueue)
139 {
140 if (kv.second)
141 queues.push_back(kv.second);
142 }
143 g_d3d12DeviceToQueue.clear();
144 g_lastObservedDirectQueue.store(nullptr, std::memory_order_release);
145 }
146 for (auto* queue : queues)
147 queue->Release();
149}
150#endif
151
152//
153// Internal flow-control hooks (file scope for PerformShutdownCleanup access)
154//
158static std::atomic<HMODULE> g_freeLibraryTarget{nullptr};
159static std::atomic<HMODULE> g_freeLibraryHost{nullptr};
160
161//
162// Per-run worker state. File scope so hook lambdas can reach it and so every
163// worker run (initial hook or rehook) starts from a clean slate.
164//
165static PHYDRAHOOK_ENGINE engine = nullptr;
166
187
188static std::shared_ptr<spdlog::logger> g_logGame;
189static std::shared_ptr<spdlog::logger> g_logD3D9;
190static std::shared_ptr<spdlog::logger> g_logD3D10;
191static std::shared_ptr<spdlog::logger> g_logD3D11;
192static std::shared_ptr<spdlog::logger> g_logD3D12;
193static std::shared_ptr<spdlog::logger> g_logArc;
194
196{
197 auto base = spdlog::get("HYDRAHOOK");
198 if (!base)
199 return;
200 g_logGame = base->clone("game");
201 g_logD3D9 = base->clone("d3d9");
202 g_logD3D10 = base->clone("d3d10");
203 g_logD3D11 = base->clone("d3d11");
204 g_logD3D12 = base->clone("d3d12");
205 g_logArc = base->clone("arc");
206}
207
209{
210 g_logGame.reset();
211 g_logD3D9.reset();
212 g_logD3D10.reset();
213 g_logD3D11.reset();
214 g_logD3D12.reset();
215 g_logArc.reset();
216}
217
219template <typename TDevice>
220bool DispatchSwapChainDevice(IDXGISwapChain* chain, BOOL enabled)
221{
222 if (!enabled || !chain)
223 return false;
224
225 TDevice* device = nullptr;
226 if (FAILED(chain->GetDevice(IID_PPV_ARGS(&device))) || !device)
227 return false;
228
229 device->Release();
230 return true;
231}
232
240
241DxgiRuntime DetectDxgiRuntime(IDXGISwapChain* chain)
242{
243 if (!chain || !engine)
244 return DxgiRuntime::None;
245
246 const auto version = engine->GameVersion.load(std::memory_order_acquire);
247 auto probe = [&](HYDRAHOOK_D3D_VERSION candidate) -> DxgiRuntime
248 {
249 switch (candidate)
250 {
251#ifndef HYDRAHOOK_NO_D3D12
253 if (DispatchSwapChainDevice<ID3D12Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D12))
254 return DxgiRuntime::D3D12;
255 break;
256#endif
257#ifndef HYDRAHOOK_NO_D3D11
259 if (DispatchSwapChainDevice<ID3D11Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D11))
260 return DxgiRuntime::D3D11;
261 break;
262#endif
263#ifndef HYDRAHOOK_NO_D3D10
265 if (DispatchSwapChainDevice<ID3D10Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D10))
266 return DxgiRuntime::D3D10;
267 break;
268#endif
269 default:
270 break;
271 }
272 return DxgiRuntime::None;
273 };
274
275 if (version != HydraHookDirect3DVersionUnknown)
276 {
277 if (const auto hit = probe(version); hit != DxgiRuntime::None)
278 return hit;
279 }
280
281 static constexpr HYDRAHOOK_D3D_VERSION kOrder[] = {
285 };
286 for (const auto candidate : kOrder)
287 {
288 if (candidate == version)
289 continue;
290 if (const auto hit = probe(candidate); hit != DxgiRuntime::None)
291 return hit;
292 }
293 return DxgiRuntime::None;
294}
295
314
316{
317 if (engine->ShutdownCleanupDone.exchange(true))
318 return;
319
320 const std::uint32_t ipcOrigin = IpcShutdownOrigin(origin);
321 engine->LastShutdownOrigin.store(ipcOrigin, std::memory_order_release);
323 static_cast<std::uint32_t>(engine->GameVersion.load(std::memory_order_acquire)), 0);
324
325 auto logChannel = "shutdown";
326 auto logMessage = "Performing pre-DLL-detach clean-up tasks";
327 switch (origin)
328 {
330 logChannel = "process";
331 logMessage = "Host process is terminating, performing pre-DLL-detach clean-up tasks";
332 break;
334 logChannel = "quit";
335 logMessage = "WM_QUIT was fired, performing pre-DLL-detach clean-up tasks";
336 break;
338 logChannel = "unload";
339 logMessage = "FreeLibrary called for HydraHook DLL, performing pre-unload clean-up tasks";
340 break;
342 logChannel = "detach";
343 break;
345 logChannel = "unhook";
346 logMessage = "HydraHookEngineUnhook called, removing hooks and stopping the worker";
347 break;
348 }
349
350 std::shared_ptr<spdlog::logger> logger;
352 {
353 logger = HydraHookCloneRegisteredLogger(logChannel);
354 if (logger)
355 logger->info(logMessage);
356 }
357
359 {
360 g_postQuitMessageHook.remove_nothrow();
361 g_freeLibraryHook.remove_nothrow();
362 }
363 else if (origin == ShutdownOrigin::PostQuitMessageHook)
364 {
365 g_exitProcessHook.remove_nothrow();
366 g_freeLibraryHook.remove_nothrow();
367 }
368 else if (origin == ShutdownOrigin::FreeLibraryHook)
369 {
370 g_postQuitMessageHook.remove_nothrow();
371 g_exitProcessHook.remove_nothrow();
372 }
373 else if (origin == ShutdownOrigin::DllMainProcessDetach)
374 {
375 g_postQuitMessageHook.remove_nothrow();
376 g_exitProcessHook.remove_nothrow();
377 g_freeLibraryHook.remove_nothrow();
378 }
379
380 else if (origin == ShutdownOrigin::ManualUnhook)
381 {
382 // The worker removes every hook (including the flow-control ones) on its own
383 // thread; touching Detours from here could race a worker still installing hooks.
384 engine->SkipDllUnloadOnExit.store(true, std::memory_order_release);
385 }
386
388 && engine->EngineConfig.EvtHydraHookGamePreExit)
389 {
390 engine->EngineConfig.EvtHydraHookGamePreExit(engine);
391 }
392
393 const auto ret = SetEvent(engine->EngineCancellationEvent);
394 if (!ret && logger)
395 {
396 logger->error("SetEvent failed: {}", GetLastError());
397 }
398
399 // wait on thread shutdown or check state
400 // A manual unhook waits long enough for HookActivityTracker::drain (5000 ms)
401 const DWORD waitTimeout = origin == ShutdownOrigin::DllMainProcessDetach
402 ? 0
403 : (origin == ShutdownOrigin::ManualUnhook ? 8000 : 6500);
404 const auto result = WaitForSingleObject(engine->EngineThread, waitTimeout);
405
406 switch (result)
407 {
408 case WAIT_ABANDONED:
409 if (logger)
410 logger->error("Unknown state, host process might crash");
411 break;
412 case WAIT_OBJECT_0:
413 if (logger)
414 logger->info("Thread shutdown complete");
415 break;
416 case WAIT_TIMEOUT:
417 if (origin == ShutdownOrigin::ManualUnhook)
418 {
419 // Never terminate on a manual unhook: the caller keeps the engine and can retry
420 if (logger)
421 logger->error("Thread hasn't finished clean-up within expected time, unhook incomplete");
422 }
423 else if (origin == ShutdownOrigin::FreeLibraryHook)
424 {
425 if (logger)
426 logger->error("Thread hasn't finished clean-up within expected time, unload incomplete");
427 }
428 else if (origin != ShutdownOrigin::DllMainProcessDetach)
429 {
430 TerminateThread(engine->EngineThread, 0);
431 if (logger)
432 logger->error("Thread hasn't finished clean-up within expected time, terminating");
433 }
434 break;
435 case WAIT_FAILED:
436 if (logger)
437 logger->error("Unknown error, host process might crash");
438 break;
439 default:
442 {
443 TerminateThread(engine->EngineThread, 0);
444 }
445 if (logger)
446 logger->error("Unexpected return value");
447 break;
448 }
449}
450
451DWORD WINAPI HydraHookMainThread(LPVOID Params)
452{
453 engine = reinterpret_cast<PHYDRAHOOK_ENGINE>(Params);
455#ifndef HYDRAHOOK_NO_D3D12
457#endif
460 auto logger = g_logGame;
461 if (!logger)
462 logger = spdlog::get("HYDRAHOOK");
463 const auto& config = engine->EngineConfig;
464
465 if (config.CrashHandler.IsEnabled)
466 {
468 logger->info("Per-thread SEH translator installed on engine worker thread");
469 }
470
471 logger->info("Library loaded into {}", HydraHook::Core::Util::process_name());
472
473 logger->info("Library enabled");
474
475 //
476 // D3D9 Hooks
477 //
478#ifndef HYDRAHOOK_NO_D3D9
480 present9Hook;
483
484 //
485 // D3D9Ex Hooks
486 //
487 static Hook<CallConvention::stdcall_t, HRESULT, LPDIRECT3DDEVICE9EX, CONST RECT*, CONST RECT*, HWND, CONST RGNDATA*,
488 DWORD> present9ExHook;
490 reset9ExHook;
491#else
492 logger->info("Direct3D 9 hooking disabled at compile time");
493#endif
494
495 //
496 // DXGI Hooks (shared across D3D10/11/12; one Detours hook per vtable slot)
497 //
501 swapChainResizeBuffersHook;
503 swapChainPresent1Hook;
504 static Hook<CallConvention::stdcall_t, HRESULT, IDXGISwapChain3*, UINT, UINT, UINT, DXGI_FORMAT, UINT, const UINT*,
505 IUnknown* const*> swapChainResizeBuffers1Hook;
506
507#ifdef HYDRAHOOK_NO_D3D10
508 logger->info("Direct3D 10 hooking disabled at compile time");
509#endif
510#ifdef HYDRAHOOK_NO_D3D11
511 logger->info("Direct3D 11 hooking disabled at compile time");
512#endif
513
514 //
515 // D3D12 Queue Capture Hooks
516 //
517#ifndef HYDRAHOOK_NO_D3D12
519 createSwapChain12Hook;
520 static Hook<CallConvention::stdcall_t, HRESULT, IUnknown*, IUnknown*, HWND, const DXGI_SWAP_CHAIN_DESC1*, const
521 DXGI_SWAP_CHAIN_FULLSCREEN_DESC*, IDXGIOutput*, IDXGISwapChain1**> createSwapChainForHwnd12Hook;
523 executeCommandLists12Hook;
524#else
525 logger->info("Direct3D 12 hooking disabled at compile time");
526#endif
527
528 //
529 // Core Audio Hooks
530 //
531#ifndef HYDRAHOOK_NO_COREAUDIO
534#else
535 logger->info("Core Audio hooking disabled at compile time");
536#endif
537
538 /*
539 * This is a bit of a gamble but ExitProcess is expected to be implicitly called
540 * _before_ the injected DLL gets unloaded (without proper call to FreeLibrary)
541 * and by hooking it we get a chance to gracefully shutdown and free resources
542 * which might otherwise become victim to a termination race condition and DLL
543 * loader-lock restrictions.
544 */
545 try
546 {
547 if (!g_exitProcessHook.is_applied())
548 g_exitProcessHook.apply((size_t)ExitProcess, [](UINT uExitCode)
549 {
551 g_exitProcessHook.call_orig(uExitCode);
552 });
553 }
554 catch (DetourException& ex)
555 {
556 logger->error("Failed to hook ExitProcess: {}", ex.what());
557 }
558
559 /*
560 * Hooking PostQuitMessage in addition to ExitProcess should be practically
561 * more reliable since a game is expected to have at least one main window
562 * which _should_ receive the WM_QUIT message upon application shutdown.
563 */
564 try
565 {
566 if (!engine->EngineConfig.Shutdown.DisableThreadQuitMonitoring && !g_postQuitMessageHook.is_applied())
567 g_postQuitMessageHook.apply((size_t)PostQuitMessage, [](int nExitCode)
568 {
570 g_postQuitMessageHook.call_orig(nExitCode);
571 });
572 }
573 catch (DetourException& ex)
574 {
575 logger->error("Failed to hook PostQuitMessage: {}", ex.what());
576 }
577
578 /*
579 * Hooking FreeLibrary allows detection of explicit host-initiated DLL unload.
580 * When the host calls FreeLibrary on our module, we perform graceful shutdown
581 * before the actual unload, avoiding loader-lock and termination race issues.
582 */
583 try
584 {
585 if (!g_freeLibraryHook.is_applied())
586 {
587 g_freeLibraryHost.store(engine->HostInstance, std::memory_order_relaxed);
588 g_freeLibraryTarget.store(engine->DllModule, std::memory_order_release);
589 g_freeLibraryHook.apply((size_t)FreeLibrary, [](HMODULE hLibModule) -> BOOL
590 {
591 if (hLibModule == g_freeLibraryTarget.load(std::memory_order_acquire))
592 {
593 // Look up the engine in the destruction path. Other FreeLibrary calls
594 // can safely inspect the published module identity without an engine pointer.
595 if (HydraHookEngineDestroyBeforeUnload(g_freeLibraryHost.load(std::memory_order_relaxed),
596 []() noexcept { return g_freeLibraryHook.remove_nothrow(); }) != HYDRAHOOK_ERROR_NONE)
597 {
598 SetLastError(ERROR_BUSY);
599 return FALSE;
600 }
601 // FreeLibraryAndExitThread does not return. The remote thread's exit code is
602 // this value. The injector treats 0 as a failed FreeLibrary, so report TRUE,
603 // which is what a successful FreeLibrary returns.
604 FreeLibraryAndExitThread(hLibModule, TRUE);
605 }
607 return g_freeLibraryHook.call_orig(hLibModule);
608 });
609 }
610 }
611 catch (DetourException& ex)
612 {
613 logger->error("Failed to hook FreeLibrary: {}", ex.what());
614 }
615
616#pragma region D3D9
617
618#ifndef HYDRAHOOK_NO_D3D9
619
620 if (config.Direct3D.HookDirect3D9)
621 {
622 try
623 {
624 const std::unique_ptr<Direct3D9Hooking::Direct3D9Ex> d3dEx(new Direct3D9Hooking::Direct3D9Ex);
625
626 logger->info("Hooking IDirect3DDevice9Ex::Present");
627
628 present9Hook.apply(d3dEx->vtable()[Direct3D9Hooking::Present], [](
629 LPDIRECT3DDEVICE9 dev,
630 CONST RECT* a1,
631 CONST RECT* a2,
632 HWND a3,
633 CONST RGNDATA* a4
634 ) -> HRESULT
635 {
636 HookActivityTracker::Guard guard;
637
638 if (guard.invoke)
639 {
640 StoreRenderPipelinePtr(engine->RenderPipeline.pD3D9Device, dev); // Keep the lookup current for further devices.
641 g_announce.present9.call([&pDev = dev]()
642 {
643 if (g_logD3D9) g_logD3D9->info(
644 "++ IDirect3DDevice9Ex::Present called");
645
646 StoreRenderPipelinePtr(engine->RenderPipeline.pD3D9Device, pDev);
647
648 INVOKE_HYDRAHOOK_GAME_HOOKED(engine, HydraHookDirect3DVersion9);
649 });
650
651 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PrePresent, dev, a1, a2, a3, a4);
652 }
653
654 const auto ret = present9Hook.call_orig(dev, a1, a2, a3, a4);
655
656 if (guard.invoke)
657 {
658 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PostPresent, dev, a1, a2, a3, a4);
659 }
660
661 return ret;
662 });
663
664 logger->info("Hooking IDirect3DDevice9Ex::Reset");
665
666 reset9Hook.apply(d3dEx->vtable()[Direct3D9Hooking::Reset], [](
667 LPDIRECT3DDEVICE9 dev,
668 D3DPRESENT_PARAMETERS* pp
669 ) -> HRESULT
670 {
672
673 if (guard.invoke)
674 {
676 {
677 if (g_logD3D9) g_logD3D9->info(
678 "++ IDirect3DDevice9Ex::Reset called");
679 });
680
681 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PreReset, dev, pp);
682 }
683
684 const auto ret = reset9Hook.call_orig(dev, pp);
685
686 if (guard.invoke)
687 {
688 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PostReset, dev, pp);
689 }
690
691 return ret;
692 });
693
694 logger->info("Hooking IDirect3DDevice9Ex::EndScene");
695
696 endScene9Hook.apply(d3dEx->vtable()[Direct3D9Hooking::EndScene], [](
697 LPDIRECT3DDEVICE9 dev
698 ) -> HRESULT
699 {
701
702 if (guard.invoke)
703 {
705 {
706 if (g_logD3D9) g_logD3D9->info(
707 "++ IDirect3DDevice9Ex::EndScene called");
708 });
709
710 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PreEndScene, dev);
711 }
712
713 const auto ret = endScene9Hook.call_orig(dev);
714
715 if (guard.invoke)
716 {
717 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PostEndScene, dev);
718 }
719
720 return ret;
721 });
722
723 logger->info("Hooking IDirect3DDevice9Ex::PresentEx");
724
725 present9ExHook.apply(d3dEx->vtable()[Direct3D9Hooking::PresentEx], [](
726 LPDIRECT3DDEVICE9EX dev,
727 CONST RECT* a1,
728 CONST RECT* a2,
729 HWND a3,
730 CONST RGNDATA* a4,
731 DWORD a5
732 ) -> HRESULT
733 {
735
736 if (guard.invoke)
737 {
738 StoreRenderPipelinePtr(engine->RenderPipeline.pD3D9ExDevice, dev); // Keep the lookup current for further devices.
739 g_announce.present9.call([&pDev = dev]()
740 {
741 if (g_logD3D9) g_logD3D9->info(
742 "++ IDirect3DDevice9Ex::PresentEx called");
743
744 StoreRenderPipelinePtr(engine->RenderPipeline.pD3D9ExDevice, pDev);
745
747 });
748
749 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PrePresentEx, dev, a1, a2, a3, a4,
750 a5);
751 }
752
753 const auto ret = present9ExHook.call_orig(dev, a1, a2, a3, a4, a5);
754
755 if (guard.invoke)
756 {
757 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PostPresentEx, dev, a1, a2, a3,
758 a4,
759 a5);
760 }
761
762 return ret;
763 });
764
765 logger->info("Hooking IDirect3DDevice9Ex::ResetEx");
766
767 reset9ExHook.apply(d3dEx->vtable()[Direct3D9Hooking::ResetEx], [](
768 LPDIRECT3DDEVICE9EX dev,
769 D3DPRESENT_PARAMETERS* pp,
770 D3DDISPLAYMODEEX* ppp
771 ) -> HRESULT
772 {
774
775 if (guard.invoke)
776 {
778 {
779 if (g_logD3D9) g_logD3D9->info(
780 "++ IDirect3DDevice9Ex::ResetEx called");
781 });
782
783 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PreResetEx, dev, pp, ppp);
784 }
785
786 const auto ret = reset9ExHook.call_orig(dev, pp, ppp);
787
788 if (guard.invoke)
789 {
790 INVOKE_D3D9_CALLBACK(engine, EvtHydraHookD3D9PostResetEx, dev, pp, ppp);
791 }
792
793 return ret;
794 });
795 }
796 catch (DetourException& ex)
797 {
798 logger->error("Hooking D3D9Ex failed: {}", ex.what());
799 }
800 catch (ModuleNotFoundException& ex)
801 {
802 logger->warn("Module not found: {}", ex.what());
803 }
804 catch (RuntimeException& ex)
805 {
806 logger->error("D3D9(Ex) runtime error: {}", ex.what());
807 }
808 }
809
810#endif
811
812#pragma endregion
813
814#pragma region DXGI / D3D10 / D3D11 / D3D12
815
816 size_t dxgiPresentAddress = 0;
817 size_t dxgiResizeTargetAddress = 0;
818 size_t dxgiResizeBuffersAddress = 0;
819 size_t dxgiPresent1Address = 0;
820 size_t dxgiResizeBuffers1Address = 0;
821
822 const auto captureDxgiVtable = [&](const std::vector<size_t>& vtable)
823 {
824 if (dxgiPresentAddress == 0 && vtable.size() > static_cast<size_t>(DXGIHooking::Present))
825 dxgiPresentAddress = vtable[DXGIHooking::Present];
826 if (dxgiResizeTargetAddress == 0 && vtable.size() > static_cast<size_t>(DXGIHooking::ResizeTarget))
827 dxgiResizeTargetAddress = vtable[DXGIHooking::ResizeTarget];
828 if (dxgiResizeBuffersAddress == 0 && vtable.size() > static_cast<size_t>(DXGIHooking::ResizeBuffers))
829 dxgiResizeBuffersAddress = vtable[DXGIHooking::ResizeBuffers];
830 if (dxgiPresent1Address == 0 && vtable.size() > static_cast<size_t>(
832 dxgiPresent1Address = vtable[DXGIHooking::DXGI1::Present1];
833 if (dxgiResizeBuffers1Address == 0 && vtable.size() > static_cast<size_t>(
835 dxgiResizeBuffers1Address = vtable[DXGIHooking::DXGI3::ResizeBuffers1];
836 };
837
838#ifndef HYDRAHOOK_NO_D3D12
839 size_t d3d12ExecuteCommandListsAddress = 0;
840 HMODULE ownedDxgiModule = nullptr;
841
842 if (config.Direct3D.HookDirect3D12)
843 {
844 // Install early-injection factory hooks BEFORE probing so concurrent game
845 // swap-chain creation on other threads is captured while the worker probes.
846 // Load system dxgi.dll if not already loaded so early injection before DXGI
847 // loads still captures the swap chain's presentation queue.
848 // Only this thread's temporary probe swap chains are suppressed via thread_local.
849 try
850 {
851 IDXGIFactory2* pFactory = nullptr;
852 HMODULE hModDXGI = GetModuleHandleW(L"dxgi.dll");
853 if (!hModDXGI)
854 {
855 ownedDxgiModule = LoadLibraryExW(L"dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
856 hModDXGI = ownedDxgiModule;
857 }
858 HRESULT hrFactory = E_FAIL;
859 if (hModDXGI)
860 {
861 auto pCreateDXGIFactory1 = reinterpret_cast<HRESULT(WINAPI*)(REFIID, void**)>(
862 GetProcAddress(hModDXGI, "CreateDXGIFactory1"));
863 if (pCreateDXGIFactory1)
864 hrFactory = pCreateDXGIFactory1(IID_PPV_ARGS(&pFactory));
865 }
866 if (SUCCEEDED(hrFactory) && pFactory)
867 {
868 void** pFactoryVtbl = *reinterpret_cast<void***>(pFactory);
869 const auto createSwapChainAddr = reinterpret_cast<size_t>(pFactoryVtbl[DXGIHooking::Factory::CreateSwapChain]);
870 const auto createSwapChainForHwndAddr = reinterpret_cast<size_t>(
872 pFactory->Release();
873 pFactory = nullptr;
874
875 try
876 {
877 if (!createSwapChain12Hook.is_applied())
878 createSwapChain12Hook.apply(createSwapChainAddr, [](
879 IUnknown* pFactoryThis,
880 IUnknown* pDevice,
881 DXGI_SWAP_CHAIN_DESC* pDesc,
882 IDXGISwapChain** ppSwapChain
883 ) -> HRESULT
884 {
886
887 const auto ret = createSwapChain12Hook.call_orig(
888 pFactoryThis, pDevice, pDesc, ppSwapChain);
890 && SUCCEEDED(ret) && ppSwapChain && *ppSwapChain && pDevice)
891 {
892 ID3D12CommandQueue* pQueue = nullptr;
893 if (SUCCEEDED(pDevice->QueryInterface(IID_PPV_ARGS(&pQueue))))
894 {
895 RecordD3D12SwapChainQueue(*ppSwapChain, pQueue);
896 pQueue->Release();
897 }
898 }
899 return ret;
900 });
901 }
902 catch (DetourException& ex)
903 {
904 logger->error("Hooking IDXGIFactory::CreateSwapChain failed: {}", ex.what());
905 }
906
907 try
908 {
909 if (!createSwapChainForHwnd12Hook.is_applied())
910 createSwapChainForHwnd12Hook.apply(createSwapChainForHwndAddr,
911 [](
912 IUnknown* pFactoryThis,
913 IUnknown* pDevice,
914 HWND hWnd,
915 const DXGI_SWAP_CHAIN_DESC1* pDesc,
916 const DXGI_SWAP_CHAIN_FULLSCREEN_DESC* pFullscreenDesc,
917 IDXGIOutput* pRestrictToOutput,
918 IDXGISwapChain1** ppSwapChain
919 ) -> HRESULT
920 {
922
923 const auto ret = createSwapChainForHwnd12Hook.call_orig(
924 pFactoryThis, pDevice, hWnd, pDesc, pFullscreenDesc,
925 pRestrictToOutput, ppSwapChain);
927 && SUCCEEDED(ret) && ppSwapChain && *ppSwapChain
928 && pDevice)
929 {
930 ID3D12CommandQueue* pQueue = nullptr;
931 if (SUCCEEDED(
932 pDevice->QueryInterface(IID_PPV_ARGS(&pQueue))))
933 {
934 RecordD3D12SwapChainQueue(*ppSwapChain, pQueue);
935 pQueue->Release();
936 }
937 }
938 return ret;
939 });
940 }
941 catch (DetourException& ex)
942 {
943 logger->error("Hooking IDXGIFactory2::CreateSwapChainForHwnd failed: {}", ex.what());
944 }
945
946 logger->info("Hooking IDXGIFactory::CreateSwapChain/CreateSwapChainForHwnd for D3D12 queue capture");
947 }
948 }
949 catch (DetourException& ex)
950 {
951 logger->error("Hooking D3D12 factory queue capture failed: {}", ex.what());
952 }
953
954 if (ownedDxgiModule && !createSwapChain12Hook.is_applied() && !createSwapChainForHwnd12Hook.is_applied())
955 {
956 FreeLibrary(ownedDxgiModule);
957 ownedDxgiModule = nullptr;
958 }
959
960 try
961 {
962 ScopedSuppressD3D12QueueCapture suppressProbeCapture;
963 const std::unique_ptr<Direct3D12Hooking::Direct3D12> d3d12(new Direct3D12Hooking::Direct3D12);
964 captureDxgiVtable(d3d12->vtable());
965
966 if (void** pQueueVtbl = d3d12->commandQueueVtable())
967 {
968 constexpr int ExecuteCommandListsIndex = 10;
969 d3d12ExecuteCommandListsAddress = reinterpret_cast<size_t>(pQueueVtbl[ExecuteCommandListsIndex]);
970 }
971 }
972 catch (ModuleNotFoundException& ex)
973 {
974 logger->warn("Module not found: {}", ex.what());
975 }
976 catch (RuntimeException& ex)
977 {
978 logger->error("D3D12 runtime error: {}", ex.what());
979 }
980 }
981#endif
982
983#ifndef HYDRAHOOK_NO_D3D11
984 if (config.Direct3D.HookDirect3D11 && dxgiPresentAddress == 0)
985 {
986 try
987 {
988#ifndef HYDRAHOOK_NO_D3D12
989 ScopedSuppressD3D12QueueCapture suppressProbeCapture;
990#endif
991 const std::unique_ptr<Direct3D11Hooking::Direct3D11> d3d11(new Direct3D11Hooking::Direct3D11);
992 captureDxgiVtable(d3d11->vtable());
993 }
994 catch (ModuleNotFoundException& ex)
995 {
996 logger->warn("Module not found: {}", ex.what());
997 }
998 catch (RuntimeException& ex)
999 {
1000 logger->error("D3D11 runtime error: {}", ex.what());
1001 }
1002 }
1003#endif
1004
1005#ifndef HYDRAHOOK_NO_D3D10
1006 if (config.Direct3D.HookDirect3D10 && dxgiPresentAddress == 0)
1007 {
1008 try
1009 {
1010#ifndef HYDRAHOOK_NO_D3D12
1011 ScopedSuppressD3D12QueueCapture suppressProbeCapture;
1012#endif
1013 const std::unique_ptr<Direct3D10Hooking::Direct3D10> d3d10(new Direct3D10Hooking::Direct3D10);
1014 captureDxgiVtable(d3d10->vtable());
1015 }
1016 catch (ModuleNotFoundException& ex)
1017 {
1018 logger->warn("Module not found: {}", ex.what());
1019 }
1020 catch (RuntimeException& ex)
1021 {
1022 logger->error("D3D10 runtime error: {}", ex.what());
1023 }
1024 }
1025#endif
1026
1027#ifndef HYDRAHOOK_NO_D3D12
1028 if (config.Direct3D.HookDirect3D12 && d3d12ExecuteCommandListsAddress != 0
1029 && !executeCommandLists12Hook.is_applied())
1030 {
1031 try
1032 {
1033 executeCommandLists12Hook.apply(d3d12ExecuteCommandListsAddress, [](
1034 ID3D12CommandQueue* pQueue,
1035 UINT NumCommandLists,
1036 ID3D12CommandList* const* ppCommandLists
1037 ) -> void
1038 {
1040
1041 if (guard.invoke && pQueue && !g_suppressD3D12QueueCapture
1042 && pQueue != g_lastObservedDirectQueue.load(std::memory_order_acquire)
1043 && pQueue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT)
1044 {
1045 ID3D12Device* pDevice = nullptr;
1046 if (SUCCEEDED(pQueue->GetDevice(IID_PPV_ARGS(&pDevice))) &&
1047 pDevice)
1048 {
1049 ID3D12CommandQueue* displaced = nullptr;
1050 {
1052 auto it = g_d3d12DeviceToQueue.find(pDevice);
1053 if (it == g_d3d12DeviceToQueue.end() || it->second != pQueue)
1054 {
1055 if (it != g_d3d12DeviceToQueue.end() && it->second)
1056 displaced = it->second;
1057 pQueue->AddRef();
1058 g_d3d12DeviceToQueue[pDevice] = pQueue;
1059 }
1060 g_lastObservedDirectQueue.store(pQueue, std::memory_order_release);
1061 }
1062 pDevice->Release();
1063 if (displaced)
1064 displaced->Release();
1065 }
1066 }
1067 executeCommandLists12Hook.call_orig(
1068 pQueue, NumCommandLists, ppCommandLists);
1069 });
1070 logger->info("Hooking ID3D12CommandQueue::ExecuteCommandLists for runtime queue capture");
1071 }
1072 catch (DetourException& ex)
1073 {
1074 logger->error("Hooking ID3D12CommandQueue::ExecuteCommandLists failed: {}", ex.what());
1075 }
1076 }
1077#endif
1078
1079 // D3D10, D3D11, and D3D12 share the same DXGI CDXGISwapChain implementation.
1080 // Install at most one Detours hook per vtable slot with isolated error boundaries
1081 // and dispatch by swap chain device; stacking multiple Detours hooks on the same
1082 // target corrupts the prologue if detached out of order.
1083 if (dxgiPresentAddress != 0 && !swapChainPresentHook.is_applied())
1084 {
1085 try
1086 {
1087 logger->info("Hooking IDXGISwapChain::Present");
1088
1089 swapChainPresentHook.apply(dxgiPresentAddress, [](
1090 IDXGISwapChain* chain,
1091 UINT SyncInterval,
1092 UINT Flags
1093 ) -> HRESULT
1094 {
1096
1097 if (!guard.invoke)
1098 return swapChainPresentHook.call_orig(chain, SyncInterval, Flags);
1099
1100 const auto runtime = DetectDxgiRuntime(chain);
1101
1102#ifndef HYDRAHOOK_NO_D3D12
1103 if (runtime == DxgiRuntime::D3D12)
1104 {
1105 {
1106
1107 g_announce.present12.call([&pChain = chain]()
1108 {
1109 if (g_logD3D12) g_logD3D12->info(
1110 "++ IDXGISwapChain::Present called");
1111
1112 StoreRenderPipelinePtr(engine->RenderPipeline.pSwapChain, pChain);
1113
1115 });
1116
1119 &pre, engine, engine->CustomContext);
1120
1121 INVOKE_D3D12_CALLBACK(engine, EvtHydraHookD3D12PrePresent, chain,
1122 SyncInterval, Flags, &pre);
1123
1124 const auto ret = swapChainPresentHook.call_orig(
1125 chain, SyncInterval, Flags);
1126
1129 &post, engine, engine->CustomContext);
1130
1131 INVOKE_D3D12_CALLBACK(engine, EvtHydraHookD3D12PostPresent, chain,
1132 SyncInterval, Flags, &post);
1133
1134 return ret;
1135 }
1136 }
1137#endif
1138
1139#ifndef HYDRAHOOK_NO_D3D11
1140 if (runtime == DxgiRuntime::D3D11)
1141 {
1142 {
1143
1144 g_announce.present11.call([&pChain = chain]()
1145 {
1146 if (g_logD3D11) g_logD3D11->info(
1147 "++ IDXGISwapChain::Present called");
1148
1149 StoreRenderPipelinePtr(engine->RenderPipeline.pSwapChain, pChain);
1150
1152 });
1153
1156 &pre, engine, engine->CustomContext);
1157
1159 engine,
1160 EvtHydraHookD3D11PrePresent,
1161 chain,
1162 SyncInterval,
1163 Flags,
1164 &pre
1165 );
1166
1167 const auto ret = swapChainPresentHook.call_orig(
1168 chain, SyncInterval, Flags);
1169
1172 &post, engine, engine->CustomContext);
1173
1175 engine,
1176 EvtHydraHookD3D11PostPresent,
1177 chain,
1178 SyncInterval,
1179 Flags,
1180 &post
1181 );
1182
1183 return ret;
1184 }
1185 }
1186#endif
1187
1188#ifndef HYDRAHOOK_NO_D3D10
1189 if (runtime == DxgiRuntime::D3D10)
1190 {
1191 {
1192
1193 // Keep the lookup current if the game swaps its swap chain.
1194 StoreRenderPipelinePtr(engine->RenderPipeline.pSwapChain, chain);
1195 g_announce.present10.call([&pChain = chain]()
1196 {
1197 if (g_logD3D10) g_logD3D10->info(
1198 "++ IDXGISwapChain::Present called");
1199
1200 StoreRenderPipelinePtr(engine->RenderPipeline.pSwapChain, pChain);
1201
1203 });
1204
1205 INVOKE_D3D10_CALLBACK(engine, EvtHydraHookD3D10PrePresent, chain,
1206 SyncInterval, Flags);
1207
1208 const auto ret = swapChainPresentHook.call_orig(
1209 chain, SyncInterval, Flags);
1210
1211 INVOKE_D3D10_CALLBACK(engine, EvtHydraHookD3D10PostPresent, chain,
1212 SyncInterval, Flags);
1213
1214 return ret;
1215 }
1216 }
1217#endif
1218
1219 return swapChainPresentHook.call_orig(chain, SyncInterval, Flags);
1220 });
1221 }
1222 catch (DetourException& ex)
1223 {
1224 logger->error("Hooking IDXGISwapChain::Present failed: {}", ex.what());
1225 }
1226 }
1227
1228 if (dxgiResizeTargetAddress != 0 && !swapChainResizeTargetHook.is_applied())
1229 {
1230 try
1231 {
1232 logger->info("Hooking IDXGISwapChain::ResizeTarget");
1233
1234 swapChainResizeTargetHook.apply(dxgiResizeTargetAddress, [](
1235 IDXGISwapChain* chain,
1236 const DXGI_MODE_DESC* pNewTargetParameters
1237 ) -> HRESULT
1238 {
1240
1241 if (!guard.invoke)
1242 return swapChainResizeTargetHook.call_orig(
1243 chain, pNewTargetParameters);
1244
1245#ifndef HYDRAHOOK_NO_D3D12
1246 if (DispatchSwapChainDevice<ID3D12Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D12))
1247 {
1248 {
1249
1251 {
1252 if (g_logD3D12) g_logD3D12->info(
1253 "++ IDXGISwapChain::ResizeTarget called");
1254 });
1255
1258 &pre, engine, engine->CustomContext);
1259
1261 engine, EvtHydraHookD3D12PreResizeTarget, chain,
1262 pNewTargetParameters, &pre);
1263
1264 const auto ret = swapChainResizeTargetHook.call_orig(
1265 chain, pNewTargetParameters);
1266
1269 &post, engine, engine->CustomContext);
1270
1272 engine, EvtHydraHookD3D12PostResizeTarget, chain,
1273 pNewTargetParameters, &post);
1274
1275 return ret;
1276 }
1277 }
1278#endif
1279
1280#ifndef HYDRAHOOK_NO_D3D11
1281 if (DispatchSwapChainDevice<ID3D11Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D11))
1282 {
1283 {
1284
1286 {
1287 if (g_logD3D11) g_logD3D11->info(
1288 "++ IDXGISwapChain::ResizeTarget called");
1289 });
1290
1293 &pre, engine, engine->CustomContext);
1294
1296 engine,
1297 EvtHydraHookD3D11PreResizeTarget,
1298 chain,
1299 pNewTargetParameters,
1300 &pre
1301 );
1302
1303 const auto ret = swapChainResizeTargetHook.call_orig(
1304 chain, pNewTargetParameters);
1305
1308 &post, engine, engine->CustomContext);
1309
1311 engine,
1312 EvtHydraHookD3D11PostResizeTarget,
1313 chain,
1314 pNewTargetParameters,
1315 &post
1316 );
1317
1318 return ret;
1319 }
1320 }
1321#endif
1322
1323#ifndef HYDRAHOOK_NO_D3D10
1324 if (DispatchSwapChainDevice<ID3D10Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D10))
1325 {
1326 {
1327
1329 {
1330 if (g_logD3D10) g_logD3D10->info(
1331 "++ IDXGISwapChain::ResizeTarget called");
1332 });
1333
1335 engine, EvtHydraHookD3D10PreResizeTarget, chain,
1336 pNewTargetParameters);
1337
1338 const auto ret = swapChainResizeTargetHook.call_orig(
1339 chain, pNewTargetParameters);
1340
1342 engine, EvtHydraHookD3D10PostResizeTarget, chain,
1343 pNewTargetParameters);
1344
1345 return ret;
1346 }
1347 }
1348#endif
1349
1350 return swapChainResizeTargetHook.call_orig(chain, pNewTargetParameters);
1351 });
1352 }
1353 catch (DetourException& ex)
1354 {
1355 logger->error("Hooking IDXGISwapChain::ResizeTarget failed: {}", ex.what());
1356 }
1357 }
1358
1359 if (dxgiResizeBuffersAddress != 0 && !swapChainResizeBuffersHook.is_applied())
1360 {
1361 try
1362 {
1363 logger->info("Hooking IDXGISwapChain::ResizeBuffers");
1364
1365 swapChainResizeBuffersHook.apply(dxgiResizeBuffersAddress, [](
1366 IDXGISwapChain* chain,
1367 UINT BufferCount,
1368 UINT Width,
1369 UINT Height,
1370 DXGI_FORMAT NewFormat,
1371 UINT SwapChainFlags
1372 ) -> HRESULT
1373 {
1375
1376 if (!guard.invoke)
1377 return swapChainResizeBuffersHook.call_orig(
1378 chain, BufferCount, Width, Height, NewFormat, SwapChainFlags);
1379
1380#ifndef HYDRAHOOK_NO_D3D12
1381 if (DispatchSwapChainDevice<ID3D12Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D12))
1382 {
1383 {
1384
1386 {
1387 if (g_logD3D12) g_logD3D12->info(
1388 "++ IDXGISwapChain::ResizeBuffers called");
1389 });
1390
1393 &pre, engine, engine->CustomContext);
1394
1395 {
1396 D3D12ResizeCallbackScope callback(pre);
1398 engine, EvtHydraHookD3D12PreResizeBuffers, chain,
1399 BufferCount, Width, Height, NewFormat, SwapChainFlags,
1400 &pre);
1401 }
1402
1403 if (pre.Deferred)
1404 return DXGI_ERROR_WAS_STILL_DRAWING;
1405
1406 const auto ret = swapChainResizeBuffersHook.call_orig(
1407 chain, BufferCount, Width, Height, NewFormat,
1408 SwapChainFlags);
1409
1412 &post, engine, engine->CustomContext);
1413
1415 engine, EvtHydraHookD3D12PostResizeBuffers, chain,
1416 BufferCount, Width, Height, NewFormat, SwapChainFlags,
1417 &post);
1418
1419 return ret;
1420 }
1421 }
1422#endif
1423
1424#ifndef HYDRAHOOK_NO_D3D11
1425 if (DispatchSwapChainDevice<ID3D11Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D11))
1426 {
1427 {
1428
1430 {
1431 if (g_logD3D11) g_logD3D11->info(
1432 "++ IDXGISwapChain::ResizeBuffers called");
1433 });
1434
1437 &pre, engine, engine->CustomContext);
1438
1440 engine, EvtHydraHookD3D11PreResizeBuffers, chain,
1441 BufferCount, Width, Height, NewFormat, SwapChainFlags,
1442 &pre);
1443
1444 const auto ret = swapChainResizeBuffersHook.call_orig(
1445 chain, BufferCount, Width, Height, NewFormat,
1446 SwapChainFlags);
1447
1450 &post, engine, engine->CustomContext);
1451
1453 engine, EvtHydraHookD3D11PostResizeBuffers, chain,
1454 BufferCount, Width, Height, NewFormat, SwapChainFlags,
1455 &post);
1456
1457 return ret;
1458 }
1459 }
1460#endif
1461
1462#ifndef HYDRAHOOK_NO_D3D10
1463 if (DispatchSwapChainDevice<ID3D10Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D10))
1464 {
1465 {
1466
1468 {
1469 if (g_logD3D10) g_logD3D10->info(
1470 "++ IDXGISwapChain::ResizeBuffers called");
1471 });
1472
1474 engine, EvtHydraHookD3D10PreResizeBuffers, chain,
1475 BufferCount, Width, Height, NewFormat, SwapChainFlags);
1476
1477 const auto ret = swapChainResizeBuffersHook.call_orig(
1478 chain, BufferCount, Width, Height, NewFormat,
1479 SwapChainFlags);
1480
1482 engine, EvtHydraHookD3D10PostResizeBuffers, chain,
1483 BufferCount, Width, Height, NewFormat, SwapChainFlags);
1484
1485 return ret;
1486 }
1487 }
1488#endif
1489
1490 return swapChainResizeBuffersHook.call_orig(
1491 chain, BufferCount, Width, Height, NewFormat, SwapChainFlags);
1492 });
1493 }
1494 catch (DetourException& ex)
1495 {
1496 logger->error("Hooking IDXGISwapChain::ResizeBuffers failed: {}", ex.what());
1497 }
1498 }
1499
1500 if (dxgiPresent1Address != 0 && !swapChainPresent1Hook.is_applied())
1501 {
1502 try
1503 {
1504 logger->info("Hooking IDXGISwapChain1::Present1");
1505
1506 swapChainPresent1Hook.apply(dxgiPresent1Address, [](
1507 IDXGISwapChain1* chain,
1508 UINT SyncInterval,
1509 UINT PresentFlags,
1510 const DXGI_PRESENT_PARAMETERS* pPresentParameters
1511 ) -> HRESULT
1512 {
1514
1515 if (!guard.invoke)
1516 return swapChainPresent1Hook.call_orig(
1517 chain, SyncInterval, PresentFlags, pPresentParameters);
1518
1519 const auto runtime = DetectDxgiRuntime(chain);
1520
1521#ifndef HYDRAHOOK_NO_D3D12
1522 if (runtime == DxgiRuntime::D3D12)
1523 {
1524 {
1525
1526 g_announce.present12.call([&pChain = chain]()
1527 {
1528 if (g_logD3D12) g_logD3D12->info(
1529 "++ IDXGISwapChain1::Present1 called (D3D12)");
1530
1531 StoreRenderPipelinePtr(engine->RenderPipeline.pSwapChain, pChain);
1532
1535 });
1536
1539 &pre, engine, engine->CustomContext);
1540
1542 engine, EvtHydraHookD3D12PrePresent, chain, SyncInterval,
1543 PresentFlags, &pre);
1544
1545 const auto ret = swapChainPresent1Hook.call_orig(
1546 chain, SyncInterval, PresentFlags, pPresentParameters);
1547
1550 &post, engine, engine->CustomContext);
1551
1553 engine, EvtHydraHookD3D12PostPresent, chain, SyncInterval,
1554 PresentFlags, &post);
1555
1556 return ret;
1557 }
1558 }
1559#endif
1560
1561#ifndef HYDRAHOOK_NO_D3D11
1562 if (runtime == DxgiRuntime::D3D11)
1563 {
1564 {
1565
1566 g_announce.present11.call([&pChain = chain]()
1567 {
1568 if (g_logD3D11) g_logD3D11->info(
1569 "++ IDXGISwapChain1::Present1 called (D3D11)");
1570
1571 StoreRenderPipelinePtr(engine->RenderPipeline.pSwapChain, pChain);
1572
1575 });
1576
1579 &pre, engine, engine->CustomContext);
1580
1582 engine, EvtHydraHookD3D11PrePresent, chain, SyncInterval,
1583 PresentFlags, &pre);
1584
1585 const auto ret = swapChainPresent1Hook.call_orig(
1586 chain, SyncInterval, PresentFlags, pPresentParameters);
1587
1590 &post, engine, engine->CustomContext);
1591
1593 engine, EvtHydraHookD3D11PostPresent, chain, SyncInterval,
1594 PresentFlags, &post);
1595
1596 return ret;
1597 }
1598 }
1599#endif
1600
1601#ifndef HYDRAHOOK_NO_D3D10
1602 if (runtime == DxgiRuntime::D3D10)
1603 {
1604 {
1605
1606 // Keep the lookup current if the game swaps its swap chain.
1607 StoreRenderPipelinePtr(engine->RenderPipeline.pSwapChain, chain);
1608 g_announce.present10.call([&pChain = chain]()
1609 {
1610 if (g_logD3D10) g_logD3D10->info(
1611 "++ IDXGISwapChain1::Present1 called (D3D10)");
1612
1613 StoreRenderPipelinePtr(engine->RenderPipeline.pSwapChain, pChain);
1614
1617 });
1618
1620 engine, EvtHydraHookD3D10PrePresent, chain, SyncInterval,
1621 PresentFlags);
1622
1623 const auto ret = swapChainPresent1Hook.call_orig(
1624 chain, SyncInterval, PresentFlags, pPresentParameters);
1625
1627 engine, EvtHydraHookD3D10PostPresent, chain, SyncInterval,
1628 PresentFlags);
1629
1630 return ret;
1631 }
1632 }
1633#endif
1634
1635 return swapChainPresent1Hook.call_orig(
1636 chain, SyncInterval, PresentFlags, pPresentParameters);
1637 });
1638 }
1639 catch (DetourException& ex)
1640 {
1641 logger->error("Hooking IDXGISwapChain1::Present1 failed: {}", ex.what());
1642 }
1643 }
1644
1645 if (dxgiResizeBuffers1Address != 0 && !swapChainResizeBuffers1Hook.is_applied())
1646 {
1647 try
1648 {
1649 logger->info("Hooking IDXGISwapChain3::ResizeBuffers1");
1650
1651 swapChainResizeBuffers1Hook.apply(dxgiResizeBuffers1Address, [](
1652 IDXGISwapChain3* chain,
1653 UINT BufferCount,
1654 UINT Width,
1655 UINT Height,
1656 DXGI_FORMAT NewFormat,
1657 UINT SwapChainFlags,
1658 const UINT* pCreationNodeMask,
1659 IUnknown* const* ppPresentQueue
1660 ) -> HRESULT
1661 {
1663
1664 if (!guard.invoke)
1665 return swapChainResizeBuffers1Hook.call_orig(
1666 chain, BufferCount, Width, Height, NewFormat, SwapChainFlags,
1667 pCreationNodeMask, ppPresentQueue);
1668
1669#ifndef HYDRAHOOK_NO_D3D12
1670 if (DispatchSwapChainDevice<ID3D12Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D12))
1671 {
1672 {
1673
1675 {
1676 if (g_logD3D12) g_logD3D12->info(
1677 "++ IDXGISwapChain3::ResizeBuffers1 called (D3D12)");
1678 });
1679
1682 &pre, engine, engine->CustomContext);
1683
1684 {
1685 D3D12ResizeCallbackScope callback(pre);
1687 engine, EvtHydraHookD3D12PreResizeBuffers, chain,
1688 BufferCount, Width, Height, NewFormat, SwapChainFlags,
1689 &pre);
1690 }
1691
1692 if (pre.Deferred)
1693 return DXGI_ERROR_WAS_STILL_DRAWING;
1694
1695 const auto ret = swapChainResizeBuffers1Hook.call_orig(
1696 chain, BufferCount, Width, Height, NewFormat,
1697 SwapChainFlags, pCreationNodeMask, ppPresentQueue);
1698
1699 if (SUCCEEDED(ret))
1700 {
1701 DXGI_SWAP_CHAIN_DESC1 desc{};
1702 const auto count = BufferCount ? BufferCount :
1703 (SUCCEEDED(chain->GetDesc1(&desc)) ? desc.BufferCount : 0);
1704 Microsoft::WRL::ComPtr<ID3D12CommandQueue> queue;
1705 queue.Attach(GetUniformD3D12PresentQueue(count, ppPresentQueue));
1706 RecordD3D12SwapChainQueue(chain, queue.Get());
1707 }
1710 &post, engine, engine->CustomContext);
1711
1713 engine, EvtHydraHookD3D12PostResizeBuffers, chain,
1714 BufferCount, Width, Height, NewFormat, SwapChainFlags,
1715 &post);
1716
1717 return ret;
1718 }
1719 }
1720#endif
1721
1722#ifndef HYDRAHOOK_NO_D3D11
1723 if (DispatchSwapChainDevice<ID3D11Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D11))
1724 {
1725 {
1726
1728 {
1729 if (g_logD3D11) g_logD3D11->info(
1730 "++ IDXGISwapChain3::ResizeBuffers1 called (D3D11)");
1731 });
1732
1735 &pre, engine, engine->CustomContext);
1736
1738 engine, EvtHydraHookD3D11PreResizeBuffers, chain,
1739 BufferCount, Width, Height, NewFormat, SwapChainFlags,
1740 &pre);
1741
1742 const auto ret = swapChainResizeBuffers1Hook.call_orig(
1743 chain, BufferCount, Width, Height, NewFormat,
1744 SwapChainFlags, pCreationNodeMask, ppPresentQueue);
1745
1748 &post, engine, engine->CustomContext);
1749
1751 engine, EvtHydraHookD3D11PostResizeBuffers, chain,
1752 BufferCount, Width, Height, NewFormat, SwapChainFlags,
1753 &post);
1754
1755 return ret;
1756 }
1757 }
1758#endif
1759
1760#ifndef HYDRAHOOK_NO_D3D10
1761 if (DispatchSwapChainDevice<ID3D10Device>(chain, engine->EngineConfig.Direct3D.HookDirect3D10))
1762 {
1763 {
1764
1766 {
1767 if (g_logD3D10) g_logD3D10->info(
1768 "++ IDXGISwapChain3::ResizeBuffers1 called (D3D10)");
1769 });
1770
1772 engine, EvtHydraHookD3D10PreResizeBuffers, chain,
1773 BufferCount, Width, Height, NewFormat, SwapChainFlags);
1774
1775 const auto ret = swapChainResizeBuffers1Hook.call_orig(
1776 chain, BufferCount, Width, Height, NewFormat,
1777 SwapChainFlags, pCreationNodeMask, ppPresentQueue);
1778
1780 engine, EvtHydraHookD3D10PostResizeBuffers, chain,
1781 BufferCount, Width, Height, NewFormat, SwapChainFlags);
1782
1783 return ret;
1784 }
1785 }
1786#endif
1787
1788 return swapChainResizeBuffers1Hook.call_orig(
1789 chain, BufferCount, Width, Height, NewFormat, SwapChainFlags,
1790 pCreationNodeMask, ppPresentQueue);
1791 });
1792 }
1793 catch (DetourException& ex)
1794 {
1795 logger->error("Hooking IDXGISwapChain3::ResizeBuffers1 failed: {}", ex.what());
1796 }
1797 }
1798
1799#pragma endregion
1800
1801#pragma region Core Audio
1802
1803#ifndef HYDRAHOOK_NO_COREAUDIO
1804
1805 if (config.CoreAudio.HookCoreAudio)
1806 {
1807 try
1808 {
1809 const std::unique_ptr<CoreAudioHooking::AudioRenderClientHook> arc(
1811
1812 logger->info("Hooking IAudioRenderClient::GetBuffer");
1813
1814 arcGetBufferHook.apply(arc->vtable()[CoreAudioHooking::GetBuffer], [](
1815 IAudioRenderClient* client,
1816 UINT32 NumFramesRequested,
1817 BYTE** ppData
1818 ) -> HRESULT
1819 {
1820 HookActivityTracker::Guard guard;
1821
1822 if (guard.invoke)
1823 {
1824 g_announce.arcGetBuffer.call([&pClient = client]()
1825 {
1826 if (g_logArc) g_logArc->info(
1827 "++ IAudioRenderClient::GetBuffer called");
1828
1829 engine->CoreAudio.pARC = pClient;
1830 });
1831
1832 HYDRAHOOK_EVT_PRE_EXTENSION pre;
1833 HYDRAHOOK_EVT_PRE_EXTENSION_INIT(&pre, engine, engine->CustomContext);
1834
1835 INVOKE_ARC_CALLBACK(engine, EvtHydraHookARCPreGetBuffer, client,
1836 NumFramesRequested, ppData, &pre);
1837 }
1838
1839 const auto ret = arcGetBufferHook.call_orig(client, NumFramesRequested, ppData);
1840
1841 if (guard.invoke)
1842 {
1843 HYDRAHOOK_EVT_POST_EXTENSION post;
1844 HYDRAHOOK_EVT_POST_EXTENSION_INIT(&post, engine, engine->CustomContext);
1845
1846 INVOKE_ARC_CALLBACK(engine, EvtHydraHookARCPostGetBuffer, client,
1847 NumFramesRequested, ppData, &post);
1848 }
1849
1850 return ret;
1851 });
1852
1853 logger->info("Hooking IAudioRenderClient::ReleaseBuffer");
1854
1855 arcReleaseBufferHook.apply(arc->vtable()[CoreAudioHooking::ReleaseBuffer], [](
1856 IAudioRenderClient* client,
1857 UINT32 NumFramesWritten,
1858 DWORD dwFlags
1859 ) -> HRESULT
1860 {
1862
1863 if (guard.invoke)
1864 {
1866 {
1867 if (g_logArc) g_logArc->info(
1868 "++ IAudioRenderClient::ReleaseBuffer called");
1869 });
1870
1872 HYDRAHOOK_EVT_PRE_EXTENSION_INIT(&pre, engine, engine->CustomContext);
1873
1874 INVOKE_ARC_CALLBACK(engine, EvtHydraHookARCPreReleaseBuffer, client,
1875 NumFramesWritten, dwFlags, &pre);
1876 }
1877
1878 const auto ret = arcReleaseBufferHook.call_orig(
1879 client, NumFramesWritten, dwFlags);
1880
1881 if (guard.invoke)
1882 {
1884 HYDRAHOOK_EVT_POST_EXTENSION_INIT(&post, engine, engine->CustomContext);
1885
1886 INVOKE_ARC_CALLBACK(engine, EvtHydraHookARCPostReleaseBuffer, client,
1887 NumFramesWritten, dwFlags, &post);
1888 }
1889
1890 return ret;
1891 });
1892 }
1893 catch (DetourException& ex)
1894 {
1895 logger->error("Hooking Core Audio (ARC) failed: {}", ex.what());
1896 }
1897 catch (ARCException& ex)
1898 {
1899 logger->error("Initializing Core Audio (ARC) failed: {} (HRESULT {})",
1900 ex.what(), ex.hresult());
1901 }
1902 catch (RuntimeException& ex)
1903 {
1904 logger->error("Core Audio (ARC) runtime error: {}", ex.what());
1905 }
1906 }
1907
1908#endif
1909
1910#pragma endregion
1911
1912 logger->info("Library initialized successfully");
1914
1915 //
1916 // Wait until cancellation requested
1917 //
1918 const auto result = WaitForSingleObject(engine->EngineCancellationEvent, INFINITE);
1919 if (result == WAIT_FAILED)
1920 logger->error("Shutting down hooks... wait failed: {}", GetLastError());
1921 else
1922 logger->info("Shutting down hooks... (result: {})", result);
1923 switch (result)
1924 {
1925 case WAIT_ABANDONED:
1926 logger->info("Shutting down hooks... Unknown state, host process might crash");
1927 break;
1928 case WAIT_OBJECT_0:
1929 logger->info("Shutting down hooks... Thread shutdown complete");
1930 break;
1931 case WAIT_FAILED:
1932 logger->info("Shutting down hooks... Unknown error, host process might crash");
1933 break;
1934 default:
1935 logger->info("Shutting down hooks... Unexpected return value, terminating");
1936 break;
1937 }
1938 //
1939 // Signal shutdown: new hook invocations will skip callbacks
1940 //
1942 logger->info("Shutdown flag set, new hook invocations will skip callbacks");
1943
1944 //
1945 // Notify host that we are about to release all render pipeline hooks
1946 //
1947 if (engine->EngineConfig.EvtHydraHookGamePreUnhook)
1948 {
1949 engine->EngineConfig.EvtHydraHookGamePreUnhook(engine);
1950 }
1951
1952 //
1953 // Remove all hooks -- after this no new threads can enter any lambda
1954 //
1955 bool allRemoved = true;
1956 const auto rm = [&allRemoved](auto& hook)
1957 {
1958 if (!hook.remove_nothrow())
1959 allRemoved = false;
1960 };
1961 {
1962 // Detach in reverse (LIFO) installation order as defense-in-depth so any
1963 // stacked Detours trampolines unwind cleanly.
1964#ifndef HYDRAHOOK_NO_COREAUDIO
1965 rm(arcReleaseBufferHook);
1966 rm(arcGetBufferHook);
1967#endif
1968
1969 rm(swapChainResizeBuffers1Hook);
1970 rm(swapChainPresent1Hook);
1971 rm(swapChainResizeBuffersHook);
1972 rm(swapChainResizeTargetHook);
1973 rm(swapChainPresentHook);
1974
1975#ifndef HYDRAHOOK_NO_D3D12
1976 rm(executeCommandLists12Hook);
1977 rm(createSwapChainForHwnd12Hook);
1978 rm(createSwapChain12Hook);
1980#endif
1981
1982#ifndef HYDRAHOOK_NO_D3D9
1983 rm(reset9ExHook);
1984 rm(present9ExHook);
1985 rm(endScene9Hook);
1986 rm(reset9Hook);
1987 rm(present9Hook);
1988#endif
1989 }
1990
1991 //
1992 // A manual unhook keeps the DLL loaded, so the flow-control hooks must go too
1993 //
1994 if (engine->SkipDllUnloadOnExit.load(std::memory_order_acquire)
1995 && !engine->FreeLibraryHookActive.load(std::memory_order_acquire))
1996 {
2000 }
2001
2002 if (allRemoved)
2003 logger->info("Hooks disabled");
2004 else
2005 logger->error("Unhooking failed for at least one hook");
2006
2007 //
2008 // Wait for all in-flight hook lambdas to finish before touching
2009 // callback tables or unloading the DLL
2010 //
2012 {
2013 logger->error("Timed out waiting for in-flight callbacks to drain");
2014 engine->DrainIncomplete.store(true, std::memory_order_release);
2015 }
2016 else
2017 {
2018 logger->info("All in-flight hook callbacks drained");
2019 engine->DrainIncomplete.store(false, std::memory_order_release);
2021
2022 ZeroMemory(&engine->EventsD3D9, sizeof(engine->EventsD3D9));
2023 ZeroMemory(&engine->EventsD3D10, sizeof(engine->EventsD3D10));
2024 ZeroMemory(&engine->EventsD3D11, sizeof(engine->EventsD3D11));
2025 ZeroMemory(&engine->EventsD3D12, sizeof(engine->EventsD3D12));
2026 ZeroMemory(&engine->EventsARC, sizeof(engine->EventsARC));
2027
2028#ifndef HYDRAHOOK_NO_D3D12
2029 if (ownedDxgiModule && allRemoved)
2030 {
2031 FreeLibrary(ownedDxgiModule);
2032 ownedDxgiModule = nullptr;
2033 }
2034#endif
2035 }
2036
2037 //
2038 // Notify host that we released all render pipeline hooks
2039 //
2040 if (engine->EngineConfig.EvtHydraHookGamePostUnhook)
2041 {
2042 engine->EngineConfig.EvtHydraHookGamePostUnhook(engine);
2043 }
2044
2045 logger->info("Exiting worker thread");
2046
2047 const std::uint32_t ipcOrigin = engine->LastShutdownOrigin.load(std::memory_order_acquire);
2048 std::uint32_t ipcFlags = 0;
2049 if (engine->DrainIncomplete.load(std::memory_order_acquire))
2051 const bool manualUnhook = ipcOrigin == HydraHookIpcShutdownOriginManualUnhook;
2052 const bool postQuit = ipcOrigin == HydraHookIpcShutdownOriginPostQuitMessage;
2053 const bool rehookAllowed = !engine->RehookDisabled.load(std::memory_order_acquire)
2054 && engine->RehookWait != nullptr
2055 && (manualUnhook || (postQuit && HydraHookPinWorkerModule()));
2056 if (rehookAllowed)
2058 if ((ipcFlags & HydraHookIpcFlagRehookSupported) != 0)
2061 static_cast<std::uint32_t>(engine->GameVersion.load(std::memory_order_acquire)),
2062 ipcFlags);
2063
2065
2066 if (engine->FreeLibraryHookActive.load(std::memory_order_acquire)
2067 || engine->SkipDllUnloadOnExit.load(std::memory_order_acquire))
2068 {
2069 ExitThread(0);
2070 }
2071 else
2072 {
2073 FreeLibraryAndExitThread(engine->HostInstance, 0);
2074 }
2075}
2076
2077ID3D12CommandQueue* GetUniformD3D12PresentQueue(UINT bufferCount, IUnknown* const* presentQueues)
2078{
2079 if (!bufferCount || !presentQueues || !presentQueues[0])
2080 return nullptr;
2081 Microsoft::WRL::ComPtr<ID3D12CommandQueue> queue;
2082 Microsoft::WRL::ComPtr<IUnknown> identity;
2083 if (FAILED(presentQueues[0]->QueryInterface(IID_PPV_ARGS(&queue))) ||
2084 queue->GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT || FAILED(queue.As(&identity)))
2085 return nullptr;
2086 for (UINT i = 1; i < bufferCount; ++i)
2087 {
2088 Microsoft::WRL::ComPtr<IUnknown> other;
2089 if (!presentQueues[i] || FAILED(presentQueues[i]->QueryInterface(IID_PPV_ARGS(&other))) || other.Get() != identity.Get())
2090 return nullptr;
2091 }
2092 return queue.Detach();
2093}
2094
2095#if defined(_M_X64) && !defined(_M_ARM64EC) && !defined(HYDRAHOOK_NO_D3D12)
2096static const BYTE* GetSupportedDXGIModule() noexcept
2097{
2098 const auto status = static_cast<DxgiModuleStatus>(g_dxgiModuleStatus.load(std::memory_order_acquire));
2099 if (status == DxgiModuleStatus::Supported)
2100 return g_dxgiModuleImage.load(std::memory_order_acquire);
2101 if (status == DxgiModuleStatus::Unsupported)
2102 return nullptr;
2103
2104 // RSDS, dxgi.pdb GUID 5772469f-b293-d6ca-f3c5-c6e237984b9f, age 1.
2105 // This is the x64 DXGI build 26100.9818 used to verify the private ABI.
2106 constexpr BYTE codeView[] = {
2107 'R', 'S', 'D', 'S', 0x9f, 0x46, 0x72, 0x57, 0x93, 0xb2, 0xca, 0xd6,
2108 0xf3, 0xc5, 0xc6, 0xe2, 0x37, 0x98, 0x4b, 0x9f, 1, 0, 0, 0
2109 };
2110 const auto* image = reinterpret_cast<const BYTE*>(GetModuleHandleW(L"dxgi.dll"));
2111 if (!image)
2112 return nullptr;
2113
2114 // Windows has already mapped and validated the PE headers. Bound the debug
2115 // directory and CodeView reads to the loaded image.
2116 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(image);
2117 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(image + dos->e_lfanew);
2118 if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64 ||
2119 nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_DEBUG)
2120 {
2121 g_dxgiModuleStatus.store(static_cast<std::uint32_t>(DxgiModuleStatus::Unsupported), std::memory_order_release);
2122 return nullptr;
2123 }
2124
2125 const DWORD imageSize = nt->OptionalHeader.SizeOfImage;
2126 const auto& directory = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
2127 if (!directory.VirtualAddress || directory.VirtualAddress >= imageSize ||
2128 directory.Size > imageSize - directory.VirtualAddress)
2129 {
2130 g_dxgiModuleStatus.store(static_cast<std::uint32_t>(DxgiModuleStatus::Unsupported), std::memory_order_release);
2131 return nullptr;
2132 }
2133
2134 const auto* entries = reinterpret_cast<const IMAGE_DEBUG_DIRECTORY*>(image + directory.VirtualAddress);
2135 for (size_t i = 0; i < directory.Size / sizeof(*entries); ++i)
2136 {
2137 const auto& entry = entries[i];
2138 if (entry.Type == IMAGE_DEBUG_TYPE_CODEVIEW && entry.SizeOfData >= sizeof(codeView) &&
2139 entry.AddressOfRawData && entry.AddressOfRawData < imageSize &&
2140 sizeof(codeView) <= imageSize - entry.AddressOfRawData &&
2141 std::memcmp(image + entry.AddressOfRawData, codeView, sizeof(codeView)) == 0)
2142 {
2143 g_dxgiModuleImage.store(image, std::memory_order_release);
2144 g_dxgiModuleStatus.store(static_cast<std::uint32_t>(DxgiModuleStatus::Supported), std::memory_order_release);
2145 return image;
2146 }
2147 }
2148 g_dxgiModuleStatus.store(static_cast<std::uint32_t>(DxgiModuleStatus::Unsupported), std::memory_order_release);
2149 return nullptr;
2150}
2151
2152static ID3D12CommandQueue* GetPrivateD3D12PresentQueue(IDXGISwapChain* chain)
2153{
2154 const auto* image = GetSupportedDXGIModule();
2155 if (!image)
2156 return nullptr;
2157
2158 // IDXGISwapChainInternal slots 0-2 are IUnknown. AcquireBuffer and
2159 // GetResourceParent precede GetCurrentCommandQueue at slot 5.
2160 constexpr IID iid = {0xd75fab3e, 0x73b6, 0x4fdf, {0xa4, 0x7e, 0xf3, 0x5c, 0xa1, 0x8a, 0x7d, 0xbf}};
2161 Microsoft::WRL::ComPtr<IUnknown> internal;
2162 if (FAILED(chain->QueryInterface(iid, reinterpret_cast<void**>(internal.GetAddressOf()))) || !internal)
2163 return nullptr;
2164
2165 // Only invoke the implementation verified in the matched image. A wrapper
2166 // may expose the same IID with its own vtable.
2167 const auto* const* vtable = *reinterpret_cast<const void* const* const*>(internal.Get());
2168 const void* method = vtable[5];
2169 if (method != image + 0x6f40)
2170 return nullptr;
2171
2172 using GetCurrentCommandQueue = HRESULT (STDMETHODCALLTYPE*)(IUnknown*, REFIID, void**);
2173 Microsoft::WRL::ComPtr<ID3D12CommandQueue> queue;
2174 if (FAILED(reinterpret_cast<GetCurrentCommandQueue>(method)(internal.Get(), IID_PPV_ARGS(&queue))) ||
2175 !queue || queue->GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT)
2176 return nullptr;
2177
2178 static std::atomic_flag logged{};
2179 if (!logged.test_and_set(std::memory_order_relaxed))
2180 {
2181 if (const auto logger = spdlog::get("HYDRAHOOK"))
2182 logger->info("Resolved the D3D12 presentation queue through the signature-matched DXGI getter");
2183 }
2184 return queue.Detach();
2185}
2186#endif
2187
2188ID3D12CommandQueue* GetD3D12CommandQueueForSwapChain(IDXGISwapChain* pSwapChain, bool requireVerifiedQueue)
2189{
2190#ifndef HYDRAHOOK_NO_D3D12
2191 if (!pSwapChain)
2192 return nullptr;
2193
2194 // 1. Exact association from swap-chain creation or a successful ResizeBuffers1.
2195 {
2197 const auto it = g_d3d12SwapChainToQueue.find(pSwapChain);
2198 if (it != g_d3d12SwapChainToQueue.end() && it->second)
2199 {
2200 it->second->AddRef();
2201 return it->second;
2202 }
2203 }
2204 // 2. Exact association for the current buffer on a known DXGI build.
2205#if defined(_M_X64) && !defined(_M_ARM64EC)
2206 if (auto* queue = GetPrivateD3D12PresentQueue(pSwapChain))
2207 return queue;
2208#endif
2209 if (requireVerifiedQueue)
2210 return nullptr;
2211 // 3. Device-scoped fallback captured from ExecuteCommandLists.
2212 Microsoft::WRL::ComPtr<ID3D12Device> device;
2213 if (SUCCEEDED(pSwapChain->GetDevice(IID_PPV_ARGS(&device))) && device)
2214 {
2216 const auto devIt = g_d3d12DeviceToQueue.find(device.Get());
2217 if (devIt != g_d3d12DeviceToQueue.end() && devIt->second)
2218 {
2219 devIt->second->AddRef();
2220 return devIt->second;
2221 }
2222 }
2223#endif
2224 return nullptr;
2225}
IAudioRenderClient vtable hook for Core Audio interception.
void HydraHookCrashHandlerInstallThreadSEH()
Installs the per-thread SEH-to-C++ translator on the calling thread.
Internal crash handler installation and teardown.
IDXGISwapChain vtable indices for D3D10/11/12 hooking.
Direct3D 9 device vtable indices and hook implementation.
Direct3D 9Ex device vtable indices (extends Direct3D9).
HYDRAHOOK_ERROR HydraHookEngineDestroyBeforeUnload(HMODULE host, bool(*detachFreeLibraryHook)() noexcept)
Tears down the registered engine before explicit unload. Busy failures keep the hook installed.
Definition Engine.cpp:573
void HydraHookLoggingEnableAsync()
Swaps the process logger to a HydraHook-owned async pool. Call from the worker, not DllMain.
Definition Engine.cpp:961
bool HydraHookPinWorkerModule()
Pins the module that contains this engine for the rest of the process.
Definition Engine.cpp:150
std::shared_ptr< spdlog::logger > HydraHookCloneRegisteredLogger(const char *channel)
Clones the registered HYDRAHOOK logger; replacement cannot drop it during this call....
Definition Engine.cpp:1059
void HydraHookLoggingDisableAsync()
Flushes, restores the sync logger, and joins the async pool. Call from the worker,...
Definition Engine.cpp:1016
Internal engine structure and callback invocation macros.
#define INVOKE_D3D10_CALLBACK(_engine_, _callback_,...)
Invokes D3D10 callback if registered.
Definition Engine.h:274
#define INVOKE_ARC_CALLBACK(_engine_, _callback_,...)
Invokes Core Audio callback if registered.
Definition Engine.h:295
#define INVOKE_D3D9_CALLBACK(_engine_, _callback_,...)
Invokes D3D9 callback if registered.
Definition Engine.h:267
void StoreRenderPipelinePtr(std::atomic< T * > &slot, U *value)
Publishes a RenderPipeline pointer. Render threads write it while other threads look engines up by it...
Definition Engine.h:143
#define INVOKE_D3D11_CALLBACK(_engine_, _callback_,...)
Invokes D3D11 callback if registered.
Definition Engine.h:281
#define INVOKE_HYDRAHOOK_GAME_HOOKED(_engine_, _version_)
Invokes EvtHydraHookGameHooked if non-NULL.
Definition Engine.h:257
#define INVOKE_D3D12_CALLBACK(_engine_, _callback_,...)
Invokes D3D12 callback if registered.
Definition Engine.h:288
void HydraHookIpcArmRehookWait(PHYDRAHOOK_ENGINE engine)
void HydraHookIpcPublish(PHYDRAHOOK_ENGINE engine, std::uint32_t state, std::uint32_t origin, std::uint32_t gameVersion, std::uint32_t flags)
void HydraHookIpcPublishRunning(PHYDRAHOOK_ENGINE engine)
Moves Initializing to Running. Does not write the graphics API a Hooked publish owns.
constexpr std::uint32_t HydraHookIpcShutdownOriginDllMainDetach
Definition EngineIpc.h:56
constexpr std::uint32_t HydraHookIpcFlagRehookSupported
Definition EngineIpc.h:59
constexpr std::uint32_t HydraHookIpcStateStopped
Definition EngineIpc.h:50
constexpr std::uint32_t HydraHookIpcShutdownOriginManualUnhook
Definition EngineIpc.h:57
constexpr std::uint32_t HydraHookIpcShutdownOriginExitProcess
Definition EngineIpc.h:53
constexpr std::uint32_t HydraHookIpcShutdownOriginFreeLibrary
Definition EngineIpc.h:55
constexpr std::uint32_t HydraHookIpcShutdownOriginPostQuitMessage
Definition EngineIpc.h:54
constexpr std::uint32_t HydraHookIpcShutdownOriginNone
Definition EngineIpc.h:52
constexpr std::uint32_t HydraHookIpcStateShuttingDown
Definition EngineIpc.h:49
constexpr std::uint32_t HydraHookIpcFlagDrainIncomplete
Definition EngineIpc.h:60
HydraHook exception types (Detours, Win32, generic).
static struct HookAnnouncements g_announce
static std::unordered_map< IDXGISwapChain *, ID3D12CommandQueue * > g_d3d12SwapChainToQueue
Definition Game.cpp:86
static void ClearChannelLoggers()
Definition Game.cpp:208
static Hook< CallConvention::stdcall_t, VOID, UINT > g_exitProcessHook
Definition Game.cpp:155
static void D3D12_ReleaseQueueMaps()
Definition Game.cpp:126
static SRWLOCK g_d3d12QueueMapLock
Definition Game.cpp:85
static std::atomic< ID3D12CommandQueue * > g_lastObservedDirectQueue
Definition Game.cpp:89
ID3D12CommandQueue * GetUniformD3D12PresentQueue(UINT bufferCount, IUnknown *const *presentQueues)
Definition Game.cpp:2077
static std::shared_ptr< spdlog::logger > g_logD3D12
Definition Game.cpp:192
static void BindChannelLoggers()
Definition Game.cpp:195
static std::atomic< const BYTE * > g_dxgiModuleImage
Definition Game.cpp:98
static std::atomic< HMODULE > g_freeLibraryHost
Definition Game.cpp:159
void PerformShutdownCleanup(PHYDRAHOOK_ENGINE engine, ShutdownOrigin origin)
Performs pre-exit cleanup based on shutdown origin.
Definition Game.cpp:315
DxgiRuntime DetectDxgiRuntime(IDXGISwapChain *chain)
Definition Game.cpp:241
static std::shared_ptr< spdlog::logger > g_logD3D9
Definition Game.cpp:189
static std::unordered_map< ID3D12Device *, ID3D12CommandQueue * > g_d3d12DeviceToQueue
Runtime capture: device -> queue (for mid-process injection when CreateSwapChain already ran).
Definition Game.cpp:88
static std::shared_ptr< spdlog::logger > g_logD3D10
Definition Game.cpp:190
static void ResetDxgiModuleCache() noexcept
Definition Game.cpp:100
static PHYDRAHOOK_ENGINE engine
Definition Game.cpp:165
bool DispatchSwapChainDevice(IDXGISwapChain *chain, BOOL enabled)
True when this swap chain was created for TDevice and that API is enabled.
Definition Game.cpp:220
DxgiModuleStatus
Definition Game.cpp:92
static std::shared_ptr< spdlog::logger > g_logGame
Definition Game.cpp:188
static Hook< CallConvention::stdcall_t, BOOL, HMODULE > g_freeLibraryHook
Definition Game.cpp:157
static std::shared_ptr< spdlog::logger > g_logArc
Definition Game.cpp:193
static std::atomic< std::uint32_t > g_dxgiModuleStatus
Definition Game.cpp:97
static std::atomic< HMODULE > g_freeLibraryTarget
Definition Game.cpp:158
static std::shared_ptr< spdlog::logger > g_logD3D11
Definition Game.cpp:191
ID3D12CommandQueue * GetD3D12CommandQueueForSwapChain(IDXGISwapChain *pSwapChain, bool requireVerifiedQueue)
Returns the D3D12 command queue associated with a swap chain.
Definition Game.cpp:2188
std::uint32_t IpcShutdownOrigin(ShutdownOrigin origin)
Definition Game.cpp:296
DxgiRuntime
Definition Game.cpp:234
static void RecordD3D12SwapChainQueue(IDXGISwapChain *chain, ID3D12CommandQueue *queue)
Definition Game.cpp:106
DWORD HydraHookMainThread(LPVOID Params)
Main hook worker thread; probes and hooks render and audio APIs.
Definition Game.cpp:451
static Hook< CallConvention::stdcall_t, void, int > g_postQuitMessageHook
Definition Game.cpp:156
Main hook worker thread entry point.
bool g_suppressD3D12QueueCapture
Definition Game.h:69
Utility functions for environment expansion and process info.
C++ wrapper for Microsoft Detours function hooking.
Core engine API for HydraHook - Direct3D and Core Audio hooking library.
VOID HYDRAHOOK_EVT_POST_EXTENSION_INIT(PHYDRAHOOK_EVT_POST_EXTENSION Extension, PHYDRAHOOK_ENGINE Engine, PVOID Context)
Initializes a post-extension structure for event callbacks.
HYDRAHOOK_D3D_VERSION
Bitmask of detected Direct3D API versions.
@ HydraHookDirect3DVersion12
@ HydraHookDirect3DVersionUnknown
@ HydraHookDirect3DVersion10
@ HydraHookDirect3DVersion9
@ HydraHookDirect3DVersion11
@ HYDRAHOOK_ERROR_NONE
struct _HYDRAHOOK_ENGINE * PHYDRAHOOK_ENGINE
Opaque handle to the HydraHook engine instance.
VOID HYDRAHOOK_EVT_PRE_EXTENSION_INIT(PHYDRAHOOK_EVT_PRE_EXTENSION Extension, PHYDRAHOOK_ENGINE Engine, PVOID Context)
Initializes a pre-extension structure for event callbacks.
Core Audio (IAudioRenderClient) hook callbacks.
Direct3D 10 hook callbacks and helpers.
Direct3D 11 hook callbacks and helpers.
Direct3D 12 hook callbacks.
Direct3D 9/9Ex hook callbacks and helpers.
Internal shutdown origin and cleanup for HydraHook engine.
ShutdownOrigin
Origin of the shutdown request; determines what is safe to call.
Definition Shutdown.h:20
@ DllMainProcessDetach
Definition Shutdown.h:24
@ PostQuitMessageHook
Definition Shutdown.h:22
RAII guards for Win32 SRWLOCK.
RAII Detours hook wrapper for function interception.
Definition Hook.h:86
void apply(T pFunc, type detour)
Attaches detour to target function.
Definition Hook.h:208
retn call_orig(args ... p)
Calls the original (unhooked) function.
Definition Hook.h:354
Once-per-hook announcement guard that can be re-armed.
Definition Engine.h:57
void call(Fn &&fn)
Runs fn once until reset() is called; concurrent callers wait for the first.
Definition Engine.h:61
void reset()
Re-arms the guard.
Definition Engine.h:75
Exclusive (writer) lock. Call unlock() to release before COM Release or similar.
Definition SrwLock.h:45
Shared (reader) lock. Call unlock() to release before COM Release or similar.
Definition SrwLock.h:17
constexpr int CreateSwapChainForHwnd
Definition DXGI.h:42
constexpr int CreateSwapChain
Definition DXGI.h:41
@ ResizeTarget
Definition DXGI.h:69
@ Present
Definition DXGI.h:63
@ ResizeBuffers
Definition DXGI.h:68
std::string process_name()
Returns the full path of the current process executable.
Definition Global.h:72
Extension data passed to post-hook event callbacks (D3D11/12, Core Audio).
Extension data passed to pre-hook event callbacks (D3D11/12, Core Audio).
RAII guard placed at the top of every hook lambda.
Definition Engine.h:186
static void shutdown() noexcept
Sets the shutdown flag so new Guard instances skip callbacks.
Definition Engine.h:205
static bool drain(DWORD timeout_ms=5000) noexcept
Spin-waits until every in-flight lambda has returned.
Definition Engine.h:226
Once-per-hook announcements; re-armed at the start of every worker run.
Definition Game.cpp:169
ResettableOnce present12
Definition Game.cpp:173
ResettableOnce arcGetBuffer
Definition Game.cpp:175
ResettableOnce endScene9
Definition Game.cpp:170
ResettableOnce resizeBuffers11
Definition Game.cpp:172
ResettableOnce resizeBuffers1D3D12
Definition Game.cpp:174
ResettableOnce arcReleaseBuffer
Definition Game.cpp:175
ResettableOnce resizeBuffers1D3D10
Definition Game.cpp:174
ResettableOnce resizeTarget12
Definition Game.cpp:173
ResettableOnce reset9
Definition Game.cpp:170
ResettableOnce present10
Definition Game.cpp:171
ResettableOnce resizeTarget10
Definition Game.cpp:171
ResettableOnce present11
Definition Game.cpp:172
ResettableOnce resizeBuffers12
Definition Game.cpp:173
ResettableOnce resizeTarget11
Definition Game.cpp:172
void reset_all()
Definition Game.cpp:177
ResettableOnce reset9Ex
Definition Game.cpp:170
ResettableOnce present9
Definition Game.cpp:170
ResettableOnce resizeBuffers10
Definition Game.cpp:171
ResettableOnce resizeBuffers1D3D11
Definition Game.cpp:174
Suppresses ExecuteCommandLists queue observation on this thread (readback, worker probes).
Definition Game.h:73