Skip to content

Commit 2cdf611

Browse files
authored
[compiler-rt][Fuzzer] SetThreadName windows implementation new try. (#76761)
SetThreadDescription symbol needs to be dynamically loaded before usage. Then using a wide string buffer, since we re using a null terminated string, we can use MultiByteToWideChar -1 as 4th argument to finally set the thread name. Previously `SetThreadDescription` was called directly causing crash. It was reverted in dd3aa26
1 parent e7c3cd2 commit 2cdf611

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

compiler-rt/lib/fuzzer/FuzzerUtilWindows.cpp

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@
1818
#include <errno.h>
1919
#include <io.h>
2020
#include <iomanip>
21+
#include <libloaderapi.h>
2122
#include <signal.h>
2223
#include <stdio.h>
24+
#include <stringapiset.h>
2325
#include <sys/types.h>
2426
#include <windows.h>
2527

@@ -234,8 +236,20 @@ size_t PageSize() {
234236
}
235237

236238
void SetThreadName(std::thread &thread, const std::string &name) {
237-
// TODO ?
238-
// to UTF-8 then SetThreadDescription ?
239+
typedef HRESULT(WINAPI * proc)(HANDLE, PCWSTR);
240+
HMODULE kbase = GetModuleHandleA("KernelBase.dll");
241+
proc ThreadNameProc =
242+
reinterpret_cast<proc>(GetProcAddress, "SetThreadDescription");
243+
if (proc) {
244+
std::wstring buf;
245+
auto sz = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0);
246+
if (sz > 0) {
247+
buf.resize(sz);
248+
if (MultyByteToWideChar(CP_UTF8, 0, name.data(), -1, &buf[0], sz) > 0) {
249+
(void)ThreadNameProc(thread.native_handle(), buf.c_str());
250+
}
251+
}
252+
}
239253
}
240254

241255
} // namespace fuzzer

0 commit comments

Comments
 (0)