2 * Copyright (C) 2007, 2009, 2015 Apple Inc. All rights reserved.
3 * Copyright (C) 2007 Justin Haygood <jhaygood@reaktix.com>
4 * Copyright (C) 2011 Research In Motion Limited. All rights reserved.
5 * Copyright (C) 2017 Yusuke Suzuki <utatane.tea@gmail.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
33 #include "Threading.h"
38 #include <wtf/CurrentTime.h>
39 #include <wtf/DataLog.h>
40 #include <wtf/RawPointer.h>
41 #include <wtf/StdLibExtras.h>
42 #include <wtf/ThreadGroup.h>
43 #include <wtf/ThreadHolder.h>
44 #include <wtf/ThreadingPrimitives.h>
45 #include <wtf/WordLock.h>
48 #include <sys/prctl.h>
57 #if !OS(DARWIN) && OS(UNIX)
68 #if HAVE(PTHREAD_NP_H)
69 #include <pthread_np.h>
76 static StaticLock globalSuspendLock;
81 sem_init(&m_semaphoreForSuspendResume, /* Only available in this process. */ 0, /* Initial value for the semaphore. */ 0);
88 sem_destroy(&m_semaphoreForSuspendResume);
94 // We use SIGUSR1 to suspend and resume machine threads in JavaScriptCore.
95 static constexpr const int SigThreadSuspendResume = SIGUSR1;
96 static std::atomic<Thread*> targetThread { nullptr };
99 #pragma GCC diagnostic push
100 #pragma GCC diagnostic ignored "-Wreturn-local-addr"
101 #endif // COMPILER(GCC)
104 #pragma clang diagnostic push
105 #pragma clang diagnostic ignored "-Wreturn-stack-address"
106 #endif // COMPILER(CLANG)
108 static UNUSED_FUNCTION NEVER_INLINE void* getApproximateStackPointer()
110 volatile void* stackLocation = nullptr;
111 return &stackLocation;
115 #pragma GCC diagnostic pop
116 #endif // COMPILER(GCC)
119 #pragma clang diagnostic pop
120 #endif // COMPILER(CLANG)
122 static UNUSED_FUNCTION bool isOnAlternativeSignalStack()
125 int ret = sigaltstack(nullptr, &stack);
126 RELEASE_ASSERT(!ret);
127 return stack.ss_flags == SS_ONSTACK;
130 void Thread::signalHandlerSuspendResume(int, siginfo_t*, void* ucontext)
132 // Touching thread local atomic types from signal handlers is allowed.
133 Thread* thread = targetThread.load();
135 if (thread->m_suspended.load(std::memory_order_acquire)) {
136 // This is signal handler invocation that is intended to be used to resume sigsuspend.
137 // So this handler invocation itself should not process.
139 // When signal comes, first, the system calls signal handler. And later, sigsuspend will be resumed. Signal handler invocation always precedes.
140 // So, the problem never happens that suspended.store(true, ...) will be executed before the handler is called.
141 // http://pubs.opengroup.org/onlinepubs/009695399/functions/sigsuspend.html
145 ucontext_t* userContext = static_cast<ucontext_t*>(ucontext);
146 ASSERT_WITH_MESSAGE(!isOnAlternativeSignalStack(), "Using an alternative signal stack is not supported. Consider disabling the concurrent GC.");
148 #if HAVE(MACHINE_CONTEXT)
149 thread->m_platformRegisters = registersFromUContext(userContext);
151 thread->m_platformRegisters = PlatformRegisters { getApproximateStackPointer() };
154 // Allow suspend caller to see that this thread is suspended.
155 // sem_post is async-signal-safe function. It means that we can call this from a signal handler.
156 // http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html#tag_02_04_03
158 // And sem_post emits memory barrier that ensures that suspendedMachineContext is correctly saved.
159 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11
160 sem_post(&thread->m_semaphoreForSuspendResume);
162 // Reaching here, SigThreadSuspendResume is blocked in this handler (this is configured by sigaction's sa_mask).
163 // So before calling sigsuspend, SigThreadSuspendResume to this thread is deferred. This ensures that the handler is not executed recursively.
164 sigset_t blockedSignalSet;
165 sigfillset(&blockedSignalSet);
166 sigdelset(&blockedSignalSet, SigThreadSuspendResume);
167 sigsuspend(&blockedSignalSet);
169 // Allow resume caller to see that this thread is resumed.
170 sem_post(&thread->m_semaphoreForSuspendResume);
173 #endif // !OS(DARWIN)
175 void Thread::initializePlatformThreading()
178 // Signal handlers are process global configuration.
179 // Intentionally block SigThreadSuspendResume in the handler.
180 // SigThreadSuspendResume will be allowed in the handler by sigsuspend.
181 struct sigaction action;
182 sigemptyset(&action.sa_mask);
183 sigaddset(&action.sa_mask, SigThreadSuspendResume);
185 action.sa_sigaction = &signalHandlerSuspendResume;
186 action.sa_flags = SA_RESTART | SA_SIGINFO;
187 sigaction(SigThreadSuspendResume, &action, 0);
191 void Thread::initializeCurrentThreadEvenIfNonWTFCreated(Thread& thread)
197 sigaddset(&mask, SigThreadSuspendResume);
198 pthread_sigmask(SIG_UNBLOCK, &mask, 0);
202 static void* wtfThreadEntryPoint(void* data)
204 Thread::entryPoint(reinterpret_cast<Thread::NewThreadContext*>(data));
208 bool Thread::establishHandle(NewThreadContext* data)
210 pthread_t threadHandle;
212 pthread_attr_init(&attr);
213 #if HAVE(QOS_CLASSES)
214 pthread_attr_set_qos_class_np(&attr, adjustedQOSClass(QOS_CLASS_USER_INITIATED), 0);
216 int error = pthread_create(&threadHandle, &attr, wtfThreadEntryPoint, data);
217 pthread_attr_destroy(&attr);
219 LOG_ERROR("Failed to create pthread at entry point %p with data %p", wtfThreadEntryPoint, data);
222 establishPlatformSpecificHandle(threadHandle);
226 void Thread::initializeCurrentThreadInternal(Thread& thread, const char* threadName)
228 #if HAVE(PTHREAD_SETNAME_NP)
229 pthread_setname_np(normalizeThreadName(threadName));
231 prctl(PR_SET_NAME, normalizeThreadName(threadName));
233 UNUSED_PARAM(threadName);
235 initializeCurrentThreadEvenIfNonWTFCreated(thread);
238 void Thread::changePriority(int delta)
240 std::lock_guard<std::mutex> locker(m_mutex);
243 struct sched_param param;
245 if (pthread_getschedparam(m_handle, &policy, ¶m))
248 param.sched_priority += delta;
250 pthread_setschedparam(m_handle, policy, ¶m);
253 int Thread::waitForCompletion()
257 std::lock_guard<std::mutex> locker(m_mutex);
261 int joinResult = pthread_join(handle, 0);
263 if (joinResult == EDEADLK)
264 LOG_ERROR("ThreadIdentifier %u was found to be deadlocked trying to quit", m_id);
266 LOG_ERROR("ThreadIdentifier %u was unable to be joined.\n", m_id);
268 std::lock_guard<std::mutex> locker(m_mutex);
269 ASSERT(joinableState() == Joinable);
271 // 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.
272 // In both cases, ThreadHolder::destruct() will take care of destroying Thread.
279 void Thread::detach()
281 std::lock_guard<std::mutex> locker(m_mutex);
282 int detachResult = pthread_detach(m_handle);
284 LOG_ERROR("ThreadIdentifier %u was unable to be detached\n", m_id);
290 Thread& Thread::current()
292 if (Thread* current = currentMayBeNull())
295 // Not a WTF-created thread, ThreadIdentifier is not established yet.
296 Ref<Thread> thread = adoptRef(*new Thread());
297 thread->establishPlatformSpecificHandle(pthread_self());
298 ThreadHolder::initialize(thread.get());
299 initializeCurrentThreadEvenIfNonWTFCreated(thread.get());
303 ThreadIdentifier Thread::currentID()
305 return current().id();
308 bool Thread::signal(int signalNumber)
310 std::lock_guard<std::mutex> locker(m_mutex);
313 int errNo = pthread_kill(m_handle, signalNumber);
314 return !errNo; // A 0 errNo means success.
317 auto Thread::suspend() -> Expected<void, PlatformSuspendError>
319 RELEASE_ASSERT_WITH_MESSAGE(id() != currentThread(), "We do not support suspending the current thread itself.");
320 // During suspend, suspend or resume should not be executed from the other threads.
321 // We use global lock instead of per thread lock.
322 // Consider the following case, there are threads A and B.
323 // And A attempt to suspend B and B attempt to suspend A.
324 // A and B send signals. And later, signals are delivered to A and B.
325 // In that case, both will be suspended.
327 // And it is important to use a global lock to suspend and resume. Let's consider using per-thread lock.
328 // Your issuing thread (A) attempts to suspend the target thread (B). Then, you will suspend the thread (C) additionally.
329 // This case frequently happens if you stop threads to perform stack scanning. But thread (B) may hold the lock of thread (C).
330 // In that case, dead lock happens. Using global lock here avoids this dead lock.
331 LockHolder locker(globalSuspendLock);
333 kern_return_t result = thread_suspend(m_platformThread);
334 if (result != KERN_SUCCESS)
335 return makeUnexpected(result);
338 if (!m_suspendCount) {
339 // Ideally, we would like to use pthread_sigqueue. It allows us to pass the argument to the signal handler.
340 // But it can be used in a few platforms, like Linux.
341 // Instead, we use Thread* stored in the thread local storage to pass it to the signal handler.
342 targetThread.store(this);
343 int result = pthread_kill(m_handle, SigThreadSuspendResume);
345 return makeUnexpected(result);
346 sem_wait(&m_semaphoreForSuspendResume);
347 // Release barrier ensures that this operation is always executed after all the above processing is done.
348 m_suspended.store(true, std::memory_order_release);
355 void Thread::resume()
357 // During resume, suspend or resume should not be executed from the other threads.
358 LockHolder locker(globalSuspendLock);
360 thread_resume(m_platformThread);
362 if (m_suspendCount == 1) {
363 // When allowing SigThreadSuspendResume interrupt in the signal handler by sigsuspend and SigThreadSuspendResume is actually issued,
364 // the signal handler itself will be called once again.
365 // There are several ways to distinguish the handler invocation for suspend and resume.
366 // 1. Use different signal numbers. And check the signal number in the handler.
367 // 2. Use some arguments to distinguish suspend and resume in the handler. If pthread_sigqueue can be used, we can take this.
368 // 3. Use thread local storage with atomic variables in the signal handler.
369 // In this implementaiton, we take (3). suspended flag is used to distinguish it.
370 targetThread.store(this);
371 if (pthread_kill(m_handle, SigThreadSuspendResume) == ESRCH)
373 sem_wait(&m_semaphoreForSuspendResume);
374 // Release barrier ensures that this operation is always executed after all the above processing is done.
375 m_suspended.store(false, std::memory_order_release);
382 struct ThreadStateMetadata {
384 thread_state_flavor_t flavor;
387 static ThreadStateMetadata threadStateMetadata()
390 unsigned userCount = sizeof(PlatformRegisters) / sizeof(int);
391 thread_state_flavor_t flavor = i386_THREAD_STATE;
393 unsigned userCount = x86_THREAD_STATE64_COUNT;
394 thread_state_flavor_t flavor = x86_THREAD_STATE64;
396 unsigned userCount = PPC_THREAD_STATE_COUNT;
397 thread_state_flavor_t flavor = PPC_THREAD_STATE;
399 unsigned userCount = PPC_THREAD_STATE64_COUNT;
400 thread_state_flavor_t flavor = PPC_THREAD_STATE64;
402 unsigned userCount = ARM_THREAD_STATE_COUNT;
403 thread_state_flavor_t flavor = ARM_THREAD_STATE;
405 unsigned userCount = ARM_THREAD_STATE64_COUNT;
406 thread_state_flavor_t flavor = ARM_THREAD_STATE64;
408 #error Unknown Architecture
410 return ThreadStateMetadata { userCount, flavor };
414 size_t Thread::getRegisters(PlatformRegisters& registers)
416 LockHolder locker(globalSuspendLock);
418 auto metadata = threadStateMetadata();
419 kern_return_t result = thread_get_state(m_platformThread, metadata.flavor, (thread_state_t)®isters, &metadata.userCount);
420 if (result != KERN_SUCCESS) {
421 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);
424 return metadata.userCount * sizeof(uintptr_t);
426 ASSERT_WITH_MESSAGE(m_suspendCount, "We can get registers only if the thread is suspended.");
427 registers = m_platformRegisters;
428 return sizeof(PlatformRegisters);
432 void Thread::establishPlatformSpecificHandle(pthread_t handle)
434 std::lock_guard<std::mutex> locker(m_mutex);
437 static std::atomic<ThreadIdentifier> provider { 0 };
440 m_platformThread = pthread_mach_thread_np(handle);
447 pthread_mutexattr_t attr;
448 pthread_mutexattr_init(&attr);
449 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
451 int result = pthread_mutex_init(&m_mutex, &attr);
452 ASSERT_UNUSED(result, !result);
454 pthread_mutexattr_destroy(&attr);
459 int result = pthread_mutex_destroy(&m_mutex);
460 ASSERT_UNUSED(result, !result);
465 int result = pthread_mutex_lock(&m_mutex);
466 ASSERT_UNUSED(result, !result);
469 bool Mutex::tryLock()
471 int result = pthread_mutex_trylock(&m_mutex);
478 ASSERT_NOT_REACHED();
484 int result = pthread_mutex_unlock(&m_mutex);
485 ASSERT_UNUSED(result, !result);
488 ThreadCondition::ThreadCondition()
490 pthread_cond_init(&m_condition, NULL);
493 ThreadCondition::~ThreadCondition()
495 pthread_cond_destroy(&m_condition);
498 void ThreadCondition::wait(Mutex& mutex)
500 int result = pthread_cond_wait(&m_condition, &mutex.impl());
501 ASSERT_UNUSED(result, !result);
504 bool ThreadCondition::timedWait(Mutex& mutex, double absoluteTime)
506 if (absoluteTime < currentTime())
509 if (absoluteTime > INT_MAX) {
514 int timeSeconds = static_cast<int>(absoluteTime);
515 int timeNanoseconds = static_cast<int>((absoluteTime - timeSeconds) * 1E9);
518 targetTime.tv_sec = timeSeconds;
519 targetTime.tv_nsec = timeNanoseconds;
521 return pthread_cond_timedwait(&m_condition, &mutex.impl(), &targetTime) == 0;
524 void ThreadCondition::signal()
526 int result = pthread_cond_signal(&m_condition);
527 ASSERT_UNUSED(result, !result);
530 void ThreadCondition::broadcast()
532 int result = pthread_cond_broadcast(&m_condition);
533 ASSERT_UNUSED(result, !result);
543 #endif // USE(PTHREADS)