#include "config.h"
#include "WorkerThread.h"
#include "ContentSecurityPolicyResponseHeaders.h"
#include "IDBConnectionProxy.h"
#include "ScriptSourceCode.h"
#include "SecurityOrigin.h"
#include "SocketProvider.h"
#include "ThreadGlobalData.h"
#include "URL.h"
#include "WorkerGlobalScope.h"
#include "WorkerInspectorController.h"
#include <utility>
#include <wtf/Lock.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/Noncopyable.h>
#include <wtf/text/WTFString.h>
#if PLATFORM(IOS)
#include "FloatingPointEnvironment.h"
#include "WebCoreThread.h"
#endif
#if USE(GLIB)
#include <wtf/glib/GRefPtr.h>
#endif
namespace WebCore {
static Lock threadSetMutex;
static HashSet<WorkerThread*>& workerThreads()
{
static NeverDestroyed<HashSet<WorkerThread*>> workerThreads;
return workerThreads;
}
unsigned WorkerThread::workerThreadCount()
{
std::lock_guard<Lock> lock(threadSetMutex);
return workerThreads().size();
}
struct WorkerThreadStartupData {
WTF_MAKE_NONCOPYABLE(WorkerThreadStartupData); WTF_MAKE_FAST_ALLOCATED;
public:
WorkerThreadStartupData(const URL& scriptURL, const String& identifier, const String& userAgent, bool isOnline, const String& sourceCode, WorkerThreadStartMode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, const SecurityOrigin& topOrigin, MonotonicTime timeOrigin, PAL::SessionID);
URL m_scriptURL;
Ref<SecurityOrigin> m_origin;
String m_identifier;
String m_userAgent;
String m_sourceCode;
WorkerThreadStartMode m_startMode;
ContentSecurityPolicyResponseHeaders m_contentSecurityPolicyResponseHeaders;
bool m_shouldBypassMainWorldContentSecurityPolicy;
bool m_isOnline;
Ref<SecurityOrigin> m_topOrigin;
MonotonicTime m_timeOrigin;
PAL::SessionID m_sessionID;
};
WorkerThreadStartupData::WorkerThreadStartupData(const URL& scriptURL, const String& identifier, const String& userAgent, bool isOnline, const String& sourceCode, WorkerThreadStartMode startMode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, const SecurityOrigin& topOrigin, MonotonicTime timeOrigin, PAL::SessionID sessionID)
: m_scriptURL(scriptURL.isolatedCopy())
, m_origin(SecurityOrigin::create(m_scriptURL)->isolatedCopy())
, m_identifier(identifier.isolatedCopy())
, m_userAgent(userAgent.isolatedCopy())
, m_sourceCode(sourceCode.isolatedCopy())
, m_startMode(startMode)
, m_contentSecurityPolicyResponseHeaders(contentSecurityPolicyResponseHeaders.isolatedCopy())
, m_shouldBypassMainWorldContentSecurityPolicy(shouldBypassMainWorldContentSecurityPolicy)
, m_isOnline(isOnline)
, m_topOrigin(topOrigin.isolatedCopy())
, m_timeOrigin(timeOrigin)
, m_sessionID(sessionID.isolatedCopy())
{
}
WorkerThread::WorkerThread(const URL& scriptURL, const String& identifier, const String& userAgent, bool isOnline, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerDebuggerProxy& workerDebuggerProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, const SecurityOrigin& topOrigin, MonotonicTime timeOrigin, IDBClient::IDBConnectionProxy* connectionProxy, SocketProvider* socketProvider, JSC::RuntimeFlags runtimeFlags, PAL::SessionID sessionID)
: m_workerLoaderProxy(workerLoaderProxy)
, m_workerDebuggerProxy(workerDebuggerProxy)
, m_workerReportingProxy(workerReportingProxy)
, m_runtimeFlags(runtimeFlags)
, m_startupData(std::make_unique<WorkerThreadStartupData>(scriptURL, identifier, userAgent, isOnline, sourceCode, startMode, contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, topOrigin, timeOrigin, sessionID))
#if ENABLE(INDEXED_DATABASE)
, m_idbConnectionProxy(connectionProxy)
#endif
, m_socketProvider(socketProvider)
{
#if !ENABLE(INDEXED_DATABASE)
UNUSED_PARAM(connectionProxy);
#endif
std::lock_guard<Lock> lock(threadSetMutex);
workerThreads().add(this);
}
WorkerThread::~WorkerThread()
{
std::lock_guard<Lock> lock(threadSetMutex);
ASSERT(workerThreads().contains(this));
workerThreads().remove(this);
}
void WorkerThread::start(WTF::Function<void(const String&)>&& evaluateCallback)
{
LockHolder lock(m_threadCreationAndWorkerGlobalScopeMutex);
if (m_thread)
return;
m_evaluateCallback = WTFMove(evaluateCallback);
m_thread = Thread::create(isServiceWorkerThread() ? "WebCore: Service Worker" : "WebCore: Worker", [this] {
workerThread();
});
}
void WorkerThread::workerThread()
{
auto protectedThis = makeRef(*this);
#if PLATFORM(IOS)
FloatingPointEnvironment::singleton().propagateMainThreadEnvironment();
#endif
#if USE(GLIB)
GRefPtr<GMainContext> mainContext = adoptGRef(g_main_context_new());
g_main_context_push_thread_default(mainContext.get());
#endif
WorkerScriptController* scriptController;
{
LockHolder lock(m_threadCreationAndWorkerGlobalScopeMutex);
m_workerGlobalScope = createWorkerGlobalScope(m_startupData->m_scriptURL, WTFMove(m_startupData->m_origin), m_startupData->m_identifier, m_startupData->m_userAgent, m_startupData->m_isOnline, m_startupData->m_contentSecurityPolicyResponseHeaders, m_startupData->m_shouldBypassMainWorldContentSecurityPolicy, WTFMove(m_startupData->m_topOrigin), m_startupData->m_timeOrigin, m_startupData->m_sessionID);
scriptController = m_workerGlobalScope->script();
if (m_runLoop.terminated()) {
scriptController->scheduleExecutionTermination();
scriptController->forbidExecution();
}
}
if (m_startupData->m_startMode == WorkerThreadStartMode::WaitForInspector) {
startRunningDebuggerTasks();
if (m_runLoop.terminated())
scriptController->forbidExecution();
}
String exceptionMessage;
scriptController->evaluate(ScriptSourceCode(m_startupData->m_sourceCode, m_startupData->m_scriptURL), &exceptionMessage);
callOnMainThread([evaluateCallback = WTFMove(m_evaluateCallback), message = exceptionMessage.isolatedCopy()] {
if (evaluateCallback)
evaluateCallback(message);
});
m_startupData = nullptr;
runEventLoop();
#if USE(GLIB)
g_main_context_pop_thread_default(mainContext.get());
#endif
RefPtr<Thread> protector = m_thread;
ASSERT(m_workerGlobalScope->hasOneRef());
RefPtr<WorkerGlobalScope> workerGlobalScopeToDelete;
{
LockHolder lock(m_threadCreationAndWorkerGlobalScopeMutex);
workerGlobalScopeToDelete = WTFMove(m_workerGlobalScope);
if (m_stoppedCallback)
callOnMainThread(WTFMove(m_stoppedCallback));
}
workerGlobalScopeToDelete = nullptr;
threadGlobalData().destroy();
callOnMainThread([protectedThis = WTFMove(protectedThis)] { });
protector->detach();
}
void WorkerThread::startRunningDebuggerTasks()
{
ASSERT(!m_pausedForDebugger);
m_pausedForDebugger = true;
MessageQueueWaitResult result;
do {
result = m_runLoop.runInMode(m_workerGlobalScope.get(), WorkerRunLoop::debuggerMode());
} while (result != MessageQueueTerminated && m_pausedForDebugger);
}
void WorkerThread::stopRunningDebuggerTasks()
{
m_pausedForDebugger = false;
}
void WorkerThread::runEventLoop()
{
m_runLoop.run(m_workerGlobalScope.get());
}
void WorkerThread::stop(WTF::Function<void()>&& stoppedCallback)
{
auto locker = Locker<Lock>::tryLock(m_threadCreationAndWorkerGlobalScopeMutex);
if (!locker) {
callOnMainThread([this, stoppedCallback = WTFMove(stoppedCallback)]() mutable {
stop(WTFMove(stoppedCallback));
});
return;
}
ASSERT(!m_stoppedCallback);
m_stoppedCallback = WTFMove(stoppedCallback);
if (m_workerGlobalScope) {
m_workerGlobalScope->script()->scheduleExecutionTermination();
m_runLoop.postTaskAndTerminate({ ScriptExecutionContext::Task::CleanupTask, [] (ScriptExecutionContext& context ) {
WorkerGlobalScope& workerGlobalScope = downcast<WorkerGlobalScope>(context);
#if ENABLE(INDEXED_DATABASE)
workerGlobalScope.stopIndexedDatabase();
#endif
workerGlobalScope.stopActiveDOMObjects();
workerGlobalScope.inspectorController().workerTerminating();
workerGlobalScope.removeAllEventListeners();
workerGlobalScope.postTask({ ScriptExecutionContext::Task::CleanupTask, [] (ScriptExecutionContext& context) {
WorkerGlobalScope& workerGlobalScope = downcast<WorkerGlobalScope>(context);
workerGlobalScope.clearScript();
} });
} });
return;
}
m_runLoop.terminate();
}
void WorkerThread::releaseFastMallocFreeMemoryInAllThreads()
{
std::lock_guard<Lock> lock(threadSetMutex);
for (auto* workerThread : workerThreads()) {
workerThread->runLoop().postTask([] (ScriptExecutionContext&) {
WTF::releaseFastMallocFreeMemory();
});
}
}
IDBClient::IDBConnectionProxy* WorkerThread::idbConnectionProxy()
{
#if ENABLE(INDEXED_DATABASE)
return m_idbConnectionProxy.get();
#else
return nullptr;
#endif
}
SocketProvider* WorkerThread::socketProvider()
{
return m_socketProvider.get();
}
}