Rename NotificationPresenter to NotificationClient
[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 COMPUTER, 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 COMPUTER, 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
29 #if ENABLE(WORKERS)
30
31 #include "WorkerThread.h"
32
33 #include "DatabaseContext.h"
34 #include "DedicatedWorkerContext.h"
35 #include "InspectorInstrumentation.h"
36 #include "KURL.h"
37 #include "PlatformString.h"
38 #include "ScriptSourceCode.h"
39 #include "ScriptValue.h"
40 #include "ThreadGlobalData.h"
41
42 #include <utility>
43 #include <wtf/Noncopyable.h>
44
45 #if ENABLE(SQL_DATABASE)
46 #include "DatabaseTask.h"
47 #include "DatabaseTracker.h"
48 #endif
49
50 namespace WebCore {
51
52 static Mutex& threadCountMutex()
53 {
54     AtomicallyInitializedStatic(Mutex&, mutex = *new Mutex);
55     return mutex;
56 }
57
58 unsigned WorkerThread::m_threadCount = 0;
59
60 unsigned WorkerThread::workerThreadCount()
61 {
62     MutexLocker lock(threadCountMutex());
63     return m_threadCount;
64 }
65
66 struct WorkerThreadStartupData {
67     WTF_MAKE_NONCOPYABLE(WorkerThreadStartupData); WTF_MAKE_FAST_ALLOCATED;
68 public:
69     static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
70     {
71         return adoptPtr(new WorkerThreadStartupData(scriptURL, userAgent, sourceCode, startMode, contentSecurityPolicy, contentSecurityPolicyType));
72     }
73
74     KURL m_scriptURL;
75     String m_userAgent;
76     String m_sourceCode;
77     WorkerThreadStartMode m_startMode;
78     String m_contentSecurityPolicy;
79     ContentSecurityPolicy::HeaderType m_contentSecurityPolicyType;
80 private:
81     WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType);
82 };
83
84 WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
85     : m_scriptURL(scriptURL.copy())
86     , m_userAgent(userAgent.isolatedCopy())
87     , m_sourceCode(sourceCode.isolatedCopy())
88     , m_startMode(startMode)
89     , m_contentSecurityPolicy(contentSecurityPolicy.isolatedCopy())
90     , m_contentSecurityPolicyType(contentSecurityPolicyType)
91 {
92 }
93
94 WorkerThread::WorkerThread(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
95     : m_threadID(0)
96     , m_workerLoaderProxy(workerLoaderProxy)
97     , m_workerReportingProxy(workerReportingProxy)
98     , m_startupData(WorkerThreadStartupData::create(scriptURL, userAgent, sourceCode, startMode, contentSecurityPolicy, contentSecurityPolicyType))
99 #if ENABLE(NOTIFICATIONS)
100     , m_notificationClient(0)
101 #endif
102 {
103     MutexLocker lock(threadCountMutex());
104     m_threadCount++;
105 }
106
107 WorkerThread::~WorkerThread()
108 {
109     MutexLocker lock(threadCountMutex());
110     ASSERT(m_threadCount > 0);
111     m_threadCount--;
112 }
113
114 bool WorkerThread::start()
115 {
116     // Mutex protection is necessary to ensure that m_threadID is initialized when the thread starts.
117     MutexLocker lock(m_threadCreationMutex);
118
119     if (m_threadID)
120         return true;
121
122     m_threadID = createThread(WorkerThread::workerThreadStart, this, "WebCore: Worker");
123
124     return m_threadID;
125 }
126
127 void WorkerThread::workerThreadStart(void* thread)
128 {
129     static_cast<WorkerThread*>(thread)->workerThread();
130 }
131
132 void WorkerThread::workerThread()
133 {
134     {
135         MutexLocker lock(m_threadCreationMutex);
136         m_workerContext = createWorkerContext(m_startupData->m_scriptURL, m_startupData->m_userAgent, m_startupData->m_contentSecurityPolicy, m_startupData->m_contentSecurityPolicyType);
137
138         if (m_runLoop.terminated()) {
139             // The worker was terminated before the thread had a chance to run. Since the context didn't exist yet,
140             // forbidExecution() couldn't be called from stop().
141            m_workerContext->script()->forbidExecution();
142         }
143     }
144 #if PLATFORM(CHROMIUM)
145     PlatformSupport::didStartWorkerRunLoop(&m_runLoop);
146 #endif
147
148     WorkerScriptController* script = m_workerContext->script();
149 #if ENABLE(INSPECTOR)
150     InspectorInstrumentation::willEvaluateWorkerScript(workerContext(), m_startupData->m_startMode);
151 #endif
152     script->evaluate(ScriptSourceCode(m_startupData->m_sourceCode, m_startupData->m_scriptURL));
153     // Free the startup data to cause its member variable deref's happen on the worker's thread (since
154     // all ref/derefs of these objects are happening on the thread at this point). Note that
155     // WorkerThread::~WorkerThread happens on a different thread where it was created.
156     m_startupData.clear();
157
158     runEventLoop();
159
160 #if PLATFORM(CHROMIUM)
161     PlatformSupport::didStopWorkerRunLoop(&m_runLoop);
162 #endif
163
164     ThreadIdentifier threadID = m_threadID;
165
166     ASSERT(m_workerContext->hasOneRef());
167
168     // The below assignment will destroy the context, which will in turn notify messaging proxy.
169     // We cannot let any objects survive past thread exit, because no other thread will run GC or otherwise destroy them.
170     m_workerContext = 0;
171
172     // Clean up WebCore::ThreadGlobalData before WTF::WTFThreadData goes away!
173     threadGlobalData().destroy();
174
175     // The thread object may be already destroyed from notification now, don't try to access "this".
176     detachThread(threadID);
177 }
178
179 void WorkerThread::runEventLoop()
180 {
181     // Does not return until terminated.
182     m_runLoop.run(m_workerContext.get());
183 }
184
185 class WorkerThreadShutdownFinishTask : public ScriptExecutionContext::Task {
186 public:
187     static PassOwnPtr<WorkerThreadShutdownFinishTask> create()
188     {
189         return adoptPtr(new WorkerThreadShutdownFinishTask());
190     }
191
192     virtual void performTask(ScriptExecutionContext *context)
193     {
194         ASSERT(context->isWorkerContext());
195         WorkerContext* workerContext = static_cast<WorkerContext*>(context);
196 #if ENABLE(INSPECTOR)
197         workerContext->clearInspector();
198 #endif
199         // It's not safe to call clearScript until all the cleanup tasks posted by functions initiated by WorkerThreadShutdownStartTask have completed.
200         workerContext->clearScript();
201     }
202
203     virtual bool isCleanupTask() const { return true; }
204 };
205
206 class WorkerThreadShutdownStartTask : public ScriptExecutionContext::Task {
207 public:
208     static PassOwnPtr<WorkerThreadShutdownStartTask> create()
209     {
210         return adoptPtr(new WorkerThreadShutdownStartTask());
211     }
212
213     virtual void performTask(ScriptExecutionContext *context)
214     {
215         ASSERT(context->isWorkerContext());
216         WorkerContext* workerContext = static_cast<WorkerContext*>(context);
217
218 #if ENABLE(SQL_DATABASE)
219         // FIXME: Should we stop the databases as part of stopActiveDOMObjects() below?
220         DatabaseTaskSynchronizer cleanupSync;
221         DatabaseContext::stopDatabases(workerContext, &cleanupSync);
222 #endif
223
224         workerContext->stopActiveDOMObjects();
225
226         workerContext->notifyObserversOfStop();
227
228         // Event listeners would keep DOMWrapperWorld objects alive for too long. Also, they have references to JS objects,
229         // which become dangling once Heap is destroyed.
230         workerContext->removeAllEventListeners();
231
232 #if ENABLE(SQL_DATABASE)
233         // We wait for the database thread to clean up all its stuff so that we
234         // can do more stringent leak checks as we exit.
235         cleanupSync.waitForTaskCompletion();
236 #endif
237
238         // Stick a shutdown command at the end of the queue, so that we deal
239         // with all the cleanup tasks the databases post first.
240         workerContext->postTask(WorkerThreadShutdownFinishTask::create());
241     }
242
243     virtual bool isCleanupTask() const { return true; }
244 };
245
246 void WorkerThread::stop()
247 {
248     // Mutex protection is necessary because stop() can be called before the context is fully created.
249     MutexLocker lock(m_threadCreationMutex);
250
251     // 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.
252     if (m_workerContext) {
253         m_workerContext->script()->scheduleExecutionTermination();
254
255 #if ENABLE(SQL_DATABASE)
256         DatabaseTracker::tracker().interruptAllDatabasesForContext(m_workerContext.get());
257 #endif
258         m_runLoop.postTask(WorkerThreadShutdownStartTask::create());
259     }
260     m_runLoop.terminate();
261 }
262
263 } // namespace WebCore
264
265 #endif // ENABLE(WORKERS)