Add support for getting the current thread's name
[folly.git] / folly / ThreadName.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/ThreadName.h>
18
19 #include <type_traits>
20
21 #include <folly/Portability.h>
22 #include <folly/Traits.h>
23 #include <folly/portability/PThread.h>
24
25 namespace folly {
26
27 // This looks a bit weird, but it's necessary to avoid
28 // having an undefined compiler function called.
29 #if defined(__GLIBC__) && !defined(__APPLE__) && !defined(__ANDROID__)
30 #if __GLIBC_PREREQ(2, 12)
31 // has pthread_setname_np(pthread_t, const char*) (2 params)
32 #define FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME 1
33 #endif
34 #endif
35
36 #if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
37 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
38 // has pthread_setname_np(const char*) (1 param)
39 #define FOLLY_HAS_PTHREAD_SETNAME_NP_NAME 1
40 #endif
41 #endif
42
43 bool canSetCurrentThreadName() {
44 #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME || \
45     FOLLY_HAS_PTHREAD_SETNAME_NP_NAME
46   return true;
47 #else
48   return false;
49 #endif
50 }
51
52 bool canSetOtherThreadName() {
53 #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME
54   return true;
55 #else
56   return false;
57 #endif
58 }
59
60 static constexpr size_t kMaxThreadNameLength = 16;
61
62 Optional<std::string> getCurrentThreadName() {
63 #if !FOLLY_HAVE_PTHREAD
64   return Optional<std::string>();
65 #else
66 #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME
67   std::array<char, kMaxThreadNameLength> buf;
68   if (pthread_getname_np(pthread_self(), buf.data(), buf.size()) != 0) {
69     return Optional<std::string>();
70   }
71   return make_optional(std::string(buf.data()));
72 #elif FOLLY_HAS_PTHREAD_SETNAME_NP_NAME
73   std::array<char, kMaxThreadNameLength> buf;
74   if (pthread_getname_np(buf.data(), buf.size()) != 0) {
75     return Optional<std::string>();
76   }
77   return make_optional(std::string(buf.data()));
78 #else
79   return Optional<std::string>();
80 #endif
81 #endif
82 }
83
84 bool setThreadName(std::thread::id tid, StringPiece name) {
85 #if !FOLLY_HAVE_PTHREAD || _WIN32
86   return false;
87 #else
88   static_assert(
89       std::is_same<pthread_t, std::thread::native_handle_type>::value,
90       "This assumes that the native handle type is pthread_t");
91   static_assert(
92       sizeof(std::thread::native_handle_type) == sizeof(std::thread::id),
93       "This assumes std::thread::id is a thin wrapper around "
94       "std::thread::native_handle_type, but that doesn't appear to be true.");
95   // In most implementations, std::thread::id is a thin wrapper around
96   // std::thread::native_handle_type, which means we can do unsafe things to
97   // extract it.
98   pthread_t id;
99   std::memcpy(&id, &tid, sizeof(id));
100   auto trimmedName = name.fbstr().substr(0, kMaxThreadNameLength - 1);
101 #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME
102   return 0 == pthread_setname_np(id, trimmedName.c_str());
103 #elif FOLLY_HAS_PTHREAD_SETNAME_NP_NAME
104   // Since OS X 10.6 it is possible for a thread to set its own name,
105   // but not that of some other thread.
106   if (pthread_equal(pthread_self(), id)) {
107     return 0 == pthread_setname_np(trimmedName.c_str());
108   }
109   return false;
110 #else
111   return false;
112 #endif
113 #endif
114 }
115
116 #if FOLLY_HAVE_PTHREAD
117 bool setThreadName(pthread_t pid, StringPiece name) {
118 #if _WIN32
119   // Not currently supported on Windows.
120   return false;
121 #else
122   static_assert(
123       std::is_same<pthread_t, std::thread::native_handle_type>::value,
124       "This assumes that the native handle type is pthread_t");
125   static_assert(
126       sizeof(std::thread::native_handle_type) == sizeof(std::thread::id),
127       "This assumes std::thread::id is a thin wrapper around "
128       "std::thread::native_handle_type, but that doesn't appear to be true.");
129   // In most implementations, std::thread::id is a thin wrapper around
130   // std::thread::native_handle_type, which means we can do unsafe things to
131   // extract it.
132   std::thread::id id;
133   std::memcpy(&id, &pid, sizeof(id));
134   return setThreadName(id, name);
135 #endif
136 }
137 #endif
138
139 bool setThreadName(StringPiece name) {
140   return setThreadName(std::this_thread::get_id(), name);
141 }
142 }