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 "DatabaseTask.h"
34 #include "DedicatedWorkerContext.h"
35 #include "KURL.h"
36 #include "PlatformString.h"
37 #include "ScriptSourceCode.h"
38 #include "ScriptValue.h"
39
40 #include <utility>
41 #include <wtf/Noncopyable.h>
42
43 namespace WebCore {
44
threadCountMutex()45 static Mutex& threadCountMutex()
46 {
47 AtomicallyInitializedStatic(Mutex&, mutex = *new Mutex);
48 return mutex;
49 }
50
51 unsigned WorkerThread::m_threadCount = 0;
52
workerThreadCount()53 unsigned WorkerThread::workerThreadCount()
54 {
55 MutexLocker lock(threadCountMutex());
56 return m_threadCount;
57 }
58
59 struct WorkerThreadStartupData : Noncopyable {
60 public:
createWebCore::WorkerThreadStartupData61 static std::auto_ptr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode)
62 {
63 return std::auto_ptr<WorkerThreadStartupData>(new WorkerThreadStartupData(scriptURL, userAgent, sourceCode));
64 }
65
66 KURL m_scriptURL;
67 String m_userAgent;
68 String m_sourceCode;
69 private:
70 WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode);
71 };
72
WorkerThreadStartupData(const KURL & scriptURL,const String & userAgent,const String & sourceCode)73 WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode)
74 : m_scriptURL(scriptURL.copy())
75 , m_userAgent(userAgent.crossThreadString())
76 , m_sourceCode(sourceCode.crossThreadString())
77 {
78 }
79
WorkerThread(const KURL & scriptURL,const String & userAgent,const String & sourceCode,WorkerLoaderProxy & workerLoaderProxy,WorkerReportingProxy & workerReportingProxy)80 WorkerThread::WorkerThread(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy)
81 : m_threadID(0)
82 , m_workerLoaderProxy(workerLoaderProxy)
83 , m_workerReportingProxy(workerReportingProxy)
84 , m_startupData(WorkerThreadStartupData::create(scriptURL, userAgent, sourceCode))
85 {
86 MutexLocker lock(threadCountMutex());
87 m_threadCount++;
88 }
89
~WorkerThread()90 WorkerThread::~WorkerThread()
91 {
92 MutexLocker lock(threadCountMutex());
93 ASSERT(m_threadCount > 0);
94 m_threadCount--;
95 }
96
start()97 bool WorkerThread::start()
98 {
99 // Mutex protection is necessary to ensure that m_threadID is initialized when the thread starts.
100 MutexLocker lock(m_threadCreationMutex);
101
102 if (m_threadID)
103 return true;
104
105 m_threadID = createThread(WorkerThread::workerThreadStart, this, "WebCore: Worker");
106
107 return m_threadID;
108 }
109
workerThreadStart(void * thread)110 void* WorkerThread::workerThreadStart(void* thread)
111 {
112 return static_cast<WorkerThread*>(thread)->workerThread();
113 }
114
workerThread()115 void* WorkerThread::workerThread()
116 {
117 {
118 MutexLocker lock(m_threadCreationMutex);
119 m_workerContext = createWorkerContext(m_startupData->m_scriptURL, m_startupData->m_userAgent);
120
121 if (m_runLoop.terminated()) {
122 // The worker was terminated before the thread had a chance to run. Since the context didn't exist yet,
123 // forbidExecution() couldn't be called from stop().
124 m_workerContext->script()->forbidExecution();
125 }
126 }
127
128 WorkerScriptController* script = m_workerContext->script();
129 script->evaluate(ScriptSourceCode(m_startupData->m_sourceCode, m_startupData->m_scriptURL));
130 // Free the startup data to cause its member variable deref's happen on the worker's thread (since
131 // all ref/derefs of these objects are happening on the thread at this point). Note that
132 // WorkerThread::~WorkerThread happens on a different thread where it was created.
133 m_startupData.clear();
134
135 runEventLoop();
136
137 ThreadIdentifier threadID = m_threadID;
138
139 ASSERT(m_workerContext->hasOneRef());
140
141 // The below assignment will destroy the context, which will in turn notify messaging proxy.
142 // We cannot let any objects survive past thread exit, because no other thread will run GC or otherwise destroy them.
143 m_workerContext = 0;
144
145 // The thread object may be already destroyed from notification now, don't try to access "this".
146 detachThread(threadID);
147
148 return 0;
149 }
150
runEventLoop()151 void WorkerThread::runEventLoop()
152 {
153 // Does not return until terminated.
154 m_runLoop.run(m_workerContext.get());
155 }
156
157 class WorkerThreadShutdownFinishTask : public ScriptExecutionContext::Task {
158 public:
create()159 static PassOwnPtr<WorkerThreadShutdownFinishTask> create()
160 {
161 return new WorkerThreadShutdownFinishTask();
162 }
163
performTask(ScriptExecutionContext * context)164 virtual void performTask(ScriptExecutionContext *context)
165 {
166 ASSERT(context->isWorkerContext());
167 WorkerContext* workerContext = static_cast<WorkerContext*>(context);
168 workerContext->thread()->runLoop().terminate();
169 }
170
isCleanupTask() const171 virtual bool isCleanupTask() const { return true; }
172 };
173
174 class WorkerThreadShutdownStartTask : public ScriptExecutionContext::Task {
175 public:
create()176 static PassOwnPtr<WorkerThreadShutdownStartTask> create()
177 {
178 return new WorkerThreadShutdownStartTask();
179 }
180
performTask(ScriptExecutionContext * context)181 virtual void performTask(ScriptExecutionContext *context)
182 {
183 ASSERT(context->isWorkerContext());
184 WorkerContext* workerContext = static_cast<WorkerContext*>(context);
185
186 // We currently ignore any DatabasePolicy used for the document's
187 // databases; if it's actually used anywhere, this should be revisited.
188 DatabaseTaskSynchronizer cleanupSync;
189 workerContext->stopDatabases(&cleanupSync);
190
191 workerContext->stopActiveDOMObjects();
192 workerContext->clearScript();
193
194 // We wait for the database thread to clean up all its stuff so that we
195 // can do more stringent leak checks as we exit.
196 cleanupSync.waitForTaskCompletion();
197
198 // Stick a shutdown command at the end of the queue, so that we deal
199 // with all the cleanup tasks the databases post first.
200 workerContext->postTask(WorkerThreadShutdownFinishTask::create());
201 }
202
isCleanupTask() const203 virtual bool isCleanupTask() const { return true; }
204 };
205
stop()206 void WorkerThread::stop()
207 {
208 // Mutex protection is necessary because stop() can be called before the context is fully created.
209 MutexLocker lock(m_threadCreationMutex);
210
211 // 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.
212 if (m_workerContext) {
213 m_workerContext->script()->forbidExecution();
214
215 // FIXME: Rudely killing the thread won't work when we allow nested workers, because they will try to post notifications of their destruction.
216 // This can likely use the same mechanism as used for databases above.
217
218 m_runLoop.postTask(WorkerThreadShutdownStartTask::create());
219 } else
220 m_runLoop.terminate();
221 }
222
223 } // namespace WebCore
224
225 #endif // ENABLE(WORKERS)
226