2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #if ENABLE(SHARED_WORKERS)
35 #include "DefaultSharedWorkerRepository.h"
37 #include "ActiveDOMObject.h"
38 #include "CrossThreadTask.h"
40 #include "ExceptionCode.h"
41 #include "InspectorInstrumentation.h"
42 #include "MessageEvent.h"
43 #include "MessagePort.h"
44 #include "NotImplemented.h"
45 #include "PlatformString.h"
46 #include "ScriptCallStack.h"
47 #include "SecurityOrigin.h"
48 #include "SecurityOriginHash.h"
49 #include "SharedWorker.h"
50 #include "SharedWorkerContext.h"
51 #include "SharedWorkerRepository.h"
52 #include "SharedWorkerThread.h"
53 #include "WorkerLoaderProxy.h"
54 #include "WorkerReportingProxy.h"
55 #include "WorkerScriptLoader.h"
56 #include "WorkerScriptLoaderClient.h"
57 #include <wtf/HashSet.h>
58 #include <wtf/Threading.h>
62 class SharedWorkerProxy : public ThreadSafeRefCounted<SharedWorkerProxy>, public WorkerLoaderProxy, public WorkerReportingProxy {
64 static PassRefPtr<SharedWorkerProxy> create(const String& name, const KURL& url, PassRefPtr<SecurityOrigin> origin) { return adoptRef(new SharedWorkerProxy(name, url, origin)); }
66 void setThread(PassRefPtr<SharedWorkerThread> thread) { m_thread = thread; }
67 SharedWorkerThread* thread() { return m_thread.get(); }
68 bool isClosing() const { return m_closing; }
71 // Don't use m_url.copy() because it isn't a threadsafe method.
72 return KURL(ParsedURLString, m_url.string().isolatedCopy());
75 String name() const { return m_name.isolatedCopy(); }
76 bool matches(const String& name, PassRefPtr<SecurityOrigin> origin, const KURL& urlToMatch) const;
79 virtual void postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task>);
80 virtual void postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task>, const String&);
82 // WorkerReportingProxy
83 virtual void postExceptionToWorkerObject(const String& errorMessage, int lineNumber, const String& sourceURL);
84 virtual void postConsoleMessageToWorkerObject(MessageSource, MessageType, MessageLevel, const String& message, int lineNumber, const String& sourceURL);
86 virtual void postMessageToPageInspector(const String&);
87 virtual void updateInspectorStateCookie(const String&);
89 virtual void workerContextClosed();
90 virtual void workerContextDestroyed();
92 // Updates the list of the worker's documents, per section 4.5 of the WebWorkers spec.
93 void addToWorkerDocuments(ScriptExecutionContext*);
95 bool isInWorkerDocuments(Document* document) { return m_workerDocuments.contains(document); }
97 // Removes a detached document from the list of worker's documents. May set the closing flag if this is the last document in the list.
98 void documentDetached(Document*);
101 SharedWorkerProxy(const String& name, const KURL&, PassRefPtr<SecurityOrigin>);
107 // The thread is freed when the proxy is destroyed, so we need to make sure that the proxy stays around until the SharedWorkerContext exits.
108 RefPtr<SharedWorkerThread> m_thread;
109 RefPtr<SecurityOrigin> m_origin;
110 HashSet<Document*> m_workerDocuments;
111 // Ensures exclusive access to the worker documents. Must not grab any other locks (such as the DefaultSharedWorkerRepository lock) while holding this one.
112 Mutex m_workerDocumentsLock;
115 SharedWorkerProxy::SharedWorkerProxy(const String& name, const KURL& url, PassRefPtr<SecurityOrigin> origin)
117 , m_name(name.isolatedCopy())
121 // We should be the sole owner of the SecurityOrigin, as we will free it on another thread.
122 ASSERT(m_origin->hasOneRef());
125 bool SharedWorkerProxy::matches(const String& name, PassRefPtr<SecurityOrigin> origin, const KURL& urlToMatch) const
127 // If the origins don't match, or the names don't match, then this is not the proxy we are looking for.
128 if (!origin->equal(m_origin.get()))
131 // If the names are both empty, compares the URLs instead per the Web Workers spec.
132 if (name.isEmpty() && m_name.isEmpty())
133 return urlToMatch == url();
135 return name == m_name;
138 void SharedWorkerProxy::postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task> task)
140 MutexLocker lock(m_workerDocumentsLock);
145 // If we aren't closing, then we must have at least one document.
146 ASSERT(m_workerDocuments.size());
148 // Just pick an arbitrary active document from the HashSet and pass load requests to it.
149 // FIXME: Do we need to deal with the case where the user closes the document mid-load, via a shadow document or some other solution?
150 Document* document = *(m_workerDocuments.begin());
151 document->postTask(task);
154 void SharedWorkerProxy::postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
159 m_thread->runLoop().postTaskForMode(task, mode);
162 static void postExceptionTask(ScriptExecutionContext* context, const String& errorMessage, int lineNumber, const String& sourceURL)
164 context->reportException(errorMessage, lineNumber, sourceURL, 0);
167 void SharedWorkerProxy::postExceptionToWorkerObject(const String& errorMessage, int lineNumber, const String& sourceURL)
169 MutexLocker lock(m_workerDocumentsLock);
170 for (HashSet<Document*>::iterator iter = m_workerDocuments.begin(); iter != m_workerDocuments.end(); ++iter)
171 (*iter)->postTask(createCallbackTask(&postExceptionTask, errorMessage, lineNumber, sourceURL));
174 static void postConsoleMessageTask(ScriptExecutionContext* document, MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL)
176 document->addMessage(source, type, level, message, lineNumber, sourceURL, 0);
179 void SharedWorkerProxy::postConsoleMessageToWorkerObject(MessageSource source, MessageType type, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
181 MutexLocker lock(m_workerDocumentsLock);
182 for (HashSet<Document*>::iterator iter = m_workerDocuments.begin(); iter != m_workerDocuments.end(); ++iter)
183 (*iter)->postTask(createCallbackTask(&postConsoleMessageTask, source, type, level, message, lineNumber, sourceURL));
186 #if ENABLE(INSPECTOR)
187 void SharedWorkerProxy::postMessageToPageInspector(const String&)
192 void SharedWorkerProxy::updateInspectorStateCookie(const String&)
198 void SharedWorkerProxy::workerContextClosed()
205 void SharedWorkerProxy::workerContextDestroyed()
207 // The proxy may be freed by this call, so do not reference it any further.
208 DefaultSharedWorkerRepository::instance().removeProxy(this);
211 void SharedWorkerProxy::addToWorkerDocuments(ScriptExecutionContext* context)
213 // Nested workers are not yet supported, so passed-in context should always be a Document.
214 ASSERT(context->isDocument());
215 ASSERT(!isClosing());
216 MutexLocker lock(m_workerDocumentsLock);
217 Document* document = static_cast<Document*>(context);
218 m_workerDocuments.add(document);
221 void SharedWorkerProxy::documentDetached(Document* document)
225 // Remove the document from our set (if it's there) and if that was the last document in the set, mark the proxy as closed.
226 MutexLocker lock(m_workerDocumentsLock);
227 m_workerDocuments.remove(document);
228 if (!m_workerDocuments.size())
232 void SharedWorkerProxy::close()
234 ASSERT(!isClosing());
236 // Stop the worker thread - the proxy will stay around until we get workerThreadExited() notification.
241 class SharedWorkerConnectTask : public ScriptExecutionContext::Task {
243 static PassOwnPtr<SharedWorkerConnectTask> create(PassOwnPtr<MessagePortChannel> channel)
245 return adoptPtr(new SharedWorkerConnectTask(channel));
249 SharedWorkerConnectTask(PassOwnPtr<MessagePortChannel> channel)
254 virtual void performTask(ScriptExecutionContext* scriptContext)
256 RefPtr<MessagePort> port = MessagePort::create(*scriptContext);
257 port->entangle(m_channel.release());
258 ASSERT(scriptContext->isWorkerContext());
259 WorkerContext* workerContext = static_cast<WorkerContext*>(scriptContext);
260 // Since close() stops the thread event loop, this should not ever get called while closing.
261 ASSERT(!workerContext->isClosing());
262 ASSERT(workerContext->isSharedWorkerContext());
263 workerContext->dispatchEvent(createConnectEvent(port));
266 OwnPtr<MessagePortChannel> m_channel;
269 // Loads the script on behalf of a worker.
270 class SharedWorkerScriptLoader : public RefCounted<SharedWorkerScriptLoader>, private WorkerScriptLoaderClient {
272 SharedWorkerScriptLoader(PassRefPtr<SharedWorker>, PassOwnPtr<MessagePortChannel>, PassRefPtr<SharedWorkerProxy>);
273 void load(const KURL&);
276 // WorkerScriptLoaderClient callbacks
277 virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&);
278 virtual void notifyFinished();
280 RefPtr<SharedWorker> m_worker;
281 OwnPtr<MessagePortChannel> m_port;
282 RefPtr<SharedWorkerProxy> m_proxy;
283 RefPtr<WorkerScriptLoader> m_scriptLoader;
286 SharedWorkerScriptLoader::SharedWorkerScriptLoader(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, PassRefPtr<SharedWorkerProxy> proxy)
293 void SharedWorkerScriptLoader::load(const KURL& url)
295 // Stay alive (and keep the SharedWorker and JS wrapper alive) until the load finishes.
297 m_worker->setPendingActivity(m_worker.get());
299 // Mark this object as active for the duration of the load.
300 m_scriptLoader = WorkerScriptLoader::create();
301 #if PLATFORM(CHROMIUM)
302 m_scriptLoader->setTargetType(ResourceRequest::TargetIsSharedWorker);
304 m_scriptLoader->loadAsynchronously(m_worker->scriptExecutionContext(), url, DenyCrossOriginRequests, this);
307 void SharedWorkerScriptLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse&)
309 InspectorInstrumentation::didReceiveScriptResponse(m_worker->scriptExecutionContext(), identifier);
312 void SharedWorkerScriptLoader::notifyFinished()
314 // FIXME: This method is not guaranteed to be invoked if we are loading from WorkerContext (see comment for WorkerScriptLoaderClient::notifyFinished()).
315 // We need to address this before supporting nested workers.
317 // Hand off the just-loaded code to the repository to start up the worker thread.
318 if (m_scriptLoader->failed())
319 m_worker->dispatchEvent(Event::create(eventNames().errorEvent, false, true));
321 InspectorInstrumentation::scriptImported(m_worker->scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
322 DefaultSharedWorkerRepository::instance().workerScriptLoaded(*m_proxy, m_worker->scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), m_port.release());
324 m_worker->unsetPendingActivity(m_worker.get());
325 this->deref(); // This frees this object - must be the last action in this function.
328 DefaultSharedWorkerRepository& DefaultSharedWorkerRepository::instance()
330 AtomicallyInitializedStatic(DefaultSharedWorkerRepository*, instance = new DefaultSharedWorkerRepository);
334 void DefaultSharedWorkerRepository::workerScriptLoaded(SharedWorkerProxy& proxy, const String& userAgent, const String& workerScript, PassOwnPtr<MessagePortChannel> port)
336 MutexLocker lock(m_lock);
337 if (proxy.isClosing())
340 // Another loader may have already started up a thread for this proxy - if so, just send a connect to the pre-existing thread.
341 if (!proxy.thread()) {
342 RefPtr<SharedWorkerThread> thread = SharedWorkerThread::create(proxy.name(), proxy.url(), userAgent, workerScript, proxy, proxy, DontPauseWorkerContextOnStart);
343 proxy.setThread(thread);
346 proxy.thread()->runLoop().postTask(SharedWorkerConnectTask::create(port));
349 bool SharedWorkerRepository::isAvailable()
351 // SharedWorkers are enabled on the default WebKit platform.
355 void SharedWorkerRepository::connect(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
357 DefaultSharedWorkerRepository::instance().connectToWorker(worker, port, url, name, ec);
360 void SharedWorkerRepository::documentDetached(Document* document)
362 DefaultSharedWorkerRepository::instance().documentDetached(document);
365 bool SharedWorkerRepository::hasSharedWorkers(Document* document)
367 return DefaultSharedWorkerRepository::instance().hasSharedWorkers(document);
370 bool DefaultSharedWorkerRepository::hasSharedWorkers(Document* document)
372 MutexLocker lock(m_lock);
373 for (unsigned i = 0; i < m_proxies.size(); i++) {
374 if (m_proxies[i]->isInWorkerDocuments(document))
380 void DefaultSharedWorkerRepository::removeProxy(SharedWorkerProxy* proxy)
382 MutexLocker lock(m_lock);
383 for (unsigned i = 0; i < m_proxies.size(); i++) {
384 if (proxy == m_proxies[i].get()) {
391 void DefaultSharedWorkerRepository::documentDetached(Document* document)
393 MutexLocker lock(m_lock);
394 for (unsigned i = 0; i < m_proxies.size(); i++)
395 m_proxies[i]->documentDetached(document);
398 void DefaultSharedWorkerRepository::connectToWorker(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
400 MutexLocker lock(m_lock);
401 ASSERT(worker->scriptExecutionContext()->securityOrigin()->canAccess(SecurityOrigin::create(url).get()));
402 // Fetch a proxy corresponding to this SharedWorker.
403 RefPtr<SharedWorkerProxy> proxy = getProxy(name, url);
404 proxy->addToWorkerDocuments(worker->scriptExecutionContext());
405 if (proxy->url() != url) {
406 // Proxy already existed under alternate URL - return an error.
407 ec = URL_MISMATCH_ERR;
410 // If proxy is already running, just connect to it - otherwise, kick off a loader to load the script.
412 proxy->thread()->runLoop().postTask(SharedWorkerConnectTask::create(port));
414 RefPtr<SharedWorkerScriptLoader> loader = adoptRef(new SharedWorkerScriptLoader(worker, port, proxy.release()));
419 // Creates a new SharedWorkerProxy or returns an existing one from the repository. Must only be called while the repository mutex is held.
420 PassRefPtr<SharedWorkerProxy> DefaultSharedWorkerRepository::getProxy(const String& name, const KURL& url)
422 // Look for an existing worker, and create one if it doesn't exist.
423 // Items in the cache are freed on another thread, so do a threadsafe copy of the URL before creating the origin,
424 // to make sure no references to external strings linger.
425 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(KURL(ParsedURLString, url.string().isolatedCopy()));
426 for (unsigned i = 0; i < m_proxies.size(); i++) {
427 if (!m_proxies[i]->isClosing() && m_proxies[i]->matches(name, origin, url))
430 // Proxy is not in the repository currently - create a new one.
431 RefPtr<SharedWorkerProxy> proxy = SharedWorkerProxy::create(name, url, origin.release());
432 m_proxies.append(proxy);
433 return proxy.release();
436 DefaultSharedWorkerRepository::DefaultSharedWorkerRepository()
440 DefaultSharedWorkerRepository::~DefaultSharedWorkerRepository()
444 } // namespace WebCore
446 #endif // ENABLE(SHARED_WORKERS)