[compiler-rt] [compiler-rt][Fuzzer] SetThreadName windows implementation new try. (PR #76761)

David CARLIER via llvm-commits llvm-commits at lists.llvm.org
Tue Jan 2 14:55:44 PST 2024


https://github.com/devnexen created https://github.com/llvm/llvm-project/pull/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.

>From d99a0f939ef40b79cac55a1212779b0004930b8c Mon Sep 17 00:00:00 2001
From: David Carlier <devnexen at gmail.com>
Date: Tue, 2 Jan 2024 22:50:51 +0000
Subject: [PATCH] [compiler-rt][Fuzzer] SetThreadName windows implementation
 new try.

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.
---
 compiler-rt/lib/fuzzer/FuzzerUtilWindows.cpp | 17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)

diff --git a/compiler-rt/lib/fuzzer/FuzzerUtilWindows.cpp b/compiler-rt/lib/fuzzer/FuzzerUtilWindows.cpp
index 71770166805f78..e47494060a0ff5 100644
--- a/compiler-rt/lib/fuzzer/FuzzerUtilWindows.cpp
+++ b/compiler-rt/lib/fuzzer/FuzzerUtilWindows.cpp
@@ -18,8 +18,10 @@
 #include <errno.h>
 #include <io.h>
 #include <iomanip>
+#include <libloaderapi.h>
 #include <signal.h>
 #include <stdio.h>
+#include <stringapiset.h>
 #include <sys/types.h>
 #include <windows.h>
 
@@ -234,8 +236,19 @@ size_t PageSize() {
 }
 
 void SetThreadName(std::thread &thread, const std::string &name) {
-  // TODO ?
-  // to UTF-8 then SetThreadDescription ?
+  typedef HRESULT(WINAPI *proc)(HANDLE, PCWSTR);
+  HMODULE kbase = GetModuleHandleA("KernelBase.dll");
+  proc ThreadNameProc = reinterpret_cast<proc>(GetProcAddress, "SetThreadDescription");
+  if (proc) {
+    std::wstring buf;
+    auto sz = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0);
+    if (sz > 0) {
+      buf.resize(sz);
+      if (MultyByteToWideChar(CP_UTF8, 0, name.data(), -1, &buf[0], sz) > 0) {
+        (void)ThreadNameProc(thread.native_handle(), buf.c_str());
+      }
+    }
+  }
 }
 
 } // namespace fuzzer



More information about the llvm-commits mailing list