Ticket #62417: Threading.inc

File Threading.inc, 5.9 KB (added by Wowfunhappy (Jonathan), 4 years ago)
Line 
1//===- Unix/Threading.inc - Unix Threading Implementation ----- -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides the Unix specific implementation of Threading functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/SmallString.h"
15#include "llvm/ADT/Twine.h"
16
17#if defined(__APPLE__)
18#include <Availability.h>
19#include <mach/mach_init.h>
20#include <mach/mach_port.h>
21#endif
22
23#include <pthread.h>
24
25#if defined(__FreeBSD__) || defined(__OpenBSD__)
26#include <pthread_np.h> // For pthread_getthreadid_np() / pthread_set_name_np()
27#endif
28
29#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
30#include <errno.h>
31#include <sys/sysctl.h>
32#include <sys/user.h>
33#include <unistd.h>
34#endif
35
36#if defined(__NetBSD__)
37#include <lwp.h> // For _lwp_self()
38#endif
39
40#if defined(__linux__)
41#include <sys/syscall.h> // For syscall codes
42#include <unistd.h>      // For syscall()
43#endif
44
45namespace {
46  struct ThreadInfo {
47    void(*UserFn)(void *);
48    void *UserData;
49  };
50}
51
52static void *ExecuteOnThread_Dispatch(void *Arg) {
53  ThreadInfo *TI = reinterpret_cast<ThreadInfo*>(Arg);
54  TI->UserFn(TI->UserData);
55  return nullptr;
56}
57
58void llvm::llvm_execute_on_thread(void(*Fn)(void*), void *UserData,
59  unsigned RequestedStackSize) {
60  ThreadInfo Info = { Fn, UserData };
61  pthread_attr_t Attr;
62  pthread_t Thread;
63
64  // Construct the attributes object.
65  if (::pthread_attr_init(&Attr) != 0)
66    return;
67
68  // Set the requested stack size, if given.
69  if (RequestedStackSize != 0) {
70    if (::pthread_attr_setstacksize(&Attr, RequestedStackSize) != 0)
71      goto error;
72  }
73
74  // Construct and execute the thread.
75  if (::pthread_create(&Thread, &Attr, ExecuteOnThread_Dispatch, &Info) != 0)
76    goto error;
77
78  // Wait for the thread and clean up.
79  ::pthread_join(Thread, nullptr);
80
81error:
82  ::pthread_attr_destroy(&Attr);
83}
84
85
86uint64_t llvm::get_threadid() {
87#if defined(__APPLE__)
88  // Calling "mach_thread_self()" bumps the reference count on the thread
89  // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
90  // count.
91  thread_port_t Self = mach_thread_self();
92  mach_port_deallocate(mach_task_self(), Self);
93  return Self;
94#elif defined(__FreeBSD__)
95  return uint64_t(pthread_getthreadid_np());
96#elif defined(__NetBSD__)
97  return uint64_t(_lwp_self());
98#elif defined(__ANDROID__)
99  return uint64_t(gettid());
100#elif defined(__linux__)
101  return uint64_t(syscall(SYS_gettid));
102#else
103  return uint64_t(pthread_self());
104#endif
105}
106
107
108static constexpr uint32_t get_max_thread_name_length_impl() {
109#if defined(__NetBSD__)
110  return PTHREAD_MAX_NAMELEN_NP;
111#elif defined(__APPLE__)
112  return 64;
113#elif defined(__linux__)
114#if HAVE_PTHREAD_SETNAME_NP
115  return 16;
116#else
117  return 0;
118#endif
119#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
120  return 16;
121#elif defined(__OpenBSD__)
122  return 32;
123#else
124  return 0;
125#endif
126}
127
128uint32_t llvm::get_max_thread_name_length() {
129  return get_max_thread_name_length_impl();
130}
131
132void llvm::set_thread_name(const Twine &Name) {
133  // Make sure the input is null terminated.
134  SmallString<64> Storage;
135  StringRef NameStr = Name.toNullTerminatedStringRef(Storage);
136
137  // Truncate from the beginning, not the end, if the specified name is too
138  // long.  For one, this ensures that the resulting string is still null
139  // terminated, but additionally the end of a long thread name will usually
140  // be more unique than the beginning, since a common pattern is for similar
141  // threads to share a common prefix.
142  // Note that the name length includes the null terminator.
143  if (get_max_thread_name_length() > 0)
144    NameStr = NameStr.take_back(get_max_thread_name_length() - 1);
145  (void)NameStr;
146#if defined(__linux__)
147#if (defined(__GLIBC__) && defined(_GNU_SOURCE)) || defined(__ANDROID__)
148#if HAVE_PTHREAD_SETNAME_NP
149  ::pthread_setname_np(::pthread_self(), NameStr.data());
150#endif
151#endif
152#elif defined(__FreeBSD__) || defined(__OpenBSD__)
153  ::pthread_set_name_np(::pthread_self(), NameStr.data());
154#elif defined(__NetBSD__)
155  ::pthread_setname_np(::pthread_self(), "%s",
156    const_cast<char *>(NameStr.data()));
157#elif defined(__APPLE__)
158#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
159  ::pthread_setname_np(NameStr.data());
160#endif
161#endif
162}
163
164void llvm::get_thread_name(SmallVectorImpl<char> &Name) {
165  Name.clear();
166
167#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
168  int pid = ::getpid();
169  uint64_t tid = get_threadid();
170
171  struct kinfo_proc *kp = nullptr, *nkp;
172  size_t len = 0;
173  int error;
174  int ctl[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD,
175    (int)pid };
176
177  while (1) {
178    error = sysctl(ctl, 4, kp, &len, nullptr, 0);
179    if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
180      // Add extra space in case threads are added before next call.
181      len += sizeof(*kp) + len / 10;
182      nkp = (struct kinfo_proc *)::realloc(kp, len);
183      if (nkp == nullptr) {
184        free(kp);
185        return;
186      }
187      kp = nkp;
188      continue;
189    }
190    if (error != 0)
191      len = 0;
192    break;
193  }
194
195  for (size_t i = 0; i < len / sizeof(*kp); i++) {
196    if (kp[i].ki_tid == (lwpid_t)tid) {
197      Name.append(kp[i].ki_tdname, kp[i].ki_tdname + strlen(kp[i].ki_tdname));
198      break;
199    }
200  }
201  free(kp);
202  return;
203#elif defined(__NetBSD__)
204  constexpr uint32_t len = get_max_thread_name_length_impl();
205  char buf[len];
206  ::pthread_getname_np(::pthread_self(), buf, len);
207
208  Name.append(buf, buf + strlen(buf));
209#elif defined(__linux__)
210#if HAVE_PTHREAD_GETNAME_NP
211  constexpr uint32_t len = get_max_thread_name_length_impl();
212  char Buffer[len] = {'\0'};  // FIXME: working around MSan false positive.
213  if (0 == ::pthread_getname_np(::pthread_self(), Buffer, len))
214    Name.append(Buffer, Buffer + strlen(Buffer));
215#endif
216#endif
217}