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