Last active
September 12, 2024 07:34
-
-
Save rossy/7faf0ab90a54d6b5a46f to your computer and use it in GitHub Desktop.
MinGW-w64 set_thread_name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <windows.h> | |
#include <winnt.h> | |
#include <winternl.h> | |
#include <pshpack8.h> | |
typedef struct { | |
DWORD dwType; | |
LPCSTR szName; | |
DWORD dwThreadID; | |
DWORD dwFlags; | |
} THREADNAME_INFO; | |
#include <poppack.h> | |
static EXCEPTION_DISPOSITION NTAPI ignore_handler(EXCEPTION_RECORD *rec, | |
void *frame, CONTEXT *ctx, | |
void *disp) | |
{ | |
return ExceptionContinueExecution; | |
} | |
static void set_thread_name(const char *name) | |
{ | |
static const DWORD MS_VC_EXCEPTION = 0x406D1388; | |
// Don't bother if a debugger isn't attached to receive the event | |
if (!IsDebuggerPresent()) | |
return; | |
// Thread information for VS compatible debugger. -1 sets current thread. | |
THREADNAME_INFO ti = { | |
.dwType = 0x1000, | |
.szName = name, | |
.dwThreadID = -1, | |
}; | |
// Push an exception handler to ignore all following exceptions | |
NT_TIB *tib = ((NT_TIB*)NtCurrentTeb()); | |
EXCEPTION_REGISTRATION_RECORD rec = { | |
.Next = tib->ExceptionList, | |
.Handler = ignore_handler, | |
}; | |
tib->ExceptionList = &rec; | |
// Visual Studio and compatible debuggers receive thread names from the | |
// program through a specially crafted exception | |
RaiseException(MS_VC_EXCEPTION, 0, sizeof(ti) / sizeof(ULONG_PTR), | |
(ULONG_PTR*)&ti); | |
// Pop exception handler | |
tib->ExceptionList = tib->ExceptionList->Next; | |
} | |
int main() | |
{ | |
set_thread_name("test thread name"); | |
Sleep(INFINITE); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i‘m finding this for long time ,thx!!!!!!!!!!!