HydraHook
Direct3D and Core Audio hooking library for Windows
Loading...
Searching...
No Matches
Engine.h
Go to the documentation of this file.
1
11
12/*
13MIT License
14
15Copyright (c) 2018-2026 Benjamin Höglinger-Stelzer
16
17Permission is hereby granted, free of charge, to any person obtaining a copy
18of this software and associated documentation files (the "Software"), to deal
19in the Software without restriction, including without limitation the rights
20to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21copies of the Software, and to permit persons to whom the Software is
22furnished to do so, subject to the following conditions:
23
24The above copyright notice and this permission notice shall be included in all
25copies or substantial portions of the Software.
26
27THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33SOFTWARE.
34*/
35
36
37#pragma once
38
39#include <atomic>
40#include <memory>
41#include <mutex>
42
43namespace spdlog
44{
45 class logger;
46}
47
48#include "EngineIpc.h"
49
57{
58public:
60 template <typename Fn>
61 void call(Fn&& fn)
62 {
63 if (done_.load(std::memory_order_acquire))
64 return;
65
66 std::lock_guard<std::mutex> lock(mutex_);
67 if (done_.load(std::memory_order_acquire))
68 return;
69
70 fn();
71 done_.store(true, std::memory_order_release);
72 }
73
75 void reset()
76 {
77 std::lock_guard<std::mutex> lock(mutex_);
78 done_.store(false, std::memory_order_release);
79 }
80
81private:
82 std::mutex mutex_;
83 std::atomic<bool> done_{false};
84};
85
89typedef struct _HYDRAHOOK_ENGINE
90{
91 HMODULE HostInstance = nullptr;
92 HMODULE DllModule = nullptr;
93 std::atomic<HYDRAHOOK_D3D_VERSION> GameVersion{HydraHookDirect3DVersionUnknown};
105 SRWLOCK LifecycleLock = SRWLOCK_INIT;
106 std::atomic<bool> SkipDllUnloadOnExit{false};
107 std::atomic<bool> DrainIncomplete{false};
108 HANDLE EngineThread = nullptr;
109 HANDLE EngineCancellationEvent = nullptr;
110 std::atomic<PVOID> CustomContext{nullptr};
112 std::atomic<bool> ShutdownCleanupDone{false};
113 std::atomic<bool> FreeLibraryHookActive{false};
114 HANDLE IpcStateMap = nullptr;
115 PVOID IpcStateView = nullptr;
116 HANDLE RehookEvent = nullptr;
117 PTP_WAIT RehookWait = nullptr;
119 std::atomic<uint32_t> RehookOwnerThread{0};
120 std::atomic<bool> RehookDisabled{false};
121 std::atomic<uint32_t> IpcGeneration{0};
123
125 {
126 std::atomic<IDXGISwapChain*> pSwapChain{nullptr};
127 std::atomic<LPDIRECT3DDEVICE9> pD3D9Device{nullptr};
128 std::atomic<LPDIRECT3DDEVICE9EX> pD3D9ExDevice{nullptr};
129 } RenderPipeline{};
130
131 struct
132 {
133 IAudioRenderClient *pARC = nullptr;
134 } CoreAudio{};
135
137
142template <typename T, typename U>
143inline void StoreRenderPipelinePtr(std::atomic<T*>& slot, U* value)
144{
145 if (slot.load(std::memory_order_relaxed) == value)
146 return;
147 slot.store(value, std::memory_order_release);
148}
149
151template <typename Pipeline>
152inline void ClearRenderPipeline(Pipeline& pipeline)
153{
154 pipeline.pSwapChain.store(nullptr, std::memory_order_release);
155 pipeline.pD3D9Device.store(nullptr, std::memory_order_release);
156 pipeline.pD3D9ExDevice.store(nullptr, std::memory_order_release);
157}
158
159template <typename T>
160inline T* LoadRenderPipelinePtr(const std::atomic<T*>& slot)
161{
162 return slot.load(std::memory_order_acquire);
163}
164
174{
175 alignas(64) static inline std::atomic<int32_t> s_active{0};
176 alignas(64) static inline std::atomic<bool> s_shutting_down{false};
177
185 struct Guard
186 {
187 bool invoke;
188
189 Guard() noexcept
190 {
191 s_active.fetch_add(1, std::memory_order_seq_cst);
192 invoke = !s_shutting_down.load(std::memory_order_seq_cst);
193 }
194
195 ~Guard() noexcept
196 {
197 s_active.fetch_sub(1, std::memory_order_release);
198 }
199
200 Guard(const Guard&) = delete;
201 Guard& operator=(const Guard&) = delete;
202 };
203
205 static void shutdown() noexcept
206 {
207 s_shutting_down.store(true, std::memory_order_seq_cst);
208 }
209
211 static void reset() noexcept
212 {
213 s_shutting_down.store(false, std::memory_order_seq_cst);
214 }
215
226 static bool drain(DWORD timeout_ms = 5000) noexcept
227 {
228 const ULONGLONG deadline = GetTickCount64() + timeout_ms;
229 while (s_active.load(std::memory_order_seq_cst) > 0)
230 {
231 if (GetTickCount64() >= deadline)
232 return false;
233 SwitchToThread();
234 }
235 return true;
236 }
237};
238
241
244
247
251std::shared_ptr<spdlog::logger> HydraHookCloneRegisteredLogger(const char* channel);
252
254HYDRAHOOK_ERROR HydraHookEngineDestroyBeforeUnload(HMODULE host, bool (*detachFreeLibraryHook)() noexcept);
255
257#define INVOKE_HYDRAHOOK_GAME_HOOKED(_engine_, _version_) \
258 do { \
259 (_engine_)->GameVersion = (_version_); \
260 HydraHookIpcPublish((_engine_), HydraHookIpcStateHooked, HydraHookIpcShutdownOriginNone, \
261 static_cast<std::uint32_t>(_version_), 0); \
262 if ((_engine_)->EngineConfig.EvtHydraHookGameHooked) \
263 (_engine_)->EngineConfig.EvtHydraHookGameHooked((_engine_), (_version_)); \
264 } while (0)
265
267#define INVOKE_D3D9_CALLBACK(_engine_, _callback_, ...) \
268 do { \
269 const auto _pfn_ = (_engine_)->EventsD3D9._callback_; \
270 if (_pfn_) _pfn_(##__VA_ARGS__); \
271 } while(0)
272
274#define INVOKE_D3D10_CALLBACK(_engine_, _callback_, ...) \
275 do { \
276 const auto _pfn_ = (_engine_)->EventsD3D10._callback_; \
277 if (_pfn_) _pfn_(##__VA_ARGS__); \
278 } while(0)
279
281#define INVOKE_D3D11_CALLBACK(_engine_, _callback_, ...) \
282 do { \
283 const auto _pfn_ = (_engine_)->EventsD3D11._callback_; \
284 if (_pfn_) _pfn_(##__VA_ARGS__); \
285 } while(0)
286
288#define INVOKE_D3D12_CALLBACK(_engine_, _callback_, ...) \
289 do { \
290 const auto _pfn_ = (_engine_)->EventsD3D12._callback_; \
291 if (_pfn_) _pfn_(##__VA_ARGS__); \
292 } while(0)
293
295#define INVOKE_ARC_CALLBACK(_engine_, _callback_, ...) \
296 do { \
297 const auto _pfn_ = (_engine_)->EventsARC._callback_; \
298 if (_pfn_) _pfn_(##__VA_ARGS__); \
299 } while(0)
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
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
T * LoadRenderPipelinePtr(const std::atomic< T * > &slot)
Definition Engine.h:160
void ClearRenderPipeline(Pipeline &pipeline)
Resets every RenderPipeline pointer atomically, so concurrent lookups never see a torn value.
Definition Engine.h:152
Session-local shared-memory engine status and rehook control.
constexpr std::uint32_t HydraHookIpcShutdownOriginNone
Definition EngineIpc.h:52
constexpr std::int32_t HydraHookIpcPhaseIdle
Definition EngineIpc.h:62
@ HydraHookDirect3DVersionUnknown
HYDRAHOOK_ERROR
Error codes returned by HydraHook engine functions.
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
Core Audio (IAudioRenderClient) event callback collection.
Direct3D 10 event callback collection.
Direct3D 11 event callback collection.
Direct3D 12 event callback collection.
Direct3D 9/9Ex event callback collection.
std::atomic< LPDIRECT3DDEVICE9 > pD3D9Device
Definition Engine.h:127
std::atomic< IDXGISwapChain * > pSwapChain
Definition Engine.h:126
std::atomic< LPDIRECT3DDEVICE9EX > pD3D9ExDevice
Definition Engine.h:128
Engine configuration passed to HydraHookEngineCreate. Initialize with HYDRAHOOK_ENGINE_CONFIG_INIT....
Internal engine instance structure (opaque in public API).
Definition Engine.h:90
HANDLE EngineThread
Definition Engine.h:108
HANDLE IpcStateMap
Definition Engine.h:114
HYDRAHOOK_D3D10_EVENT_CALLBACKS EventsD3D10
Definition Engine.h:96
HMODULE HostInstance
Definition Engine.h:91
std::atomic< bool > DrainIncomplete
Definition Engine.h:107
HYDRAHOOK_D3D12_EVENT_CALLBACKS SavedEventsD3D12
Definition Engine.h:103
std::atomic< uint32_t > LastShutdownOrigin
Definition Engine.h:122
HYDRAHOOK_ARC_EVENT_CALLBACKS SavedEventsARC
Definition Engine.h:104
HANDLE RehookEvent
Definition Engine.h:116
HYDRAHOOK_D3D10_EVENT_CALLBACKS SavedEventsD3D10
Definition Engine.h:101
HYDRAHOOK_D3D9_EVENT_CALLBACKS EventsD3D9
Definition Engine.h:95
std::atomic< uint32_t > IpcGeneration
Definition Engine.h:121
HANDLE EngineCancellationEvent
Definition Engine.h:109
std::atomic< uint32_t > RehookOwnerThread
Definition Engine.h:119
std::atomic< int32_t > RehookWaitPhase
Definition Engine.h:118
HYDRAHOOK_D3D11_EVENT_CALLBACKS SavedEventsD3D11
Definition Engine.h:102
HYDRAHOOK_D3D12_EVENT_CALLBACKS EventsD3D12
Definition Engine.h:98
PTP_WAIT RehookWait
Definition Engine.h:117
SRWLOCK LifecycleLock
Definition Engine.h:105
PVOID IpcStateView
Definition Engine.h:115
HYDRAHOOK_ARC_EVENT_CALLBACKS EventsARC
Definition Engine.h:99
std::atomic< bool > ShutdownCleanupDone
Definition Engine.h:112
std::atomic< bool > FreeLibraryHookActive
Definition Engine.h:113
std::atomic< HYDRAHOOK_D3D_VERSION > GameVersion
Definition Engine.h:93
HYDRAHOOK_D3D9_EVENT_CALLBACKS SavedEventsD3D9
Definition Engine.h:100
BOOL CrashHandlerInstalled
Definition Engine.h:111
HMODULE DllModule
Definition Engine.h:92
HYDRAHOOK_ENGINE_CONFIG EngineConfig
Definition Engine.h:94
HYDRAHOOK_D3D11_EVENT_CALLBACKS EventsD3D11
Definition Engine.h:97
std::atomic< bool > SkipDllUnloadOnExit
Definition Engine.h:106
std::atomic< PVOID > CustomContext
Definition Engine.h:110
std::atomic< bool > RehookDisabled
Definition Engine.h:120
Guard(const Guard &)=delete
Guard & operator=(const Guard &)=delete
Lock-free tracker for in-flight hook lambda invocations.
Definition Engine.h:174
static void shutdown() noexcept
Sets the shutdown flag so new Guard instances skip callbacks.
Definition Engine.h:205
static std::atomic< bool > s_shutting_down
Definition Engine.h:176
static void reset() noexcept
Clears the shutdown flag so a rehook invokes callbacks again.
Definition Engine.h:211
static bool drain(DWORD timeout_ms=5000) noexcept
Spin-waits until every in-flight lambda has returned.
Definition Engine.h:226
static std::atomic< int32_t > s_active
Definition Engine.h:175