blob: c87a166bf11e49d4582a98614d91eaec5b677192 [file] [log] [blame]
Zachary Turner757dbc92017-03-03 17:15:17 +00001//===- Unix/Threading.inc - Unix Threading Implementation ----- -*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Zachary Turner757dbc92017-03-03 17:15:17 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file provides the Unix specific implementation of Threading functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/SmallString.h"
14#include "llvm/ADT/Twine.h"
15
16#if defined(__APPLE__)
17#include <mach/mach_init.h>
18#include <mach/mach_port.h>
19#endif
20
21#include <pthread.h>
22
Brad Smith8c17d592018-06-23 22:02:59 +000023#if defined(__FreeBSD__) || defined(__OpenBSD__)
24#include <pthread_np.h> // For pthread_getthreadid_np() / pthread_set_name_np()
Zachary Turnerd9738132017-03-03 18:38:22 +000025#endif
26
27#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include <errno.h>
Kamil Rytarowski71efce22017-03-04 17:42:46 +000029#include <sys/sysctl.h>
30#include <sys/user.h>
Zachary Turnerd9738132017-03-03 18:38:22 +000031#include <unistd.h>
Zachary Turner757dbc92017-03-03 17:15:17 +000032#endif
33
34#if defined(__NetBSD__)
Chandler Carruth6bda14b2017-06-06 11:49:48 +000035#include <lwp.h> // For _lwp_self()
Zachary Turner757dbc92017-03-03 17:15:17 +000036#endif
37
38#if defined(__linux__)
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include <sys/syscall.h> // For syscall codes
40#include <unistd.h> // For syscall()
Zachary Turner757dbc92017-03-03 17:15:17 +000041#endif
42
Zachary Turner757dbc92017-03-03 17:15:17 +000043namespace {
44 struct ThreadInfo {
45 void(*UserFn)(void *);
46 void *UserData;
47 };
48}
49
50static void *ExecuteOnThread_Dispatch(void *Arg) {
51 ThreadInfo *TI = reinterpret_cast<ThreadInfo*>(Arg);
52 TI->UserFn(TI->UserData);
53 return nullptr;
54}
55
56void llvm::llvm_execute_on_thread(void(*Fn)(void*), void *UserData,
57 unsigned RequestedStackSize) {
58 ThreadInfo Info = { Fn, UserData };
59 pthread_attr_t Attr;
60 pthread_t Thread;
61
62 // Construct the attributes object.
63 if (::pthread_attr_init(&Attr) != 0)
64 return;
65
66 // Set the requested stack size, if given.
67 if (RequestedStackSize != 0) {
68 if (::pthread_attr_setstacksize(&Attr, RequestedStackSize) != 0)
69 goto error;
70 }
71
72 // Construct and execute the thread.
73 if (::pthread_create(&Thread, &Attr, ExecuteOnThread_Dispatch, &Info) != 0)
74 goto error;
75
76 // Wait for the thread and clean up.
77 ::pthread_join(Thread, nullptr);
78
79error:
80 ::pthread_attr_destroy(&Attr);
81}
82
83
84uint64_t llvm::get_threadid() {
85#if defined(__APPLE__)
86 // Calling "mach_thread_self()" bumps the reference count on the thread
87 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
88 // count.
89 thread_port_t Self = mach_thread_self();
90 mach_port_deallocate(mach_task_self(), Self);
91 return Self;
92#elif defined(__FreeBSD__)
93 return uint64_t(pthread_getthreadid_np());
94#elif defined(__NetBSD__)
95 return uint64_t(_lwp_self());
96#elif defined(__ANDROID__)
97 return uint64_t(gettid());
98#elif defined(__linux__)
99 return uint64_t(syscall(SYS_gettid));
Zachary Turner757dbc92017-03-03 17:15:17 +0000100#else
101 return uint64_t(pthread_self());
102#endif
103}
104
105
Zachary Turner1f004c42017-03-04 18:53:09 +0000106static constexpr uint32_t get_max_thread_name_length_impl() {
Zachary Turner777de772017-03-04 16:42:25 +0000107#if defined(__NetBSD__)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000108 return PTHREAD_MAX_NAMELEN_NP;
Zachary Turner777de772017-03-04 16:42:25 +0000109#elif defined(__APPLE__)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000110 return 64;
Zachary Turner777de772017-03-04 16:42:25 +0000111#elif defined(__linux__)
112#if HAVE_PTHREAD_SETNAME_NP
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000113 return 16;
Zachary Turner777de772017-03-04 16:42:25 +0000114#else
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000115 return 0;
Zachary Turner777de772017-03-04 16:42:25 +0000116#endif
117#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
118 return 16;
Brad Smith8c17d592018-06-23 22:02:59 +0000119#elif defined(__OpenBSD__)
120 return 32;
Zachary Turner777de772017-03-04 16:42:25 +0000121#else
122 return 0;
123#endif
124}
125
Zachary Turner1f004c42017-03-04 18:53:09 +0000126uint32_t llvm::get_max_thread_name_length() {
127 return get_max_thread_name_length_impl();
128}
129
Zachary Turner757dbc92017-03-03 17:15:17 +0000130void llvm::set_thread_name(const Twine &Name) {
131 // Make sure the input is null terminated.
132 SmallString<64> Storage;
133 StringRef NameStr = Name.toNullTerminatedStringRef(Storage);
Zachary Turner777de772017-03-04 16:42:25 +0000134
135 // Truncate from the beginning, not the end, if the specified name is too
136 // long. For one, this ensures that the resulting string is still null
137 // terminated, but additionally the end of a long thread name will usually
138 // be more unique than the beginning, since a common pattern is for similar
139 // threads to share a common prefix.
Sam McCall63580642018-02-13 23:23:59 +0000140 // Note that the name length includes the null terminator.
Zachary Turner1f004c42017-03-04 18:53:09 +0000141 if (get_max_thread_name_length() > 0)
Sam McCall63580642018-02-13 23:23:59 +0000142 NameStr = NameStr.take_back(get_max_thread_name_length() - 1);
Krzysztof Parzyszek75464e12017-03-03 22:21:02 +0000143 (void)NameStr;
Zachary Turner757dbc92017-03-03 17:15:17 +0000144#if defined(__linux__)
145#if (defined(__GLIBC__) && defined(_GNU_SOURCE)) || defined(__ANDROID__)
Krzysztof Parzyszek6cf25402017-03-03 21:53:12 +0000146#if HAVE_PTHREAD_SETNAME_NP
Zachary Turner757dbc92017-03-03 17:15:17 +0000147 ::pthread_setname_np(::pthread_self(), NameStr.data());
148#endif
Krzysztof Parzyszek6cf25402017-03-03 21:53:12 +0000149#endif
Brad Smith8c17d592018-06-23 22:02:59 +0000150#elif defined(__FreeBSD__) || defined(__OpenBSD__)
Zachary Turner757dbc92017-03-03 17:15:17 +0000151 ::pthread_set_name_np(::pthread_self(), NameStr.data());
152#elif defined(__NetBSD__)
153 ::pthread_setname_np(::pthread_self(), "%s",
154 const_cast<char *>(NameStr.data()));
155#elif defined(__APPLE__)
156 ::pthread_setname_np(NameStr.data());
157#endif
158}
159
160void llvm::get_thread_name(SmallVectorImpl<char> &Name) {
161 Name.clear();
162
163#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
Zachary Turner45337cf2017-03-03 18:21:04 +0000164 int pid = ::getpid();
165 uint64_t tid = get_threadid();
Zachary Turner757dbc92017-03-03 17:15:17 +0000166
167 struct kinfo_proc *kp = nullptr, *nkp;
168 size_t len = 0;
169 int error;
170 int ctl[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD,
171 (int)pid };
172
173 while (1) {
174 error = sysctl(ctl, 4, kp, &len, nullptr, 0);
175 if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
176 // Add extra space in case threads are added before next call.
177 len += sizeof(*kp) + len / 10;
Serge Pavlovce719a02018-02-15 09:35:36 +0000178 nkp = (struct kinfo_proc *)::realloc(kp, len);
Zachary Turner757dbc92017-03-03 17:15:17 +0000179 if (nkp == nullptr) {
180 free(kp);
181 return;
182 }
183 kp = nkp;
184 continue;
185 }
186 if (error != 0)
187 len = 0;
188 break;
189 }
190
191 for (size_t i = 0; i < len / sizeof(*kp); i++) {
192 if (kp[i].ki_tid == (lwpid_t)tid) {
193 Name.append(kp[i].ki_tdname, kp[i].ki_tdname + strlen(kp[i].ki_tdname));
194 break;
195 }
196 }
197 free(kp);
198 return;
199#elif defined(__NetBSD__)
Zachary Turner1f004c42017-03-04 18:53:09 +0000200 constexpr uint32_t len = get_max_thread_name_length_impl();
201 char buf[len];
202 ::pthread_getname_np(::pthread_self(), buf, len);
Zachary Turner757dbc92017-03-03 17:15:17 +0000203
204 Name.append(buf, buf + strlen(buf));
205#elif defined(__linux__)
Krzysztof Parzyszek6cf25402017-03-03 21:53:12 +0000206#if HAVE_PTHREAD_GETNAME_NP
Zachary Turner1f004c42017-03-04 18:53:09 +0000207 constexpr uint32_t len = get_max_thread_name_length_impl();
Sam McCall0e142492017-11-02 12:29:47 +0000208 char Buffer[len] = {'\0'}; // FIXME: working around MSan false positive.
Zachary Turner1f004c42017-03-04 18:53:09 +0000209 if (0 == ::pthread_getname_np(::pthread_self(), Buffer, len))
Zachary Turner757dbc92017-03-03 17:15:17 +0000210 Name.append(Buffer, Buffer + strlen(Buffer));
211#endif
212#endif
Zachary Turner757dbc92017-03-03 17:15:17 +0000213}