1/*
2 * Copyright (C) 2007, 2009, 2015 Apple Inc. All rights reserved.
3 * Copyright (C) 2007 Justin Haygood <[email protected]>
4 * Copyright (C) 2011 Research In Motion Limited. All rights reserved.
5 * Copyright (C) 2017 Yusuke Suzuki <[email protected]>
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of Apple Inc. ("Apple") nor the names of
17 * its contributors may be used to endorse or promote products derived
18 * from this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
21 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
24 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#include "config.h"
33#include <wtf/Threading.h>
34
35#if USE(PTHREADS)
36
37#include <errno.h>
38#include <wtf/DataLog.h>
39#include <wtf/NeverDestroyed.h>
40#include <wtf/RawPointer.h>
41#include <wtf/StdLibExtras.h>
42#include <wtf/ThreadGroup.h>
43#include <wtf/ThreadingPrimitives.h>
44#include <wtf/WordLock.h>
45
46#if OS(LINUX)
47#include <sys/prctl.h>
48#endif
49
50#if !COMPILER(MSVC)
51#include <limits.h>
52#include <sched.h>
53#include <sys/time.h>
54#endif
55
56#if !OS(DARWIN) && OS(UNIX)
57
58#include <semaphore.h>
59#include <sys/mman.h>
60#include <unistd.h>
61#include <pthread.h>
62
63#if HAVE(PTHREAD_NP_H)
64#include <pthread_np.h>
65#endif
66
67#endif
68
69namespace WTF {
70
71static Lock globalSuspendLock;
72
73Thread::~Thread()
74{
75}
76
77#if !OS(DARWIN)
78class Semaphore final {
79 WTF_MAKE_NONCOPYABLE(Semaphore);
80 WTF_MAKE_FAST_ALLOCATED;
81public:
82 explicit Semaphore(unsigned initialValue)
83 {
84 int sharedBetweenProcesses = 0;
85 sem_init(&m_platformSemaphore, sharedBetweenProcesses, initialValue);
86 }
87
88 ~Semaphore()
89 {
90 sem_destroy(&m_platformSemaphore);
91 }
92
93 void wait()
94 {
95 sem_wait(&m_platformSemaphore);
96 }
97
98 void post()
99 {
100 sem_post(&m_platformSemaphore);
101 }
102
103private:
104 sem_t m_platformSemaphore;
105};
106static LazyNeverDestroyed<Semaphore> globalSemaphoreForSuspendResume;
107
108static std::atomic<Thread*> targetThread { nullptr };
109
110void Thread::signalHandlerSuspendResume(int, siginfo_t*, void* ucontext)
111{
112 // Touching a global variable atomic types from signal handlers is allowed.
113 Thread* thread = targetThread.load();
114
115 if (thread->m_suspendCount) {
116 // This is signal handler invocation that is intended to be used to resume sigsuspend.
117 // So this handler invocation itself should not process.
118 //
119 // When signal comes, first, the system calls signal handler. And later, sigsuspend will be resumed. Signal handler invocation always precedes.
120 // So, the problem never happens that suspended.store(true, ...) will be executed before the handler is called.
121 // http://pubs.opengroup.org/onlinepubs/009695399/functions/sigsuspend.html
122 return;
123 }
124
125 void* approximateStackPointer = currentStackPointer();
126 if (!thread->m_stack.contains(approximateStackPointer)) {
127 // This happens if we use an alternative signal stack.
128 // 1. A user-defined signal handler is invoked with an alternative signal stack.
129 // 2. In the middle of the execution of the handler, we attempt to suspend the target thread.
130 // 3. A nested signal handler is executed.
131 // 4. The stack pointer saved in the machine context will be pointing to the alternative signal stack.
132 // In this case, we back off the suspension and retry a bit later.
133 thread->m_platformRegisters = nullptr;
134 globalSemaphoreForSuspendResume->post();
135 return;
136 }
137
138#if HAVE(MACHINE_CONTEXT)
139 ucontext_t* userContext = static_cast<ucontext_t*>(ucontext);
140 thread->m_platformRegisters = &registersFromUContext(userContext);
141#else
142 UNUSED_PARAM(ucontext);
143 PlatformRegisters platformRegisters { approximateStackPointer };
144 thread->m_platformRegisters = &platformRegisters;
145#endif
146
147 // Allow suspend caller to see that this thread is suspended.
148 // sem_post is async-signal-safe function. It means that we can call this from a signal handler.
149 // http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html#tag_02_04_03
150 //
151 // And sem_post emits memory barrier that ensures that PlatformRegisters are correctly saved.
152 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11
153 globalSemaphoreForSuspendResume->post();
154
155 // Reaching here, SigThreadSuspendResume is blocked in this handler (this is configured by sigaction's sa_mask).
156 // So before calling sigsuspend, SigThreadSuspendResume to this thread is deferred. This ensures that the handler is not executed recursively.
157 sigset_t blockedSignalSet;
158 sigfillset(&blockedSignalSet);
159 sigdelset(&blockedSignalSet, SigThreadSuspendResume);
160 sigsuspend(&blockedSignalSet);
161
162 thread->m_platformRegisters = nullptr;
163
164 // Allow resume caller to see that this thread is resumed.
165 globalSemaphoreForSuspendResume->post();
166}
167
168#endif // !OS(DARWIN)
169
170void Thread::initializePlatformThreading()
171{
172#if !OS(DARWIN)
173 globalSemaphoreForSuspendResume.construct(0);
174
175 // Signal handlers are process global configuration.
176 // Intentionally block SigThreadSuspendResume in the handler.
177 // SigThreadSuspendResume will be allowed in the handler by sigsuspend.
178 struct sigaction action;
179 sigemptyset(&action.sa_mask);
180 sigaddset(&action.sa_mask, SigThreadSuspendResume);
181
182 action.sa_sigaction = &signalHandlerSuspendResume;
183 action.sa_flags = SA_RESTART | SA_SIGINFO;
184 sigaction(SigThreadSuspendResume, &action, 0);
185#endif
186}
187
188void Thread::initializeCurrentThreadEvenIfNonWTFCreated()
189{
190#if !OS(DARWIN)
191 sigset_t mask;
192 sigemptyset(&mask);
193 sigaddset(&mask, SigThreadSuspendResume);
194 pthread_sigmask(SIG_UNBLOCK, &mask, 0);
195#endif
196}
197
198static void* wtfThreadEntryPoint(void* context)
199{
200 Thread::entryPoint(reinterpret_cast<Thread::NewThreadContext*>(context));
201 return nullptr;
202}
203
204bool Thread::establishHandle(NewThreadContext* context)
205{
206 pthread_t threadHandle;
207 pthread_attr_t attr;
208 pthread_attr_init(&attr);
209#if HAVE(QOS_CLASSES)
210 pthread_attr_set_qos_class_np(&attr, adjustedQOSClass(QOS_CLASS_USER_INITIATED), 0);
211#endif
212 int error = pthread_create(&threadHandle, &attr, wtfThreadEntryPoint, context);
213 pthread_attr_destroy(&attr);
214 if (error) {
215 LOG_ERROR("Failed to create pthread at entry point %p with context %p", wtfThreadEntryPoint, context);
216 return false;
217 }
218 establishPlatformSpecificHandle(threadHandle);
219 return true;
220}
221
222void Thread::initializeCurrentThreadInternal(const char* threadName)
223{
224#if HAVE(PTHREAD_SETNAME_NP)
225 pthread_setname_np(normalizeThreadName(threadName));
226#elif OS(LINUX)
227 prctl(PR_SET_NAME, normalizeThreadName(threadName));
228#else
229 UNUSED_PARAM(threadName);
230#endif
231 initializeCurrentThreadEvenIfNonWTFCreated();
232}
233
234void Thread::changePriority(int delta)
235{
236#if HAVE(PTHREAD_SETSCHEDPARAM)
237 auto locker = holdLock(m_mutex);
238
239 int policy;
240 struct sched_param param;
241
242 if (pthread_getschedparam(m_handle, &policy, &param))
243 return;
244
245 param.sched_priority += delta;
246
247 pthread_setschedparam(m_handle, policy, &param);
248#endif
249}
250
251int Thread::waitForCompletion()
252{
253 pthread_t handle;
254 {
255 auto locker = holdLock(m_mutex);
256 handle = m_handle;
257 }
258
259 int joinResult = pthread_join(handle, 0);
260
261 if (joinResult == EDEADLK)
262 LOG_ERROR("Thread %p was found to be deadlocked trying to quit", this);
263 else if (joinResult)
264 LOG_ERROR("Thread %p was unable to be joined.\n", this);
265
266 auto locker = holdLock(m_mutex);
267 ASSERT(joinableState() == Joinable);
268
269 // If the thread has already exited, then do nothing. If the thread hasn't exited yet, then just signal that we've already joined on it.
270 // In both cases, Thread::destructTLS() will take care of destroying Thread.
271 if (!hasExited())
272 didJoin();
273
274 return joinResult;
275}
276
277void Thread::detach()
278{
279 auto locker = holdLock(m_mutex);
280 int detachResult = pthread_detach(m_handle);
281 if (detachResult)
282 LOG_ERROR("Thread %p was unable to be detached\n", this);
283
284 if (!hasExited())
285 didBecomeDetached();
286}
287
288Thread& Thread::initializeCurrentTLS()
289{
290 // Not a WTF-created thread, Thread is not established yet.
291 Ref<Thread> thread = adoptRef(*new Thread());
292 thread->establishPlatformSpecificHandle(pthread_self());
293 thread->initializeInThread();
294 initializeCurrentThreadEvenIfNonWTFCreated();
295
296 return initializeTLS(WTFMove(thread));
297}
298
299bool Thread::signal(int signalNumber)
300{
301 auto locker = holdLock(m_mutex);
302 if (hasExited())
303 return false;
304 int errNo = pthread_kill(m_handle, signalNumber);
305 return !errNo; // A 0 errNo means success.
306}
307
308auto Thread::suspend() -> Expected<void, PlatformSuspendError>
309{
310 RELEASE_ASSERT_WITH_MESSAGE(this != &Thread::current(), "We do not support suspending the current thread itself.");
311 // During suspend, suspend or resume should not be executed from the other threads.
312 // We use global lock instead of per thread lock.
313 // Consider the following case, there are threads A and B.
314 // And A attempt to suspend B and B attempt to suspend A.
315 // A and B send signals. And later, signals are delivered to A and B.
316 // In that case, both will be suspended.
317 //
318 // And it is important to use a global lock to suspend and resume. Let's consider using per-thread lock.
319 // Your issuing thread (A) attempts to suspend the target thread (B). Then, you will suspend the thread (C) additionally.
320 // This case frequently happens if you stop threads to perform stack scanning. But thread (B) may hold the lock of thread (C).
321 // In that case, dead lock happens. Using global lock here avoids this dead lock.
322 LockHolder locker(globalSuspendLock);
323#if OS(DARWIN)
324 kern_return_t result = thread_suspend(m_platformThread);
325 if (result != KERN_SUCCESS)
326 return makeUnexpected(result);
327 return { };
328#else
329 if (!m_suspendCount) {
330 // Ideally, we would like to use pthread_sigqueue. It allows us to pass the argument to the signal handler.
331 // But it can be used in a few platforms, like Linux.
332 // Instead, we use Thread* stored in a global variable to pass it to the signal handler.
333 targetThread.store(this);
334
335 while (true) {
336 int result = pthread_kill(m_handle, SigThreadSuspendResume);
337 if (result)
338 return makeUnexpected(result);
339 globalSemaphoreForSuspendResume->wait();
340 if (m_platformRegisters)
341 break;
342 // Because of an alternative signal stack, we failed to suspend this thread.
343 // Retry suspension again after yielding.
344 Thread::yield();
345 }
346 }
347 ++m_suspendCount;
348 return { };
349#endif
350}
351
352void Thread::resume()
353{
354 // During resume, suspend or resume should not be executed from the other threads.
355 LockHolder locker(globalSuspendLock);
356#if OS(DARWIN)
357 thread_resume(m_platformThread);
358#else
359 if (m_suspendCount == 1) {
360 // When allowing SigThreadSuspendResume interrupt in the signal handler by sigsuspend and SigThreadSuspendResume is actually issued,
361 // the signal handler itself will be called once again.
362 // There are several ways to distinguish the handler invocation for suspend and resume.
363 // 1. Use different signal numbers. And check the signal number in the handler.
364 // 2. Use some arguments to distinguish suspend and resume in the handler. If pthread_sigqueue can be used, we can take this.
365 // 3. Use thread's flag.
366 // In this implementaiton, we take (3). m_suspendCount is used to distinguish it.
367 targetThread.store(this);
368 if (pthread_kill(m_handle, SigThreadSuspendResume) == ESRCH)
369 return;
370 globalSemaphoreForSuspendResume->wait();
371 }
372 --m_suspendCount;
373#endif
374}
375
376#if OS(DARWIN)
377struct ThreadStateMetadata {
378 WTF_MAKE_STRUCT_FAST_ALLOCATED;
379 unsigned userCount;
380 thread_state_flavor_t flavor;
381};
382
383static ThreadStateMetadata threadStateMetadata()
384{
385#if CPU(X86)
386 unsigned userCount = sizeof(PlatformRegisters) / sizeof(int);
387 thread_state_flavor_t flavor = i386_THREAD_STATE;
388#elif CPU(X86_64)
389 unsigned userCount = x86_THREAD_STATE64_COUNT;
390 thread_state_flavor_t flavor = x86_THREAD_STATE64;
391#elif CPU(PPC)
392 unsigned userCount = PPC_THREAD_STATE_COUNT;
393 thread_state_flavor_t flavor = PPC_THREAD_STATE;
394#elif CPU(PPC64)
395 unsigned userCount = PPC_THREAD_STATE64_COUNT;
396 thread_state_flavor_t flavor = PPC_THREAD_STATE64;
397#elif CPU(ARM)
398 unsigned userCount = ARM_THREAD_STATE_COUNT;
399 thread_state_flavor_t flavor = ARM_THREAD_STATE;
400#elif CPU(ARM64)
401 unsigned userCount = ARM_THREAD_STATE64_COUNT;
402 thread_state_flavor_t flavor = ARM_THREAD_STATE64;
403#else
404#error Unknown Architecture
405#endif
406 return ThreadStateMetadata { userCount, flavor };
407}
408#endif // OS(DARWIN)
409
410size_t Thread::getRegisters(PlatformRegisters& registers)
411{
412 LockHolder locker(globalSuspendLock);
413#if OS(DARWIN)
414 auto metadata = threadStateMetadata();
415 kern_return_t result = thread_get_state(m_platformThread, metadata.flavor, (thread_state_t)&registers, &metadata.userCount);
416 if (result != KERN_SUCCESS) {
417 WTFReportFatalError(__FILE__, __LINE__, WTF_PRETTY_FUNCTION, "JavaScript garbage collection failed because thread_get_state returned an error (%d). This is probably the result of running inside Rosetta, which is not supported.", result);
418 CRASH();
419 }
420 return metadata.userCount * sizeof(uintptr_t);
421#else
422 ASSERT_WITH_MESSAGE(m_suspendCount, "We can get registers only if the thread is suspended.");
423 ASSERT(m_platformRegisters);
424 registers = *m_platformRegisters;
425 return sizeof(PlatformRegisters);
426#endif
427}
428
429void Thread::establishPlatformSpecificHandle(pthread_t handle)
430{
431 auto locker = holdLock(m_mutex);
432 m_handle = handle;
433#if OS(DARWIN)
434 m_platformThread = pthread_mach_thread_np(handle);
435#endif
436}
437
438#if !HAVE(FAST_TLS)
439void Thread::initializeTLSKey()
440{
441 threadSpecificKeyCreate(&s_key, destructTLS);
442}
443#endif
444
445Thread& Thread::initializeTLS(Ref<Thread>&& thread)
446{
447 // We leak the ref to keep the Thread alive while it is held in TLS. destructTLS will deref it later at thread destruction time.
448 auto& threadInTLS = thread.leakRef();
449#if !HAVE(FAST_TLS)
450 ASSERT(s_key != InvalidThreadSpecificKey);
451 threadSpecificSet(s_key, &threadInTLS);
452#else
453 _pthread_setspecific_direct(WTF_THREAD_DATA_KEY, &threadInTLS);
454 pthread_key_init_np(WTF_THREAD_DATA_KEY, &destructTLS);
455#endif
456 return threadInTLS;
457}
458
459void Thread::destructTLS(void* data)
460{
461 Thread* thread = static_cast<Thread*>(data);
462 ASSERT(thread);
463
464 if (thread->m_isDestroyedOnce) {
465 thread->didExit();
466 thread->deref();
467 return;
468 }
469
470 thread->m_isDestroyedOnce = true;
471 // Re-setting the value for key causes another destructTLS() call after all other thread-specific destructors were called.
472#if !HAVE(FAST_TLS)
473 ASSERT(s_key != InvalidThreadSpecificKey);
474 threadSpecificSet(s_key, thread);
475#else
476 _pthread_setspecific_direct(WTF_THREAD_DATA_KEY, thread);
477 pthread_key_init_np(WTF_THREAD_DATA_KEY, &destructTLS);
478#endif
479}
480
481Mutex::~Mutex()
482{
483 int result = pthread_mutex_destroy(&m_mutex);
484 ASSERT_UNUSED(result, !result);
485}
486
487void Mutex::lock()
488{
489 int result = pthread_mutex_lock(&m_mutex);
490 ASSERT_UNUSED(result, !result);
491}
492
493bool Mutex::tryLock()
494{
495 int result = pthread_mutex_trylock(&m_mutex);
496
497 if (result == 0)
498 return true;
499 if (result == EBUSY)
500 return false;
501
502 ASSERT_NOT_REACHED();
503 return false;
504}
505
506void Mutex::unlock()
507{
508 int result = pthread_mutex_unlock(&m_mutex);
509 ASSERT_UNUSED(result, !result);
510}
511
512ThreadCondition::~ThreadCondition()
513{
514 pthread_cond_destroy(&m_condition);
515}
516
517void ThreadCondition::wait(Mutex& mutex)
518{
519 int result = pthread_cond_wait(&m_condition, &mutex.impl());
520 ASSERT_UNUSED(result, !result);
521}
522
523bool ThreadCondition::timedWait(Mutex& mutex, WallTime absoluteTime)
524{
525 if (absoluteTime < WallTime::now())
526 return false;
527
528 if (absoluteTime > WallTime::fromRawSeconds(INT_MAX)) {
529 wait(mutex);
530 return true;
531 }
532
533 double rawSeconds = absoluteTime.secondsSinceEpoch().value();
534
535 int timeSeconds = static_cast<int>(rawSeconds);
536 int timeNanoseconds = static_cast<int>((rawSeconds - timeSeconds) * 1E9);
537
538 timespec targetTime;
539 targetTime.tv_sec = timeSeconds;
540 targetTime.tv_nsec = timeNanoseconds;
541
542 return pthread_cond_timedwait(&m_condition, &mutex.impl(), &targetTime) == 0;
543}
544
545void ThreadCondition::signal()
546{
547 int result = pthread_cond_signal(&m_condition);
548 ASSERT_UNUSED(result, !result);
549}
550
551void ThreadCondition::broadcast()
552{
553 int result = pthread_cond_broadcast(&m_condition);
554 ASSERT_UNUSED(result, !result);
555}
556
557void Thread::yield()
558{
559 sched_yield();
560}
561
562} // namespace WTF
563
564#endif // USE(PTHREADS)
565