From 929b5176ceebfd3fdfc2b63d0031d5c9ba0696ef Mon Sep 17 00:00:00 2001 From: WerWolv Date: Tue, 9 Jan 2024 13:43:34 +0100 Subject: [PATCH] impr: Fallback to old thread name API when new one isn't available --- lib/libimhex/source/api/task_manager.cpp | 33 ++++++++++++++++++++++-- lib/libimhex/source/helpers/logger.cpp | 2 +- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/lib/libimhex/source/api/task_manager.cpp b/lib/libimhex/source/api/task_manager.cpp index d78369c5f..bb49cdd31 100644 --- a/lib/libimhex/source/api/task_manager.cpp +++ b/lib/libimhex/source/api/task_manager.cpp @@ -367,8 +367,37 @@ namespace hex { void TaskManager::setCurrentThreadName(const std::string &name) { #if defined(OS_WINDOWS) - auto longName = hex::utf8ToUtf16(name); - ::SetThreadDescription(::GetCurrentThread(), longName.c_str()); + using SetThreadDescriptionFunc = HRESULT(WINAPI*)(HANDLE hThread, PCWSTR lpThreadDescription); + + static auto setThreadDescription = reinterpret_cast( + reinterpret_cast( + ::GetProcAddress( + ::GetModuleHandle("Kernel32.dll"), + "SetThreadDescription" + ) + ) + ); + + if (setThreadDescription != nullptr) { + const auto longName = hex::utf8ToUtf16(name); + setThreadDescription(::GetCurrentThread(), longName.c_str()); + } else { + struct THREADNAME_INFO { + DWORD dwType; + LPCSTR szName; + DWORD dwThreadID; + DWORD dwFlags; + }; + + THREADNAME_INFO info = { }; + info.dwType = 0x1000; + info.szName = name.c_str(); + info.dwThreadID = ::GetCurrentThreadId(); + info.dwFlags = 0; + + constexpr static DWORD MS_VC_EXCEPTION = 0x406D1388; + RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), reinterpret_cast(&info)); + } #elif defined(OS_LINUX) pthread_setname_np(pthread_self(), name.c_str()); #elif defined(OS_WEB) diff --git a/lib/libimhex/source/helpers/logger.cpp b/lib/libimhex/source/helpers/logger.cpp index 12b36ab91..120c9b855 100644 --- a/lib/libimhex/source/helpers/logger.cpp +++ b/lib/libimhex/source/helpers/logger.cpp @@ -75,7 +75,7 @@ namespace hex::log::impl { std::string projectThreadTag = projectName; if (auto threadName = TaskManager::getCurrentThreadName(); !threadName.empty()) - projectThreadTag += fmt::format("|{0}", threadName); + projectThreadTag += fmt::format(" | {0}", threadName); constexpr static auto MaxTagLength = 25; if (projectThreadTag.length() > MaxTagLength)