summaryrefslogtreecommitdiffhomepage
path: root/compat/thread-name.cpp
blob: da9aacd51c4f9c34c57db514b4ba4bfeb4023794 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "thread-name.hpp"
#ifdef _WIN32
#   include <QDebug>
#   include <windows.h>
#else
#   include <QThread>
#endif

namespace portable {

#if defined _MSC_VER

struct THREADNAME_INFO
{
    DWORD dwType;      // must be 0x1000
    LPCSTR szName;     // pointer to name (in user addr space)
    HANDLE dwThreadID; // thread ID (-1=caller thread)
    DWORD dwFlags;     // reserved for future use, must be zero
};

static inline
void set_curthread_name_old(const QString& name_)
{
    QByteArray str = name_.toLocal8Bit();
    const char* name = str.constData();
    HANDLE curthread = GetCurrentThread();

    THREADNAME_INFO info; // NOLINT(cppcoreguidelines-pro-type-member-init)
    info.dwType = 0x1000;
    info.szName = name;
    info.dwThreadID = curthread;
    info.dwFlags = 0;
    __try
    {
        static_assert(sizeof(info) % sizeof(unsigned) == 0);
        unsigned sz = sizeof(info)/sizeof(unsigned);
        RaiseException(0x406D1388, 0, sz, (const ULONG_PTR*)&info);
    }
    __except (EXCEPTION_CONTINUE_EXECUTION)
    {
    }
}

void set_curthread_name(const QString& name)
{
    static_assert(sizeof(wchar_t) == sizeof(decltype(*QString().utf16())));

    HMODULE module;
    HRESULT (__stdcall *fn)(HANDLE, const wchar_t*);
    if (GetModuleHandleExA(0, "kernel32.dll", &module) &&
        (fn = (decltype(fn))GetProcAddress(module, "SetThreadDescription")))
    {
        fn(GetCurrentThread(), (const wchar_t*)name.utf16());
    }
    else
    {
        set_curthread_name_old(name);
    }
}

#elif defined _WIN32

void set_curthread_name(const QString& name)
{
    (void)name;
}

#else

void set_curthread_name(const QString& name)
{
    QThread::currentThread()->setObjectName(name);
}

#endif

} // ns portable