HydraHook
Direct3D and Core Audio hooking library for Windows
Loading...
Searching...
No Matches
Engine.cpp
Go to the documentation of this file.
1
10
11/*
12MIT License
13
14Copyright (c) 2018-2026 Benjamin Höglinger-Stelzer
15
16Permission is hereby granted, free of charge, to any person obtaining a copy
17of this software and associated documentation files (the "Software"), to deal
18in the Software without restriction, including without limitation the rights
19to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20copies of the Software, and to permit persons to whom the Software is
21furnished to do so, subject to the following conditions:
22
23The above copyright notice and this permission notice shall be included in all
24copies or substantial portions of the Software.
25
26THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32SOFTWARE.
33*/
34
35
36#define WIN32_LEAN_AND_MEAN
37#include <Windows.h>
38#include <stdarg.h>
39
40//
41// Public
42//
49
50//
51// Internal
52//
53#include "Engine.h"
54#include "CrashHandler.h"
55#include "Game/Game.h"
56#include "Game/Shutdown.h"
57#include "Utils/Global.h"
58#include "Utils/Hook.h"
59#include "Utils/SrwLock.h"
60
61//
62// Logging
63//
64#include <spdlog/spdlog.h>
65#include <spdlog/async.h>
66#include <spdlog/async_logger.h>
67#include <spdlog/sinks/basic_file_sink.h>
68#include <spdlog/sinks/null_sink.h>
69#include <spdlog/sinks/stdout_color_sinks.h>
70
71//
72// STL
73//
74#include <algorithm>
75#include <cstddef>
76#include <memory>
77#include <new>
78#include <string>
79#include <string_view>
80#include <utility>
81#include <vector>
82
83//
84// Keep track of HINSTANCE/HANDLE to engine handle association
85//
86static SRWLOCK g_EngineHostInstancesLock = SRWLOCK_INIT;
87static std::vector<std::pair<HMODULE, PHYDRAHOOK_ENGINE>> g_EngineHostInstances;
88static SRWLOCK g_engineDestroyLock = SRWLOCK_INIT;
89
90namespace
91{
92 SRWLOCK g_hostLoggerLock = SRWLOCK_INIT;
93 std::shared_ptr<spdlog::logger> g_hostLogger;
94 std::shared_ptr<spdlog::logger> g_installedDefaultLogger;
95 std::shared_ptr<spdlog::logger> g_syncLogger;
96 std::shared_ptr<spdlog::details::thread_pool> g_logThreadPool;
97 std::atomic<bool> g_hostLoggingEnabled{false};
98 std::atomic<int> g_hostLogLevel{static_cast<int>(spdlog::level::off)};
99 std::atomic<bool> g_asyncLoggingActive{false};
100
101 void ResetHostLogger()
102 {
103 SrwExclusiveLock lock(&g_hostLoggerLock);
104 g_hostLogger.reset();
105 }
106
107 void RememberInstalledDefaultLogger(const std::shared_ptr<spdlog::logger>& logger)
108 {
109 SrwExclusiveLock lock(&g_hostLoggerLock);
110 g_installedDefaultLogger = logger;
111 }
112
113 std::shared_ptr<spdlog::logger> TakeInstalledDefaultLogger()
114 {
115 SrwExclusiveLock lock(&g_hostLoggerLock);
116 auto installed = g_installedDefaultLogger;
117 g_installedDefaultLogger.reset();
118 return installed;
119 }
120
121 PHYDRAHOOK_ENGINE FindHostEngineUnlocked(HMODULE host)
122 {
123 for (const auto& kv : g_EngineHostInstances)
124 {
125 if (kv.first == host)
126 return kv.second;
127 }
128 return nullptr;
129 }
130
131 void EraseHostEngineUnlocked(HMODULE host)
132 {
134 std::remove_if(g_EngineHostInstances.begin(), g_EngineHostInstances.end(),
135 [host](const auto& kv) { return kv.first == host; }),
137 }
138
139 HYDRAHOOK_ERROR RetainEngine(const std::shared_ptr<spdlog::logger>& logger, const char* reason)
140 {
143 if (logger && !std::dynamic_pointer_cast<spdlog::async_logger>(logger))
144 logger->warn("{}", reason);
146 }
147}
148
149
151{
152 // PIN cannot be undone. The worker's code stays mapped for the process lifetime.
153 HMODULE module = nullptr;
154 return GetModuleHandleExW(
155 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
156 reinterpret_cast<LPCWSTR>(&HydraHookPinWorkerModule),
157 &module) != FALSE;
158}
159
160
161HYDRAHOOK_API HYDRAHOOK_ERROR HydraHookEngineCreate(HMODULE HostInstance, PHYDRAHOOK_ENGINE_CONFIG EngineConfig,
162 PHYDRAHOOK_ENGINE* Engine)
163{
164 if (!EngineConfig)
165 {
167 }
168
169 // The first layout ends at DisableThreadQuitMonitoring. Do not include
170 // trailing alignment padding or fields added in future versions.
171 constexpr SIZE_T minimumConfigSize = offsetof(HYDRAHOOK_ENGINE_CONFIG, Shutdown) + sizeof(BOOL);
172 const SIZE_T configSize = EngineConfig->Size;
173 if (configSize < minimumConfigSize)
175
176 {
178 if (FindHostEngineUnlocked(HostInstance))
180 }
181
182 HMODULE hMod;
183 if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
184 reinterpret_cast<LPCTSTR>(HostInstance),
185 &hMod))
186 {
188 }
189
190 const auto engine = new (std::nothrow) HYDRAHOOK_ENGINE();
191
192 if (!engine)
193 {
195 }
196
197 engine->HostInstance = HostInstance;
198 engine->DllModule = hMod;
200 auto& config = engine->EngineConfig;
202 const SIZE_T copySize = configSize < sizeof(config) ? configSize : sizeof(config);
203 CopyMemory(&config, EngineConfig, copySize);
204 config.Size = copySize;
205
206 //
207 // Set up logging: disabled config uses a null sink. Otherwise try the process
208 // directory, then the DLL directory, then the configured fallback path.
209 //
210 auto logger = spdlog::get("HYDRAHOOK");
211 if (!logger)
212 {
213 if (!config.Logging.IsEnabled)
214 {
215 try
216 {
217 logger = std::make_shared<spdlog::logger>(
218 "HYDRAHOOK",
219 std::make_shared<spdlog::sinks::null_sink_mt>());
220 spdlog::register_logger(logger);
221 }
222 catch (const std::exception&)
223 {
224 delete engine;
226 }
227 }
228 else
229 {
230 const std::string processDir = HydraHook::Core::Util::get_process_directory();
231 const std::string dllDir = HydraHook::Core::Util::get_module_directory(HostInstance);
232 const char* configuredPath = config.Logging.FilePath;
233 const std::string tempPath = configuredPath
235 : std::string();
236
237 auto tryCreateLogger = [](const std::string& path) -> bool
238 {
239 if (path.empty())
240 return false;
241 try
242 {
243 (void)spdlog::basic_logger_mt("HYDRAHOOK", path);
244 return true;
245 }
246 catch (const std::exception&)
247 {
248 return false;
249 }
250 };
251
252 if (!processDir.empty() && tryCreateLogger(processDir + "HydraHook.log"))
253 {
254 /* ok */
255 }
256 else if (!dllDir.empty() && tryCreateLogger(dllDir + "HydraHook.log"))
257 {
258 /* ok */
259 }
260 else if (!tempPath.empty())
261 {
262 tryCreateLogger(tempPath);
263 }
264
265 logger = spdlog::get("HYDRAHOOK");
266 if (!logger)
267 {
268 try
269 {
270 logger = spdlog::stdout_color_mt("HYDRAHOOK");
271 }
272 catch (const std::exception&)
273 {
274 delete engine;
276 }
277 }
278 }
279 }
280
281 if (!config.Logging.IsEnabled)
282 {
283 logger->set_level(spdlog::level::off);
284 g_hostLoggingEnabled.store(false, std::memory_order_release);
285 g_hostLogLevel.store(static_cast<int>(spdlog::level::off), std::memory_order_release);
286 }
287 else
288 {
289#if _DEBUG
290 spdlog::set_level(spdlog::level::debug);
291 logger->set_level(spdlog::level::debug);
292 logger->flush_on(spdlog::level::debug);
293 g_hostLogLevel.store(static_cast<int>(spdlog::level::debug), std::memory_order_release);
294#else
295 logger->set_level(spdlog::level::info);
296 logger->flush_on(spdlog::level::info);
297 g_hostLogLevel.store(static_cast<int>(spdlog::level::info), std::memory_order_release);
298#endif
299 g_hostLoggingEnabled.store(true, std::memory_order_release);
300 spdlog::set_default_logger(logger);
301 RememberInstalledDefaultLogger(logger);
302 }
303
304 {
305 SrwExclusiveLock lock(&g_hostLoggerLock);
306 g_syncLogger = spdlog::get("HYDRAHOOK");
307 }
308
309 logger = logger->clone("api");
310
311 //
312 // Install crash handler if enabled
313 //
314 if (config.CrashHandler.IsEnabled)
315 {
316 engine->CrashHandlerInstalled = HydraHookCrashHandlerInstall(engine) ? TRUE : FALSE;
317 }
318
319 //
320 // Event to notify engine thread about termination
321 //
322 engine->EngineCancellationEvent = CreateEvent(
323 nullptr,
324 FALSE, // Auto-reset event
325 FALSE, // Initial state non-signaled
326 nullptr // Unnamed event
327 );
328
329 if (engine->EngineCancellationEvent == nullptr)
330 {
331 logger->error("Failed to create the Engine Cancellation Event: {}", GetLastError());
332 if (engine->CrashHandlerInstalled)
333 {
335 engine->CrashHandlerInstalled = FALSE;
336 }
338 delete engine;
340 }
341
342 HydraHookIpcCreate(engine);
343
344 logger->info("HydraHook engine initialized, attempting to launch main thread");
345
346 //
347 // Kickstart hooking the rendering pipeline
348 //
349 // Suspended until the host is reserved, so the worker cannot run against an engine
350 // that a losing create is about to delete.
351 engine->EngineThread = CreateThread(
352 nullptr,
353 0,
354 reinterpret_cast<LPTHREAD_START_ROUTINE>(HydraHookMainThread),
355 engine,
356 CREATE_SUSPENDED,
357 nullptr
358 );
359
360 if (!engine->EngineThread)
361 {
362 logger->error("Could not create main thread, library unusable");
363 if (engine->CrashHandlerInstalled)
364 {
366 engine->CrashHandlerInstalled = FALSE;
367 }
368 CloseHandle(engine->EngineCancellationEvent);
369 HydraHookIpcClose(engine);
371 delete engine;
373 }
374
376 {
378 if (FindHostEngineUnlocked(HostInstance))
380 else
381 {
382 g_EngineHostInstances.emplace_back(HostInstance, engine);
383 if (ResumeThread(engine->EngineThread) == static_cast<DWORD>(-1))
384 {
385 EraseHostEngineUnlocked(HostInstance);
387 }
388 }
389 }
390 if (resumeError != HYDRAHOOK_ERROR_NONE)
391 {
392 // The thread has not executed. Terminating it cannot race the worker.
393 TerminateThread(engine->EngineThread, 0);
394 if (engine->CrashHandlerInstalled)
396 CloseHandle(engine->EngineCancellationEvent);
397 CloseHandle(engine->EngineThread);
398 HydraHookIpcClose(engine);
400 delete engine;
401 return resumeError;
402 }
403
404 logger->info("Main thread created successfully");
405
406 if (Engine)
407 {
408 *Engine = engine;
409 }
410
412}
413
414static HYDRAHOOK_ERROR DestroyEngine(HMODULE HostInstance, bool (*detachFreeLibraryHook)() noexcept)
415{
416 const bool explicitUnload = detachFreeLibraryHook != nullptr;
417 const auto incomplete = [explicitUnload](const std::shared_ptr<spdlog::logger>& logger, const char* reason)
418 {
419 return explicitUnload ? HYDRAHOOK_ERROR_UNHOOK_INCOMPLETE : RetainEngine(logger, reason);
420 };
421 // Explicit unload may block on the logger lock, so clone before taking
422 // the destroy lock. DllMain does not log: a sync warn can flush under the
423 // loader lock and delay the no-wait retain path.
424 auto logger = explicitUnload ? HydraHookCloneRegisteredLogger("api") : nullptr;
426 if (!destroy)
427 return incomplete(logger, "Engine kept alive; another destroy is running");
428
429 PHYDRAHOOK_ENGINE engine = nullptr;
430 {
432 if (!lock)
433 return incomplete(logger, "Engine kept alive; host map lock is busy");
434 engine = FindHostEngineUnlocked(HostInstance);
435 if (!engine)
437 }
438
439 {
440 // Unhook holds this lock for its worker wait. Blocking here would wait
441 // under the loader lock, so a busy lock keeps the engine allocated.
442 SrwTryExclusiveLock lifecycle(&engine->LifecycleLock);
443 if (!lifecycle)
444 return incomplete(logger, "Engine kept alive; lifecycle lock is busy");
445 if (explicitUnload)
446 {
447 engine->RehookDisabled.store(true, std::memory_order_release);
448 engine->FreeLibraryHookActive.store(true, std::memory_order_release);
450 }
451 else
452 {
454 }
455 }
456
457 // DllMain cannot wait: the worker may need the loader lock. A finished
458 // cleanup flag is not enough, because Unhook sets it before the worker exits.
459 // Rehook closes and replaces EngineThread under this lock, so the read stays inside it.
460 {
461 SrwTryExclusiveLock lifecycle(&engine->LifecycleLock);
462 if (!lifecycle)
463 return incomplete(logger, "Engine kept alive; lifecycle lock is busy");
464
465 const bool onWorker = engine->EngineThread != nullptr
466 && GetThreadId(engine->EngineThread) == GetCurrentThreadId();
467 bool workerExited = engine->EngineThread == nullptr;
468 if (!workerExited && !onWorker)
469 workerExited = WaitForSingleObject(engine->EngineThread, 0) == WAIT_OBJECT_0;
470 if (!workerExited)
471 return incomplete(logger, "Engine kept alive; worker is still running");
472 }
473
474 // TerminateThread can signal the worker before it closes the tracker.
475 // A false DrainIncomplete flag is not a drain. Shut the tracker first so a
476 // callback cannot pass the check and then enter.
479 return incomplete(logger, "Engine kept alive; hook callbacks are still running");
480
481 {
482 // A rehook callback takes this lock while it replaces the worker. Trying
483 // again here, after the exited-worker check, catches that replacement.
484 SrwTryExclusiveLock lifecycle(&engine->LifecycleLock);
485 if (!lifecycle)
486 return incomplete(logger, "Engine kept alive; lifecycle lock is busy");
487
489 return incomplete(logger, "Engine kept alive; rehook callback is running");
490
491 if (engine->EngineThread != nullptr
492 && WaitForSingleObject(engine->EngineThread, 0) != WAIT_OBJECT_0)
493 return incomplete(logger, "Engine kept alive; worker is still running");
494 }
495
496 bool lastEngine = false;
497 {
499 if (!lock)
500 return incomplete(logger, "Engine kept alive; host map lock is busy");
501 // No remaining contention checks can abort after the eject hook is removed.
502 if (explicitUnload && !detachFreeLibraryHook())
504 EraseHostEngineUnlocked(HostInstance);
505 lastEngine = g_EngineHostInstances.empty();
506 }
508
509 if (logger)
510 logger->info("Freeing remaining resources");
511
512 if (PVOID ctx = engine->CustomContext.exchange(nullptr, std::memory_order_acq_rel))
513 {
514 free(ctx);
515 }
516
517 if (engine->CrashHandlerInstalled)
518 {
520 engine->CrashHandlerInstalled = FALSE;
521 }
522
523 HydraHookIpcClose(engine);
524
525 if (engine->EngineCancellationEvent)
526 {
527 CloseHandle(engine->EngineCancellationEvent);
528 }
529 if (engine->EngineThread)
530 {
531 CloseHandle(engine->EngineThread);
532 }
533
534 if (logger)
535 {
536 logger->info("Engine shutdown complete");
537 logger->flush();
538 }
539
541 {
542 // A dump writer may still read this engine. Deleting it here would race that
543 // writer, and waiting would deadlock DllMain against the loader lock.
544 }
545 else
546 {
547 delete engine;
548 }
549
550 if (lastEngine)
551 {
552 ResetHostLogger();
553 const auto installedDefault = TakeInstalledDefaultLogger();
554 if (installedDefault && spdlog::default_logger() == installedDefault)
555 {
556 spdlog::set_default_logger(std::make_shared<spdlog::logger>(
557 "hydrahook-default",
558 std::make_shared<spdlog::sinks::null_sink_mt>()));
559 }
560 spdlog::drop("HYDRAHOOK");
561 g_hostLoggingEnabled.store(false, std::memory_order_release);
562 g_hostLogLevel.store(static_cast<int>(spdlog::level::off), std::memory_order_release);
563 }
564
566}
567
569{
570 return DestroyEngine(HostInstance, nullptr);
571}
572
573HYDRAHOOK_ERROR HydraHookEngineDestroyBeforeUnload(HMODULE host, bool (*detachFreeLibraryHook)() noexcept)
574{
575 return DestroyEngine(host, detachFreeLibraryHook);
576}
577
579{
580 return engine != nullptr ? engine->GameVersion.load(std::memory_order_acquire) : HydraHookDirect3DVersionUnknown;
581}
582
584{
585 if (!engine)
586 return;
587 if (acquire)
588 AcquireSRWLockExclusive(&engine->LifecycleLock);
589 else
590 ReleaseSRWLockExclusive(&engine->LifecycleLock);
591}
592
594{
595 if (!Engine)
596 {
598 }
599
600 SrwExclusiveLock lifecycle(&Engine->LifecycleLock);
601
602 if (!Engine->EngineThread)
603 {
605 }
606
607 // The worker cannot wait for itself
608 if (GetThreadId(Engine->EngineThread) == GetCurrentThreadId())
609 {
611 }
612
613 // Keep the DLL loaded even if another shutdown path already claimed cleanup
614 Engine->SkipDllUnloadOnExit.store(true, std::memory_order_release);
615
617
618 // PerformShutdownCleanup returns early when another path owns cleanup, and
619 // never terminates the worker on a manual unhook; confirm the worker is gone
620 // before releasing its handle or any engine state.
621 if (WaitForSingleObject(Engine->EngineThread, 8000) != WAIT_OBJECT_0)
622 {
624 }
625
626 // The worker exits even if a callback outlives the drain timeout; keep the
627 // engine until those callbacks have returned.
628 if (Engine->DrainIncomplete.load(std::memory_order_acquire))
629 {
631 {
633 }
634
635 ZeroMemory(&Engine->EventsD3D9, sizeof(Engine->EventsD3D9));
636 ZeroMemory(&Engine->EventsD3D10, sizeof(Engine->EventsD3D10));
637 ZeroMemory(&Engine->EventsD3D11, sizeof(Engine->EventsD3D11));
638 ZeroMemory(&Engine->EventsD3D12, sizeof(Engine->EventsD3D12));
639 ZeroMemory(&Engine->EventsARC, sizeof(Engine->EventsARC));
640 Engine->DrainIncomplete.store(false, std::memory_order_release);
641 }
642
643 CloseHandle(Engine->EngineThread);
644 Engine->EngineThread = nullptr;
645
646 ClearRenderPipeline(Engine->RenderPipeline);
647 ZeroMemory(&Engine->CoreAudio, sizeof(Engine->CoreAudio));
648 Engine->GameVersion = HydraHookDirect3DVersionUnknown;
649
651}
652
654{
655 if (!Engine)
656 {
658 }
659
660 SrwExclusiveLock lifecycle(&Engine->LifecycleLock);
662 // Destroy sets this flag under the same lock. Do not start a worker after that.
663 if (Engine->RehookDisabled.load(std::memory_order_acquire))
665
666 if (Engine->EngineThread)
667 {
668 if (WaitForSingleObject(Engine->EngineThread, 0) == WAIT_TIMEOUT)
669 {
671 }
672
673 if (Engine->DrainIncomplete.load(std::memory_order_acquire)
675 {
677 }
678
679 CloseHandle(Engine->EngineThread);
680 Engine->EngineThread = nullptr;
681 }
682
683 Engine->DrainIncomplete.store(false, std::memory_order_release);
684
686 Engine->ShutdownCleanupDone.store(false);
687 Engine->FreeLibraryHookActive.store(false);
688 Engine->SkipDllUnloadOnExit.store(false);
689 ResetEvent(Engine->EngineCancellationEvent);
690
691 Engine->EventsD3D9 = Engine->SavedEventsD3D9;
692 Engine->EventsD3D10 = Engine->SavedEventsD3D10;
693 Engine->EventsD3D11 = Engine->SavedEventsD3D11;
694 Engine->EventsD3D12 = Engine->SavedEventsD3D12;
695 Engine->EventsARC = Engine->SavedEventsARC;
696
697 ClearRenderPipeline(Engine->RenderPipeline);
698 ZeroMemory(&Engine->CoreAudio, sizeof(Engine->CoreAudio));
699 Engine->GameVersion = HydraHookDirect3DVersionUnknown;
700 Engine->LastShutdownOrigin.store(HydraHookIpcShutdownOriginNone, std::memory_order_release);
701 Engine->IpcGeneration.fetch_add(1, std::memory_order_acq_rel);
703
704 Engine->EngineThread = CreateThread(
705 nullptr,
706 0,
707 reinterpret_cast<LPTHREAD_START_ROUTINE>(HydraHookMainThread),
708 Engine,
709 0,
710 nullptr
711 );
712
713 if (!Engine->EngineThread)
714 {
715 Engine->ShutdownCleanupDone.store(true);
716 const std::uint32_t flags = Engine->RehookDisabled.load(std::memory_order_acquire) || !Engine->RehookWait
717 ? 0u
720 // The rehook callback arms after this returns. Arming here would drop InCallback first,
721 // and that later call would use a freed engine.
722 const std::int32_t phase = Engine->RehookWaitPhase.load(std::memory_order_acquire);
723 if (flags != 0
728 }
729
731}
732
734 size_t ContextSize)
735{
736 if (!Engine || !Context)
737 {
739 }
740
741 if (Engine->CustomContext.load(std::memory_order_acquire))
742 {
744 }
745
746 void* block = malloc(ContextSize);
747
748 if (!block)
749 {
751 }
752
753 // Zero before publishing: other threads may read Engine->CustomContext concurrently.
754 ZeroMemory(block, ContextSize);
755 Engine->CustomContext.store(block, std::memory_order_release);
756 *Context = block;
757
759}
760
762{
763 if (!Engine)
764 {
766 }
767
768 if (PVOID ctx = Engine->CustomContext.exchange(nullptr, std::memory_order_acq_rel))
769 {
770 free(ctx);
771 }
772
774}
775
777{
778 if (!Engine)
779 {
780 return nullptr;
781 }
782
783 return Engine->CustomContext.load(std::memory_order_acquire);
784}
785
787{
788 if (!Engine)
789 {
790 return FALSE;
791 }
792
793 return Engine->DrainIncomplete.load(std::memory_order_acquire) ? FALSE : TRUE;
794}
795
796#ifndef HYDRAHOOK_NO_D3D9
797
800{
801 if (Engine && Callbacks)
802 {
803 Engine->EventsD3D9 = *Callbacks;
804 Engine->SavedEventsD3D9 = *Callbacks;
805 }
806}
807
809{
810 if (Device == nullptr)
811 {
812 return nullptr;
813 }
814
816 for (const auto& kv : g_EngineHostInstances)
817 {
818 const auto& engine = kv.second;
819
820 if (LoadRenderPipelinePtr(engine->RenderPipeline.pD3D9Device) == Device)
821 {
822 return engine;
823 }
824 }
825
826 // Several devices can present concurrently and only one is tracked. This module normally
827 // hosts one engine, which then is the only candidate.
828 if (Device != nullptr && g_EngineHostInstances.size() == 1)
829 return g_EngineHostInstances.front().second;
830
831 return nullptr;
832}
833
835{
836 if (Device == nullptr)
837 {
838 return nullptr;
839 }
840
842 for (const auto& kv : g_EngineHostInstances)
843 {
844 const auto& engine = kv.second;
845
846 if (LoadRenderPipelinePtr(engine->RenderPipeline.pD3D9ExDevice) == Device)
847 {
848 return engine;
849 }
850 }
851
852 // Several devices can present concurrently and only one is tracked. This module normally
853 // hosts one engine, which then is the only candidate.
854 if (Device != nullptr && g_EngineHostInstances.size() == 1)
855 return g_EngineHostInstances.front().second;
856
857 return nullptr;
858}
859
860#endif
861
862#ifndef HYDRAHOOK_NO_D3D10
863
866{
867 if (Engine && Callbacks)
868 {
869 Engine->EventsD3D10 = *Callbacks;
870 Engine->SavedEventsD3D10 = *Callbacks;
871 }
872}
873
875{
876 if (SwapChain == nullptr)
877 return nullptr;
878
880 for (const auto& kv : g_EngineHostInstances)
881 {
882 const auto& engine = kv.second;
883
884 if (LoadRenderPipelinePtr(engine->RenderPipeline.pSwapChain) == SwapChain)
885 {
886 return engine;
887 }
888 }
889
890 // A game can own several swap chains and only the latest presented one is tracked. This
891 // module normally hosts one engine, which then is the only candidate.
892 if (g_EngineHostInstances.size() == 1)
893 return g_EngineHostInstances.front().second;
894
895 return nullptr;
896}
897
898#endif
899
900#ifndef HYDRAHOOK_NO_D3D11
901
904{
905 if (Engine && Callbacks)
906 {
907 Engine->EventsD3D11 = *Callbacks;
908 Engine->SavedEventsD3D11 = *Callbacks;
909 }
910}
911
912#endif
913
914#ifndef HYDRAHOOK_NO_D3D12
915
918{
919 if (Engine && Callbacks)
920 {
921 Engine->EventsD3D12 = *Callbacks;
922 Engine->SavedEventsD3D12 = *Callbacks;
923 }
924}
925
926HYDRAHOOK_API ID3D12CommandQueue* HydraHookEngineGetD3D12CommandQueue(IDXGISwapChain* pSwapChain)
927{
928 return GetD3D12CommandQueueForSwapChain(pSwapChain);
929}
930
931HYDRAHOOK_API ID3D12CommandQueue* HydraHookEngineGetVerifiedD3D12CommandQueue(IDXGISwapChain* pSwapChain)
932{
933 return GetD3D12CommandQueueForSwapChain(pSwapChain, true);
934}
935
936HYDRAHOOK_API BOOL HydraHookEngineDeferD3D12Resize(PHYDRAHOOK_EVT_PRE_EXTENSION Extension)
937{
939 if (!resize || resize != Extension)
940 return FALSE;
941 resize->Deferred = true;
942 return TRUE;
943}
944
945#endif
946
947#ifndef HYDRAHOOK_NO_COREAUDIO
948
951{
952 if (Engine && Callbacks)
953 {
954 Engine->EventsARC = *Callbacks;
955 Engine->SavedEventsARC = *Callbacks;
956 }
957}
958
959#endif
960
962{
963 if (!g_hostLoggingEnabled.load(std::memory_order_acquire))
964 return;
965
966 SrwExclusiveLock lock(&g_hostLoggerLock);
967 if (g_asyncLoggingActive.load(std::memory_order_acquire))
968 return;
969
970 auto sync = spdlog::get("HYDRAHOOK");
971 if (!sync || std::dynamic_pointer_cast<spdlog::async_logger>(sync))
972 return;
973
974 try
975 {
976 auto pool = std::make_shared<spdlog::details::thread_pool>(4096, 1);
977 auto asyncLogger = std::make_shared<spdlog::async_logger>(
978 "HYDRAHOOK",
979 sync->sinks().begin(),
980 sync->sinks().end(),
981 pool,
982 spdlog::async_overflow_policy::overrun_oldest);
983 asyncLogger->set_level(sync->level());
984#if _DEBUG
985 asyncLogger->flush_on(spdlog::level::debug);
986#else
987 asyncLogger->flush_on(spdlog::level::info);
988#endif
989 const bool wasDefault = spdlog::default_logger() == sync;
990 spdlog::drop("HYDRAHOOK");
991 spdlog::register_logger(asyncLogger);
992 if (wasDefault)
993 {
994 spdlog::set_default_logger(asyncLogger);
995 g_installedDefaultLogger = asyncLogger;
996 }
997
998 g_syncLogger = sync;
999 g_logThreadPool = std::move(pool);
1000 g_hostLogger.reset();
1001 g_asyncLoggingActive.store(true, std::memory_order_release);
1002 }
1003 catch (const std::exception&)
1004 {
1005 try
1006 {
1007 if (!spdlog::get("HYDRAHOOK"))
1008 spdlog::register_logger(sync);
1009 }
1010 catch (const std::exception&)
1011 {
1012 }
1013 }
1014}
1015
1017{
1018 std::shared_ptr<spdlog::logger> asyncLogger;
1019 std::shared_ptr<spdlog::logger> sync;
1020 std::shared_ptr<spdlog::details::thread_pool> pool;
1021 {
1022 SrwExclusiveLock lock(&g_hostLoggerLock);
1023 if (!g_asyncLoggingActive.load(std::memory_order_acquire))
1024 return;
1025 asyncLogger = spdlog::get("HYDRAHOOK");
1026 sync = g_syncLogger;
1027 g_syncLogger.reset();
1028 pool = std::move(g_logThreadPool);
1029 g_hostLogger.reset();
1030 g_asyncLoggingActive.store(false, std::memory_order_release);
1031 }
1032
1033 if (asyncLogger)
1034 asyncLogger->flush();
1035
1036 if (sync)
1037 {
1038 SrwExclusiveLock lock(&g_hostLoggerLock);
1039 const bool wasDefault = asyncLogger && spdlog::default_logger() == asyncLogger;
1040 spdlog::drop("HYDRAHOOK");
1041 try
1042 {
1043 spdlog::register_logger(sync);
1044 if (wasDefault)
1045 {
1046 spdlog::set_default_logger(sync);
1047 g_installedDefaultLogger = sync;
1048 }
1049 }
1050 catch (const std::exception&)
1051 {
1052 }
1053 g_hostLogger.reset();
1054 }
1055
1056 pool.reset();
1057}
1058
1059std::shared_ptr<spdlog::logger> HydraHookCloneRegisteredLogger(const char* channel)
1060{
1061 SrwSharedLock lock(&g_hostLoggerLock);
1062 auto base = spdlog::get("HYDRAHOOK");
1063 if (!base)
1064 return nullptr;
1065 return channel ? base->clone(channel) : base;
1066}
1067
1076static std::shared_ptr<spdlog::logger> GetHostLogger()
1077{
1078 {
1079 SrwSharedLock lock(&g_hostLoggerLock);
1080 if (g_hostLogger)
1081 return g_hostLogger;
1082 }
1083
1084 SrwExclusiveLock lock(&g_hostLoggerLock);
1085 if (g_hostLogger)
1086 return g_hostLogger;
1087 auto base = spdlog::get("HYDRAHOOK");
1088 if (!base)
1089 return nullptr;
1090 g_hostLogger = base->clone("host");
1091 return g_hostLogger;
1092}
1093
1104static void HydraHookEngineLogImpl(spdlog::level::level_enum level, LPCSTR Format, va_list args)
1105{
1106 if (!g_hostLoggingEnabled.load(std::memory_order_relaxed))
1107 return;
1108 if (static_cast<int>(level) < g_hostLogLevel.load(std::memory_order_relaxed))
1109 return;
1110 if (!Format)
1111 return;
1112
1113 auto logger = GetHostLogger();
1114 if (!logger || !logger->should_log(level))
1115 return;
1116
1117 char stack[512];
1118 va_list copy;
1119 va_copy(copy, args);
1120 const int needed = vsnprintf(stack, sizeof(stack), Format, copy);
1121 va_end(copy);
1122 if (needed < 0)
1123 return;
1124
1125 if (static_cast<size_t>(needed) < sizeof(stack))
1126 {
1127 logger->log(level, std::string_view(stack, static_cast<size_t>(needed)));
1128 return;
1129 }
1130
1131 std::string message(static_cast<size_t>(needed) + 1, '\0');
1132 vsnprintf(message.data(), message.size(), Format, args);
1133 message.resize(static_cast<size_t>(needed));
1134 logger->log(level, message);
1135}
1136
1137_Use_decl_annotations_
1139{
1140 va_list args;
1141 va_start(args, Format);
1142 HydraHookEngineLogImpl(spdlog::level::debug, Format, args);
1143 va_end(args);
1144}
1145
1146_Use_decl_annotations_
1148{
1149 va_list args;
1150 va_start(args, Format);
1151 HydraHookEngineLogImpl(spdlog::level::info, Format, args);
1152 va_end(args);
1153}
1154
1155_Use_decl_annotations_
1157{
1158 va_list args;
1159 va_start(args, Format);
1160 HydraHookEngineLogImpl(spdlog::level::warn, Format, args);
1161 va_end(args);
1162}
1163
1164_Use_decl_annotations_
1166{
1167 va_list args;
1168 va_start(args, Format);
1169 HydraHookEngineLogImpl(spdlog::level::err, Format, args);
1170 va_end(args);
1171}
bool HydraHookCrashHandlerInstall(PHYDRAHOOK_ENGINE engine)
Installs global crash handlers (ref-counted) for the given engine.
bool HydraHookCrashHandlerReferencesEngine(PHYDRAHOOK_ENGINE engine)
True when a published or deferred snapshot still names this engine. Destroy must not free the engine ...
void HydraHookCrashHandlerUninstall(PHYDRAHOOK_ENGINE engine)
Decrements the crash handler reference count.
Internal crash handler installation and teardown.
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
static SRWLOCK g_engineDestroyLock
Definition Engine.cpp:88
void HydraHookLoggingEnableAsync()
Swaps the process logger to a HydraHook-owned async pool. Call from the worker, not DllMain.
Definition Engine.cpp:961
static std::shared_ptr< spdlog::logger > GetHostLogger()
Returns a cached host-scoped logger clone for the process-wide "HYDRAHOOK" logger.
Definition Engine.cpp:1076
static SRWLOCK g_EngineHostInstancesLock
Definition Engine.cpp:86
void HydraHookEngineSetLifecycleLockForTest(PHYDRAHOOK_ENGINE engine, BOOL acquire)
Definition Engine.cpp:583
static void HydraHookEngineLogImpl(spdlog::level::level_enum level, LPCSTR Format, va_list args)
Format a printf-style message and emit it to the host logger at the specified level.
Definition Engine.cpp:1104
static std::vector< std::pair< HMODULE, PHYDRAHOOK_ENGINE > > g_EngineHostInstances
Definition Engine.cpp:87
static HYDRAHOOK_ERROR DestroyEngine(HMODULE HostInstance, bool(*detachFreeLibraryHook)() noexcept)
Definition Engine.cpp:414
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
HYDRAHOOK_D3D_VERSION HydraHookEngineGameVersionForTest(PHYDRAHOOK_ENGINE engine)
Definition Engine.cpp:578
Internal engine structure and callback invocation macros.
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
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)
bool HydraHookIpcAbandonRehookWait(PHYDRAHOOK_ENGINE engine)
Cancels a pending rehook wait so the engine can be freed.
void HydraHookIpcCreate(PHYDRAHOOK_ENGINE engine)
constexpr std::int32_t HydraHookIpcPhaseInCallbackExternal
Definition EngineIpc.h:65
constexpr std::uint32_t HydraHookIpcFlagRehookSupported
Definition EngineIpc.h:59
constexpr std::uint32_t HydraHookIpcStateStopped
Definition EngineIpc.h:50
constexpr std::uint32_t HydraHookIpcStateInitializing
Definition EngineIpc.h:46
constexpr std::uint32_t HydraHookIpcShutdownOriginNone
Definition EngineIpc.h:52
constexpr std::int32_t HydraHookIpcPhaseInCallback
Definition EngineIpc.h:64
void PerformShutdownCleanup(PHYDRAHOOK_ENGINE engine, ShutdownOrigin origin)
Performs pre-exit cleanup based on shutdown origin.
Definition Game.cpp:315
ID3D12CommandQueue * GetD3D12CommandQueueForSwapChain(IDXGISwapChain *pSwapChain, bool requireVerifiedQueue)
Returns the D3D12 command queue associated with a swap chain.
Definition Game.cpp:2188
DWORD HydraHookMainThread(LPVOID Params)
Main hook worker thread; probes and hooks render and audio APIs.
Definition Game.cpp:451
Main hook worker thread entry point.
Utility functions for environment expansion and process info.
C++ wrapper for Microsoft Detours function hooking.
bool g_hookDestructorDetachSuppressed
When set, ~Hook() does not detach.
Definition Hook.h:53
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.
struct _HYDRAHOOK_D3D11_EVENT_CALLBACKS * PHYDRAHOOK_D3D11_EVENT_CALLBACKS
VOID HydraHookEngineSetD3D11EventCallbacks(_In_ PHYDRAHOOK_ENGINE Engine, _In_ PHYDRAHOOK_D3D11_EVENT_CALLBACKS Callbacks)
Registers Direct3D 11 render pipeline callbacks.
struct _HYDRAHOOK_D3D12_EVENT_CALLBACKS * PHYDRAHOOK_D3D12_EVENT_CALLBACKS
#define HYDRAHOOK_API
HYDRAHOOK_D3D_VERSION
Bitmask of detected Direct3D API versions.
@ HydraHookDirect3DVersionUnknown
BOOL HydraHookEngineAreCallbacksDrained(_In_ PHYDRAHOOK_ENGINE Engine)
Reports whether all in-flight render callbacks were confirmed finished by the last unhook.
VOID HydraHookEngineLogError(_In_ LPCSTR Format, _In_opt_ ...)
Logs an error message (printf-style format).
VOID HydraHookEngineLogWarning(_In_ LPCSTR Format, _In_opt_ ...)
Logs a warning message (printf-style format).
HYDRAHOOK_ERROR
Error codes returned by HydraHook engine functions.
@ HYDRAHOOK_ERROR_CONTEXT_ALLOCATION_FAILED
@ HYDRAHOOK_ERROR_INVALID_ENGINE_HANDLE
@ HYDRAHOOK_ERROR_ENGINE_ALREADY_ALLOCATED
@ HYDRAHOOK_ERROR_ENGINE_ALLOCATION_FAILED
@ HYDRAHOOK_ERROR_NONE
@ HYDRAHOOK_ERROR_INVALID_ENGINE_CONFIG
@ HYDRAHOOK_ERROR_CREATE_THREAD_FAILED
@ HYDRAHOOK_ERROR_CREATE_EVENT_FAILED
@ HYDRAHOOK_ERROR_UNHOOK_INCOMPLETE
@ HYDRAHOOK_ERROR_INVALID_HMODULE_HANDLE
@ HYDRAHOOK_ERROR_CREATE_LOGGER_FAILED
@ HYDRAHOOK_ERROR_GET_MODULE_HANDLE_FAILED
HYDRAHOOK_ERROR HydraHookEngineDestroy(_In_ HMODULE HostInstance)
Destroys the engine and frees all resources.
HYDRAHOOK_ERROR HydraHookEngineAllocCustomContext(_In_ PHYDRAHOOK_ENGINE Engine, _Out_ PVOID *Context, _In_ size_t ContextSize)
Allocates custom context memory accessible from all event callbacks.
struct _HYDRAHOOK_D3D10_EVENT_CALLBACKS * PHYDRAHOOK_D3D10_EVENT_CALLBACKS
PVOID HydraHookEngineGetCustomContext(_In_ PHYDRAHOOK_ENGINE Engine)
Returns pointer to custom context memory, or NULL if none allocated.
VOID HydraHookEngineSetD3D9EventCallbacks(_In_ PHYDRAHOOK_ENGINE Engine, _In_ PHYDRAHOOK_D3D9_EVENT_CALLBACKS Callbacks)
Registers Direct3D 9/9Ex render pipeline callbacks.
VOID HYDRAHOOK_ENGINE_CONFIG_INIT(PHYDRAHOOK_ENGINE_CONFIG EngineConfig)
struct _HYDRAHOOK_D3D9_EVENT_CALLBACKS * PHYDRAHOOK_D3D9_EVENT_CALLBACKS
VOID HydraHookEngineLogDebug(_In_ LPCSTR Format, _In_opt_ ...)
Logs a debug message (printf-style format).
HYDRAHOOK_ERROR HydraHookEngineFreeCustomContext(_In_ PHYDRAHOOK_ENGINE Engine)
Frees custom context memory for the engine.
VOID HydraHookEngineLogInfo(_In_ LPCSTR Format, _In_opt_ ...)
Logs an informational message (printf-style format).
struct _HYDRAHOOK_ENGINE * PHYDRAHOOK_ENGINE
Opaque handle to the HydraHook engine instance.
struct _HYDRAHOOK_ARC_EVENT_CALLBACKS * PHYDRAHOOK_ARC_EVENT_CALLBACKS
HYDRAHOOK_ERROR HydraHookEngineUnhook(_In_ PHYDRAHOOK_ENGINE Engine)
Removes all render and audio hooks while keeping the DLL and engine loaded.
VOID HydraHookEngineSetARCEventCallbacks(_In_ PHYDRAHOOK_ENGINE Engine, _In_ PHYDRAHOOK_ARC_EVENT_CALLBACKS Callbacks)
Registers Core Audio (IAudioRenderClient) event callbacks.
VOID HydraHookEngineSetD3D10EventCallbacks(_In_ PHYDRAHOOK_ENGINE Engine, _In_ PHYDRAHOOK_D3D10_EVENT_CALLBACKS Callbacks)
Registers Direct3D 10 render pipeline callbacks.
HYDRAHOOK_ERROR HydraHookEngineCreate(_In_ HMODULE HostInstance, _In_ PHYDRAHOOK_ENGINE_CONFIG EngineConfig, _Out_opt_ PHYDRAHOOK_ENGINE *Engine)
Creates and initializes the HydraHook engine.
Core Audio (IAudioRenderClient) hook callbacks.
Direct3D 10 hook callbacks and helpers.
PHYDRAHOOK_ENGINE HydraHookEngineGetHandleFromD3D10SwapChain(_In_ IDXGISwapChain *SwapChain)
Resolves the engine handle from the swap chain passed to a Direct3D 10 callback.
Direct3D 11 hook callbacks and helpers.
Direct3D 12 hook callbacks.
VOID HydraHookEngineSetD3D12EventCallbacks(_In_ PHYDRAHOOK_ENGINE Engine, _In_ PHYDRAHOOK_D3D12_EVENT_CALLBACKS Callbacks)
Registers Direct3D 12 render pipeline callbacks.
ID3D12CommandQueue * HydraHookEngineGetD3D12CommandQueue(_In_ IDXGISwapChain *pSwapChain)
Returns the D3D12 command queue for a swap chain (for overlay rendering). Exact associations are reco...
BOOL HydraHookEngineDeferD3D12Resize(_In_ PHYDRAHOOK_EVT_PRE_EXTENSION Extension)
Defers the active D3D12 ResizeBuffers or ResizeBuffers1 call.
ID3D12CommandQueue * HydraHookEngineGetVerifiedD3D12CommandQueue(_In_ IDXGISwapChain *pSwapChain)
Returns the verified direct queue for the current D3D12 back buffer.
Direct3D 9/9Ex hook callbacks and helpers.
PHYDRAHOOK_ENGINE HydraHookEngineGetHandleFromD3D9Device(_In_ LPDIRECT3DDEVICE9 Device)
Resolves engine handle from IDirect3DDevice9 pointer.
PHYDRAHOOK_ENGINE HydraHookEngineGetHandleFromD3D9ExDevice(_In_ LPDIRECT3DDEVICE9EX Device)
Resolves engine handle from IDirect3DDevice9Ex pointer.
Internal shutdown origin and cleanup for HydraHook engine.
@ DllMainProcessDetach
Definition Shutdown.h:24
RAII guards for Win32 SRWLOCK.
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
Non-blocking exclusive lock. True when the lock was acquired.
Definition SrwLock.h:73
std::string get_module_directory(HMODULE hMod)
Returns the directory containing the given module.
Definition Global.h:100
std::string get_process_directory()
Returns the directory containing the main process executable.
Definition Global.h:129
std::string expand_environment_variables(const std::string &str)
Expands environment variables (e.g. TEMP%) in a string.
Definition Global.h:49
static D3D12ResizePreExtension * Current
Definition Game.h:54
Engine configuration passed to HydraHookEngineCreate. Initialize with HYDRAHOOK_ENGINE_CONFIG_INIT....
Internal engine instance structure (opaque in public API).
Definition Engine.h:90
HMODULE HostInstance
Definition Engine.h:91
static void shutdown() noexcept
Sets the shutdown flag so new Guard instances skip callbacks.
Definition Engine.h:205
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