Support Performance API (performance.now(), UserTiming) in Workers
[WebKit-https.git] / Source / WebCore / workers / WorkerThread.cpp
1 /*
2  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  *
25  */
26
27 #include "config.h"
28 #include "WorkerThread.h"
29
30 #include "ContentSecurityPolicyResponseHeaders.h"
31 #include "IDBConnectionProxy.h"
32 #include "ScriptSourceCode.h"
33 #include "SecurityOrigin.h"
34 #include "SocketProvider.h"
35 #include "ThreadGlobalData.h"
36 #include "URL.h"
37 #include "WorkerGlobalScope.h"
38 #include "WorkerInspectorController.h"
39 #include <utility>
40 #include <wtf/Lock.h>
41 #include <wtf/NeverDestroyed.h>
42 #include <wtf/Noncopyable.h>
43 #include <wtf/text/WTFString.h>
44
45 #if PLATFORM(IOS)
46 #include "FloatingPointEnvironment.h"
47 #include "WebCoreThread.h"
48 #endif
49
50 #if PLATFORM(GTK)
51 #include <wtf/glib/GRefPtr.h>
52 #endif
53
54 namespace WebCore {
55
56 static StaticLock threadSetMutex;
57
58 static HashSet<WorkerThread*>& workerThreads()
59 {
60     static NeverDestroyed<HashSet<WorkerThread*>> workerThreads;
61
62     return workerThreads;
63 }
64
65 unsigned WorkerThread::workerThreadCount()
66 {
67     std::lock_guard<StaticLock> lock(threadSetMutex);
68
69     return workerThreads().size();
70 }
71
72 struct WorkerThreadStartupData {
73     WTF_MAKE_NONCOPYABLE(WorkerThreadStartupData); WTF_MAKE_FAST_ALLOCATED;
74 public:
75     WorkerThreadStartupData(const URL& scriptURL, const String& identifier, const String& userAgent, const String& sourceCode, WorkerThreadStartMode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, const SecurityOrigin& topOrigin, double timeOrigin);
76
77     URL m_scriptURL;
78     String m_identifier;
79     String m_userAgent;
80     String m_sourceCode;
81     WorkerThreadStartMode m_startMode;
82     ContentSecurityPolicyResponseHeaders m_contentSecurityPolicyResponseHeaders;
83     bool m_shouldBypassMainWorldContentSecurityPolicy;
84     Ref<SecurityOrigin> m_topOrigin;
85     double m_timeOrigin;
86 };
87
88 WorkerThreadStartupData::WorkerThreadStartupData(const URL& scriptURL, const String& identifier, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, const SecurityOrigin& topOrigin, double timeOrigin)
89     : m_scriptURL(scriptURL.isolatedCopy())
90     , m_identifier(identifier.isolatedCopy())
91     , m_userAgent(userAgent.isolatedCopy())
92     , m_sourceCode(sourceCode.isolatedCopy())
93     , m_startMode(startMode)
94     , m_contentSecurityPolicyResponseHeaders(contentSecurityPolicyResponseHeaders.isolatedCopy())
95     , m_shouldBypassMainWorldContentSecurityPolicy(shouldBypassMainWorldContentSecurityPolicy)
96     , m_topOrigin(topOrigin.isolatedCopy())
97     , m_timeOrigin(timeOrigin)
98 {
99 }
100
101 WorkerThread::WorkerThread(const URL& scriptURL, const String& identifier, const String& userAgent, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, const SecurityOrigin& topOrigin, double timeOrigin, IDBClient::IDBConnectionProxy* connectionProxy, SocketProvider* socketProvider, JSC::RuntimeFlags runtimeFlags)
102     : m_threadID(0)
103     , m_workerLoaderProxy(workerLoaderProxy)
104     , m_workerReportingProxy(workerReportingProxy)
105     , m_runtimeFlags(runtimeFlags)
106     , m_startupData(std::make_unique<WorkerThreadStartupData>(scriptURL, identifier, userAgent, sourceCode, startMode, contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, topOrigin, timeOrigin))
107 #if ENABLE(INDEXED_DATABASE)
108     , m_idbConnectionProxy(connectionProxy)
109 #endif
110 #if ENABLE(WEB_SOCKETS)
111     , m_socketProvider(socketProvider)
112 #endif
113 {
114 #if !ENABLE(INDEXED_DATABASE)
115     UNUSED_PARAM(connectionProxy);
116 #endif
117 #if !ENABLE(WEB_SOCKETS)
118     UNUSED_PARAM(socketProvider);
119 #endif
120
121     std::lock_guard<StaticLock> lock(threadSetMutex);
122
123     workerThreads().add(this);
124 }
125
126 WorkerThread::~WorkerThread()
127 {
128     std::lock_guard<StaticLock> lock(threadSetMutex);
129
130     ASSERT(workerThreads().contains(this));
131     workerThreads().remove(this);
132 }
133
134 bool WorkerThread::start()
135 {
136     // Mutex protection is necessary to ensure that m_threadID is initialized when the thread starts.
137     LockHolder lock(m_threadCreationMutex);
138
139     if (m_threadID)
140         return true;
141
142     m_threadID = createThread(WorkerThread::workerThreadStart, this, "WebCore: Worker");
143
144     return m_threadID;
145 }
146
147 void WorkerThread::workerThreadStart(void* thread)
148 {
149     static_cast<WorkerThread*>(thread)->workerThread();
150 }
151
152 void WorkerThread::workerThread()
153 {
154     // Propagate the mainThread's fenv to workers.
155 #if PLATFORM(IOS)
156     FloatingPointEnvironment::singleton().propagateMainThreadEnvironment();
157 #endif
158
159 #if PLATFORM(GTK)
160     GRefPtr<GMainContext> mainContext = adoptGRef(g_main_context_new());
161     g_main_context_push_thread_default(mainContext.get());
162 #endif
163
164     {
165         LockHolder lock(m_threadCreationMutex);
166         m_workerGlobalScope = createWorkerGlobalScope(m_startupData->m_scriptURL, m_startupData->m_identifier, m_startupData->m_userAgent, m_startupData->m_contentSecurityPolicyResponseHeaders, m_startupData->m_shouldBypassMainWorldContentSecurityPolicy, WTFMove(m_startupData->m_topOrigin), m_startupData->m_timeOrigin);
167
168         if (m_runLoop.terminated()) {
169             // The worker was terminated before the thread had a chance to run. Since the context didn't exist yet,
170             // forbidExecution() couldn't be called from stop().
171             m_workerGlobalScope->script()->forbidExecution();
172         }
173     }
174
175     if (m_startupData->m_startMode == WorkerThreadStartMode::WaitForInspector) {
176         startRunningDebuggerTasks();
177
178         // If the worker was somehow terminated while processing debugger commands.
179         if (m_runLoop.terminated())
180             m_workerGlobalScope->script()->forbidExecution();
181     }
182
183     WorkerScriptController* script = m_workerGlobalScope->script();
184     script->evaluate(ScriptSourceCode(m_startupData->m_sourceCode, m_startupData->m_scriptURL));
185     // Free the startup data to cause its member variable deref's happen on the worker's thread (since
186     // all ref/derefs of these objects are happening on the thread at this point). Note that
187     // WorkerThread::~WorkerThread happens on a different thread where it was created.
188     m_startupData = nullptr;
189
190     runEventLoop();
191
192 #if PLATFORM(GTK)
193     g_main_context_pop_thread_default(mainContext.get());
194 #endif
195
196     ThreadIdentifier threadID = m_threadID;
197
198     ASSERT(m_workerGlobalScope->hasOneRef());
199
200     // The below assignment will destroy the context, which will in turn notify messaging proxy.
201     // We cannot let any objects survive past thread exit, because no other thread will run GC or otherwise destroy them.
202     m_workerGlobalScope = nullptr;
203
204     // Clean up WebCore::ThreadGlobalData before WTF::WTFThreadData goes away!
205     threadGlobalData().destroy();
206
207     // The thread object may be already destroyed from notification now, don't try to access "this".
208     detachThread(threadID);
209 }
210
211 void WorkerThread::startRunningDebuggerTasks()
212 {
213     ASSERT(!m_pausedForDebugger);
214     m_pausedForDebugger = true;
215
216     MessageQueueWaitResult result;
217     do {
218         result = m_runLoop.runInMode(m_workerGlobalScope.get(), WorkerRunLoop::debuggerMode());
219     } while (result != MessageQueueTerminated && m_pausedForDebugger);
220 }
221
222 void WorkerThread::stopRunningDebuggerTasks()
223 {
224     m_pausedForDebugger = false;
225 }
226
227 void WorkerThread::runEventLoop()
228 {
229     // Does not return until terminated.
230     m_runLoop.run(m_workerGlobalScope.get());
231 }
232
233 void WorkerThread::stop()
234 {
235     // Mutex protection is necessary because stop() can be called before the context is fully created.
236     LockHolder lock(m_threadCreationMutex);
237
238     // 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.
239     if (m_workerGlobalScope) {
240         m_workerGlobalScope->script()->scheduleExecutionTermination();
241
242         m_runLoop.postTaskAndTerminate({ ScriptExecutionContext::Task::CleanupTask, [] (ScriptExecutionContext& context ) {
243             WorkerGlobalScope& workerGlobalScope = downcast<WorkerGlobalScope>(context);
244
245 #if ENABLE(INDEXED_DATABASE)
246             workerGlobalScope.stopIndexedDatabase();
247 #endif
248
249             workerGlobalScope.stopActiveDOMObjects();
250
251             workerGlobalScope.inspectorController().workerTerminating();
252
253             // Event listeners would keep DOMWrapperWorld objects alive for too long. Also, they have references to JS objects,
254             // which become dangling once Heap is destroyed.
255             workerGlobalScope.removeAllEventListeners();
256
257             // Stick a shutdown command at the end of the queue, so that we deal
258             // with all the cleanup tasks the databases post first.
259             workerGlobalScope.postTask({ ScriptExecutionContext::Task::CleanupTask, [] (ScriptExecutionContext& context) {
260                 WorkerGlobalScope& workerGlobalScope = downcast<WorkerGlobalScope>(context);
261                 // It's not safe to call clearScript until all the cleanup tasks posted by functions initiated by WorkerThreadShutdownStartTask have completed.
262                 workerGlobalScope.clearScript();
263             } });
264
265         } });
266         return;
267     }
268     m_runLoop.terminate();
269 }
270
271 void WorkerThread::releaseFastMallocFreeMemoryInAllThreads()
272 {
273     std::lock_guard<StaticLock> lock(threadSetMutex);
274
275     for (auto* workerThread : workerThreads()) {
276         workerThread->runLoop().postTask([] (ScriptExecutionContext&) {
277             WTF::releaseFastMallocFreeMemory();
278         });
279     }
280 }
281
282 IDBClient::IDBConnectionProxy* WorkerThread::idbConnectionProxy()
283 {
284 #if ENABLE(INDEXED_DATABASE)
285     return m_idbConnectionProxy.get();
286 #else
287     return nullptr;
288 #endif
289 }
290
291 SocketProvider* WorkerThread::socketProvider()
292 {
293 #if ENABLE(WEB_SOCKETS)
294     return m_socketProvider.get();
295 #else
296     return nullptr;
297 #endif
298 }
299
300 } // namespace WebCore