ScriptExecutionContext: Use FINAL instead of foo() { virtualFoo() }
[WebKit-https.git] / Source / WebCore / workers / WorkerGlobalScope.cpp
1 /*
2  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
3  * Copyright (C) 2009, 2011 Google Inc. All Rights Reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  *
26  */
27
28 #include "config.h"
29
30 #if ENABLE(WORKERS)
31
32 #include "WorkerGlobalScope.h"
33
34 #include "ActiveDOMObject.h"
35 #include "ContentSecurityPolicy.h"
36 #include "DOMTimer.h"
37 #include "DOMURL.h"
38 #include "DOMWindow.h"
39 #include "ErrorEvent.h"
40 #include "Event.h"
41 #include "EventException.h"
42 #include "InspectorConsoleInstrumentation.h"
43 #include "KURL.h"
44 #include "MessagePort.h"
45 #include "NotImplemented.h"
46 #include "ScheduledAction.h"
47 #include "ScriptCallStack.h"
48 #include "ScriptSourceCode.h"
49 #include "ScriptValue.h"
50 #include "SecurityOrigin.h"
51 #include "WorkerInspectorController.h"
52 #include "WorkerLocation.h"
53 #include "WorkerNavigator.h"
54 #include "WorkerObjectProxy.h"
55 #include "WorkerScriptLoader.h"
56 #include "WorkerThread.h"
57 #include "WorkerThreadableLoader.h"
58 #include "XMLHttpRequestException.h"
59 #include <wtf/RefPtr.h>
60
61 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
62 #include "NotificationCenter.h"
63 #endif
64
65 #include "ExceptionCode.h"
66
67 namespace WebCore {
68
69 class CloseWorkerGlobalScopeTask : public ScriptExecutionContext::Task {
70 public:
71     static PassOwnPtr<CloseWorkerGlobalScopeTask> create()
72     {
73         return adoptPtr(new CloseWorkerGlobalScopeTask);
74     }
75
76     virtual void performTask(ScriptExecutionContext *context)
77     {
78         ASSERT_WITH_SECURITY_IMPLICATION(context->isWorkerGlobalScope());
79         WorkerGlobalScope* workerGlobalScope = static_cast<WorkerGlobalScope*>(context);
80         // Notify parent that this context is closed. Parent is responsible for calling WorkerThread::stop().
81         workerGlobalScope->thread()->workerReportingProxy().workerGlobalScopeClosed();
82     }
83
84     virtual bool isCleanupTask() const { return true; }
85 };
86
87 WorkerGlobalScope::WorkerGlobalScope(const KURL& url, const String& userAgent, PassOwnPtr<GroupSettings> settings, WorkerThread* thread, PassRefPtr<SecurityOrigin> topOrigin)
88     : m_url(url)
89     , m_userAgent(userAgent)
90     , m_groupSettings(settings)
91     , m_script(adoptPtr(new WorkerScriptController(this)))
92     , m_thread(thread)
93 #if ENABLE(INSPECTOR)
94     , m_workerInspectorController(adoptPtr(new WorkerInspectorController(this)))
95 #endif
96     , m_closing(false)
97     , m_eventQueue(WorkerEventQueue::create(this))
98     , m_topOrigin(topOrigin)
99 {
100     setSecurityOrigin(SecurityOrigin::create(url));
101 }
102
103 WorkerGlobalScope::~WorkerGlobalScope()
104 {
105     ASSERT(currentThread() == thread()->threadID());
106
107     // Make sure we have no observers.
108     notifyObserversOfStop();
109
110     // Notify proxy that we are going away. This can free the WorkerThread object, so do not access it after this.
111     thread()->workerReportingProxy().workerGlobalScopeDestroyed();
112 }
113
114 void WorkerGlobalScope::applyContentSecurityPolicyFromString(const String& policy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
115 {
116     setContentSecurityPolicy(ContentSecurityPolicy::create(this));
117     contentSecurityPolicy()->didReceiveHeader(policy, contentSecurityPolicyType);
118 }
119
120 ScriptExecutionContext* WorkerGlobalScope::scriptExecutionContext() const
121 {
122     return const_cast<WorkerGlobalScope*>(this);
123 }
124
125 KURL WorkerGlobalScope::completeURL(const String& url) const
126 {
127     // Always return a null URL when passed a null string.
128     // FIXME: Should we change the KURL constructor to have this behavior?
129     if (url.isNull())
130         return KURL();
131     // Always use UTF-8 in Workers.
132     return KURL(m_url, url);
133 }
134
135 String WorkerGlobalScope::userAgent(const KURL&) const
136 {
137     return m_userAgent;
138 }
139
140 void WorkerGlobalScope::disableEval(const String& errorMessage)
141 {
142     m_script->disableEval(errorMessage);
143 }
144
145 WorkerLocation* WorkerGlobalScope::location() const
146 {
147     if (!m_location)
148         m_location = WorkerLocation::create(m_url);
149     return m_location.get();
150 }
151
152 void WorkerGlobalScope::close()
153 {
154     if (m_closing)
155         return;
156
157     // Let current script run to completion but prevent future script evaluations.
158     // After m_closing is set, all the tasks in the queue continue to be fetched but only
159     // tasks with isCleanupTask()==true will be executed.
160     m_closing = true;
161     postTask(CloseWorkerGlobalScopeTask::create());
162 }
163
164 WorkerNavigator* WorkerGlobalScope::navigator() const
165 {
166     if (!m_navigator)
167         m_navigator = WorkerNavigator::create(m_userAgent);
168     return m_navigator.get();
169 }
170
171 bool WorkerGlobalScope::hasPendingActivity() const
172 {
173     ActiveDOMObjectsSet::const_iterator activeObjectsEnd = activeDOMObjects().end();
174     for (ActiveDOMObjectsSet::const_iterator iter = activeDOMObjects().begin(); iter != activeObjectsEnd; ++iter) {
175         if ((*iter)->hasPendingActivity())
176             return true;
177     }
178
179     HashSet<MessagePort*>::const_iterator messagePortsEnd = messagePorts().end();
180     for (HashSet<MessagePort*>::const_iterator iter = messagePorts().begin(); iter != messagePortsEnd; ++iter) {
181         if ((*iter)->hasPendingActivity())
182             return true;
183     }
184
185     return false;
186 }
187
188 void WorkerGlobalScope::postTask(PassOwnPtr<Task> task)
189 {
190     thread()->runLoop().postTask(task);
191 }
192
193 int WorkerGlobalScope::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout)
194 {
195     return DOMTimer::install(scriptExecutionContext(), action, timeout, true);
196 }
197
198 void WorkerGlobalScope::clearTimeout(int timeoutId)
199 {
200     DOMTimer::removeById(scriptExecutionContext(), timeoutId);
201 }
202
203 #if ENABLE(INSPECTOR)
204 void WorkerGlobalScope::clearInspector()
205 {
206     m_workerInspectorController.clear();
207 }
208 #endif
209
210 int WorkerGlobalScope::setInterval(PassOwnPtr<ScheduledAction> action, int timeout)
211 {
212     return DOMTimer::install(scriptExecutionContext(), action, timeout, false);
213 }
214
215 void WorkerGlobalScope::clearInterval(int timeoutId)
216 {
217     DOMTimer::removeById(scriptExecutionContext(), timeoutId);
218 }
219
220 void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionCode& ec)
221 {
222     ASSERT(contentSecurityPolicy());
223     ec = 0;
224     Vector<String>::const_iterator urlsEnd = urls.end();
225     Vector<KURL> completedURLs;
226     for (Vector<String>::const_iterator it = urls.begin(); it != urlsEnd; ++it) {
227         const KURL& url = scriptExecutionContext()->completeURL(*it);
228         if (!url.isValid()) {
229             ec = SYNTAX_ERR;
230             return;
231         }
232         completedURLs.append(url);
233     }
234     Vector<KURL>::const_iterator end = completedURLs.end();
235
236     for (Vector<KURL>::const_iterator it = completedURLs.begin(); it != end; ++it) {
237         RefPtr<WorkerScriptLoader> scriptLoader(WorkerScriptLoader::create());
238 #if PLATFORM(BLACKBERRY)
239         scriptLoader->setTargetType(ResourceRequest::TargetIsScript);
240 #endif
241         scriptLoader->loadSynchronously(scriptExecutionContext(), *it, AllowCrossOriginRequests);
242
243         // If the fetching attempt failed, throw a NETWORK_ERR exception and abort all these steps.
244         if (scriptLoader->failed()) {
245             ec = XMLHttpRequestException::NETWORK_ERR;
246             return;
247         }
248
249         InspectorInstrumentation::scriptImported(scriptExecutionContext(), scriptLoader->identifier(), scriptLoader->script());
250
251         ScriptValue exception;
252         m_script->evaluate(ScriptSourceCode(scriptLoader->script(), scriptLoader->responseURL()), &exception);
253         if (!exception.hasNoValue()) {
254             m_script->setException(exception);
255             return;
256         }
257     }
258 }
259
260 EventTarget* WorkerGlobalScope::errorEventTarget()
261 {
262     return this;
263 }
264
265 void WorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>)
266 {
267     thread()->workerReportingProxy().postExceptionToWorkerObject(errorMessage, lineNumber, columnNumber, sourceURL);
268 }
269
270 void WorkerGlobalScope::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
271 {
272     if (!isContextThread()) {
273         postTask(AddConsoleMessageTask::create(source, level, message));
274         return;
275     }
276
277     thread()->workerReportingProxy().postConsoleMessageToWorkerObject(source, level, message, 0, 0, String());
278     addMessageToWorkerConsole(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
279 }
280
281 void WorkerGlobalScope::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
282 {
283     if (!isContextThread()) {
284         postTask(AddConsoleMessageTask::create(source, level, message));
285         return;
286     }
287
288     thread()->workerReportingProxy().postConsoleMessageToWorkerObject(source, level, message, lineNumber, columnNumber, sourceURL);
289     addMessageToWorkerConsole(source, level, message, sourceURL, lineNumber, columnNumber, callStack, state, requestIdentifier);
290 }
291
292 void WorkerGlobalScope::addMessageToWorkerConsole(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
293 {
294     ASSERT(isContextThread());
295     if (callStack)
296         InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, callStack, requestIdentifier);
297     else
298         InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, sourceURL, lineNumber, columnNumber, state, requestIdentifier);
299 }
300
301 bool WorkerGlobalScope::isContextThread() const
302 {
303     return currentThread() == thread()->threadID();
304 }
305
306 bool WorkerGlobalScope::isJSExecutionForbidden() const
307 {
308     return m_script->isExecutionForbidden();
309 }
310
311 EventTargetData* WorkerGlobalScope::eventTargetData()
312 {
313     return &m_eventTargetData;
314 }
315
316 EventTargetData& WorkerGlobalScope::ensureEventTargetData()
317 {
318     return m_eventTargetData;
319 }
320
321 WorkerGlobalScope::Observer::Observer(WorkerGlobalScope* context)
322     : m_context(context)
323 {
324     ASSERT(m_context && m_context->isContextThread());
325     m_context->registerObserver(this);
326 }
327
328 WorkerGlobalScope::Observer::~Observer()
329 {
330     if (!m_context)
331         return;
332     ASSERT(m_context->isContextThread());
333     m_context->unregisterObserver(this);
334 }
335
336 void WorkerGlobalScope::Observer::stopObserving()
337 {
338     if (!m_context)
339         return;
340     ASSERT(m_context->isContextThread());
341     m_context->unregisterObserver(this);
342     m_context = 0;
343 }
344
345 void WorkerGlobalScope::registerObserver(Observer* observer)
346 {
347     ASSERT(observer);
348     m_workerObservers.add(observer);
349 }
350
351 void WorkerGlobalScope::unregisterObserver(Observer* observer)
352 {
353     ASSERT(observer);
354     m_workerObservers.remove(observer);
355 }
356
357 void WorkerGlobalScope::notifyObserversOfStop()
358 {
359     HashSet<Observer*>::iterator iter = m_workerObservers.begin();
360     while (iter != m_workerObservers.end()) {
361         WorkerGlobalScope::Observer* observer = *iter;
362         observer->stopObserving();
363         observer->notifyStop();
364         iter = m_workerObservers.begin();
365     }
366 }
367
368 WorkerEventQueue* WorkerGlobalScope::eventQueue() const
369 {
370     return m_eventQueue.get();
371 }
372
373 } // namespace WebCore
374
375 #endif // ENABLE(WORKERS)