Branch data Line data Source code
1 : : // Copyright (c) 2018-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <bitcoin-build-config.h> // IWYU pragma: keep
6 : :
7 : : #include <util/threadnames.h>
8 : : #include <util/check.h>
9 : :
10 : : #include <algorithm>
11 : : #include <cstring>
12 : : #include <string>
13 : :
14 : : #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
15 : : #include <pthread.h>
16 : : #include <pthread_np.h>
17 : : #endif
18 : :
19 : : #if __has_include(<sys/prctl.h>)
20 : : #include <sys/prctl.h>
21 : : #endif
22 : :
23 : : #ifdef HAVE_SETTHREADDESCRIPTION
24 : : #include <windows.h>
25 : : #endif
26 : :
27 : : //! Set the thread's name at the process level. Does not affect the
28 : : //! internal name.
29 : 14934 : static void SetThreadName(const char* name)
30 : : {
31 : : #if defined(PR_SET_NAME)
32 : : // Only the first 15 characters are used (16 - NUL terminator)
33 : 14934 : ::prctl(PR_SET_NAME, name, 0, 0, 0);
34 : : #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
35 : : pthread_set_name_np(pthread_self(), name);
36 : : #elif defined(__APPLE__)
37 : : pthread_setname_np(name);
38 : : #elif defined(HAVE_SETTHREADDESCRIPTION)
39 : : // Thread names are ASCII-only, so widening each character is sufficient as
40 : : // a conversion to UTF-16.
41 : : const std::wstring wname{name, name + std::strlen(name)};
42 : : ::SetThreadDescription(::GetCurrentThread(), wname.c_str());
43 : : #else
44 : : // Prevent warnings for unused parameters...
45 : : (void)name;
46 : : #endif
47 : 14934 : }
48 : :
49 : : /**
50 : : * The name of the thread. We use char array instead of std::string to avoid
51 : : * complications with running a destructor when the thread exits. Avoid adding
52 : : * other thread_local variables.
53 : : * @see https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=278701
54 : : */
55 : : static thread_local char g_thread_name[128]{'\0'};
56 : 6388251 : std::string util::ThreadGetInternalName() { return g_thread_name; }
57 : : //! Set the in-memory internal name for this thread. Does not affect the process
58 : : //! name.
59 : 16211 : static void SetInternalName(const std::string& name)
60 : : {
61 [ - + - + ]: 16211 : const size_t copy_bytes{std::min(sizeof(g_thread_name) - 1, name.length())};
62 : 16211 : std::memcpy(g_thread_name, name.data(), copy_bytes);
63 : 16211 : g_thread_name[copy_bytes] = '\0';
64 : 16211 : }
65 : :
66 : 14934 : void util::ThreadRename(const std::string& name)
67 : : {
68 [ - + ]: 14934 : Assume(name.size() <= 13); // Linux keeps 15 bytes
69 : 14934 : SetThreadName(("b-" + name).c_str());
70 : 14934 : SetInternalName(name);
71 : 14934 : }
72 : :
73 : 1277 : void util::ThreadSetInternalName(const std::string& name)
74 : : {
75 : 1277 : SetInternalName(name);
76 : 1277 : }
|