bf24d50cb2ff246c3f4a5f155561906425c62bd4
[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);
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 };
86
87 WorkerThreadStartupData::WorkerThreadStartupData(const URL& scriptURL, const String& identifier, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, const SecurityOrigin& topOrigin)
88     : m_scriptURL(scriptURL.isolatedCopy())
89     , m_identifier(identifier.isolatedCopy())
90     , m_userAgent(userAgent.isolatedCopy())
91     , m_sourceCode(sourceCode.isolatedCopy())
92     , m_startMode(startMode)
93     , m_contentSecurityPolicyResponseHeaders(contentSecurityPolicyResponseHeaders.isolatedCopy())
94     , m_shouldBypassMainWorldContentSecurityPolicy(shouldBypassMainWorldContentSecurityPolicy)
95     , m_topOrigin(topOrigin.isolatedCopy())
96 {
97 }
98
99 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, IDBClient::IDBConnectionProxy* connectionProxy, SocketProvider* socketProvider, JSC::RuntimeFlags runtimeFlags)
100     : m_threadID(0)
101     , m_workerLoaderProxy(workerLoaderProxy)
102     , m_workerReportingProxy(workerReportingProxy)
103     , m_runtimeFlags(runtimeFlags)
104     , m_startupData(std::make_unique<WorkerThreadStartupData>(scriptURL, identifier, userAgent, sourceCode, startMode, contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, topOrigin))
105 #if ENABLE(INDEXED_DATABASE)
106     , m_idbConnectionProxy(connectionProxy)
107 #endif
108 #if ENABLE(WEB_SOCKETS)
109     , m_socketProvider(socketProvider)
110 #endif
111 {
112 #if !ENABLE(INDEXED_DATABASE)
113     UNUSED_PARAM(connectionProxy);
114 #endif
115 #if !ENABLE(WEB_SOCKETS)
116     UNUSED_PARAM(socketProvider);
117 #endif
118
119     std::lock_guard<StaticLock> lock(threadSetMutex);
120
121     workerThreads().add(this);
122 }
123
124 WorkerThread::~WorkerThread()
125 {
126     std::lock_guard<StaticLock> lock(threadSetMutex);
127
128     ASSERT(workerThreads().contains(this));
129     workerThreads().remove(this);
130 }
131
132 bool WorkerThread::start()
133 {
134     // Mutex protection is necessary to ensure that m_threadID is initialized when the thread starts.
135     LockHolder lock(m_threadCreationMutex);
136
137     if (m_threadID)
138         return true;
139
140     m_threadID = createThread(WorkerThread::workerThreadStart, this, "WebCore: Worker");
141
142     return m_threadID;
143 }
144
145 void WorkerThread::workerThreadStart(void* thread)
146 {
147     static_cast<WorkerThread*>(thread)->workerThread();
148 }
149
150 void WorkerThread::workerThread()
151 {
152     // Propagate the mainThread's fenv to workers.
153 #if PLATFORM(IOS)
154     FloatingPointEnvironment::singleton().propagateMainThreadEnvironment();
155 #endif
156
157 #if PLATFORM(GTK)
158     GRefPtr<GMainContext> mainContext = adoptGRef(g_main_context_new());
159     g_main_context_push_thread_default(mainContext.get());
160 #endif
161
162     {
163         LockHolder lock(m_threadCreationMutex);
164         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));
165
166         if (m_runLoop.terminated()) {
167             // The worker was terminated before the thread had a chance to run. Since the context didn't exist yet,
168             // forbidExecution() couldn't be called from stop().
169             m_workerGlobalScope->script()->forbidExecution();
170         }
171     }
172
173     if (m_startupData->m_startMode == WorkerThreadStartMode::WaitForInspector) {
174         startRunningDebuggerTasks();
175
176         // If the worker was somehow terminated while processing debugger commands.
177         if (m_runLoop.terminated())
178             m_workerGlobalScope->script()->forbidExecution();
179     }
180
181     WorkerScriptController* script = m_workerGlobalScope->script();
182     script->evaluate(ScriptSourceCode(m_startupData->m_sourceCode, m_startupData->m_scriptURL));
183     // Free the startup data to cause its member variable deref's happen on the worker's thread (since
184     // all ref/derefs of these objects are happening on the thread at this point). Note that
185     // WorkerThread::~WorkerThread happens on a different thread where it was created.
186     m_startupData = nullptr;
187
188     runEventLoop();
189
190 #if PLATFORM(GTK)
191     g_main_context_pop_thread_default(mainContext.get());
192 #endif
193
194     ThreadIdentifier threadID = m_threadID;
195
196     ASSERT(m_workerGlobalScope->hasOneRef());
197
198     // The below assignment will destroy the context, which will in turn notify messaging proxy.
199     // We cannot let any objects survive past thread exit, because no other thread will run GC or otherwise destroy them.
200     m_workerGlobalScope = nullptr;
201
202     // Clean up WebCore::ThreadGlobalData before WTF::WTFThreadData goes away!
203     threadGlobalData().destroy();
204
205     // The thread object may be already destroyed from notification now, don't try to access "this".
206     detachThread(threadID);
207 }
208
209 void WorkerThread::startRunningDebuggerTasks()
210 {
211     ASSERT(!m_pausedForDebugger);
212     m_pausedForDebugger = true;
213
214     MessageQueueWaitResult result;
215     do {
216         result = m_runLoop.runInMode(m_workerGlobalScope.get(), WorkerRunLoop::debuggerMode());
217     } while (result != MessageQueueTerminated && m_pausedForDebugger);
218 }
219
220 void WorkerThread::stopRunningDebuggerTasks()
221 {
222     m_pausedForDebugger = false;
223 }
224
225 void WorkerThread::runEventLoop()
226 {
227     // Does not return until terminated.
228     m_runLoop.run(m_workerGlobalScope.get());
229 }
230
231 void WorkerThread::stop()
232 {
233     // Mutex protection is necessary because stop() can be called before the context is fully created.
234     LockHolder lock(m_threadCreationMutex);
235
236     // 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.
237     if (m_workerGlobalScope) {
238         m_workerGlobalScope->script()->scheduleExecutionTermination();
239
240         m_runLoop.postTaskAndTerminate({ ScriptExecutionContext::Task::CleanupTask, [] (ScriptExecutionContext& context ) {
241             WorkerGlobalScope& workerGlobalScope = downcast<WorkerGlobalScope>(context);
242
243 #if ENABLE(INDEXED_DATABASE)
244             workerGlobalScope.stopIndexedDatabase();
245 #endif
246
247             workerGlobalScope.stopActiveDOMObjects();
248
249             workerGlobalScope.inspectorController().workerTerminating();
250
251             // Event listeners would keep DOMWrapperWorld objects alive for too long. Also, they have references to JS objects,
252             // which become dangling once Heap is destroyed.
253             workerGlobalScope.removeAllEventListeners();
254
255             // Stick a shutdown command at the end of the queue, so that we deal
256             // with all the cleanup tasks the databases post first.
257             workerGlobalScope.postTask({ ScriptExecutionContext::Task::CleanupTask, [] (ScriptExecutionContext& context) {
258                 WorkerGlobalScope& workerGlobalScope = downcast<WorkerGlobalScope>(context);
259                 // It's not safe to call clearScript until all the cleanup tasks posted by functions initiated by WorkerThreadShutdownStartTask have completed.
260                 workerGlobalScope.clearScript();
261             } });
262
263         } });
264         return;
265     }
266     m_runLoop.terminate();
267 }
268
269 void WorkerThread::releaseFastMallocFreeMemoryInAllThreads()
270 {
271     std::lock_guard<StaticLock> lock(threadSetMutex);
272
273     for (auto* workerThread : workerThreads()) {
274         workerThread->runLoop().postTask([] (ScriptExecutionContext&) {
275             WTF::releaseFastMallocFreeMemory();
276         });
277     }
278 }
279
280 IDBClient::IDBConnectionProxy* WorkerThread::idbConnectionProxy()
281 {
282 #if ENABLE(INDEXED_DATABASE)
283     return m_idbConnectionProxy.get();
284 #else
285     return nullptr;
286 #endif
287 }
288
289 SocketProvider* WorkerThread::socketProvider()
290 {
291 #if ENABLE(WEB_SOCKETS)
292     return m_socketProvider.get();
293 #else
294     return nullptr;
295 #endif
296 }
297
298 } // namespace WebCore