Skip to content

Commit faace44

Browse files
committed
[compiler-rt] [fuzzer] Implement setting the thread name for MinGW
This detects the kind of thread handle that is returned by std::thread::native_handle(), and calls either SetThreadDescription() or pthread_setname_np() based on that.
1 parent bbc3af0 commit faace44

File tree

1 file changed

+28
-18
lines changed

1 file changed

+28
-18
lines changed

compiler-rt/lib/fuzzer/FuzzerUtilWindows.cpp

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@
3131
#include <psapi.h>
3232
// clang-format on
3333

34+
#if __has_include(<pthread.h>)
35+
#include <pthread.h>
36+
#endif
37+
3438
namespace fuzzer {
3539

3640
static const FuzzingOptions* HandlerOpt = nullptr;
@@ -238,27 +242,33 @@ size_t PageSize() {
238242
return PageSizeCached;
239243
}
240244

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+
}
258265
}
259266
}
260267
}
261-
#endif
268+
}
269+
270+
void SetThreadName(std::thread &thread, const std::string &name) {
271+
maybe_set_thread_name(thread, name);
262272
}
263273

264274
} // namespace fuzzer

0 commit comments

Comments
 (0)