Support Performance API (performance.now(), UserTiming) in Workers
[WebKit-https.git] / Source / WebCore / workers / Worker.cpp
1 /*
2  * Copyright (C) 2008-2017 Apple Inc. All Rights Reserved.
3  * Copyright (C) 2009 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 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 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 #include "config.h"
28 #include "Worker.h"
29
30 #include "ContentSecurityPolicy.h"
31 #include "Event.h"
32 #include "EventNames.h"
33 #include "InspectorInstrumentation.h"
34 #include "NetworkStateNotifier.h"
35 #include "ResourceResponse.h"
36 #include "SecurityOrigin.h"
37 #include "WorkerGlobalScopeProxy.h"
38 #include "WorkerScriptLoader.h"
39 #include "WorkerThread.h"
40 #include <inspector/IdentifiersFactory.h>
41 #include <wtf/HashSet.h>
42 #include <wtf/MainThread.h>
43
44 namespace WebCore {
45
46 static HashSet<Worker*>* allWorkers;
47
48 void networkStateChanged(bool isOnLine)
49 {
50     for (auto& worker : *allWorkers)
51         worker->notifyNetworkStateChange(isOnLine);
52 }
53
54 inline Worker::Worker(ScriptExecutionContext& context, JSC::RuntimeFlags runtimeFlags)
55     : ActiveDOMObject(&context)
56     , m_identifier("worker:" + Inspector::IdentifiersFactory::createIdentifier())
57     , m_contextProxy(WorkerGlobalScopeProxy::create(*this))
58     , m_runtimeFlags(runtimeFlags)
59 {
60     if (!allWorkers) {
61         allWorkers = new HashSet<Worker*>;
62         networkStateNotifier().addNetworkStateChangeListener(networkStateChanged);
63     }
64
65     auto addResult = allWorkers->add(this);
66     ASSERT_UNUSED(addResult, addResult.isNewEntry);
67 }
68
69 ExceptionOr<Ref<Worker>> Worker::create(ScriptExecutionContext& context, const String& url, JSC::RuntimeFlags runtimeFlags)
70 {
71     ASSERT(isMainThread());
72
73     // We don't currently support nested workers, so workers can only be created from documents.
74     ASSERT_WITH_SECURITY_IMPLICATION(context.isDocument());
75
76     auto worker = adoptRef(*new Worker(context, runtimeFlags));
77
78     worker->suspendIfNeeded();
79
80     bool shouldBypassMainWorldContentSecurityPolicy = context.shouldBypassMainWorldContentSecurityPolicy();
81     auto scriptURL = worker->resolveURL(url, shouldBypassMainWorldContentSecurityPolicy);
82     if (scriptURL.hasException())
83         return scriptURL.releaseException();
84
85     worker->m_shouldBypassMainWorldContentSecurityPolicy = shouldBypassMainWorldContentSecurityPolicy;
86
87     // The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners.
88     worker->setPendingActivity(worker.ptr());
89
90     // https://html.spec.whatwg.org/multipage/workers.html#official-moment-of-creation
91     worker->m_momentOfCreation = monotonicallyIncreasingTime();
92
93     worker->m_scriptLoader = WorkerScriptLoader::create();
94     auto contentSecurityPolicyEnforcement = shouldBypassMainWorldContentSecurityPolicy ? ContentSecurityPolicyEnforcement::DoNotEnforce : ContentSecurityPolicyEnforcement::EnforceChildSrcDirective;
95     worker->m_scriptLoader->loadAsynchronously(&context, scriptURL.releaseReturnValue(), FetchOptions::Mode::SameOrigin, contentSecurityPolicyEnforcement, worker->m_identifier, worker.ptr());
96     return WTFMove(worker);
97 }
98
99 Worker::~Worker()
100 {
101     ASSERT(isMainThread());
102     ASSERT(scriptExecutionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
103     allWorkers->remove(this);
104     m_contextProxy.workerObjectDestroyed();
105 }
106
107 ExceptionOr<void> Worker::postMessage(JSC::ExecState& state, JSC::JSValue messageValue, Vector<JSC::Strong<JSC::JSObject>>&& transfer)
108 {
109     Vector<RefPtr<MessagePort>> ports;
110     auto message = SerializedScriptValue::create(state, messageValue, WTFMove(transfer), ports);
111     if (message.hasException())
112         return message.releaseException();
113
114     // Disentangle the port in preparation for sending it to the remote context.
115     auto channels = MessagePort::disentanglePorts(WTFMove(ports));
116     if (channels.hasException())
117         return channels.releaseException();
118     m_contextProxy.postMessageToWorkerGlobalScope(message.releaseReturnValue(), channels.releaseReturnValue());
119     return { };
120 }
121
122 void Worker::terminate()
123 {
124     m_contextProxy.terminateWorkerGlobalScope();
125 }
126
127 bool Worker::canSuspendForDocumentSuspension() const
128 {
129     // FIXME: It is not currently possible to suspend a worker, so pages with workers can not go into page cache.
130     return false;
131 }
132
133 const char* Worker::activeDOMObjectName() const
134 {
135     return "Worker";
136 }
137
138 void Worker::stop()
139 {
140     terminate();
141 }
142
143 bool Worker::hasPendingActivity() const
144 {
145     return m_contextProxy.hasPendingActivity() || ActiveDOMObject::hasPendingActivity();
146 }
147
148 void Worker::notifyNetworkStateChange(bool isOnLine)
149 {
150     m_contextProxy.notifyNetworkStateChange(isOnLine);
151 }
152
153 void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
154 {
155     const URL& responseURL = response.url();
156     if (!responseURL.protocolIsBlob() && !responseURL.protocolIs("file") && !SecurityOrigin::create(responseURL)->isUnique())
157         m_contentSecurityPolicyResponseHeaders = ContentSecurityPolicyResponseHeaders(response);
158     InspectorInstrumentation::didReceiveScriptResponse(scriptExecutionContext(), identifier);
159 }
160
161 void Worker::notifyFinished()
162 {
163     if (m_scriptLoader->failed())
164         dispatchEvent(Event::create(eventNames().errorEvent, false, true));
165     else {
166         const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders = m_contentSecurityPolicyResponseHeaders ? m_contentSecurityPolicyResponseHeaders.value() : scriptExecutionContext()->contentSecurityPolicy()->responseHeaders();
167         m_contextProxy.startWorkerGlobalScope(m_scriptLoader->url(), scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_momentOfCreation, m_runtimeFlags);
168         InspectorInstrumentation::scriptImported(*scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
169     }
170     m_scriptLoader = nullptr;
171
172     unsetPendingActivity(this);
173 }
174
175 } // namespace WebCore