|
31 | 31 | #include <psapi.h>
|
32 | 32 | // clang-format on
|
33 | 33 |
|
| 34 | +#if __has_include(<pthread.h>) |
| 35 | +#include <pthread.h> |
| 36 | +#endif |
| 37 | + |
34 | 38 | namespace fuzzer {
|
35 | 39 |
|
36 | 40 | static const FuzzingOptions* HandlerOpt = nullptr;
|
@@ -238,27 +242,33 @@ size_t PageSize() {
|
238 | 242 | return PageSizeCached;
|
239 | 243 | }
|
240 | 244 |
|
241 |
| -void SetThreadName(std::thread &thread, const std::string &name) { |
242 |
| -#ifndef __MINGW32__ |
243 |
| - // Not setting the thread name in MinGW environments. MinGW C++ standard |
244 |
| - // libraries can either use native Windows threads or pthreads, so we |
245 |
| - // don't know with certainty what kind of thread handle we're getting |
246 |
| - // from thread.native_handle() here. |
247 |
| - typedef HRESULT(WINAPI * proc)(HANDLE, PCWSTR); |
248 |
| - HMODULE kbase = GetModuleHandleA("KernelBase.dll"); |
249 |
| - proc ThreadNameProc = reinterpret_cast<proc>( |
250 |
| - (void *)GetProcAddress(kbase, "SetThreadDescription")); |
251 |
| - if (ThreadNameProc) { |
252 |
| - std::wstring buf; |
253 |
| - auto sz = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0); |
254 |
| - if (sz > 0) { |
255 |
| - buf.resize(sz); |
256 |
| - if (MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, &buf[0], sz) > 0) { |
257 |
| - (void)ThreadNameProc(thread.native_handle(), buf.c_str()); |
| 245 | +template <class Thread> |
| 246 | +void maybe_set_thread_name(Thread &thread, const std::string &name) { |
| 247 | +#if __has_include(<pthread.h>) |
| 248 | + if constexpr (std::is_same_v<std::thread::native_handle_type, ::pthread_t>) { |
| 249 | + (void)pthread_setname_np(thread.native_handle(), name.c_str()); |
| 250 | + } |
| 251 | +#endif |
| 252 | + if constexpr (std::is_same_v<std::thread::native_handle_type, HANDLE>) { |
| 253 | + typedef HRESULT(WINAPI * proc)(HANDLE, PCWSTR); |
| 254 | + HMODULE kbase = GetModuleHandleA("KernelBase.dll"); |
| 255 | + proc ThreadNameProc = reinterpret_cast<proc>( |
| 256 | + (void *)GetProcAddress(kbase, "SetThreadDescription")); |
| 257 | + if (ThreadNameProc) { |
| 258 | + std::wstring buf; |
| 259 | + auto sz = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0); |
| 260 | + if (sz > 0) { |
| 261 | + buf.resize(sz); |
| 262 | + if (MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, &buf[0], sz) > 0) { |
| 263 | + (void)ThreadNameProc(thread.native_handle(), buf.c_str()); |
| 264 | + } |
258 | 265 | }
|
259 | 266 | }
|
260 | 267 | }
|
261 |
| -#endif |
| 268 | +} |
| 269 | + |
| 270 | +void SetThreadName(std::thread &thread, const std::string &name) { |
| 271 | + maybe_set_thread_name(thread, name); |
262 | 272 | }
|
263 | 273 |
|
264 | 274 | } // namespace fuzzer
|
|
0 commit comments