1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/threading/platform_thread.h"
6
7 #include <errno.h>
8 #include <pthread.h>
9 #include <sched.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <sys/resource.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16
17 #include <memory>
18
19 #include "base/debug/activity_tracker.h"
20 #include "base/lazy_instance.h"
21 #include "base/logging.h"
22 #include "base/threading/platform_thread_internal_posix.h"
23 #include "base/threading/thread_id_name_manager.h"
24 #include "base/threading/thread_restrictions.h"
25 #include "build/build_config.h"
26
27 #if defined(OS_LINUX)
28 #include <sys/syscall.h>
29 #endif
30
31 #if defined(OS_FUCHSIA)
32 #include <magenta/process.h>
33 #endif
34
35 namespace base {
36
37 void InitThreading();
38 void TerminateOnThread();
39 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
40
41 namespace {
42
43 struct ThreadParams {
ThreadParamsbase::__anon901b7c0d0111::ThreadParams44 ThreadParams()
45 : delegate(NULL), joinable(false), priority(ThreadPriority::NORMAL) {}
46
47 PlatformThread::Delegate* delegate;
48 bool joinable;
49 ThreadPriority priority;
50 };
51
ThreadFunc(void * params)52 void* ThreadFunc(void* params) {
53 PlatformThread::Delegate* delegate = nullptr;
54
55 {
56 std::unique_ptr<ThreadParams> thread_params(
57 static_cast<ThreadParams*>(params));
58
59 delegate = thread_params->delegate;
60 if (!thread_params->joinable)
61 base::ThreadRestrictions::SetSingletonAllowed(false);
62
63 #if !defined(OS_NACL)
64 // Threads on linux/android may inherit their priority from the thread
65 // where they were created. This explicitly sets the priority of all new
66 // threads.
67 PlatformThread::SetCurrentThreadPriority(thread_params->priority);
68 #endif
69 }
70
71 ThreadIdNameManager::GetInstance()->RegisterThread(
72 PlatformThread::CurrentHandle().platform_handle(),
73 PlatformThread::CurrentId());
74
75 delegate->ThreadMain();
76
77 ThreadIdNameManager::GetInstance()->RemoveName(
78 PlatformThread::CurrentHandle().platform_handle(),
79 PlatformThread::CurrentId());
80
81 base::TerminateOnThread();
82 return NULL;
83 }
84
CreateThread(size_t stack_size,bool joinable,PlatformThread::Delegate * delegate,PlatformThreadHandle * thread_handle,ThreadPriority priority)85 bool CreateThread(size_t stack_size,
86 bool joinable,
87 PlatformThread::Delegate* delegate,
88 PlatformThreadHandle* thread_handle,
89 ThreadPriority priority) {
90 DCHECK(thread_handle);
91 base::InitThreading();
92
93 pthread_attr_t attributes;
94 pthread_attr_init(&attributes);
95
96 // Pthreads are joinable by default, so only specify the detached
97 // attribute if the thread should be non-joinable.
98 if (!joinable)
99 pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
100
101 // Get a better default if available.
102 if (stack_size == 0)
103 stack_size = base::GetDefaultThreadStackSize(attributes);
104
105 if (stack_size > 0)
106 pthread_attr_setstacksize(&attributes, stack_size);
107
108 std::unique_ptr<ThreadParams> params(new ThreadParams);
109 params->delegate = delegate;
110 params->joinable = joinable;
111 params->priority = priority;
112
113 pthread_t handle;
114 int err = pthread_create(&handle, &attributes, ThreadFunc, params.get());
115 bool success = !err;
116 if (success) {
117 // ThreadParams should be deleted on the created thread after used.
118 ignore_result(params.release());
119 } else {
120 // Value of |handle| is undefined if pthread_create fails.
121 handle = 0;
122 errno = err;
123 PLOG(ERROR) << "pthread_create";
124 }
125 *thread_handle = PlatformThreadHandle(handle);
126
127 pthread_attr_destroy(&attributes);
128
129 return success;
130 }
131
132 } // namespace
133
134 // static
CurrentId()135 PlatformThreadId PlatformThread::CurrentId() {
136 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
137 // into the kernel.
138 #if defined(OS_MACOSX)
139 return pthread_mach_thread_np(pthread_self());
140 #elif defined(OS_LINUX)
141 return syscall(__NR_gettid);
142 #elif defined(OS_ANDROID)
143 return gettid();
144 #elif defined(OS_FUCHSIA)
145 return mx_thread_self();
146 #elif defined(OS_SOLARIS) || defined(OS_QNX)
147 return pthread_self();
148 #elif defined(OS_NACL) && defined(__GLIBC__)
149 return pthread_self();
150 #elif defined(OS_NACL) && !defined(__GLIBC__)
151 // Pointers are 32-bits in NaCl.
152 return reinterpret_cast<int32_t>(pthread_self());
153 #elif defined(OS_POSIX) && defined(OS_AIX)
154 return pthread_self();
155 #elif defined(OS_POSIX) && !defined(OS_AIX)
156 return reinterpret_cast<int64_t>(pthread_self());
157 #endif
158 }
159
160 // static
CurrentRef()161 PlatformThreadRef PlatformThread::CurrentRef() {
162 return PlatformThreadRef(pthread_self());
163 }
164
165 // static
CurrentHandle()166 PlatformThreadHandle PlatformThread::CurrentHandle() {
167 return PlatformThreadHandle(pthread_self());
168 }
169
170 // static
YieldCurrentThread()171 void PlatformThread::YieldCurrentThread() {
172 sched_yield();
173 }
174
175 // static
Sleep(TimeDelta duration)176 void PlatformThread::Sleep(TimeDelta duration) {
177 struct timespec sleep_time, remaining;
178
179 // Break the duration into seconds and nanoseconds.
180 // NOTE: TimeDelta's microseconds are int64s while timespec's
181 // nanoseconds are longs, so this unpacking must prevent overflow.
182 sleep_time.tv_sec = duration.InSeconds();
183 duration -= TimeDelta::FromSeconds(sleep_time.tv_sec);
184 sleep_time.tv_nsec = duration.InMicroseconds() * 1000; // nanoseconds
185
186 while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
187 sleep_time = remaining;
188 }
189
190 // static
GetName()191 const char* PlatformThread::GetName() {
192 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
193 }
194
195 // static
CreateWithPriority(size_t stack_size,Delegate * delegate,PlatformThreadHandle * thread_handle,ThreadPriority priority)196 bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
197 PlatformThreadHandle* thread_handle,
198 ThreadPriority priority) {
199 return CreateThread(stack_size, true /* joinable thread */, delegate,
200 thread_handle, priority);
201 }
202
203 // static
CreateNonJoinable(size_t stack_size,Delegate * delegate)204 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
205 return CreateNonJoinableWithPriority(stack_size, delegate,
206 ThreadPriority::NORMAL);
207 }
208
209 // static
CreateNonJoinableWithPriority(size_t stack_size,Delegate * delegate,ThreadPriority priority)210 bool PlatformThread::CreateNonJoinableWithPriority(size_t stack_size,
211 Delegate* delegate,
212 ThreadPriority priority) {
213 PlatformThreadHandle unused;
214
215 bool result = CreateThread(stack_size, false /* non-joinable thread */,
216 delegate, &unused, priority);
217 return result;
218 }
219
220 // static
Join(PlatformThreadHandle thread_handle)221 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
222 // Record the event that this thread is blocking upon (for hang diagnosis).
223 base::debug::ScopedThreadJoinActivity thread_activity(&thread_handle);
224
225 // Joining another thread may block the current thread for a long time, since
226 // the thread referred to by |thread_handle| may still be running long-lived /
227 // blocking tasks.
228 base::ThreadRestrictions::AssertIOAllowed();
229 CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), NULL));
230 }
231
232 // static
Detach(PlatformThreadHandle thread_handle)233 void PlatformThread::Detach(PlatformThreadHandle thread_handle) {
234 CHECK_EQ(0, pthread_detach(thread_handle.platform_handle()));
235 }
236
237 // Mac has its own Set/GetCurrentThreadPriority() implementations.
238 #if !defined(OS_MACOSX)
239
240 // static
CanIncreaseCurrentThreadPriority()241 bool PlatformThread::CanIncreaseCurrentThreadPriority() {
242 #if defined(OS_NACL)
243 return false;
244 #else
245 // Only root can raise thread priority on POSIX environment. On Linux, users
246 // who have CAP_SYS_NICE permission also can raise the thread priority, but
247 // libcap.so would be needed to check the capability.
248 return geteuid() == 0;
249 #endif // defined(OS_NACL)
250 }
251
252 // static
SetCurrentThreadPriority(ThreadPriority priority)253 void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
254 #if defined(OS_NACL)
255 NOTIMPLEMENTED();
256 #else
257 if (internal::SetCurrentThreadPriorityForPlatform(priority))
258 return;
259
260 // setpriority(2) should change the whole thread group's (i.e. process)
261 // priority. However, as stated in the bugs section of
262 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
263 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
264 // attribute". Also, 0 is prefered to the current thread id since it is
265 // equivalent but makes sandboxing easier (https://crbug.com/399473).
266 const int nice_setting = internal::ThreadPriorityToNiceValue(priority);
267 if (setpriority(PRIO_PROCESS, 0, nice_setting)) {
268 DVPLOG(1) << "Failed to set nice value of thread ("
269 << PlatformThread::CurrentId() << ") to " << nice_setting;
270 }
271 #endif // defined(OS_NACL)
272 }
273
274 // static
GetCurrentThreadPriority()275 ThreadPriority PlatformThread::GetCurrentThreadPriority() {
276 #if defined(OS_NACL)
277 NOTIMPLEMENTED();
278 return ThreadPriority::NORMAL;
279 #else
280 // Mirrors SetCurrentThreadPriority()'s implementation.
281 ThreadPriority platform_specific_priority;
282 if (internal::GetCurrentThreadPriorityForPlatform(
283 &platform_specific_priority)) {
284 return platform_specific_priority;
285 }
286
287 // Need to clear errno before calling getpriority():
288 // http://man7.org/linux/man-pages/man2/getpriority.2.html
289 errno = 0;
290 int nice_value = getpriority(PRIO_PROCESS, 0);
291 if (errno != 0) {
292 DVPLOG(1) << "Failed to get nice value of thread ("
293 << PlatformThread::CurrentId() << ")";
294 return ThreadPriority::NORMAL;
295 }
296
297 return internal::NiceValueToThreadPriority(nice_value);
298 #endif // !defined(OS_NACL)
299 }
300
301 #endif // !defined(OS_MACOSX)
302
303 } // namespace base
304