Skip to content

Instantly share code, notes, and snippets.

@rossy
Last active May 6, 2019 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rossy/7faf0ab90a54d6b5a46f to your computer and use it in GitHub Desktop.
Save rossy/7faf0ab90a54d6b5a46f to your computer and use it in GitHub Desktop.
MinGW-w64 set_thread_name
#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