Coverage Report

Created: 2026-09-14 20:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/util/threadnames.cpp
Line
Count
Source
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
static void SetThreadName(const char* name)
30
14.5k
{
31
14.5k
#if defined(PR_SET_NAME)
32
    // Only the first 15 characters are used (16 - NUL terminator)
33
14.5k
    ::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
14.5k
}
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
74.1M
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
static void SetInternalName(const std::string& name)
60
15.8k
{
61
15.8k
    const size_t copy_bytes{std::min(sizeof(g_thread_name) - 1, name.length())};
62
15.8k
    std::memcpy(g_thread_name, name.data(), copy_bytes);
63
15.8k
    g_thread_name[copy_bytes] = '\0';
64
15.8k
}
65
66
void util::ThreadRename(const std::string& name)
67
14.5k
{
68
14.5k
    Assume(name.size() <= 13); // Linux keeps 15 bytes
69
14.5k
    SetThreadName(("b-" + name).c_str());
70
14.5k
    SetInternalName(name);
71
14.5k
}
72
73
void util::ThreadSetInternalName(const std::string& name)
74
1.25k
{
75
1.25k
    SetInternalName(name);
76
1.25k
}