Clean up ScriptExecutionContext::Task and subclasses
[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 "URL.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 URL& url, const String& userAgent, std::unique_ptr<GroupSettings> settings, WorkerThread* thread, PassRefPtr<SecurityOrigin> topOrigin)
88     : m_url(url)
89     , m_userAgent(userAgent)
90     , m_groupSettings(std::move(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(*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 URL WorkerGlobalScope::completeURL(const String& url) const
121 {
122     // Always return a null URL when passed a null string.
123     // FIXME: Should we change the URL constructor to have this behavior?
124     if (url.isNull())
125         return URL();
126     // Always use UTF-8 in Workers.
127     return URL(m_url, url);
128 }
129
130 String WorkerGlobalScope::userAgent(const URL&) const
131 {
132     return m_userAgent;
133 }
134
135 void WorkerGlobalScope::disableEval(const String& errorMessage)
136 {
137     m_script->disableEval(errorMessage);
138 }
139
140 WorkerLocation* WorkerGlobalScope::location() const
141 {
142     if (!m_location)
143         m_location = WorkerLocation::create(m_url);
144     return m_location.get();
145 }
146
147 void WorkerGlobalScope::close()
148 {
149     if (m_closing)
150         return;
151
152     // Let current script run to completion but prevent future script evaluations.
153     // After m_closing is set, all the tasks in the queue continue to be fetched but only
154     // tasks with isCleanupTask()==true will be executed.
155     m_closing = true;
156     postTask(std::make_unique<CloseWorkerGlobalScopeTask>());
157 }
158
159 WorkerNavigator* WorkerGlobalScope::navigator() const
160 {
161     if (!m_navigator)
162         m_navigator = WorkerNavigator::create(m_userAgent);
163     return m_navigator.get();
164 }
165
166 bool WorkerGlobalScope::hasPendingActivity() const
167 {
168     ActiveDOMObjectsSet::const_iterator activeObjectsEnd = activeDOMObjects().end();
169     for (ActiveDOMObjectsSet::const_iterator iter = activeDOMObjects().begin(); iter != activeObjectsEnd; ++iter) {
170         if ((*iter)->hasPendingActivity())
171             return true;
172     }
173
174     HashSet<MessagePort*>::const_iterator messagePortsEnd = messagePorts().end();
175     for (HashSet<MessagePort*>::const_iterator iter = messagePorts().begin(); iter != messagePortsEnd; ++iter) {
176         if ((*iter)->hasPendingActivity())
177             return true;
178     }
179
180     return false;
181 }
182
183 void WorkerGlobalScope::postTask(std::unique_ptr<Task> task)
184 {
185     thread()->runLoop().postTask(std::move(task));
186 }
187
188 int WorkerGlobalScope::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout)
189 {
190     return DOMTimer::install(scriptExecutionContext(), action, timeout, true);
191 }
192
193 void WorkerGlobalScope::clearTimeout(int timeoutId)
194 {
195     DOMTimer::removeById(scriptExecutionContext(), timeoutId);
196 }
197
198 #if ENABLE(INSPECTOR)
199 void WorkerGlobalScope::clearInspector()
200 {
201     m_workerInspectorController.clear();
202 }
203 #endif
204
205 int WorkerGlobalScope::setInterval(PassOwnPtr<ScheduledAction> action, int timeout)
206 {
207     return DOMTimer::install(scriptExecutionContext(), action, timeout, false);
208 }
209
210 void WorkerGlobalScope::clearInterval(int timeoutId)
211 {
212     DOMTimer::removeById(scriptExecutionContext(), timeoutId);
213 }
214
215 void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionCode& ec)
216 {
217     ASSERT(contentSecurityPolicy());
218     ec = 0;
219     Vector<String>::const_iterator urlsEnd = urls.end();
220     Vector<URL> completedURLs;
221     for (Vector<String>::const_iterator it = urls.begin(); it != urlsEnd; ++it) {
222         const URL& url = scriptExecutionContext()->completeURL(*it);
223         if (!url.isValid()) {
224             ec = SYNTAX_ERR;
225             return;
226         }
227         completedURLs.append(url);
228     }
229     Vector<URL>::const_iterator end = completedURLs.end();
230
231     for (Vector<URL>::const_iterator it = completedURLs.begin(); it != end; ++it) {
232         RefPtr<WorkerScriptLoader> scriptLoader(WorkerScriptLoader::create());
233 #if PLATFORM(BLACKBERRY)
234         scriptLoader->setTargetType(ResourceRequest::TargetIsScript);
235 #endif
236         scriptLoader->loadSynchronously(scriptExecutionContext(), *it, AllowCrossOriginRequests);
237
238         // If the fetching attempt failed, throw a NETWORK_ERR exception and abort all these steps.
239         if (scriptLoader->failed()) {
240             ec = XMLHttpRequestException::NETWORK_ERR;
241             return;
242         }
243
244         InspectorInstrumentation::scriptImported(scriptExecutionContext(), scriptLoader->identifier(), scriptLoader->script());
245
246         ScriptValue exception;
247         m_script->evaluate(ScriptSourceCode(scriptLoader->script(), scriptLoader->responseURL()), &exception);
248         if (!exception.hasNoValue()) {
249             m_script->setException(exception);
250             return;
251         }
252     }
253 }
254
255 EventTarget* WorkerGlobalScope::errorEventTarget()
256 {
257     return this;
258 }
259
260 void WorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>)
261 {
262     thread()->workerReportingProxy().postExceptionToWorkerObject(errorMessage, lineNumber, columnNumber, sourceURL);
263 }
264
265 void WorkerGlobalScope::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
266 {
267     if (!isContextThread()) {
268         postTask(std::make_unique<AddConsoleMessageTask>(source, level, message));
269         return;
270     }
271
272     thread()->workerReportingProxy().postConsoleMessageToWorkerObject(source, level, message, 0, 0, String());
273     addMessageToWorkerConsole(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
274 }
275
276 void WorkerGlobalScope::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, PassRefPtr<ScriptCallStack> callStack, JSC::ExecState* state, unsigned long requestIdentifier)
277 {
278     if (!isContextThread()) {
279         postTask(std::make_unique<AddConsoleMessageTask>(source, level, message));
280         return;
281     }
282
283     thread()->workerReportingProxy().postConsoleMessageToWorkerObject(source, level, message, lineNumber, columnNumber, sourceURL);
284     addMessageToWorkerConsole(source, level, message, sourceURL, lineNumber, columnNumber, callStack, state, requestIdentifier);
285 }
286
287 void WorkerGlobalScope::addMessageToWorkerConsole(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, PassRefPtr<ScriptCallStack> callStack, JSC::ExecState* state, unsigned long requestIdentifier)
288 {
289     ASSERT(isContextThread());
290     if (callStack)
291         InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, callStack, requestIdentifier);
292     else
293         InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, sourceURL, lineNumber, columnNumber, state, requestIdentifier);
294 }
295
296 bool WorkerGlobalScope::isContextThread() const
297 {
298     return currentThread() == thread()->threadID();
299 }
300
301 bool WorkerGlobalScope::isJSExecutionForbidden() const
302 {
303     return m_script->isExecutionForbidden();
304 }
305
306 WorkerGlobalScope::Observer::Observer(WorkerGlobalScope* context)
307     : m_context(context)
308 {
309     ASSERT(m_context && m_context->isContextThread());
310     m_context->registerObserver(this);
311 }
312
313 WorkerGlobalScope::Observer::~Observer()
314 {
315     if (!m_context)
316         return;
317     ASSERT(m_context->isContextThread());
318     m_context->unregisterObserver(this);
319 }
320
321 void WorkerGlobalScope::Observer::stopObserving()
322 {
323     if (!m_context)
324         return;
325     ASSERT(m_context->isContextThread());
326     m_context->unregisterObserver(this);
327     m_context = 0;
328 }
329
330 void WorkerGlobalScope::registerObserver(Observer* observer)
331 {
332     ASSERT(observer);
333     m_workerObservers.add(observer);
334 }
335
336 void WorkerGlobalScope::unregisterObserver(Observer* observer)
337 {
338     ASSERT(observer);
339     m_workerObservers.remove(observer);
340 }
341
342 void WorkerGlobalScope::notifyObserversOfStop()
343 {
344     HashSet<Observer*>::iterator iter = m_workerObservers.begin();
345     while (iter != m_workerObservers.end()) {
346         WorkerGlobalScope::Observer* observer = *iter;
347         observer->stopObserving();
348         observer->notifyStop();
349         iter = m_workerObservers.begin();
350     }
351 }
352
353 WorkerEventQueue& WorkerGlobalScope::eventQueue() const
354 {
355     return m_eventQueue;
356 }
357
358 } // namespace WebCore
359
360 #endif // ENABLE(WORKERS)