#include "config.h"
#include "Threading.h"
#if OS(WINDOWS)
#include <process.h>
#include <windows.h>
#include <wtf/CurrentTime.h>
#include <wtf/MainThread.h>
#include <wtf/MathExtras.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/ThreadFunctionInvocation.h>
#include <wtf/ThreadHolder.h>
#include <wtf/ThreadingPrimitives.h>
#if HAVE(ERRNO_H)
#include <errno.h>
#endif
namespace WTF {
Thread::Thread()
{
}
Thread::~Thread()
{
if (m_handle != INVALID_HANDLE_VALUE)
CloseHandle(m_handle);
}
static const DWORD MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push, 8)
typedef struct tagTHREADNAME_INFO {
DWORD dwType; LPCSTR szName; DWORD dwThreadID; DWORD dwFlags; } THREADNAME_INFO;
#pragma pack(pop)
void Thread::initializeCurrentThreadInternal(const char* szThreadName)
{
#if COMPILER(MINGW)
UNUSED_PARAM(szThreadName);
#else
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = Thread::normalizeThreadName(szThreadName);
info.dwThreadID = GetCurrentThreadId();
info.dwFlags = 0;
__try {
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), reinterpret_cast<ULONG_PTR*>(&info));
} __except (EXCEPTION_CONTINUE_EXECUTION) {
}
#endif
}
void Thread::initializePlatformThreading()
{
}
static unsigned __stdcall wtfThreadEntryPoint(void* param)
{
auto invocation = std::unique_ptr<ThreadFunctionInvocation>(static_cast<ThreadFunctionInvocation*>(param));
ThreadHolder::initialize(*invocation->thread, Thread::currentID());
invocation->thread = nullptr;
invocation->function(invocation->data);
return 0;
}
RefPtr<Thread> Thread::createInternal(ThreadFunction entryPoint, void* data, const char* threadName)
{
Ref<Thread> thread = adoptRef(*new Thread());
unsigned threadIdentifier = 0;
ThreadIdentifier threadID = 0;
auto invocation = std::make_unique<ThreadFunctionInvocation>(entryPoint, thread.ptr(), data);
HANDLE threadHandle = reinterpret_cast<HANDLE>(_beginthreadex(0, 0, wtfThreadEntryPoint, invocation.get(), 0, &threadIdentifier));
if (!threadHandle) {
#if !HAVE(ERRNO_H)
LOG_ERROR("Failed to create thread at entry point %p with data %p.", entryPoint, data);
#else
LOG_ERROR("Failed to create thread at entry point %p with data %p: %ld", entryPoint, data, errno);
#endif
return 0;
}
ThreadFunctionInvocation* leakedInvocation = invocation.release();
UNUSED_PARAM(leakedInvocation);
threadID = static_cast<ThreadIdentifier>(threadIdentifier);
thread->establish(threadHandle, threadIdentifier);
return thread;
}
void Thread::changePriority(int delta)
{
std::lock_guard<std::mutex> locker(m_mutex);
SetThreadPriority(m_handle, THREAD_PRIORITY_NORMAL + delta);
}
int Thread::waitForCompletion()
{
HANDLE handle;
{
std::lock_guard<std::mutex> locker(m_mutex);
handle = m_handle;
}
DWORD joinResult = WaitForSingleObject(handle, INFINITE);
if (joinResult == WAIT_FAILED)
LOG_ERROR("ThreadIdentifier %u was found to be deadlocked trying to quit", m_id);
std::lock_guard<std::mutex> locker(m_mutex);
ASSERT(joinableState() == Joinable);
if (!hasExited())
didJoin();
return joinResult;
}
void Thread::detach()
{
std::lock_guard<std::mutex> locker(m_mutex);
if (!hasExited())
didBecomeDetached();
}
auto Thread::suspend() -> Expected<void, PlatformSuspendError>
{
RELEASE_ASSERT_WITH_MESSAGE(id() != currentThread(), "We do not support suspending the current thread itself.");
std::lock_guard<std::mutex> locker(m_mutex);
DWORD result = SuspendThread(m_handle);
if (result != (DWORD)-1)
return { };
return makeUnexpected(result);
}
void Thread::resume()
{
std::lock_guard<std::mutex> locker(m_mutex);
ResumeThread(m_handle);
}
size_t Thread::getRegisters(PlatformRegisters& registers)
{
std::lock_guard<std::mutex> locker(m_mutex);
registers.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;
GetThreadContext(m_handle, ®isters);
return sizeof(CONTEXT);
}
Thread& Thread::current()
{
ThreadHolder* data = ThreadHolder::current();
if (data)
return data->thread();
Ref<Thread> thread = adoptRef(*new Thread());
HANDLE handle;
bool isSuccessful = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &handle, 0, FALSE, DUPLICATE_SAME_ACCESS);
RELEASE_ASSERT(isSuccessful);
thread->establish(handle, currentID());
ThreadHolder::initialize(thread.get(), Thread::currentID());
return thread.get();
}
ThreadIdentifier Thread::currentID()
{
return static_cast<ThreadIdentifier>(GetCurrentThreadId());
}
void Thread::establish(HANDLE handle, ThreadIdentifier threadID)
{
std::lock_guard<std::mutex> locker(m_mutex);
m_handle = handle;
m_id = threadID;
}
Mutex::Mutex()
{
m_mutex.m_recursionCount = 0;
InitializeCriticalSection(&m_mutex.m_internalMutex);
}
Mutex::~Mutex()
{
DeleteCriticalSection(&m_mutex.m_internalMutex);
}
void Mutex::lock()
{
EnterCriticalSection(&m_mutex.m_internalMutex);
++m_mutex.m_recursionCount;
}
#pragma warning(suppress: 26115)
bool Mutex::tryLock()
{
DWORD result = TryEnterCriticalSection(&m_mutex.m_internalMutex);
if (result != 0) { if (m_mutex.m_recursionCount > 0) {
LeaveCriticalSection(&m_mutex.m_internalMutex);
return false;
}
++m_mutex.m_recursionCount;
return true;
}
return false;
}
void Mutex::unlock()
{
ASSERT(m_mutex.m_recursionCount);
--m_mutex.m_recursionCount;
LeaveCriticalSection(&m_mutex.m_internalMutex);
}
bool PlatformCondition::timedWait(PlatformMutex& mutex, DWORD durationMilliseconds)
{
DWORD res = WaitForSingleObject(m_blockLock, INFINITE);
ASSERT_UNUSED(res, res == WAIT_OBJECT_0);
++m_waitersBlocked;
res = ReleaseSemaphore(m_blockLock, 1, 0);
ASSERT_UNUSED(res, res);
--mutex.m_recursionCount;
LeaveCriticalSection(&mutex.m_internalMutex);
bool timedOut = (WaitForSingleObject(m_blockQueue, durationMilliseconds) == WAIT_TIMEOUT);
res = WaitForSingleObject(m_unblockLock, INFINITE);
ASSERT_UNUSED(res, res == WAIT_OBJECT_0);
int signalsLeft = m_waitersToUnblock;
if (m_waitersToUnblock)
--m_waitersToUnblock;
else if (++m_waitersGone == (INT_MAX / 2)) { res = WaitForSingleObject(m_blockLock, INFINITE);
ASSERT_UNUSED(res, res == WAIT_OBJECT_0);
m_waitersBlocked -= m_waitersGone;
res = ReleaseSemaphore(m_blockLock, 1, 0);
ASSERT_UNUSED(res, res);
m_waitersGone = 0;
}
res = ReleaseMutex(m_unblockLock);
ASSERT_UNUSED(res, res);
if (signalsLeft == 1) {
res = ReleaseSemaphore(m_blockLock, 1, 0); ASSERT_UNUSED(res, res);
}
EnterCriticalSection (&mutex.m_internalMutex);
++mutex.m_recursionCount;
return !timedOut;
}
void PlatformCondition::signal(bool unblockAll)
{
unsigned signalsToIssue = 0;
DWORD res = WaitForSingleObject(m_unblockLock, INFINITE);
ASSERT_UNUSED(res, res == WAIT_OBJECT_0);
if (m_waitersToUnblock) { if (!m_waitersBlocked) { res = ReleaseMutex(m_unblockLock);
ASSERT_UNUSED(res, res);
return;
}
if (unblockAll) {
signalsToIssue = m_waitersBlocked;
m_waitersToUnblock += m_waitersBlocked;
m_waitersBlocked = 0;
} else {
signalsToIssue = 1;
++m_waitersToUnblock;
--m_waitersBlocked;
}
} else if (m_waitersBlocked > m_waitersGone) {
res = WaitForSingleObject(m_blockLock, INFINITE); ASSERT_UNUSED(res, res == WAIT_OBJECT_0);
if (m_waitersGone != 0) {
m_waitersBlocked -= m_waitersGone;
m_waitersGone = 0;
}
if (unblockAll) {
signalsToIssue = m_waitersBlocked;
m_waitersToUnblock = m_waitersBlocked;
m_waitersBlocked = 0;
} else {
signalsToIssue = 1;
m_waitersToUnblock = 1;
--m_waitersBlocked;
}
} else { res = ReleaseMutex(m_unblockLock);
ASSERT_UNUSED(res, res);
return;
}
res = ReleaseMutex(m_unblockLock);
ASSERT_UNUSED(res, res);
if (signalsToIssue) {
res = ReleaseSemaphore(m_blockQueue, signalsToIssue, 0);
ASSERT_UNUSED(res, res);
}
}
static const long MaxSemaphoreCount = static_cast<long>(~0UL >> 1);
ThreadCondition::ThreadCondition()
{
m_condition.m_waitersGone = 0;
m_condition.m_waitersBlocked = 0;
m_condition.m_waitersToUnblock = 0;
m_condition.m_blockLock = CreateSemaphore(0, 1, 1, 0);
m_condition.m_blockQueue = CreateSemaphore(0, 0, MaxSemaphoreCount, 0);
m_condition.m_unblockLock = CreateMutex(0, 0, 0);
if (!m_condition.m_blockLock || !m_condition.m_blockQueue || !m_condition.m_unblockLock) {
if (m_condition.m_blockLock)
CloseHandle(m_condition.m_blockLock);
if (m_condition.m_blockQueue)
CloseHandle(m_condition.m_blockQueue);
if (m_condition.m_unblockLock)
CloseHandle(m_condition.m_unblockLock);
}
}
ThreadCondition::~ThreadCondition()
{
CloseHandle(m_condition.m_blockLock);
CloseHandle(m_condition.m_blockQueue);
CloseHandle(m_condition.m_unblockLock);
}
void ThreadCondition::wait(Mutex& mutex)
{
m_condition.timedWait(mutex.impl(), INFINITE);
}
bool ThreadCondition::timedWait(Mutex& mutex, double absoluteTime)
{
DWORD interval = absoluteTimeToWaitTimeoutInterval(absoluteTime);
if (!interval) {
return false;
}
return m_condition.timedWait(mutex.impl(), interval);
}
void ThreadCondition::signal()
{
m_condition.signal(false); }
void ThreadCondition::broadcast()
{
m_condition.signal(true); }
DWORD absoluteTimeToWaitTimeoutInterval(double absoluteTime)
{
double currentTime = WTF::currentTime();
if (absoluteTime < currentTime)
return 0;
if (absoluteTime - currentTime > static_cast<double>(INT_MAX) / 1000.0)
return INFINITE;
return static_cast<DWORD>((absoluteTime - currentTime) * 1000.0);
}
ThreadIdentifier createThread(ThreadFunction function, void* data, const char* threadName)
{
return Thread::create(threadName, [function, data] {
function(data);
})->id();
}
int waitForThreadCompletion(ThreadIdentifier threadID)
{
ASSERT(threadID);
RefPtr<Thread> thread = ThreadHolder::get(threadID);
if (!thread) {
LOG_ERROR("ThreadIdentifier %u did not correspond to an active thread when trying to quit", threadID);
return WAIT_FAILED;
}
return thread->waitForCompletion();
}
}
#endif // OS(WINDOWS)