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