1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
|
/*
* Copyright (C) 2008-2020 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WorkerOrWorkletThread.h"
#include "ThreadGlobalData.h"
#include "WorkerEventLoop.h"
#include "WorkerOrWorkletGlobalScope.h"
#include "WorkerOrWorkletScriptController.h"
#if PLATFORM(IOS_FAMILY)
#include "FloatingPointEnvironment.h"
#endif
#if USE(GLIB)
#include <wtf/glib/GRefPtr.h>
#endif
namespace WebCore {
ThreadSafeWeakHashSet<WorkerOrWorkletThread>& WorkerOrWorkletThread::workerOrWorkletThreads()
{
static LazyNeverDestroyed<ThreadSafeWeakHashSet<WorkerOrWorkletThread>> workerOrWorkletThreads;
static std::once_flag onceFlag;
std::call_once(onceFlag, [] {
workerOrWorkletThreads.construct();
});
return workerOrWorkletThreads;
}
static UniqueRef<WorkerRunLoop> constructRunLoop(WorkerThreadMode workerThreadMode)
{
switch (workerThreadMode) {
case WorkerThreadMode::UseMainThread:
return makeUniqueRef<WorkerMainRunLoop>();
case WorkerThreadMode::CreateNewThread:
break;
}
return makeUniqueRef<WorkerDedicatedRunLoop>();
}
WorkerOrWorkletThread::WorkerOrWorkletThread(const String& inspectorIdentifier, WorkerThreadMode workerThreadMode)
: m_inspectorIdentifier(inspectorIdentifier)
, m_runLoop(constructRunLoop(workerThreadMode))
{
workerOrWorkletThreads().add(*this);
}
WorkerOrWorkletThread::~WorkerOrWorkletThread()
{
workerOrWorkletThreads().remove(*this);
}
void WorkerOrWorkletThread::dispatch(Function<void()>&& func)
{
runLoop().postTask([func = WTFMove(func)](auto&) mutable {
func();
});
}
bool WorkerOrWorkletThread::isCurrent() const
{
return thread() ? thread()->uid() == Thread::current().uid() : false;
}
void WorkerOrWorkletThread::startRunningDebuggerTasks()
{
ASSERT(!m_pausedForDebugger);
m_pausedForDebugger = true;
// FIXME: Add support for debugging workers running on the main thread.
if (!is<WorkerDedicatedRunLoop>(m_runLoop.get()))
return;
MessageQueueWaitResult result;
do {
result = downcast<WorkerDedicatedRunLoop>(m_runLoop.get()).runInDebuggerMode(*m_globalScope);
} while (result != MessageQueueTerminated && m_pausedForDebugger);
}
void WorkerOrWorkletThread::stopRunningDebuggerTasks()
{
m_pausedForDebugger = false;
}
void WorkerOrWorkletThread::runEventLoop()
{
// Does not return until terminated.
if (auto* runLoop = dynamicDowncast<WorkerDedicatedRunLoop>(m_runLoop.get()))
runLoop->run(RefPtr { m_globalScope }.get());
}
void WorkerOrWorkletThread::workerOrWorkletThread()
{
Ref protectedThis { *this };
if (isMainThread()) {
m_globalScope = createGlobalScope();
if (!m_globalScope)
return;
downcast<WorkerMainRunLoop>(m_runLoop.get()).setGlobalScope(*m_globalScope);
String exceptionMessage;
evaluateScriptIfNecessary(exceptionMessage);
callOnMainThread([evaluateCallback = WTFMove(m_evaluateCallback), message = WTFMove(exceptionMessage)] {
if (evaluateCallback)
evaluateCallback(message);
});
return;
}
// Propagate the mainThread's fenv to workers.
#if PLATFORM(IOS_FAMILY)
FloatingPointEnvironment::singleton().propagateMainThreadEnvironment();
#endif
#if USE(GLIB)
GRefPtr<GMainContext> mainContext = adoptGRef(g_main_context_new());
g_main_context_push_thread_default(mainContext.get());
#endif
WorkerOrWorkletScriptController* scriptController;
{
// Mutex protection is necessary to ensure that we don't change m_globalScope
// while WorkerThread::stop() is accessing it. Note that WorkerThread::stop() can
// be called before we've finished creating the WorkerGlobalScope.
Locker locker { m_threadCreationAndGlobalScopeLock };
m_globalScope = createGlobalScope();
// When running out of memory, createGlobalScope() may return null because we could not allocate a JSC::VM.
if (!m_globalScope) {
WTFLogAlways("Error: Failed to create a WorkerOrWorkerGlobalScope.");
return;
}
scriptController = m_globalScope->script();
if (m_runLoop->terminated()) {
// The worker was terminated before the thread had a chance to run. Since the context didn't exist yet,
// forbidExecution() couldn't be called from stop().
scriptController->scheduleExecutionTermination();
scriptController->forbidExecution();
}
}
if (shouldWaitForWebInspectorOnStartup()) {
startRunningDebuggerTasks();
// If the worker was somehow terminated while processing debugger commands.
if (m_runLoop->terminated())
scriptController->forbidExecution();
}
String exceptionMessage;
evaluateScriptIfNecessary(exceptionMessage);
callOnMainThread([evaluateCallback = WTFMove(m_evaluateCallback), message = exceptionMessage.isolatedCopy()] {
if (evaluateCallback)
evaluateCallback(message);
});
runEventLoop();
#if USE(GLIB)
g_main_context_pop_thread_default(mainContext.get());
#endif
if (!m_childThreads.isEmptyIgnoringNullReferences()) {
m_runWhenLastChildThreadIsGone = [this, protectedThis = WTFMove(protectedThis)]() mutable {
destroyWorkerGlobalScope(WTFMove(protectedThis));
};
return;
}
destroyWorkerGlobalScope(WTFMove(protectedThis));
}
void WorkerOrWorkletThread::destroyWorkerGlobalScope(Ref<WorkerOrWorkletThread>&& protectedThis)
{
ASSERT(m_childThreads.isEmptyIgnoringNullReferences());
RefPtr<Thread> protector = m_thread;
ASSERT(m_globalScope->hasOneRef());
RefPtr<WorkerOrWorkletGlobalScope> workerGlobalScopeToDelete;
Function<void()> stoppedCallback;
{
// Mutex protection is necessary to ensure that we don't change m_globalScope
// while WorkerThread::stop is accessing it.
Locker locker { m_threadCreationAndGlobalScopeLock };
// Delay the destruction of the WorkerGlobalScope context until after we've unlocked the
// m_threadCreationAndWorkerGlobalScopeMutex. This is needed because destructing the
// context will trigger the main thread to race against us to delete the WorkerThread
// object, and the WorkerThread object owns the mutex we need to unlock after this.
workerGlobalScopeToDelete = std::exchange(m_globalScope, nullptr);
stoppedCallback = std::exchange(m_stoppedCallback, nullptr);
}
// The below assignment will destroy the context, which will in turn notify messaging proxy.
// We cannot let any objects survive past thread exit, because no other thread will run GC or otherwise destroy them.
workerGlobalScopeToDelete = nullptr;
// Make sure we don't call the stoppedCallback before the WorkerGlobalScope has been destroyed.
if (stoppedCallback)
callOnMainThread(WTFMove(stoppedCallback));
// Clean up WebCore::ThreadGlobalData before WTF::Thread goes away!
threadGlobalData().destroy();
// Send the last WorkerThread Ref to be Deref'ed on the main thread.
callOnMainThread([protectedThis = WTFMove(protectedThis)] { });
// The thread object may be already destroyed from notification now, don't try to access "this".
protector->detach();
}
void WorkerOrWorkletThread::start(Function<void(const String&)>&& evaluateCallback)
{
// Mutex protection is necessary to ensure that m_thread is initialized when the thread starts.
Locker locker { m_threadCreationAndGlobalScopeLock };
if (m_thread)
return;
m_evaluateCallback = WTFMove(evaluateCallback);
auto thread = createThread();
// Force the Thread object to be initialized fully before storing it to m_thread (and becoming visible to other threads).
WTF::storeStoreFence();
m_thread = WTFMove(thread);
}
void WorkerOrWorkletThread::stop(Function<void()>&& stoppedCallback)
{
// Mutex protection is necessary to ensure that m_workerGlobalScope isn't changed by
// WorkerThread::workerThread() while we're accessing it. Note also that stop() can
// be called before m_workerGlobalScope is fully created.
if (!m_threadCreationAndGlobalScopeLock.tryLock()) {
// The thread is still starting, spin the runloop and try again to avoid deadlocks if the worker thread
// needs to interact with the main thread during startup.
callOnMainThread([this, stoppedCallback = WTFMove(stoppedCallback)]() mutable {
stop(WTFMove(stoppedCallback));
});
return;
}
Locker locker { AdoptLock, m_threadCreationAndGlobalScopeLock };
// If the thread is suspended, resume it now so that we can dispatch the cleanup tasks below.
if (m_isSuspended)
resume();
ASSERT(!m_stoppedCallback);
m_stoppedCallback = WTFMove(stoppedCallback);
// Ensure that tasks are being handled by thread event loop. If script execution weren't forbidden, a while(1) loop in JS could keep the thread alive forever.
if (globalScope()) {
if (auto* script = globalScope()->script())
script->scheduleExecutionTermination();
if (is<WorkerMainRunLoop>(m_runLoop.get())) {
auto globalScope = std::exchange(m_globalScope, nullptr);
globalScope->prepareForDestruction();
globalScope->clearScript();
m_runLoop->terminate();
if (m_stoppedCallback)
callOnMainThread(std::exchange(m_stoppedCallback, nullptr));
return;
}
m_runLoop->postTaskAndTerminate({ ScriptExecutionContext::Task::CleanupTask, [] (ScriptExecutionContext& context ) {
auto& globalScope = downcast<WorkerOrWorkletGlobalScope>(context);
globalScope.prepareForDestruction();
// Stick a shutdown command at the end of the queue, so that we deal
// with all the cleanup tasks the databases post first.
globalScope.postTask({ ScriptExecutionContext::Task::CleanupTask, [] (ScriptExecutionContext& context) {
auto& globalScope = downcast<WorkerOrWorkletGlobalScope>(context);
// It's not safe to call clearScript until all the cleanup tasks posted by functions initiated by WorkerThreadShutdownStartTask have completed.
globalScope.clearScript();
} });
} });
return;
}
m_runLoop->terminate();
}
void WorkerOrWorkletThread::suspend()
{
m_isSuspended = true;
if (is<WorkerMainRunLoop>(m_runLoop.get()))
return;
m_runLoop->postTask([&](ScriptExecutionContext&) {
if (globalScope())
globalScope()->suspend();
m_suspensionSemaphore.wait();
if (globalScope())
globalScope()->resume();
});
}
void WorkerOrWorkletThread::resume()
{
ASSERT(m_isSuspended);
m_isSuspended = false;
if (is<WorkerMainRunLoop>(m_runLoop.get()))
return;
m_suspensionSemaphore.signal();
}
void WorkerOrWorkletThread::releaseFastMallocFreeMemoryInAllThreads()
{
for (auto& workerOrWorkletThread : workerOrWorkletThreads()) {
workerOrWorkletThread.runLoop().postTask([] (ScriptExecutionContext&) {
WTF::releaseFastMallocFreeMemory();
});
}
}
void WorkerOrWorkletThread::addChildThread(WorkerOrWorkletThread& childThread)
{
m_childThreads.add(childThread);
}
void WorkerOrWorkletThread::removeChildThread(WorkerOrWorkletThread& childThread)
{
m_childThreads.remove(childThread);
if (m_childThreads.isEmptyIgnoringNullReferences() && m_runWhenLastChildThreadIsGone)
std::exchange(m_runWhenLastChildThreadIsGone, nullptr)();
}
} // namespace WebCore
|