Port Android relocation packer to chromium build
[chromium-blink-merge.git] / base / threading / platform_thread_posix.cc
blob5c5023b1c27a996b2b4c617653d7bbefd57ca904
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.
5 #include "base/threading/platform_thread.h"
7 #include <errno.h>
8 #include <pthread.h>
9 #include <sched.h>
10 #include <sys/resource.h>
11 #include <sys/time.h>
13 #include "base/lazy_instance.h"
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/safe_strerror_posix.h"
17 #include "base/synchronization/waitable_event.h"
18 #include "base/threading/platform_thread_internal_posix.h"
19 #include "base/threading/thread_id_name_manager.h"
20 #include "base/threading/thread_restrictions.h"
21 #include "base/tracked_objects.h"
23 #if defined(OS_LINUX)
24 #include <sys/syscall.h>
25 #elif defined(OS_ANDROID)
26 #include <sys/types.h>
27 #endif
29 namespace base {
31 void InitThreading();
32 void InitOnThread();
33 void TerminateOnThread();
34 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
36 namespace {
38 struct ThreadParams {
39 ThreadParams()
40 : delegate(NULL),
41 joinable(false),
42 priority(kThreadPriority_Normal),
43 handle(NULL),
44 handle_set(false, false) {
47 PlatformThread::Delegate* delegate;
48 bool joinable;
49 ThreadPriority priority;
50 PlatformThreadHandle* handle;
51 WaitableEvent handle_set;
54 void* ThreadFunc(void* params) {
55 base::InitOnThread();
56 ThreadParams* thread_params = static_cast<ThreadParams*>(params);
58 PlatformThread::Delegate* delegate = thread_params->delegate;
59 if (!thread_params->joinable)
60 base::ThreadRestrictions::SetSingletonAllowed(false);
62 if (thread_params->priority != kThreadPriority_Normal) {
63 PlatformThread::SetThreadPriority(PlatformThread::CurrentHandle(),
64 thread_params->priority);
67 // Stash the id in the handle so the calling thread has a complete
68 // handle, and unblock the parent thread.
69 *(thread_params->handle) = PlatformThreadHandle(pthread_self(),
70 PlatformThread::CurrentId());
71 thread_params->handle_set.Signal();
73 ThreadIdNameManager::GetInstance()->RegisterThread(
74 PlatformThread::CurrentHandle().platform_handle(),
75 PlatformThread::CurrentId());
77 delegate->ThreadMain();
79 ThreadIdNameManager::GetInstance()->RemoveName(
80 PlatformThread::CurrentHandle().platform_handle(),
81 PlatformThread::CurrentId());
83 base::TerminateOnThread();
84 return NULL;
87 bool CreateThread(size_t stack_size, bool joinable,
88 PlatformThread::Delegate* delegate,
89 PlatformThreadHandle* thread_handle,
90 ThreadPriority priority) {
91 base::InitThreading();
93 bool success = false;
94 pthread_attr_t attributes;
95 pthread_attr_init(&attributes);
97 // Pthreads are joinable by default, so only specify the detached
98 // attribute if the thread should be non-joinable.
99 if (!joinable) {
100 pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
103 // Get a better default if available.
104 if (stack_size == 0)
105 stack_size = base::GetDefaultThreadStackSize(attributes);
107 if (stack_size > 0)
108 pthread_attr_setstacksize(&attributes, stack_size);
110 ThreadParams params;
111 params.delegate = delegate;
112 params.joinable = joinable;
113 params.priority = priority;
114 params.handle = thread_handle;
116 pthread_t handle;
117 int err = pthread_create(&handle,
118 &attributes,
119 ThreadFunc,
120 &params);
121 success = !err;
122 if (!success) {
123 // Value of |handle| is undefined if pthread_create fails.
124 handle = 0;
125 errno = err;
126 PLOG(ERROR) << "pthread_create";
129 pthread_attr_destroy(&attributes);
131 // Don't let this call complete until the thread id
132 // is set in the handle.
133 if (success)
134 params.handle_set.Wait();
135 CHECK_EQ(handle, thread_handle->platform_handle());
137 return success;
140 } // namespace
142 // static
143 PlatformThreadId PlatformThread::CurrentId() {
144 // Pthreads doesn't have the concept of a thread ID, so we have to reach down
145 // into the kernel.
146 #if defined(OS_MACOSX)
147 return pthread_mach_thread_np(pthread_self());
148 #elif defined(OS_LINUX)
149 return syscall(__NR_gettid);
150 #elif defined(OS_ANDROID)
151 return gettid();
152 #elif defined(OS_SOLARIS) || defined(OS_QNX)
153 return pthread_self();
154 #elif defined(OS_NACL) && defined(__GLIBC__)
155 return pthread_self();
156 #elif defined(OS_NACL) && !defined(__GLIBC__)
157 // Pointers are 32-bits in NaCl.
158 return reinterpret_cast<int32>(pthread_self());
159 #elif defined(OS_POSIX)
160 return reinterpret_cast<int64>(pthread_self());
161 #endif
164 // static
165 PlatformThreadRef PlatformThread::CurrentRef() {
166 return PlatformThreadRef(pthread_self());
169 // static
170 PlatformThreadHandle PlatformThread::CurrentHandle() {
171 return PlatformThreadHandle(pthread_self(), CurrentId());
174 // static
175 void PlatformThread::YieldCurrentThread() {
176 sched_yield();
179 // static
180 void PlatformThread::Sleep(TimeDelta duration) {
181 struct timespec sleep_time, remaining;
183 // Break the duration into seconds and nanoseconds.
184 // NOTE: TimeDelta's microseconds are int64s while timespec's
185 // nanoseconds are longs, so this unpacking must prevent overflow.
186 sleep_time.tv_sec = duration.InSeconds();
187 duration -= TimeDelta::FromSeconds(sleep_time.tv_sec);
188 sleep_time.tv_nsec = duration.InMicroseconds() * 1000; // nanoseconds
190 while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
191 sleep_time = remaining;
194 // static
195 const char* PlatformThread::GetName() {
196 return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
199 // static
200 bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
201 PlatformThreadHandle* thread_handle) {
202 base::ThreadRestrictions::ScopedAllowWait allow_wait;
203 return CreateThread(stack_size, true /* joinable thread */,
204 delegate, thread_handle, kThreadPriority_Normal);
207 // static
208 bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
209 PlatformThreadHandle* thread_handle,
210 ThreadPriority priority) {
211 base::ThreadRestrictions::ScopedAllowWait allow_wait;
212 return CreateThread(stack_size, true, // joinable thread
213 delegate, thread_handle, priority);
216 // static
217 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
218 PlatformThreadHandle unused;
220 base::ThreadRestrictions::ScopedAllowWait allow_wait;
221 bool result = CreateThread(stack_size, false /* non-joinable thread */,
222 delegate, &unused, kThreadPriority_Normal);
223 return result;
226 // static
227 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
228 // Joining another thread may block the current thread for a long time, since
229 // the thread referred to by |thread_handle| may still be running long-lived /
230 // blocking tasks.
231 base::ThreadRestrictions::AssertIOAllowed();
232 CHECK_EQ(0, pthread_join(thread_handle.handle_, NULL));
235 // Mac has its own SetThreadPriority() implementation.
236 #if !defined(OS_MACOSX)
237 // static
238 void PlatformThread::SetThreadPriority(PlatformThreadHandle handle,
239 ThreadPriority priority) {
240 #if !defined(OS_NACL)
241 if (internal::HandleSetThreadPriorityForPlatform(handle, priority))
242 return;
244 // setpriority(2) should change the whole thread group's (i.e. process)
245 // priority. However, as stated in the bugs section of
246 // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
247 // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
248 // attribute". Also, 0 is prefered to the current thread id since it is
249 // equivalent but makes sandboxing easier (https://crbug.com/399473).
250 DCHECK_NE(handle.id_, kInvalidThreadId);
251 const int nice_setting = internal::ThreadPriorityToNiceValue(priority);
252 const PlatformThreadId current_id = PlatformThread::CurrentId();
253 if (setpriority(PRIO_PROCESS, handle.id_ == current_id ? 0 : handle.id_,
254 nice_setting)) {
255 DVPLOG(1) << "Failed to set nice value of thread (" << handle.id_ << ") to "
256 << nice_setting;
258 #endif // !defined(OS_NACL)
260 #endif // !defined(OS_MACOSX)
262 } // namespace base