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 "InspectorInstrumentation.h"
41 #include "MessageEvent.h"
42 #include "MessagePort.h"
43 #include "NotImplemented.h"
44 #include "PlatformString.h"
45 #include "ScriptCallStack.h"
46 #include "SecurityOrigin.h"
47 #include "SecurityOriginHash.h"
48 #include "SharedWorker.h"
49 #include "SharedWorkerContext.h"
50 #include "SharedWorkerRepository.h"
51 #include "SharedWorkerThread.h"
52 #include "WorkerLoaderProxy.h"
53 #include "WorkerReportingProxy.h"
54 #include "WorkerScriptLoader.h"
55 #include "WorkerScriptLoaderClient.h"
56 #include <wtf/HashSet.h>
57 #include <wtf/Threading.h>
61 class SharedWorkerProxy : public ThreadSafeRefCounted<SharedWorkerProxy>, public WorkerLoaderProxy, public WorkerReportingProxy {
63 static PassRefPtr<SharedWorkerProxy> create(const String& name, const KURL& url, PassRefPtr<SecurityOrigin> origin) { return adoptRef(new SharedWorkerProxy(name, url, origin)); }
65 void setThread(PassRefPtr<SharedWorkerThread> thread) { m_thread = thread; }
66 SharedWorkerThread* thread() { return m_thread.get(); }
67 bool isClosing() const { return m_closing; }
70 // Don't use m_url.copy() because it isn't a threadsafe method.
71 return KURL(ParsedURLString, m_url.string().threadsafeCopy());
74 String name() const { return m_name.threadsafeCopy(); }
75 bool matches(const String& name, PassRefPtr<SecurityOrigin> origin, const KURL& urlToMatch) const;
78 virtual void postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task>);
79 virtual void postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task>, const String&);
81 // WorkerReportingProxy
82 virtual void postExceptionToWorkerObject(const String& errorMessage, int lineNumber, const String& sourceURL);
83 virtual void postConsoleMessageToWorkerObject(MessageSource, MessageType, MessageLevel, const String& message, int lineNumber, const String& sourceURL);
85 virtual void postMessageToPageInspector(const String&);
87 virtual void workerContextClosed();
88 virtual void workerContextDestroyed();
90 // Updates the list of the worker's documents, per section 4.5 of the WebWorkers spec.
91 void addToWorkerDocuments(ScriptExecutionContext*);
93 bool isInWorkerDocuments(Document* document) { return m_workerDocuments.contains(document); }
95 // 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.
96 void documentDetached(Document*);
99 SharedWorkerProxy(const String& name, const KURL&, PassRefPtr<SecurityOrigin>);
105 // The thread is freed when the proxy is destroyed, so we need to make sure that the proxy stays around until the SharedWorkerContext exits.
106 RefPtr<SharedWorkerThread> m_thread;
107 RefPtr<SecurityOrigin> m_origin;
108 HashSet<Document*> m_workerDocuments;
109 // Ensures exclusive access to the worker documents. Must not grab any other locks (such as the DefaultSharedWorkerRepository lock) while holding this one.
110 Mutex m_workerDocumentsLock;
113 SharedWorkerProxy::SharedWorkerProxy(const String& name, const KURL& url, PassRefPtr<SecurityOrigin> origin)
115 , m_name(name.crossThreadString())
119 // We should be the sole owner of the SecurityOrigin, as we will free it on another thread.
120 ASSERT(m_origin->hasOneRef());
123 bool SharedWorkerProxy::matches(const String& name, PassRefPtr<SecurityOrigin> origin, const KURL& urlToMatch) const
125 // If the origins don't match, or the names don't match, then this is not the proxy we are looking for.
126 if (!origin->equal(m_origin.get()))
129 // If the names are both empty, compares the URLs instead per the Web Workers spec.
130 if (name.isEmpty() && m_name.isEmpty())
131 return urlToMatch == url();
133 return name == m_name;
136 void SharedWorkerProxy::postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task> task)
138 MutexLocker lock(m_workerDocumentsLock);
143 // If we aren't closing, then we must have at least one document.
144 ASSERT(m_workerDocuments.size());
146 // Just pick an arbitrary active document from the HashSet and pass load requests to it.
147 // 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?
148 Document* document = *(m_workerDocuments.begin());
149 document->postTask(task);
152 void SharedWorkerProxy::postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
157 m_thread->runLoop().postTaskForMode(task, mode);
160 static void postExceptionTask(ScriptExecutionContext* context, const String& errorMessage, int lineNumber, const String& sourceURL)
162 context->reportException(errorMessage, lineNumber, sourceURL, 0);
165 void SharedWorkerProxy::postExceptionToWorkerObject(const String& errorMessage, int lineNumber, const String& sourceURL)
167 MutexLocker lock(m_workerDocumentsLock);
168 for (HashSet<Document*>::iterator iter = m_workerDocuments.begin(); iter != m_workerDocuments.end(); ++iter)
169 (*iter)->postTask(createCallbackTask(&postExceptionTask, errorMessage, lineNumber, sourceURL));
172 static void postConsoleMessageTask(ScriptExecutionContext* document, MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL)
174 document->addMessage(source, type, level, message, lineNumber, sourceURL, 0);
177 void SharedWorkerProxy::postConsoleMessageToWorkerObject(MessageSource source, MessageType type, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
179 MutexLocker lock(m_workerDocumentsLock);
180 for (HashSet<Document*>::iterator iter = m_workerDocuments.begin(); iter != m_workerDocuments.end(); ++iter)
181 (*iter)->postTask(createCallbackTask(&postConsoleMessageTask, source, type, level, message, lineNumber, sourceURL));
184 #if ENABLE(INSPECTOR)
185 void SharedWorkerProxy::postMessageToPageInspector(const String&)
190 void SharedWorkerProxy::workerContextClosed()
197 void SharedWorkerProxy::workerContextDestroyed()
199 // The proxy may be freed by this call, so do not reference it any further.
200 DefaultSharedWorkerRepository::instance().removeProxy(this);
203 void SharedWorkerProxy::addToWorkerDocuments(ScriptExecutionContext* context)
205 // Nested workers are not yet supported, so passed-in context should always be a Document.
206 ASSERT(context->isDocument());
207 ASSERT(!isClosing());
208 MutexLocker lock(m_workerDocumentsLock);
209 Document* document = static_cast<Document*>(context);
210 m_workerDocuments.add(document);
213 void SharedWorkerProxy::documentDetached(Document* document)
217 // 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.
218 MutexLocker lock(m_workerDocumentsLock);
219 m_workerDocuments.remove(document);
220 if (!m_workerDocuments.size())
224 void SharedWorkerProxy::close()
226 ASSERT(!isClosing());
228 // Stop the worker thread - the proxy will stay around until we get workerThreadExited() notification.
233 class SharedWorkerConnectTask : public ScriptExecutionContext::Task {
235 static PassOwnPtr<SharedWorkerConnectTask> create(PassOwnPtr<MessagePortChannel> channel)
237 return adoptPtr(new SharedWorkerConnectTask(channel));
241 SharedWorkerConnectTask(PassOwnPtr<MessagePortChannel> channel)
246 virtual void performTask(ScriptExecutionContext* scriptContext)
248 RefPtr<MessagePort> port = MessagePort::create(*scriptContext);
249 port->entangle(m_channel.release());
250 ASSERT(scriptContext->isWorkerContext());
251 WorkerContext* workerContext = static_cast<WorkerContext*>(scriptContext);
252 // Since close() stops the thread event loop, this should not ever get called while closing.
253 ASSERT(!workerContext->isClosing());
254 ASSERT(workerContext->isSharedWorkerContext());
255 workerContext->toSharedWorkerContext()->dispatchEvent(createConnectEvent(port));
258 OwnPtr<MessagePortChannel> m_channel;
261 // Loads the script on behalf of a worker.
262 class SharedWorkerScriptLoader : public RefCounted<SharedWorkerScriptLoader>, private WorkerScriptLoaderClient {
264 SharedWorkerScriptLoader(PassRefPtr<SharedWorker>, PassOwnPtr<MessagePortChannel>, PassRefPtr<SharedWorkerProxy>);
265 void load(const KURL&);
268 // WorkerScriptLoaderClient callback
269 virtual void notifyFinished();
271 RefPtr<SharedWorker> m_worker;
272 OwnPtr<MessagePortChannel> m_port;
273 RefPtr<SharedWorkerProxy> m_proxy;
274 RefPtr<WorkerScriptLoader> m_scriptLoader;
277 SharedWorkerScriptLoader::SharedWorkerScriptLoader(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, PassRefPtr<SharedWorkerProxy> proxy)
284 void SharedWorkerScriptLoader::load(const KURL& url)
286 // Stay alive (and keep the SharedWorker and JS wrapper alive) until the load finishes.
288 m_worker->setPendingActivity(m_worker.get());
290 // Mark this object as active for the duration of the load.
291 m_scriptLoader = WorkerScriptLoader::create(ResourceRequestBase::TargetIsSharedWorker);
292 m_scriptLoader->loadAsynchronously(m_worker->scriptExecutionContext(), url, DenyCrossOriginRequests, this);
295 void SharedWorkerScriptLoader::notifyFinished()
297 // FIXME: This method is not guaranteed to be invoked if we are loading from WorkerContext (see comment for WorkerScriptLoaderClient::notifyFinished()).
298 // We need to address this before supporting nested workers.
300 // Hand off the just-loaded code to the repository to start up the worker thread.
301 if (m_scriptLoader->failed())
302 m_worker->dispatchEvent(Event::create(eventNames().errorEvent, false, true));
304 InspectorInstrumentation::scriptImported(m_worker->scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
305 DefaultSharedWorkerRepository::instance().workerScriptLoaded(*m_proxy, m_worker->scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), m_port.release());
307 m_worker->unsetPendingActivity(m_worker.get());
308 this->deref(); // This frees this object - must be the last action in this function.
311 DefaultSharedWorkerRepository& DefaultSharedWorkerRepository::instance()
313 AtomicallyInitializedStatic(DefaultSharedWorkerRepository*, instance = new DefaultSharedWorkerRepository);
317 void DefaultSharedWorkerRepository::workerScriptLoaded(SharedWorkerProxy& proxy, const String& userAgent, const String& workerScript, PassOwnPtr<MessagePortChannel> port)
319 MutexLocker lock(m_lock);
320 if (proxy.isClosing())
323 // Another loader may have already started up a thread for this proxy - if so, just send a connect to the pre-existing thread.
324 if (!proxy.thread()) {
325 RefPtr<SharedWorkerThread> thread = SharedWorkerThread::create(proxy.name(), proxy.url(), userAgent, workerScript, proxy, proxy);
326 proxy.setThread(thread);
329 proxy.thread()->runLoop().postTask(SharedWorkerConnectTask::create(port));
332 bool SharedWorkerRepository::isAvailable()
334 // SharedWorkers are enabled on the default WebKit platform.
338 void SharedWorkerRepository::connect(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
340 DefaultSharedWorkerRepository::instance().connectToWorker(worker, port, url, name, ec);
343 void SharedWorkerRepository::documentDetached(Document* document)
345 DefaultSharedWorkerRepository::instance().documentDetached(document);
348 bool SharedWorkerRepository::hasSharedWorkers(Document* document)
350 return DefaultSharedWorkerRepository::instance().hasSharedWorkers(document);
353 bool DefaultSharedWorkerRepository::hasSharedWorkers(Document* document)
355 MutexLocker lock(m_lock);
356 for (unsigned i = 0; i < m_proxies.size(); i++) {
357 if (m_proxies[i]->isInWorkerDocuments(document))
363 void DefaultSharedWorkerRepository::removeProxy(SharedWorkerProxy* proxy)
365 MutexLocker lock(m_lock);
366 for (unsigned i = 0; i < m_proxies.size(); i++) {
367 if (proxy == m_proxies[i].get()) {
374 void DefaultSharedWorkerRepository::documentDetached(Document* document)
376 MutexLocker lock(m_lock);
377 for (unsigned i = 0; i < m_proxies.size(); i++)
378 m_proxies[i]->documentDetached(document);
381 void DefaultSharedWorkerRepository::connectToWorker(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
383 MutexLocker lock(m_lock);
384 ASSERT(worker->scriptExecutionContext()->securityOrigin()->canAccess(SecurityOrigin::create(url).get()));
385 // Fetch a proxy corresponding to this SharedWorker.
386 RefPtr<SharedWorkerProxy> proxy = getProxy(name, url);
387 proxy->addToWorkerDocuments(worker->scriptExecutionContext());
388 if (proxy->url() != url) {
389 // Proxy already existed under alternate URL - return an error.
390 ec = URL_MISMATCH_ERR;
393 // If proxy is already running, just connect to it - otherwise, kick off a loader to load the script.
395 proxy->thread()->runLoop().postTask(SharedWorkerConnectTask::create(port));
397 RefPtr<SharedWorkerScriptLoader> loader = adoptRef(new SharedWorkerScriptLoader(worker, port, proxy.release()));
402 // Creates a new SharedWorkerProxy or returns an existing one from the repository. Must only be called while the repository mutex is held.
403 PassRefPtr<SharedWorkerProxy> DefaultSharedWorkerRepository::getProxy(const String& name, const KURL& url)
405 // Look for an existing worker, and create one if it doesn't exist.
406 // Items in the cache are freed on another thread, so do a threadsafe copy of the URL before creating the origin,
407 // to make sure no references to external strings linger.
408 RefPtr<SecurityOrigin> origin = SecurityOrigin::create(KURL(ParsedURLString, url.string().threadsafeCopy()));
409 for (unsigned i = 0; i < m_proxies.size(); i++) {
410 if (!m_proxies[i]->isClosing() && m_proxies[i]->matches(name, origin, url))
413 // Proxy is not in the repository currently - create a new one.
414 RefPtr<SharedWorkerProxy> proxy = SharedWorkerProxy::create(name, url, origin.release());
415 m_proxies.append(proxy);
416 return proxy.release();
419 DefaultSharedWorkerRepository::DefaultSharedWorkerRepository()
423 DefaultSharedWorkerRepository::~DefaultSharedWorkerRepository()
427 } // namespace WebCore
429 #endif // ENABLE(SHARED_WORKERS)