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