HydraHook
Direct3D and Core Audio hooking library for Windows
Loading...
Searching...
No Matches
EngineIpc.cpp
Go to the documentation of this file.
1
8
9#define WIN32_LEAN_AND_MEAN
10#include <Windows.h>
11
18
19#include "EngineIpc.h"
20#include "Engine.h"
21#include "Utils/SrwLock.h"
22
23#include <spdlog/spdlog.h>
24
25#include <cstring>
26
27std::atomic<HydraHookIpcRehookHold> HydraHookIpcRehookHoldForTest{nullptr};
28
29namespace
30{
31 void LogIpc(const char* message, DWORD error)
32 {
33 const auto logger = spdlog::get("HYDRAHOOK");
34 if (logger)
35 logger->warn("{} ({})", message, error);
36 }
37
38 bool CallbackOwnsPhase(std::int32_t phase)
39 {
41 }
42
43 // Drops this callback's ownership. The phase store is the last engine access.
44 void ReleaseOwnedRehookPhase(PHYDRAHOOK_ENGINE engine, std::int32_t next)
45 {
46 engine->RehookOwnerThread.store(0, std::memory_order_release);
47 std::int32_t owned = HydraHookIpcPhaseInCallback;
48 if (!engine->RehookWaitPhase.compare_exchange_strong(owned, next)
50 {
51 engine->RehookWaitPhase.compare_exchange_strong(owned, next);
52 }
53 }
54
55 // Relative 100ms. The callback uses this when the request is already accepted but cannot run yet.
56 // Phase stays InCallback until the last engine access, so abandon cannot free the engine first.
57 void QueueRehookRetry(PHYDRAHOOK_ENGINE engine)
58 {
59 if (!engine)
60 return;
61
62 const auto finish = [&](std::int32_t next)
63 {
64 ReleaseOwnedRehookPhase(engine, next);
65 };
66
67 if (!engine->RehookWait || !engine->RehookEvent || engine->RehookDisabled.load(std::memory_order_acquire))
68 {
70 return;
71 }
72
73 ULARGE_INTEGER due;
74 due.QuadPart = static_cast<ULONGLONG>(static_cast<LONGLONG>(-100) * 10000);
75 FILETIME timeout;
76 timeout.dwLowDateTime = due.LowPart;
77 timeout.dwHighDateTime = due.HighPart;
78 SetThreadpoolWait(engine->RehookWait, engine->RehookEvent, &timeout);
79
80 if (engine->RehookDisabled.load(std::memory_order_acquire)
81 && SetThreadpoolWaitEx(engine->RehookWait, nullptr, nullptr, nullptr))
82 {
84 return;
85 }
86
88 }
89
90 VOID CALLBACK HydraHookIpcOnRehook(PTP_CALLBACK_INSTANCE, PVOID context, PTP_WAIT, TP_WAIT_RESULT)
91 {
92 auto* target = static_cast<PHYDRAHOOK_ENGINE>(context);
93 if (!target)
94 return;
95
96 // A retry publishes its wait before it leaves InCallback. If this callback arrives in that window,
97 // wait until the publisher stores Armed, then take ownership. Idle means the publisher cancelled it.
98 std::int32_t expected = HydraHookIpcPhaseArmed;
99 while (!target->RehookWaitPhase.compare_exchange_strong(expected, HydraHookIpcPhaseInCallback))
100 {
101 if (!CallbackOwnsPhase(expected))
102 return;
103 expected = HydraHookIpcPhaseArmed;
104 SwitchToThread();
105 }
106
107 target->RehookOwnerThread.store(GetCurrentThreadId(), std::memory_order_release);
108
109 const auto leave = [&]()
110 {
111 // A worker may have registered a wait under InCallbackExternal. Keep that registration.
112 target->RehookOwnerThread.store(0, std::memory_order_release);
113 std::int32_t owned = HydraHookIpcPhaseInCallback;
114 if (target->RehookWaitPhase.compare_exchange_strong(owned, HydraHookIpcPhaseIdle))
115 return;
117 target->RehookWaitPhase.compare_exchange_strong(owned, HydraHookIpcPhaseArmed);
118 };
119
120 if (target->RehookDisabled.load(std::memory_order_acquire))
121 {
122 leave();
123 return;
124 }
125
126 bool retry = false;
127 HANDLE thread = nullptr;
128 {
129 SrwTryExclusiveLock lifecycle(&target->LifecycleLock);
130 if (lifecycle)
131 {
132 if (target->EngineThread != nullptr
133 && !DuplicateHandle(GetCurrentProcess(), target->EngineThread, GetCurrentProcess(), &thread,
134 SYNCHRONIZE, FALSE, 0))
135 {
136 thread = nullptr;
137 retry = true;
138 }
139 }
140 else
141 {
142 retry = true;
143 }
144 }
145
146 if (thread != nullptr)
147 {
148 const DWORD waited = WaitForSingleObject(thread, 1000);
149 CloseHandle(thread);
150 if (waited != WAIT_OBJECT_0 && waited != WAIT_ABANDONED)
151 retry = true;
152 }
153
154 if (target->RehookDisabled.load(std::memory_order_acquire))
155 {
156 leave();
157 return;
158 }
159
160 if (retry)
161 {
162 QueueRehookRetry(target);
163 return;
164 }
165
166 const HYDRAHOOK_ERROR error = HydraHookEngineRehook(target);
167 if (error != HYDRAHOOK_ERROR_NONE)
168 {
169 // Arm may drop this callback's ownership. Do not touch the engine after it returns.
171 return;
172 }
173
174 if (const HydraHookIpcRehookHold hold = HydraHookIpcRehookHoldForTest.load(std::memory_order_acquire))
175 hold(target);
176
177 leave();
178 }
179}
180
182{
183 if (!engine)
184 return;
185
186 wchar_t stateName[96] = {};
187 wchar_t rehookName[96] = {};
188 HydraHookIpcFormatNames(GetCurrentProcessId(), reinterpret_cast<std::uintptr_t>(engine->HostInstance), stateName,
189 96, rehookName, 96);
190
191 SetLastError(ERROR_SUCCESS);
192 const HANDLE mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0,
193 static_cast<DWORD>(sizeof(HydraHookIpcStatus)), stateName);
194 if (!mapping)
195 {
196 LogIpc("HydraHook status section was not created", GetLastError());
197 return;
198 }
199 if (GetLastError() == ERROR_ALREADY_EXISTS)
200 {
201 LogIpc("HydraHook status section already exists", ERROR_ALREADY_EXISTS);
202 CloseHandle(mapping);
203 return;
204 }
205
206 void* view = MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(HydraHookIpcStatus));
207 if (!view)
208 {
209 LogIpc("HydraHook status section could not be mapped", GetLastError());
210 CloseHandle(mapping);
211 return;
212 }
213
214 std::memset(view, 0, sizeof(HydraHookIpcStatus));
215 auto* status = static_cast<HydraHookIpcStatus*>(view);
217 status->Size = static_cast<std::uint32_t>(sizeof(HydraHookIpcStatus));
218 InterlockedExchange(reinterpret_cast<volatile LONG*>(&status->Magic), static_cast<LONG>(HydraHookIpcMagic));
219
220 SetLastError(ERROR_SUCCESS);
221 HANDLE rehookEvent = CreateEventW(nullptr, FALSE, FALSE, rehookName);
222 const DWORD rehookError = GetLastError();
223 if (!rehookEvent || rehookError == ERROR_ALREADY_EXISTS)
224 {
225 LogIpc("HydraHook rehook event was not created", rehookError);
226 if (rehookEvent)
227 CloseHandle(rehookEvent);
228 rehookEvent = nullptr;
229 }
230
231 PTP_WAIT rehookWait = nullptr;
232 if (rehookEvent)
233 {
234 rehookWait = CreateThreadpoolWait(&HydraHookIpcOnRehook, engine, nullptr);
235 if (!rehookWait)
236 LogIpc("HydraHook rehook wait was not created", GetLastError());
237 }
238
239 engine->IpcStateMap = mapping;
240 engine->IpcStateView = view;
241 engine->RehookEvent = rehookEvent;
242 engine->RehookWait = rehookWait;
243 engine->IpcGeneration.store(1, std::memory_order_release);
245}
246
247void HydraHookIpcPublish(PHYDRAHOOK_ENGINE engine, std::uint32_t state, std::uint32_t origin, std::uint32_t gameVersion,
248 std::uint32_t flags)
249{
250 if (!engine || !engine->IpcStateView)
251 return;
252
253 auto* status = static_cast<HydraHookIpcStatus*>(engine->IpcStateView);
254 InterlockedExchange(reinterpret_cast<volatile LONG*>(&status->ShutdownOrigin), static_cast<LONG>(origin));
255 InterlockedExchange(reinterpret_cast<volatile LONG*>(&status->GameVersion), static_cast<LONG>(gameVersion));
256 InterlockedExchange(reinterpret_cast<volatile LONG*>(&status->Generation),
257 static_cast<LONG>(engine->IpcGeneration.load(std::memory_order_acquire)));
258 InterlockedExchange(reinterpret_cast<volatile LONG*>(&status->Flags), static_cast<LONG>(flags));
259 InterlockedExchange64(reinterpret_cast<volatile LONG64*>(&status->LastTransitionTick64),
260 static_cast<LONG64>(GetTickCount64()));
261 InterlockedExchange(reinterpret_cast<volatile LONG*>(&status->State), static_cast<LONG>(state));
262}
263
265{
266 if (!engine || !engine->IpcStateView)
267 return;
268
269 auto* status = static_cast<HydraHookIpcStatus*>(engine->IpcStateView);
270 // Leave GameVersion alone. A Hooked announcement publishes that field, and writing it here can
271 // replace the announced API after State has already become Hooked.
272 InterlockedCompareExchange(reinterpret_cast<volatile LONG*>(&status->State),
273 static_cast<LONG>(HydraHookIpcStateRunning),
274 static_cast<LONG>(HydraHookIpcStateInitializing));
275}
276
278{
279 if (!engine)
280 return;
281
282 // Only the callback thread owns InCallback. A worker that stops during that window must not take it.
283 const bool ownedByCallback =
284 engine->RehookOwnerThread.load(std::memory_order_acquire) == GetCurrentThreadId();
285
286 if (!engine->RehookWait || !engine->RehookEvent || engine->RehookDisabled.load(std::memory_order_acquire))
287 {
288 if (ownedByCallback)
289 ReleaseOwnedRehookPhase(engine, HydraHookIpcPhaseIdle);
290 return;
291 }
292
293 const std::int32_t observed = engine->RehookWaitPhase.load(std::memory_order_acquire);
294 if (!ownedByCallback && CallbackOwnsPhase(observed))
295 {
296 // Publish the phase before registering. A signal that arrives while the phase is still
297 // InCallback is consumed once and then dropped if leave() stores Idle first.
298 std::int32_t owned = HydraHookIpcPhaseInCallback;
299 const bool markedExternal =
300 engine->RehookWaitPhase.compare_exchange_strong(owned, HydraHookIpcPhaseInCallbackExternal);
301 if (!markedExternal)
302 {
303 if (owned != HydraHookIpcPhaseIdle)
304 return;
305 if (!engine->RehookWaitPhase.compare_exchange_strong(owned, HydraHookIpcPhaseArmed))
306 return;
307 if (engine->RehookDisabled.load(std::memory_order_acquire))
308 {
309 std::int32_t armed = HydraHookIpcPhaseArmed;
310 engine->RehookWaitPhase.compare_exchange_strong(armed, HydraHookIpcPhaseIdle);
311 return;
312 }
313 }
314 else if (engine->RehookDisabled.load(std::memory_order_acquire))
315 {
316 std::int32_t external = HydraHookIpcPhaseInCallbackExternal;
317 engine->RehookWaitPhase.compare_exchange_strong(external, HydraHookIpcPhaseInCallback);
318 return;
319 }
320
321 ResetEvent(engine->RehookEvent);
322 SetThreadpoolWait(engine->RehookWait, engine->RehookEvent, nullptr);
323 if (engine->RehookDisabled.load(std::memory_order_acquire)
324 && SetThreadpoolWaitEx(engine->RehookWait, nullptr, nullptr, nullptr))
325 {
326 if (markedExternal)
327 {
328 std::int32_t external = HydraHookIpcPhaseInCallbackExternal;
329 if (!engine->RehookWaitPhase.compare_exchange_strong(external, HydraHookIpcPhaseInCallback)
330 && external == HydraHookIpcPhaseArmed)
331 engine->RehookWaitPhase.compare_exchange_strong(external, HydraHookIpcPhaseIdle);
332 }
333 else
334 {
335 std::int32_t armed = HydraHookIpcPhaseArmed;
336 engine->RehookWaitPhase.compare_exchange_strong(armed, HydraHookIpcPhaseIdle);
337 }
338 }
339 return;
340 }
341
342 if (!ownedByCallback)
343 {
344 std::int32_t expected = HydraHookIpcPhaseIdle;
345 if (!engine->RehookWaitPhase.compare_exchange_strong(expected, HydraHookIpcPhaseArmed))
346 return;
347
348 if (engine->RehookDisabled.load(std::memory_order_acquire))
349 {
350 std::int32_t armed = HydraHookIpcPhaseArmed;
351 engine->RehookWaitPhase.compare_exchange_strong(armed, HydraHookIpcPhaseIdle);
352 return;
353 }
354 }
355
356 ResetEvent(engine->RehookEvent);
357 SetThreadpoolWait(engine->RehookWait, engine->RehookEvent, nullptr);
358
359 if (engine->RehookDisabled.load(std::memory_order_acquire)
360 && SetThreadpoolWaitEx(engine->RehookWait, nullptr, nullptr, nullptr))
361 {
362 if (ownedByCallback)
363 ReleaseOwnedRehookPhase(engine, HydraHookIpcPhaseIdle);
364 else
365 {
366 std::int32_t armed = HydraHookIpcPhaseArmed;
367 engine->RehookWaitPhase.compare_exchange_strong(armed, HydraHookIpcPhaseIdle);
368 }
369 return;
370 }
371
372 if (ownedByCallback)
373 ReleaseOwnedRehookPhase(engine, HydraHookIpcPhaseArmed);
374}
375
377{
378 if (!engine || !engine->RehookWait)
379 return;
380 if (engine->RehookWaitPhase.load(std::memory_order_acquire) != HydraHookIpcPhaseArmed)
381 return;
382
383 if (!SetThreadpoolWaitEx(engine->RehookWait, nullptr, nullptr, nullptr))
384 return;
385
386 std::int32_t armed = HydraHookIpcPhaseArmed;
387 engine->RehookWaitPhase.compare_exchange_strong(armed, HydraHookIpcPhaseIdle);
388}
389
391{
392 if (!engine)
393 return true;
394
395 engine->RehookDisabled.store(true, std::memory_order_release);
396 if (!engine->RehookWait)
397 return true;
398
399 // One snapshot decides. A second load can observe InCallback and skip the cancel
400 // after this read already saw Armed, which lets destroy free a live callback.
401 const std::int32_t phase = engine->RehookWaitPhase.load(std::memory_order_acquire);
402 if (CallbackOwnsPhase(phase))
403 return false;
404
405 if (phase == HydraHookIpcPhaseArmed)
406 {
407 if (!SetThreadpoolWaitEx(engine->RehookWait, nullptr, nullptr, nullptr))
408 return false;
409
410 std::int32_t armed = HydraHookIpcPhaseArmed;
411 engine->RehookWaitPhase.compare_exchange_strong(armed, HydraHookIpcPhaseIdle);
412 if (CallbackOwnsPhase(engine->RehookWaitPhase.load(std::memory_order_acquire)))
413 return false;
414 }
415
416 return true;
417}
418
420{
421 if (!engine)
422 return;
423
424 if (engine->RehookWait)
425 {
426 SetThreadpoolWaitEx(engine->RehookWait, nullptr, nullptr, nullptr);
427 CloseThreadpoolWait(engine->RehookWait);
428 engine->RehookWait = nullptr;
429 }
430 if (engine->RehookEvent)
431 {
432 CloseHandle(engine->RehookEvent);
433 engine->RehookEvent = nullptr;
434 }
435 if (engine->IpcStateView)
436 {
437 UnmapViewOfFile(engine->IpcStateView);
438 engine->IpcStateView = nullptr;
439 }
440 if (engine->IpcStateMap)
441 {
442 CloseHandle(engine->IpcStateMap);
443 engine->IpcStateMap = nullptr;
444 }
445}
Internal engine structure and callback invocation macros.
void HydraHookIpcDisarmRehookWait(PHYDRAHOOK_ENGINE engine)
void HydraHookIpcArmRehookWait(PHYDRAHOOK_ENGINE engine)
void HydraHookIpcClose(PHYDRAHOOK_ENGINE engine)
Closes IPC objects. The caller guarantees no rehook callback is running.
void HydraHookIpcPublish(PHYDRAHOOK_ENGINE engine, std::uint32_t state, std::uint32_t origin, std::uint32_t gameVersion, std::uint32_t flags)
std::atomic< HydraHookIpcRehookHold > HydraHookIpcRehookHoldForTest
Definition EngineIpc.cpp:27
bool HydraHookIpcAbandonRehookWait(PHYDRAHOOK_ENGINE engine)
Cancels a pending rehook wait so the engine can be freed.
void HydraHookIpcCreate(PHYDRAHOOK_ENGINE engine)
void HydraHookIpcPublishRunning(PHYDRAHOOK_ENGINE engine)
Moves Initializing to Running. Does not write the graphics API a Hooked publish owns.
Session-local shared-memory engine status and rehook control.
constexpr std::int32_t HydraHookIpcPhaseInCallbackExternal
Definition EngineIpc.h:65
constexpr std::uint32_t HydraHookIpcStateInitializing
Definition EngineIpc.h:46
constexpr std::uint32_t HydraHookIpcStateRunning
Definition EngineIpc.h:47
void HydraHookIpcFormatNames(DWORD pid, std::uintptr_t host, wchar_t *stateName, std::size_t stateCch, wchar_t *rehookName, std::size_t rehookCch)
Definition EngineIpc.h:87
constexpr std::int32_t HydraHookIpcPhaseArmed
Definition EngineIpc.h:63
constexpr std::uint32_t HydraHookIpcShutdownOriginNone
Definition EngineIpc.h:52
constexpr std::int32_t HydraHookIpcPhaseInCallback
Definition EngineIpc.h:64
constexpr std::uint32_t HydraHookIpcVersion
Definition EngineIpc.h:43
constexpr std::int32_t HydraHookIpcPhaseIdle
Definition EngineIpc.h:62
constexpr std::uint32_t HydraHookIpcMagic
Definition EngineIpc.h:42
void(*)(PHYDRAHOOK_ENGINE engine) HydraHookIpcRehookHold
Definition EngineIpc.h:96
Core engine API for HydraHook - Direct3D and Core Audio hooking library.
HYDRAHOOK_ERROR HydraHookEngineRehook(_In_ PHYDRAHOOK_ENGINE Engine)
Reinstalls hooks on an engine previously stopped with HydraHookEngineUnhook.
HYDRAHOOK_ERROR
Error codes returned by HydraHook engine functions.
@ HYDRAHOOK_ERROR_NONE
struct _HYDRAHOOK_ENGINE * PHYDRAHOOK_ENGINE
Opaque handle to the HydraHook engine instance.
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.
RAII guards for Win32 SRWLOCK.
Non-blocking exclusive lock. True when the lock was acquired.
Definition SrwLock.h:73
std::uint32_t Version
Definition EngineIpc.h:71